Migrating to rhino3dm 9.2 (Python)
rhino3dm 9.2’s Python bindings are generated from RhinoCommon, the .NET SDK of Rhino,
so the API is RhinoCommon’s: its names, signatures and behaviour. The typings that ship with the package (rhino3dm/__init__.pyi) list every
member with its documentation.
rhino3dm 8.x was written by hand and often differed from RhinoCommon. The changes below are the ones most scripts will hit. Renamed and removed members maps each 8.x member that is gone to its replacement.
The changes most scripts hit · Files and tables · Geometry · Annotations · Rendering and settings · Renamed classes · Enums · Errors, values and identity · Packaging
The changes most scripts hit
1. Editing an object’s geometry no longer changes the file
obj.Geometry is now a copy-on-write view, like it is in RhinoCommon. This means that the first edit makes a
private copy, and the file stays as it was (no error). To change the file, replace the object:
# 8.x
for obj in model.Objects:
obj.Geometry.Transform(xform)
# 9.2
for obj in list(model.Objects):
geometry = obj.Geometry
geometry.Transform(xform)
model.Objects.Delete(obj.Id)
model.Objects.Add(geometry, obj.Attributes)
obj.Attributes still writes through. A brep face’s surface and mesh, an
extrusion’s mesh and a material’s textures are copy-on-write views too (Geometry).
2. out parameters come back as a tuple, success first
# 8.x
frustum = viewport.GetFrustum() # a dict
left, near = frustum['left'], frustum['near']
# 9.2
ok, left, right, bottom, top, near, far = viewport.GetFrustum()
ok, plane = curve.TryGetPlane() # new in 9.2, same pattern
3. Editing tables
# 8.x
model.Write(path)
index = model.Layers.Add(layer)
model.Layers.Delete(layer.Id)
# 9.2
model.Write(path, 0) # 0 is the current version
model.Layers.Add(layer) # returns nothing
index = len(model.Layers) - 1
model.Layers.Delete(layer) # or Delete(index), which raises for a bad index
model.Layers.AddLayer(name, color) still returns the index.
The same goes for the other tables (materials, linetypes, dimension styles, …).
4. In-place methods return nothing
# 8.x
p = p.Transform(xform) # edited p and returned it
v.Unitize() # returned None
# 9.2
p.Transform(xform) # edits p, returns None
ok = v.Unitize() # False for a zero vector
5. Bad arguments raise
RhinoCommon’s argument checks run here too: curve.SpanDomain(-1) raises IndexError, and
File3dm.Read('missing.3dm') raises FileNotFoundError.
See Errors for how .NET’s exceptions map to Python’s.
6. Arrays are lists
Array results are lists (8.x returned tuples in places), and None where RhinoCommon returns null, for example
BoundingBox.GetCorners() of an invalid box.
Files and tables
Getting items: iterating and indexing
# 8.x
for i in range(len(model.Objects)):
obj = model.Objects[i]
# 9.2
for obj in model.Objects:
...
third = list(model.Objects)[2]
Iteration walks the live components (
for layer in model.Layers), skipping deleted ones. 8.x raised at the first deleted item.model.Objects[i]is gone, as in RhinoCommon: iterate, orlist(model.Objects)[i].len(model.Objects)works.FindIndex(i)returnsNonefor a deleted or out-of-range index.table[i]still raisesIndexError.Bitmaps:
FindIdfinds images, andFindIndex(i)/[i]give the i-th image.Decals: iterate them (
for d in attributes.Decals); hidden decals are skipped, as in RhinoCommon.len(attributes.Decals)counts what iteration yields. There is no index: uselist(attributes.Decals)[i].
Table items are live
A layer you hold reflects later edits to the file, and raises
RuntimeErroronce its layer is deleted from the file. In 8.x it kept stale data.model.Views[i]andNamedViews[i]are live too: the same view while it is in the file, and aRuntimeErroronce it is not.Objects come back as their most specific class: a plane surface is a
PlaneSurface, not aSurface, soisinstancechecks change.
Tables and their members
model.Layersandmodel.AllLayersboth exist, as in RhinoCommon (also materials, linetypes, dimension styles, instance definitions and hatch patterns).model.Stringshas RhinoCommon’s members:Count,GetKey(i),GetValue(i),GetValue(key),SetString(key, value),Delete(key). There is nolenand no indexing.File3dm.Manifestlists every component of the file. Its images areBitmapobjects.File3dm.AllViewsandAllNamedViewsare not available yet (ViewsandNamedViewsare).model.Objects.Add(geometry, attributes)adds leaders, text and radial or ordinate dimensions too, as 8.x did, although RhinoCommon throws for them.Adding a bitmap: set
bitmap.FileFullPath = path, thenmodel.Bitmaps.Add(bitmap)returns the file’s copy.
Embedded files
# 8.x
file = rhino3dm.EmbeddedFile.Read(path)
model.EmbeddedFiles.Add(file)
paths = model.EmbeddedFilePaths()
# 9.2
file = rhino3dm.File3dmEmbeddedFile.Read(path) # named after path
model.EmbeddedFiles.Add(file)
paths = [f.Filename for f in model.EmbeddedFiles]
An embedded file’s
Filenameis read-only: the name comes from the path given toFile3dmEmbeddedFile.Read(path).Paths are cleaned for the platform, so a path saved on Windows reads with
/on Linux and macOS.
File settings
File3dm.CreatedandLastEditedare new:datetime.datetimevalues.ConstructionPlaneandFile3dmWriteOptionsgain RhinoCommon’s members:ShowGrid,ShowAxes,ShowZAxis, and the write options’ mesh options.The model’s notes can be written:
model.Notes.Notes,IsVisible,IsHtmlandWindowRectangle((x, y, width, height)) are read-write and go into the written file.
Geometry
All geometry
Copy-on-write. Like
obj.Geometry,BrepFace.UnderlyingSurface(),BrepFace.GetMesh(type),Extrusion.GetMesh(type)andMaterial.GetBitmapTexture()(and the other texture getters) return copy-on-write views: an edit does not reach the file. Put changes back withBrepFace.SetMesh(type, mesh)orMaterial.SetBitmapTexture(texture).Values of invalid inputs follow RhinoCommon. For example the distance to an unset point is
0.0(8.x: infinity).IsValidWithLogis a method:ok, log = obj.IsValidWithLog().Constructors RhinoCommon does not have are gone:
Group(),Hatch(),RevSurface(),TextureMapping(),Decal(),Point(). Use RhinoCommon’s factories (model.AllGroups.AddGroup,Hatch.CreateFromBrep,RevSurface.Create,TextureMapping.Create*Mapping,Point(location)).Some RhinoCommon overloads differ only in their
outparameters, so Python can reach only one of them under RhinoCommon’s name. The others have names of their own, listed in each section below.
Points, vectors and transforms
Transformis a value type, so assignment copies it.Point3d.TransformandVector3d.Unitizechange the value in place: see the changes most scripts hit.Plane.WorldXY,Transform.Identity,Vector3d.Lengthand the other members that are properties in RhinoCommon are properties:Plane.WorldXY, notPlane.WorldXY().Transform.DecomposeAffinewith all fouroutvalues isTransform.DecomposeAffineFull.
Curves
Curve.CreateControlPointCurve(points, degree)builds the curve as RhinoCommon does. Two points still give aLineCurve, and degree 1 still gives aPolylineCurve. For a NURBS curve:The domain is
0to the length of the control polygon. 8.x used knot spacing 1, so the domain was0to the number of points minus the degree. The shape is the same, but every parameter changes:PointAt(t),Domainand closest-point results.A closed point list (last point equal to the first) gives a smooth periodic curve. 8.x made a clamped curve with a kink where it closes.
Too few points for the degree lowers the degree to the number of points minus one. 8.x returned
None. The degree is also clamped to 1–11.
Curve.DerivativeAtreturnsVector3ds (the point first, as a vector).NurbsCurvePointList.GetPoint(i)returning aPoint4disGetPoint4d(i).
Polylines and point lists
PolylineandPoint3dListare RhinoCommon’s lists, with all ofRhinoList’s members (AddRange,RemoveRange,IndexOf,Sort,Reverse,First,Last,ToArray, …). They are reference types: an assignment shares the list. Index with[]andlen().Polyline.GetSegments()(8.xGetSegments2()) returnsLinevalues, notLineCurveobjects, andNonewith fewer than two points.Point3dList.Append(points)isAddRange(points).
Surfaces
NurbsSurface.Create(...)with invalid arguments returnsNone.NurbsSurfacePointList.GetPoint(u, v)returning aPoint4disGetPoint4d(u, v).
Breps
Editing a face’s surface no longer changes the brep.
BrepFace.UnderlyingSurface()andbrep.Surfaces[i]return copy-on-write views. In 8.x an edit moved the surface inside the brep but left its edges and trims where they were, which made the brep invalid (brep.IsValidbecame false) and could write a broken brep to the file. To move the brep, transform it (brep.Transform(xform)). To use the edited surface, build a new brep from it:# 8.x surface = face.UnderlyingSurface() surface.Transform(xform) # moved the face's surface inside the brep, not its edges and trims brep.IsValid # False: the brep is now invalid # 9.2 surface = face.UnderlyingSurface() surface.Transform(xform) # moves a copy: the brep is unchanged new_brep = rhino3dm.Brep.CreateFromSurface(surface)
Editing a
BrepEdgeorBrepTrimthrough aCurvemethod (edge.Reverse()) raisesRuntimeError.BrepFace.PerFaceColorof a face without one is(0, 0, 0, 0)(8.x(255, 255, 255, 0)), and it can be set.BrepFace.GetMesh(type)returns a copy-on-write view: editing it does not change the face. Put the change back withBrepFace.SetMesh(type, mesh).
Extrusions
Editing the mesh
Extrusion.GetMesh(type)returns no longer changes the extrusion or the meshes it stores: it is a copy-on-write view. In 8.x the edit changed the extrusion’s stored mesh. Put the change back withExtrusion.SetMesh(mesh, type).
Meshes
mesh.Faces[i]is aMeshFace(A,B,C,D,IsQuad), not a 4-tuple:# 8.x a, b, c, d = mesh.Faces[i] is_quad = c != d # 9.2 face = mesh.Faces[i] a, b, c, d = face.A, face.B, face.C, face.D is_quad = face.IsQuad
mesh.Normals.Add(x, y, z)stores the vector as given. 8.x unitized it on add. Unitize afterwards, once the mesh has a normal for each vertex:# 8.x mesh.Normals.Add(0.0, 0.0, 5.0) # stored as (0, 0, 1) # 9.2 mesh.Normals.Add(0.0, 0.0, 5.0) # stored as (0, 0, 5) mesh.Normals.UnitizeNormals() # now (0, 0, 1)
Mesh.GetCachedTextureCoordinates(id)is a view into the mesh, not a copy.Mesh.GetCachedTextureCoordinatesFromTexture(file, objectId, texture)is an overload ofGetCachedTextureCoordinates, andSetCachedTextureCoordinatesFromMaterialreturns nothing.
SubD
subd.Faces,subd.Edgesandsubd.Verticesare lists withlen, iteration andFind(id). TheFirst/Next/Currentcursors are gone. In 8.x,Next()did not stop after the last component: awhileloop over it never ended, or crashed.for face in subd.Facesworks in both.# 8.x count = subd.Faces.Count face = subd.Faces[face_id] # by id # 9.2 count = len(subd.Faces) face = subd.Faces.Find(face_id)
A component’s neighbours are lists:
face.Edges,face.Vertices,edge.Faces,edge.Vertices,vertex.Edgesandvertex.Faces, not 8.x’s cursors. RhinoCommon’sEdgeCountplusEdgeAt(i)(alsoVertexAt,FaceAt) work too, and an edge’s vertices are alsoVertexFromandVertexTo.# 8.x edges = face.Edges # a cursor count = edges.Count edge = edges[0] # 9.2 edges = face.Edges # a list count = len(edges) # or face.EdgeCount edge = edges[0] # or face.EdgeAt(0) start, end = edge.VertexFrom, edge.VertexTo
SubDVertex.SurfacePoint()is a method, andNext,PreviousandFirstare properties.SubD.SharpEdgeCount()is a method.# 8.x point = vertex.SurfacePoint following = vertex.Next() first = subd.Vertices.First() sharp = subd.SharpEdgeCount # 9.2 point = vertex.SurfacePoint() following = vertex.Next first = subd.Vertices.First sharp = subd.SharpEdgeCount()
A component whose SubD changed raises
RuntimeError; 8.x kept answering as if nothing had changed. Components compare equal when they are the same component of the same SubD (==).# 8.x face = subd.Faces[1] subd.Subdivide(1) face.EdgeCount # still answered # 9.2 face = subd.Faces.Find(1) subd.Subdivide(1) face.EdgeCount # RuntimeError: the component is no longer in its owner
SubDFace.IsNotConvexandIsNotPlanar(tol)are gone: usenot IsConvexandnot IsPlanar(tol). They differ only for a degenerate face; testControlNetCenterNormal.IsZerofirst when that matters.# 8.x if face.IsNotConvex or face.IsNotPlanar(tol): ... # 9.2 if not face.IsConvex or not face.IsPlanar(tol): ...
SubDFace.PerFaceColorof a face without one is(0, 0, 0, 0)(8.x(255, 255, 255, 0)), and it can be set.# 8.x face.PerFaceColor # (255, 255, 255, 0) when unset; read-only # 9.2 face.PerFaceColor # (0, 0, 0, 0) when unset face.PerFaceColor = (255, 0, 0, 255)
Annotations
The explicit-parent accessors (
GetTextHeight(style),SetMaskColor(style, color), …) are gone. Set the parent, then use the property, as in RhinoCommon:# 8.x style = model.DimStyles.FindId(ann.DimensionStyleId) height = ann.GetTextHeight(style) # 9.2 ann.ParentDimensionStyle = model.DimStyles.FindId(ann.DimensionStyleId) height = ann.TextHeight
Pass the annotation’s own style. Assigning a different style makes it the annotation’s style and drops its overrides. Without a parent, these properties read the defaults, as in RhinoCommon.
DimLinear.Points(and the other dimensions’Pointsdicts) isGet3dPoints(), a tuple(success, p1, p2, ...).Leader.PointsisPoints3D(andPoints2D), and an angular dimension’s angle isNumericValue.Arrowheadhas its staticGetPoints(type)only; its constructors and properties are not bound yet.TextHasRtfFormattingis true for more than one text run.PlainTextjoins the runs, and for a dimension it returns the authored text (the<>formula), not the measurement.On macOS and Windows, text may not be measured: an annotation’s
GetBoundingBoxis then empty (IsValidis false) andTextModelWidthis -2. 8.x returned a zero-width box there. Linux measures text.
Rendering and settings
RenderContent.GetParameter(name)returns the value by its type (bool,int,float,str,uuid.UUID, a tuple of doubles,Color4f,Transform,bytes), andNonewhen there is no such parameter. 8.x always returned a string.SetParameteraccepts the same values.RenderContent.TopLevelof a grandchild is its parent, as in RhinoCommon.SetChildSlotOn(name, on)andSetChildSlotAmount(name, amount)take the slot name first.ChildSlotAmountof an unset slot is0.0.RenderSettings.PostEffectsis aPostEffectCollectionofPostEffectData: iterate it, or usePostEffectDataFromId(id).PhysicallyBasedMaterial.BaseColor(andEmission,SubsurfaceScatteringColor) is aColor4f(R,G,B,A), not a tuple. Python accepts a 4-sequence where aColor4fis expected.Sun: the date is a
datetime.datetime:sun.GetDateTime(DateTimeKind.Local)andsun.SetDateTime(d, DateTimeKind.Local), in place of the year, month, day and hours properties. Times are whole seconds.SunColorFromAltitudeisColorFromAltitude, which rounds each channel (8.x truncated, so a channel can differ by 1).TextureMapping.RequiresVertexNormalsis gone. UseMappingType,ProjectionandCapped.TextureMapping.TryGetMappingBox,TryGetMappingCylinderandTryGetMappingPlanewith the cappedoutvalues areTryGetMappingBoxCapped,TryGetMappingCylinderCappedandTryGetMappingPlaneCapped.ObjectAttributes.DrawColor(file)for a colour by material uses Rhino’s rules: the material the attributes select, and its PBR base colour when it is physically based.
Renamed classes
These 8.x classes have RhinoCommon’s names. Their members keep their names, unless Renamed and removed members lists them:
8.x
9.2
TextTextEntityDimLinear,DimAngular,DimRadial,DimOrdinateLinearDimension,AngularDimension,RadialDimension,OrdinateDimensionInstanceDefinitionInstanceDefinitionGeometryInstanceReferenceInstanceReferenceGeometryEmbeddedFileFile3dmEmbeddedFileFile3dmEmbeddedFileTableFile3dmEmbeddedFilesMeshNormalListMeshVertexNormalListCurvePiping,Displacement,EdgeSoftening,ShutLining,ThickeningFile3dmCurvePiping,File3dmDisplacement,File3dmEdgeSoftening,File3dmShutLining,File3dmThickeningRenderContentFile3dmRenderContentRenderMaterial,RenderEnvironment,RenderTextureFile3dmRenderMaterial,File3dmRenderEnvironment,File3dmRenderTexturePostEffectPostEffectDataFile3dmDecalTableDecalsFile3dmPostEffectTablePostEffectCollectionPointGridandFile3dmRdkDocumentDataare gone.File3dm.RdkXmlstill returns the document’s RDK XML.
Enums
Every enum is RhinoCommon’s, with RhinoCommon’s names and values. Fifteen 8.x enums had no RhinoCommon namesake and are replaced:
8.x
9.2
AnnotationTypesAnnotationTypeArrowheadTypesDimensionStyle.ArrowTypeCurvePipingCapTypesFile3dmCurvePiping.CapTypesDecalMappings,MappingsDecalMappingDecalProjections,ProjectionsDecalProjectionDisplacementSweepResolutionFormulasFile3dmDisplacement.SweepResolutionFormulasDitheringMethodsDithering.MethodsEnvironmentBackgroundProjectionsEnvironment.BackgroundProjectionsLengthDisplayDimensionStyle.LengthDisplayMaskFrameDimensionStyle.MaskFrameMaskTypeDimensionStyle.MaskTypePostEffectTypesPostEffectTypeRenderChannelsModesRenderChannels.ModesAn enum is nested in its class, as in RhinoCommon.
Some values are numbered differently:
Dithering.MethodsisNone = 0, FloydSteinberg = 1, SimpleNoise = 2(8.x:SimpleNoise = 0), andPostEffectTypeisEarly = 0, ToneMapping = 1, Late = 2.LightStyle.UnknownisLightStyle.None.BlendContinuity,CurveExtensionStyle,CurveKnotStyle,CurveOffsetCornerStyle,LoftType,PointContainmentandRegionContainmentare gone: no 9.2 member takes or returns them.Noneis a keyword, so a value namedNoneis also available asNone_(rhino3dm.LightStyle.None_).E['None']andgetattr(E, 'None')work too, and the value’s name is still'None'.Enums are integer-like (
int(e)ande == 2work), but passing a plain int where an enum is expected raisesTypeError.
Errors, values and identity
Errors
.NET |
Python |
|---|---|
|
|
|
|
|
|
|
|
Where RhinoCommon accepts null, None is accepted and behaves as in .NET:
PolyCurve.Append(None) returns False, and
model.Objects.AddPoint(p, None) uses the default attributes.
Arrays and sequences
Wherever RhinoCommon takes a sequence of points, any sequence works (a list, a tuple, a
Point3dList). GetUserStrings() returns
a list of [key, value] lists.
Strings and values
str(point)is RhinoCommon’sToString(): full precision (0.30000000000000004, where 8.x printed 6 significant digits).strworks on every value type and on classes (str(layer)is its full path).repr(Point3d(1, 2, 3))isPoint3d(1.0, 2.0, 3.0).An empty string reads
''where RhinoCommon returnsnull(ViewInfo().Name, the log ofIsValidWithLog()when there is nothing to report): test withif not name:, which is true for both.ViewportInfo.ScreenPortandGetScreenPort()are RhinoCommon’s(x, y, width, height), with y the smaller of top and bottom. A newViewportInfo()reads(0, 0, 1000, 1000).File3dm.FromByteArraytakes any buffer (bytes,bytearray, numpy).On Linux, a string read back from a file or an object loses its end when it contains a character outside the Basic Multilingual Plane (an emoji such as 😀, or a rare CJK character): one character per such character, so
'😀'reads back''. macOS and Windows read these strings correctly. Fixed in 9.3.
Object identity
Contents and behaviour follow RhinoCommon, but object identity may not. Accessors such as
obj.Geometry, brep.Faces and brep.Faces[0] return a new view each time, so brep.Faces[0] is brep.Faces[0] is False. Compare components by their index or id.
Brep.TryConvertBrep(geometry) on a file’s brep returns
a new view of it, not geometry itself.
Packaging
The module is built with nanobind. On Python 3.12 and newer it is one stable-ABI (
abi3) module, so one wheel covers 3.12 and every later version. It does not support free-threaded CPython: on 3.14t, importing it turns the GIL back on.The package ships typings (
__init__.pyi) with RhinoCommon’s documentation, so editors complete and type-check rhino3dm code.