### Initialize lib3mf Wrapper and Get Version Info Source: https://context7.com/3mfconsortium/lib3mf_python/llms.txt Initializes the lib3mf wrapper to access library functionalities and retrieves version information. It automatically loads the correct native library for the platform and checks for prerelease or build details. ```python import lib3mf from lib3mf import get_wrapper # Initialize the wrapper wrapper = get_wrapper() # Get library version information major, minor, micro = wrapper.GetLibraryVersion() print(f"Lib3MF version: {major}.{minor}.{micro}") # Check for prerelease/build info has_prerelease, prerelease_info = wrapper.GetPrereleaseInformation() if has_prerelease: print(f"Prerelease: {prerelease_info}") has_build, build_info = wrapper.GetBuildInformation() if has_build: print(f"Build: {build_info}") ``` -------------------------------- ### Manage Metadata in lib3mf_python Source: https://context7.com/3mfconsortium/lib3mf_python/llms.txt This example demonstrates how to add and read metadata for both the model and individual mesh objects using lib3mf_python. It covers standard metadata fields and custom namespaces, including specifying whether metadata must be preserved. ```python import lib3mf from lib3mf import get_wrapper wrapper = get_wrapper() model = wrapper.CreateModel() # Get model-level metadata group metadata_group = model.GetMetadataGroup() # Add metadata entries metadata_group.AddMetadata("", "Title", "My 3D Model", "xs:string", True) metadata_group.AddMetadata("", "Designer", "John Doe", "xs:string", True) metadata_group.AddMetadata("", "CreationDate", "2024-01-15", "xs:string", False) # Custom namespace metadata metadata_group.AddMetadata("http://mycompany.com/metadata", "ProjectID", "PRJ-12345", "xs:string", True) # Read metadata count = metadata_group.GetMetadataCount() for i in range(count): meta = metadata_group.GetMetadata(i) namespace = meta.GetNamespace() name = meta.GetName() value = meta.GetValue() must_preserve = meta.GetMustPreserve() print(f"Metadata [{namespace}]{name} = {value} (preserve: {must_preserve})") # Mesh objects also have metadata mesh = model.AddMeshObject() mesh.SetName("MetadataMesh") mesh_metadata = mesh.GetMetadataGroup() mesh_metadata.AddMetadata("", "Weight", "150g", "xs:string", True) ``` -------------------------------- ### Read 3MF File and Iterate Mesh Objects/Build Items using Python Source: https://context7.com/3mfconsortium/lib3mf_python/llms.txt This Python snippet shows how to load a 3MF file using lib3mf, iterate through its mesh objects to get vertex and triangle counts, and access individual vertices. It also demonstrates how to retrieve build items, their associated objects, part numbers, and UUIDs. ```python import lib3mf from lib3mf import get_wrapper wrapper = get_wrapper() model = wrapper.CreateModel() # Create reader and load file reader = model.QueryReader("3mf") reader.ReadFromFile("input_model.3mf") # Check for warnings during read warning_count = reader.GetWarningCount() for i in range(warning_count): warning_code, warning_message = reader.GetWarning(i) print(f"Warning {warning_code}: {warning_message}") # Get all mesh objects mesh_iterator = model.GetMeshObjects() while mesh_iterator.MoveNext(): mesh = mesh_iterator.GetCurrentMeshObject() name = mesh.GetName() vertex_count = mesh.GetVertexCount() triangle_count = mesh.GetTriangleCount() print(f"Mesh '{name}': {vertex_count} vertices, {triangle_count} triangles") # Get individual vertices for i in range(min(5, vertex_count)): # Print first 5 vertices vertex = mesh.GetVertex(i) print(f" Vertex {i}: ({vertex.Coordinates[0]}, {vertex.Coordinates[1]}, {vertex.Coordinates[2]})") # Get build items build_iterator = model.GetBuildItems() while build_iterator.MoveNext(): build_item = build_iterator.GetCurrent() obj = build_item.GetObjectResource() part_number = build_item.GetPartNumber() has_transform, uuid = build_item.GetUUID() print(f"Build item: {obj.GetName()}, Part#: {part_number}, UUID: {uuid}") ``` -------------------------------- ### Create a New 3MF Model and Set Properties Source: https://context7.com/3mfconsortium/lib3mf_python/llms.txt Demonstrates how to create a new, empty 3MF model using the lib3mf wrapper. It also shows how to set the model's units (e.g., millimeters) and language. ```python import lib3mf from lib3mf import get_wrapper wrapper = get_wrapper() # Create a new model model = wrapper.CreateModel() # Set model units (default is millimeters) model.SetUnit(lib3mf.ModelUnit.MilliMeter) # Get current unit unit = model.GetUnit() print(f"Model unit: {unit}") # Set model language model.SetLanguage("en-US") ``` -------------------------------- ### Create a Cube Model in Python using lib3mf Source: https://github.com/3mfconsortium/lib3mf_python/blob/main/README-base.md This Python script demonstrates how to create a simple cube model using the lib3mf library. It involves initializing the library, creating a model and mesh object, defining vertices and triangles, and finally saving the model to a 'cube.3mf' file. Dependencies include the 'lib3mf' Python package. ```python import lib3mf from lib3mf import get_wrapper # Get version def get_version(wrapper): major, minor, micro = wrapper.GetLibraryVersion() print("Lib3MF version: {:d}.{:d}.{:d}".format(major, minor, micro), end="") hasInfo, prereleaseinfo = wrapper.GetPrereleaseInformation() if hasInfo: print("-" + prereleaseinfo, end="") hasInfo, buildinfo = wrapper.GetBuildInformation() if hasInfo: print("+" + buildinfo, end="") print("") # Create vertex in a mesh def create_vertex(_mesh, x, y, z): position = lib3mf.Position() position.Coordinates[0] = float(x) position.Coordinates[1] = float(y) position.Coordinates[2] = float(z) _mesh.AddVertex(position) return position # Add triangle in a mesh def add_triangle(_mesh, p1, p2, p3): triangle = lib3mf.Triangle() triangle.Indices[0] = p1 triangle.Indices[1] = p2 triangle.Indices[2] = p3 _mesh.AddTriangle(triangle) return triangle # Get a wrapper object wrapper = get_wrapper() # Check version always get_version(wrapper) # Create a model model = wrapper.CreateModel() mesh_object = model.AddMeshObject() mesh_object.SetName("Box") # Define the size of the cube fSizeX, fSizeY, fSizeZ = 100.0, 200.0, 300.0 # Create vertices vertices = [ create_vertex(mesh_object, 0, 0, 0), create_vertex(mesh_object, fSizeX, 0, 0), create_vertex(mesh_object, fSizeX, fSizeY, 0), create_vertex(mesh_object, 0, fSizeY, 0), create_vertex(mesh_object, 0, 0, fSizeZ), create_vertex(mesh_object, fSizeX, 0, fSizeZ), create_vertex(mesh_object, fSizeX, fSizeY, fSizeZ), create_vertex(mesh_object, 0, fSizeY, fSizeZ) ] # Define triangles by vertices indices triangle_indices = [ (2, 1, 0), (0, 3, 2), (4, 5, 6), (6, 7, 4), (0, 1, 5), (5, 4, 0), (2, 3, 7), (7, 6, 2), (1, 2, 6), (6, 5, 1), (3, 0, 4), (4, 7, 3) ] # Create triangles triangles = [] for v0, v1, v2 in triangle_indices: triangles.append(add_triangle(mesh_object, v0, v1, v2)) # Set geometry to the mesh object after creating vertices and triangles mesh_object.SetGeometry(vertices, triangles) # Add build item with an identity transform model.AddBuildItem(mesh_object, wrapper.GetIdentityTransform()) # Save the model to a 3MF file writer = model.QueryWriter("3mf") writer.WriteToFile("cube.3mf") ``` -------------------------------- ### Python Creating Assemblies with Components and Transforms Source: https://context7.com/3mfconsortium/lib3mf_python/llms.txt Illustrates how to create assemblies of multiple mesh objects using components in lib3mf. It covers adding base mesh objects, creating a ComponentsObject, adding components with transformations (identity and translation), setting UUIDs, and iterating through components to retrieve their properties. ```python import lib3mf from lib3mf import get_wrapper wrapper = get_wrapper() model = wrapper.CreateModel() # Create base mesh objects mesh1 = model.AddMeshObject() mesh1.SetName("Part1") # ... add geometry to mesh1 ... mesh2 = model.AddMeshObject() mesh2.SetName("Part2") # ... add geometry to mesh2 ... # Create a components object (assembly) components = model.AddComponentsObject() # Add components with transforms transform1 = wrapper.GetIdentityTransform() component1 = components.AddComponent(mesh1, transform1) # Second component translated transform2 = wrapper.GetTranslationTransform(100.0, 0.0, 0.0) component2 = components.AddComponent(mesh2, transform2) # Set UUIDs for tracking component1.SetUUID("550e8400-e29b-41d4-a716-446655440001") component2.SetUUID("550e8400-e29b-41d4-a716-446655440002") # Get component count count = components.GetComponentCount() print(f"Assembly has {count} components") # Iterate through components for i in range(count): comp = components.GetComponent(i) obj = comp.GetObjectResource() has_uuid, uuid = comp.GetUUID() has_transform = comp.HasTransform() print(f"Component {i}: {obj.GetName()}, UUID: {uuid}, HasTransform: {has_transform}") # Add assembly to build model.AddBuildItem(components, wrapper.GetIdentityTransform()) writer = model.QueryWriter("3mf") writer.WriteToFile("assembly.3mf") ``` -------------------------------- ### Create and Write a Cube Mesh to 3MF File using Python Source: https://context7.com/3mfconsortium/lib3mf_python/llms.txt This snippet demonstrates how to create a simple cube mesh object, define its vertices and triangles, add it to a model, and write the model to a 3MF file using the lib3mf Python library. It also shows how to retrieve the model's bounding box and set a part number for the build item. ```python import lib3mf from lib3mf import get_wrapper wrapper = get_wrapper() model = wrapper.CreateModel() mesh_object = model.AddMeshObject() mesh_object.SetName("CubeMesh") # Add vertices and triangles (simplified for brevity) size = 50.0 vertices = [] for z in [0, size]: for y in [0, size]: for x in [0, size]: pos = lib3mf.Position() pos.Coordinates[0], pos.Coordinates[1], pos.Coordinates[2] = x, y, z mesh_object.AddVertex(pos) vertices.append(pos) # Add triangles for all 6 faces faces = [ (0,2,1), (1,2,3), (4,5,6), (5,7,6), # bottom, top (0,1,4), (1,5,4), (2,6,3), (3,6,7), # front, back (1,3,5), (3,7,5), (0,4,2), (2,4,6) # right, left ] triangles = [] for f in faces: tri = lib3mf.Triangle() tri.Indices[0], tri.Indices[1], tri.Indices[2] = f mesh_object.AddTriangle(tri) triangles.append(tri) mesh_object.SetGeometry(vertices, triangles) # Add build item with identity transform (no transformation) identity_transform = wrapper.GetIdentityTransform() build_item = model.AddBuildItem(mesh_object, identity_transform) # Optionally set a part number build_item.SetPartNumber("CUBE-001") # Get bounding box of the model outbox = model.GetOutbox() print(f"Model bounds: ({outbox.MinCoordinate[0]}, {outbox.MinCoordinate[1]}, {outbox.MinCoordinate[2]}) to " f"({outbox.MaxCoordinate[0]}, {outbox.MaxCoordinate[1]}, {outbox.MaxCoordinate[2]})") # Write to 3MF file writer = model.QueryWriter("3mf") writer.WriteToFile("output_cube.3mf") print("Successfully wrote output_cube.3mf") ``` -------------------------------- ### Create Mesh Object with Vertices and Triangles in Python Source: https://context7.com/3mfconsortium/lib3mf_python/llms.txt Illustrates the creation of a mesh object, defining its geometry using vertices (3D positions) and triangles (faces). Helper functions are provided for creating vertex positions and triangles from indices. It also includes validation and statistics retrieval for the mesh. ```python import lib3mf from lib3mf import get_wrapper def create_vertex(mesh, x, y, z): """Helper to create a vertex position""" position = lib3mf.Position() position.Coordinates[0] = float(x) position.Coordinates[1] = float(y) position.Coordinates[2] = float(z) mesh.AddVertex(position) return position def add_triangle(mesh, v0, v1, v2): """Helper to create a triangle from vertex indices""" triangle = lib3mf.Triangle() triangle.Indices[0] = v0 triangle.Indices[1] = v1 triangle.Indices[2] = v2 mesh.AddTriangle(triangle) return triangle wrapper = get_wrapper() model = wrapper.CreateModel() # Create a mesh object mesh_object = model.AddMeshObject() mesh_object.SetName("Cube") # Define cube dimensions size_x, size_y, size_z = 100.0, 100.0, 100.0 # Create 8 vertices for a cube vertices = [ create_vertex(mesh_object, 0, 0, 0), # 0: origin create_vertex(mesh_object, size_x, 0, 0), # 1: +X create_vertex(mesh_object, size_x, size_y, 0), # 2: +X+Y create_vertex(mesh_object, 0, size_y, 0), # 3: +Y create_vertex(mesh_object, 0, 0, size_z), # 4: +Z create_vertex(mesh_object, size_x, 0, size_z), # 5: +X+Z create_vertex(mesh_object, size_x, size_y, size_z), # 6: +X+Y+Z create_vertex(mesh_object, 0, size_y, size_z) # 7: +Y+Z ] # Define 12 triangles (2 per face) triangle_indices = [ (2, 1, 0), (0, 3, 2), # Bottom face (4, 5, 6), (6, 7, 4), # Top face (0, 1, 5), (5, 4, 0), # Front face (2, 3, 7), (7, 6, 2), # Back face (1, 2, 6), (6, 5, 1), # Right face (3, 0, 4), (4, 7, 3) # Left face ] triangles = [add_triangle(mesh_object, *indices) for indices in triangle_indices] # Set geometry (required after adding vertices and triangles) mesh_object.SetGeometry(vertices, triangles) # Check if mesh is manifold and oriented is_valid = mesh_object.IsManifoldAndOriented() print(f"Mesh is valid: {is_valid}") # Get mesh statistics vertex_count = mesh_object.GetVertexCount() triangle_count = mesh_object.GetTriangleCount() print(f"Vertices: {vertex_count}, Triangles: {triangle_count}") ``` -------------------------------- ### Add Materials and Colors to 3MF Model using Python Source: https://context7.com/3mfconsortium/lib3mf_python/llms.txt This Python code illustrates how to define and assign materials and colors to a 3MF model using lib3mf. It covers creating base material groups, adding individual materials with RGBA colors, creating color groups for per-vertex coloring, and assigning material properties to triangles. ```python import lib3mf from lib3mf import get_wrapper wrapper = get_wrapper() model = wrapper.CreateModel() # Create a base material group material_group = model.AddBaseMaterialGroup() # Add materials with colors red_color = lib3mf.Color() red_color.Red, red_color.Green, red_color.Blue, red_color.Alpha = 255, 0, 0, 255 red_id = material_group.AddMaterial("Red PLA", red_color) blue_color = lib3mf.Color() blue_color.Red, blue_color.Green, blue_color.Blue, blue_color.Alpha = 0, 0, 255, 255 blue_id = material_group.AddMaterial("Blue PLA", blue_color) # Create a color group for per-vertex colors color_group = model.AddColorGroup() color_id_1 = color_group.AddColor(wrapper.RGBAToColor(255, 128, 0, 255)) # Orange color_id_2 = color_group.AddColor(wrapper.RGBAToColor(0, 255, 128, 255)) # Cyan # Create mesh and assign materials to triangles mesh = model.AddMeshObject() mesh.SetName("ColoredMesh") # Add vertices (simple triangle) v0 = lib3mf.Position() v0.Coordinates[0], v0.Coordinates[1], v0.Coordinates[2] = 0, 0, 0 v1 = lib3mf.Position() v1.Coordinates[0], v1.Coordinates[1], v1.Coordinates[2] = 100, 0, 0 v2 = lib3mf.Position() v2.Coordinates[0], v2.Coordinates[1], v2.Coordinates[2] = 50, 100, 0 mesh.AddVertex(v0) mesh.AddVertex(v1) mesh.AddVertex(v2) tri = lib3mf.Triangle() tri.Indices[0], tri.Indices[1], tri.Indices[2] = 0, 1, 2 mesh.AddTriangle(tri) mesh.SetGeometry([v0, v1, v2], [tri]) # Assign material to triangle tri_props = lib3mf.TriangleProperties() tri_props.ResourceID = material_group.GetResourceID() tri_props.PropertyIDs[0] = red_id tri_props.PropertyIDs[1] = red_id tri_props.PropertyIDs[2] = red_id mesh.SetTriangleProperties(0, tri_props) # Add to build and save model.AddBuildItem(mesh, wrapper.GetIdentityTransform()) writer = model.QueryWriter("3mf") writer.WriteToFile("colored_model.3mf") ``` -------------------------------- ### Python Error Handling with ELib3MFException Source: https://context7.com/3mfconsortium/lib3mf_python/llms.txt Demonstrates how to handle exceptions raised by the lib3mf library using the custom ELib3MFException class. It shows how to access detailed error information like error code, name, message, and description, and how to check for specific error codes. ```python import lib3mf from lib3mf import get_wrapper, ELib3MFException, ErrorCodes wrapper = get_wrapper() model = wrapper.CreateModel() try: # Attempt to read a non-existent file reader = model.QueryReader("3mf") reader.ReadFromFile("nonexistent_file.3mf") except ELib3MFException as e: # Access error details print(f"Error code: {e.error_code}") print(f"Error name: {e.error_name}") print(f"Error message: {e.error_message}") print(f"Error description: {e.error_description}") # Check specific error codes if e.error_code == ErrorCodes.COULDNOTLOADLIBRARY: print("Library loading failed") elif e.error_code == ErrorCodes.INVALIDMODEL: print("Invalid model file") try: # Attempt to use invalid reader class reader = model.QueryReader("invalid_format") except ELib3MFException as e: print(f"Caught expected error: {e}") # Strict mode for validation writer = model.QueryWriter("3mf") writer.SetStrictModeActive(True) is_strict = writer.GetStrictModeActive() print(f"Strict mode: {is_strict}") ``` -------------------------------- ### Handle Attachments and Textures in lib3mf_python Source: https://context7.com/3mfconsortium/lib3mf_python/llms.txt This code snippet illustrates how to add file attachments (like textures) to a 3MF model, create texture resources from these attachments, and define texture coordinates using lib3mf_python. It also shows how to iterate through existing attachments. ```python import lib3mf from lib3mf import get_wrapper wrapper = get_wrapper() model = wrapper.CreateModel() # Add an attachment from file attachment = model.AddAttachment("/3D/Textures/wood.png", "http://schemas.microsoft.com/3dmanufacturing/2013/01/3dtexture") attachment.ReadFromFile("wood_texture.png") # Create a texture resource from the attachment texture = model.AddTexture2DFromAttachment(attachment) texture.SetContentType(lib3mf.TextureType.PNG) texture.SetTileStyleUV(lib3mf.TextureTileStyle.Wrap, lib3mf.TextureTileStyle.Wrap) texture.SetFilter(lib3mf.TextureFilter.Linear) # Create a texture coordinate group tex_group = model.AddTexture2DGroup(texture) # Add texture coordinates (U, V pairs) uv1 = tex_group.AddTex2Coord(lib3mf.Tex2Coord()) # Will need to set U, V tex_coord = lib3mf.Tex2Coord() tex_coord.U = 0.0 tex_coord.V = 0.0 uv1 = tex_group.AddTex2Coord(tex_coord) tex_coord.U = 1.0 tex_coord.V = 0.0 uv2 = tex_group.AddTex2Coord(tex_coord) tex_coord.U = 0.5 tex_coord.V = 1.0 uv3 = tex_group.AddTex2Coord(tex_coord) # Get attachment count attachment_count = model.GetAttachmentCount() print(f"Model has {attachment_count} attachments") # Iterate through attachments for i in range(attachment_count): att = model.GetAttachment(i) path = att.GetPath() rel_type = att.GetRelationshipType() size = att.GetStreamSize() print(f"Attachment: {path}, Type: {rel_type}, Size: {size} bytes") ``` -------------------------------- ### Add Build Items to 3MF Model in Python Source: https://context7.com/3mfconsortium/lib3mf_python/llms.txt Shows how to add build items to a 3MF model, which represent objects to be manufactured. The `AddBuildItem()` method allows adding mesh objects with optional transformation matrices. ```python import lib3mf from lib3mf import get_wrapper wrapper = get_wrapper() model = wrapper.CreateModel() # Create a simple mesh (cube) mesh_object = model.AddMeshObject() mesh_object.SetName("PrintableCube") # Example of adding a build item (assuming mesh_object is already defined and populated) # build_item = model.AddBuildItem(mesh_object) # You can then apply transformations to the build_item if needed. ``` -------------------------------- ### Apply Transforms to Objects in lib3mf_python Source: https://context7.com/3mfconsortium/lib3mf_python/llms.txt This snippet shows how to apply various transformations (identity, scaling, translation, custom matrices) to mesh objects within a 3MF model using lib3mf_python. It demonstrates creating build items with different transforms and writing the model to a file. ```python import lib3mf from lib3mf import get_wrapper wrapper = get_wrapper() model = wrapper.CreateModel() # Create a mesh object mesh = model.AddMeshObject() mesh.SetName("TransformedCube") # ... add vertices and triangles ... # Get different transform types identity = wrapper.GetIdentityTransform() scale_uniform = wrapper.GetUniformScaleTransform(2.0) # Scale 2x scale_xyz = wrapper.GetScaleTransform(1.0, 2.0, 0.5) # Different per axis translation = wrapper.GetTranslationTransform(50.0, 100.0, 0.0) # Move X+50, Y+100 # Add multiple build items with different transforms # Instance 1: Original position build1 = model.AddBuildItem(mesh, identity) # Instance 2: Translated build2 = model.AddBuildItem(mesh, translation) # Instance 3: Scaled build3 = model.AddBuildItem(mesh, scale_uniform) # Custom transform matrix custom_transform = lib3mf.Transform() # Set 4x3 matrix (row-major: rotation/scale in 3x3, translation in column 4) # Identity rotation with translation [200, 0, 0] custom_transform.Fields[0][0] = 1.0 # m00 custom_transform.Fields[0][1] = 0.0 # m01 custom_transform.Fields[0][2] = 0.0 # m02 custom_transform.Fields[1][0] = 0.0 # m10 custom_transform.Fields[1][1] = 1.0 # m11 custom_transform.Fields[1][2] = 0.0 # m12 custom_transform.Fields[2][0] = 0.0 # m20 custom_transform.Fields[2][1] = 0.0 # m21 custom_transform.Fields[2][2] = 1.0 # m22 custom_transform.Fields[3][0] = 200.0 # tx custom_transform.Fields[3][1] = 0.0 # ty custom_transform.Fields[3][2] = 0.0 # tz build4 = model.AddBuildItem(mesh, custom_transform) writer = model.QueryWriter("3mf") writer.WriteToFile("multi_instance.3mf") ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.