Creating a 3D B-Spline Surface and Extruded Solid with PythonOCC

In the realm of 3D computer graphics and CAD (Computer-Aided Design), Python, combined with the Open CASCADE Technology (OCC) library, offers powerful tools for creating and manipulating complex geometries. One such application is the creation of a 3D B-spline surface, a versatile type of surface that can be used in various design and engineering tasks. This article will guide you through the process of creating a 3D B-spline surface using Python and OCC.

Setting Up the Environment

First, ensure you have the OCC library installed. This library provides the necessary tools for working with 3D geometries in Python. Our code begins with importing the required modules from the OCC library:

from OCC.Core.gp import gp_Pnt, gp_Vec
from OCC.Core.BRepBuilderAPI import BRepBuilderAPI_MakeFace
from OCC.Core.BRepPrimAPI import BRepPrimAPI_MakePrism
from OCC.Core.GeomAPI import GeomAPI_PointsToBSplineSurface
from OCC.Core.TColgp import TColgp_Array2OfPnt

Defining Control Points

The heart of a B-spline surface is its control points. These points define the shape and curvature of the surface. In our example, we define a grid of control points:

control_points = [
    [0, 0, 0], [1, 0, 0], [2, 0, 0], [3, 0, 0],
    [0, 1, 1], [1, 1, 1], [2, 1, 1], [3, 1, 1],
    [0, 2, 0], [1, 2, 0], [2, 2, 0], [3, 2, 0],
    [0, 3, 0], [1, 3, 0], [2, 3, 0], [3, 3, 0]
]

Creating the B-Spline Surface

We then convert these points into a format that OCC can use and create the B-spline surface:

points_array = TColgp_Array2OfPnt(1, 4, 1, 4)
for i in range(4):
    for j in range(4):
        pnt = gp_Pnt(*control_points[i * 4 + j])
        points_array.SetValue(i + 1, j + 1, pnt)

surface_builder = GeomAPI_PointsToBSplineSurface(points_array)
surface = surface_builder.Surface()

Generating the 3D Model

After creating the surface, we convert it into a 3D shape, suitable for display and further manipulation:

face_builder = BRepBuilderAPI_MakeFace(surface, 1e-6)
face = face_builder.Face()
extrusion_vector= gp_Vec(0,0,1.0)
prism_builder = BRepPrimAPI_MakePrism(face, extrusion_vector)
prism_builder.Build()
solid = prism_builder.Shape()

Visualizing the Model

Finally, we use OCC's visualization tools to display the model:

from OCC.Display.SimpleGui import init_display
display, start_display, add_menu, add_function_to_menu = init_display()
display.DisplayShape(solid, update=True)
display.FitAll()
start_display()

Result


Conclusion

Creating a 3D B-spline surface using Python and the OCC library demonstrates the power and flexibility of these tools for 3D modeling and CAD applications. Whether you are a hobbyist, designer, or engineer, this approach offers a programmable and highly customizable way to create complex 3D geometries.

Comments

Popular posts from this blog

Crafting Arc and 3D Models with PythonOCC

Creating a 3D prism using PythonOCC