Help us shape the future of Go! Take the 2026 Go Developer Survey

tmf

package module
v0.0.0-...-6101195 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 5, 2026 License: MIT Imports: 18 Imported by: 0

README

3mf

Parse and construct 3MF (3D Manufacturing Format) files in Go.

This module implements the 3MF Core Specification plus the major 3MF extensions (Materials, Production, Beam Lattice, Slice, Secure Content, Volumetric). XML I/O uses Go's encoding/xml package; the public API uses functional options via github.com/lestrrat-go/option/v3.

Status

Early. The package builds and round-trips the core spec plus every extension listed above through write → ZIP → re-read. Many sharper edges of the spec (secure-content key wrap policies, exotic volumetric node taxonomies, etc.) are surfaced as escape hatches rather than fully typed APIs; see the per-package docs.

Install

go get github.com/lestrrat-go/3mf

Read a package

pkg, err := tmf.Open("model.3mf")
if err != nil {
    log.Fatal(err)
}
model := pkg.Model()
fmt.Println("unit:", model.Unit())
for _, obj := range model.Resources().Objects() {
    fmt.Printf("object %d: %d vertices, %d triangles\n",
        obj.ID(),
        len(obj.Mesh().Vertices()),
        len(obj.Mesh().Triangles()))
}

Construct a package

mesh := tmf.NewMesh(
    tmf.WithVertices([]tmf.Vertex{
        {X: 0, Y: 0, Z: 0},
        {X: 10, Y: 0, Z: 0},
        {X: 0, Y: 10, Z: 0},
        {X: 0, Y: 0, Z: 10},
    }),
    tmf.WithTriangles([]tmf.Triangle{
        {V1: 0, V2: 1, V3: 2},
        {V1: 0, V2: 1, V3: 3},
        {V1: 0, V2: 2, V3: 3},
        {V1: 1, V2: 2, V3: 3},
    }),
)
obj := tmf.NewObject(
    tmf.WithObjectID(1),
    tmf.WithObjectName("tetrahedron"),
    tmf.WithMesh(mesh),
)
model := tmf.NewModel(
    tmf.WithUnit(tmf.UnitMillimeter),
    tmf.WithObject(obj),
    tmf.WithBuildItem(tmf.NewBuildItem(tmf.WithObjectRef(obj))),
)
pkg := tmf.NewPackage(tmf.WithModel(model))
if err := pkg.Save("out.3mf"); err != nil {
    log.Fatal(err)
}

Extensions

Extensions live in sub-packages and register themselves on import. Blank- import the ones you need:

import (
    _ "github.com/lestrrat-go/3mf/production"
    _ "github.com/lestrrat-go/3mf/materials"
    _ "github.com/lestrrat-go/3mf/beamlattice"
    _ "github.com/lestrrat-go/3mf/slice"
    _ "github.com/lestrrat-go/3mf/securecontent"
    _ "github.com/lestrrat-go/3mf/volumetric"
)
Sub-package Namespace prefix Notes
production p Per-element UUIDs, cross-part references
materials m Color groups, textures, composites, multi-properties
beamlattice b Beam lattices and ball sets on meshes
slice s Slice stacks for printer-ready 2D contours
securecontent sc Encryption metadata + AES-GCM helpers; user supplies key resolver
volumetric v Implicit / volumetric functions (preserved as opaque trees)

Custom extension readers receive *tmf.Element values. The XML writer provides StartDocument and EndDocument methods alongside its element, attribute, and text methods.

To mark an extension as required by your model so its namespace appears in requiredextensions and a prefix is declared on the root <model>:

import "github.com/lestrrat-go/3mf/production"

production.Require(model)
model.Resources().Objects()[0].SetUUID("00000000-0000-0000-0000-000000000001")

License

MIT — see LICENSE.

Documentation

Overview

Package tmf implements parsing and construction of 3MF (3D Manufacturing Format) files.

3MF is an XML-based packaging format for additive manufacturing data, distributed as an OPC (Open Packaging Conventions) ZIP container. This package implements the 3MF core specification together with the major 3MF extensions (Materials, Production, Beam Lattice, Slice, Secure Content, and Volumetric Extensions).

Reading

pkg, err := tmf.Open("model.3mf")
if err != nil { ... }
defer pkg.Close()
model := pkg.Model()
for _, obj := range model.Resources().Objects() {
    // ...
}

Writing

mesh := tmf.NewMesh(
    tmf.WithVertices(verts),
    tmf.WithTriangles(tris),
)
obj := tmf.NewObject(
    tmf.WithObjectID(1),
    tmf.WithObjectType(tmf.ObjectTypeModel),
    tmf.WithMesh(mesh),
)
model := tmf.NewModel(
    tmf.WithUnit(tmf.UnitMillimeter),
    tmf.WithObjects(obj),
    tmf.WithBuildItem(tmf.NewBuildItem(tmf.WithObjectRef(obj))),
)
pkg := tmf.NewPackage(tmf.WithModel(model))
if err := pkg.Save("output.3mf"); err != nil { ... }

Extensions

Extension data is exposed both through the typed sub-packages (github.com/lestrrat-go/3mf/materials, .../production, .../beamlattice, .../slice, .../securecontent, .../volumetric) and through a generic attachment mechanism on Object, Mesh, Build, and Model values so that unrecognized extension data is preserved on round-trip.

Index

Constants

View Source
const (
	// NSCore is the 3MF core specification namespace.
	NSCore = "http://schemas.microsoft.com/3dmanufacturing/core/2015/02"

	// NSMaterials is the 3MF Materials and Properties Extension namespace.
	NSMaterials = "http://schemas.microsoft.com/3dmanufacturing/material/2015/02"

	// NSProduction is the 3MF Production Extension namespace.
	NSProduction = "http://schemas.microsoft.com/3dmanufacturing/production/2015/06"

	// NSBeamLattice is the 3MF Beam Lattice Extension namespace.
	NSBeamLattice = "http://schemas.microsoft.com/3dmanufacturing/beamlattice/2017/02"

	// NSSlice is the 3MF Slice Extension namespace.
	NSSlice = "http://schemas.microsoft.com/3dmanufacturing/slice/2015/07"

	// NSSecureContent is the 3MF Secure Content Extension namespace.
	NSSecureContent = "http://schemas.microsoft.com/3dmanufacturing/securecontent/2019/04"

	// NSVolumetric is the 3MF Volumetric Extension namespace.
	NSVolumetric = "http://schemas.microsoft.com/3dmanufacturing/volumetric/2022/01"

	// NSXML is the XML namespace itself (used for xml:lang etc.).
	NSXML = "http://www.w3.org/XML/1998/namespace"

	// NSOPCContentTypes is the OPC Content Types namespace.
	NSOPCContentTypes = "http://schemas.openxmlformats.org/package/2006/content-types"

	// NSOPCRelationships is the OPC Relationships namespace.
	NSOPCRelationships = "http://schemas.openxmlformats.org/package/2006/relationships"

	// NSOPCMetadataCoreProperties is the OPC Core Properties namespace.
	NSOPCMetadataCoreProperties = "http://schemas.openxmlformats.org/package/2006/metadata/core-properties"
)

Namespace URIs used in 3MF documents and OPC packages.

View Source
const (
	PrefixMaterials     = "m"
	PrefixProduction    = "p"
	PrefixBeamLattice   = "b"
	PrefixSlice         = "s"
	PrefixSecureContent = "sc"
	PrefixVolumetric    = "v"
)

Conventional prefixes used when writing 3MF XML. These are the same prefixes used by Microsoft's reference implementation and are widely recognized by 3MF consumers.

View Source
const (
	// RelTypeStartPart is the OPC relationship type for the primary 3MF model part.
	RelTypeStartPart = "http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel"

	// RelTypeThumbnail is the OPC relationship type for a package-level thumbnail.
	RelTypeThumbnail = "http://schemas.openxmlformats.org/package/2006/relationships/metadata/thumbnail"

	// RelTypeTexture is the relationship type for a texture referenced from a model part.
	RelTypeTexture = "http://schemas.microsoft.com/3dmanufacturing/2013/01/3dtexture"

	// RelTypePrintTicket is the relationship type for a print ticket.
	RelTypePrintTicket = "http://schemas.microsoft.com/3dmanufacturing/2013/01/printticket"

	// RelTypeCoreProperties is the relationship type for OPC core metadata.
	RelTypeCoreProperties = "http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties"

	// RelTypeMustPreserve is the relationship type used by the Production
	// extension to flag non-root model parts that must be preserved.
	RelTypeMustPreserve = "http://schemas.openxmlformats.org/package/2006/relationships/mustpreserve"
)

Relationship type URIs.

View Source
const (
	ContentType3DModel        = "application/vnd.ms-package.3dmanufacturing-3dmodel+xml"
	ContentTypePrintTicket    = "application/vnd.ms-printing.printticket+xml"
	ContentTypeCoreProperties = "application/vnd.openxmlformats-package.core-properties+xml"
	ContentTypeRelationships  = "application/vnd.openxmlformats-package.relationships+xml"
	ContentTypePNG            = "image/png"
	ContentTypeJPEG           = "image/jpeg"
	ContentTypeTexture        = "application/vnd.ms-package.3dmanufacturing-3dmodeltexture"
)

Content types for parts contained in a 3MF package.

View Source
const DefaultModelPath = "/3D/3dmodel.model"

DefaultModelPath is the conventional path for the root 3MF model part.

Variables

View Source
var (
	// ErrInvalidPackage is returned when an OPC package cannot be read because
	// it is malformed or missing required parts.
	ErrInvalidPackage = errors.New("tmf: invalid package")

	// ErrNoModelPart is returned when an OPC package has no relationship that
	// points to a 3MF model part.
	ErrNoModelPart = errors.New("tmf: no 3D model part")

	// ErrUnknownExtension is returned when a parser encounters a namespace
	// declared in the requiredextensions list that this library does not
	// implement.
	ErrUnknownExtension = errors.New("tmf: unknown required extension")

	// ErrMalformedModel is returned when the 3dmodel.model XML does not
	// match the expected schema.
	ErrMalformedModel = errors.New("tmf: malformed model XML")
)
View Source
var ReservedMetadataNames = map[string]struct{}{
	"Title":            {},
	"Designer":         {},
	"Description":      {},
	"Copyright":        {},
	"LicenseTerms":     {},
	"Rating":           {},
	"CreationDate":     {},
	"ModificationDate": {},
	"Application":      {},
}

ReservedMetadataNames is the set of metadata names reserved by the 3MF core specification. Producers should not use these names with custom semantics.

Functions

func FormatMatrix

func FormatMatrix(m Matrix) string

FormatMatrix serializes m as a 12-component, space-separated transform string suitable for use as a transform attribute. The shortest decimal representation that round-trips is used.

func MarshalModel

func MarshalModel(m *Model) ([]byte, error)

MarshalModel serializes m as a 3dmodel.model XML document.

func RegisterExtensionReader

func RegisterExtensionReader(r ExtensionReader)

RegisterExtensionReader installs r as the reader for r.Namespace(). It is safe to call from package init functions. Re-registering a namespace replaces the previous handler.

func RegisterExtensionWriter

func RegisterExtensionWriter(w ExtensionWriter)

RegisterExtensionWriter installs w as the writer for w.Namespace().

func WriteModel

func WriteModel(w io.Writer, m *Model) error

WriteModel serializes m as a 3dmodel.model XML document to w.

Types

type Attachment

type Attachment struct {
	Path        string
	ContentType string
	RelType     string // when non-empty, a package relationship is created
	Data        []byte
}

Attachment is an extra OPC part written into the package, optionally with a package-level relationship of the given type.

type BaseExtensionReader

type BaseExtensionReader struct{}

BaseExtensionReader is a convenience embedding that provides no-op implementations of every ExtensionReader hook. Extension implementations embed it and override only the hooks they care about.

func (BaseExtensionReader) ReadBuildElement

func (BaseExtensionReader) ReadBuildElement(*Build, *Element) error

func (BaseExtensionReader) ReadMeshElement

func (BaseExtensionReader) ReadMeshElement(*Mesh, *Element) error

func (BaseExtensionReader) ReadObjectElement

func (BaseExtensionReader) ReadObjectElement(*Object, *Element) error

func (BaseExtensionReader) ReadResourceElement

func (BaseExtensionReader) ReadResourceElement(*Resources, *Element) error

type BaseExtensionWriter

type BaseExtensionWriter struct{}

BaseExtensionWriter is the write-side analog of BaseExtensionReader.

func (BaseExtensionWriter) WriteBuildElements

func (BaseExtensionWriter) WriteBuildElements(*Build, *Writer) error

func (BaseExtensionWriter) WriteMeshElements

func (BaseExtensionWriter) WriteMeshElements(*Mesh, *Writer) error

func (BaseExtensionWriter) WriteObjectElements

func (BaseExtensionWriter) WriteObjectElements(*Object, *Writer) error

func (BaseExtensionWriter) WriteResourceElements

func (BaseExtensionWriter) WriteResourceElements(*Resources, *Writer) error

type BaseMaterial

type BaseMaterial struct {
	Name         string
	DisplayColor Color
}

BaseMaterial is a single named material with an optional display color.

type BaseMaterials

type BaseMaterials struct {
	// contains filtered or unexported fields
}

BaseMaterials is a resource that groups one or more named, colored Base materials. Triangles and Objects reference a BaseMaterials by its id and an index into the slice returned by Materials.

func NewBaseMaterials

func NewBaseMaterials(id uint32, mats ...BaseMaterial) *BaseMaterials

NewBaseMaterials constructs a BaseMaterials resource.

func (*BaseMaterials) Append

func (b *BaseMaterials) Append(m BaseMaterial) uint32

Append appends a single material and returns its zero-based index.

func (*BaseMaterials) ID

func (b *BaseMaterials) ID() uint32

ID returns the resource id.

func (*BaseMaterials) Materials

func (b *BaseMaterials) Materials() []BaseMaterial

Materials returns the contained materials slice.

func (*BaseMaterials) SetID

func (b *BaseMaterials) SetID(id uint32)

SetID sets the resource id.

type Build

type Build struct {
	UUID  string
	Items []*BuildItem
}

Build represents the model's <build> element: the ordered list of items to be manufactured, plus an optional Production-extension UUID.

func (*Build) AppendItem

func (b *Build) AppendItem(item *BuildItem)

AppendItem appends an item to the build list.

type BuildItem

type BuildItem struct {
	// ObjectID is the id of the referenced object in the model part named by
	// Path (or in the current part when Path is empty).
	ObjectID uint32

	// Path, when non-empty, identifies the model part holding the referenced
	// object (Production extension, p:path attribute).
	Path string

	// Transform is the affine transform applied to the referenced object
	// during build. IdentityMatrix means no transform is serialized.
	Transform Matrix

	// PartNumber is an optional human-readable part identifier.
	PartNumber string

	// UUID is the Production-extension UUID for this build item.
	UUID string

	// Metadata is the optional list of metadata entries attached to this
	// build item. The 3MF spec allows metadata on build items via the
	// production extension.
	Metadata []*Metadata
}

BuildItem is one entry in the model's build list. Each item references an Object resource (by id, or by id plus path when the Production extension is in use) and may apply an affine transform when the object is placed on the print bed.

func NewBuildItem

func NewBuildItem(opts ...Option) *BuildItem

NewBuildItem constructs a BuildItem from functional options.

type Color

type Color struct {
	R, G, B, A uint8
	Set        bool
}

Color is an sRGB color with 8-bit channels and an alpha channel. A zero Color (R=G=B=A=0) is treated as "unspecified" so that 3MF's distinction between "no color" and "fully transparent black" can be preserved.

func NewColor

func NewColor(r, g, b uint8) Color

NewColor returns an opaque Color with the given channels marked as set.

func NewColorRGBA

func NewColorRGBA(r, g, b, a uint8) Color

NewColorRGBA returns a Color with the given channels marked as set.

func ParseColor

func ParseColor(s string) (Color, error)

ParseColor parses a 3MF color string of the form "#RRGGBB" or "#RRGGBBAA" (case-insensitive). An empty string returns an unset Color.

func (Color) String

func (c Color) String() string

String formats the color as a 3MF #RRGGBB or #RRGGBBAA string. An unset color formats to the empty string.

type Component

type Component struct {
	// ObjectID is the id attribute of the referenced object in the same
	// model part. When Path is non-empty (Production extension) the reference
	// is resolved against that part instead.
	ObjectID uint32

	// Path, when non-empty, identifies the model part that holds the
	// referenced object (Production extension, p:path attribute).
	Path string

	// UUID is the Production-extension UUID of this component instance.
	UUID string

	// Transform is the affine transform applied to the referenced object.
	// IdentityMatrix is treated as "no transform" and is not serialized.
	Transform Matrix
}

Component is a reference to another Object that participates in the containing Object's geometry, optionally with an affine transform applied.

func NewComponent

func NewComponent(opts ...Option) *Component

NewComponent constructs a Component from functional options.

type Element

type Element struct {
	// contains filtered or unexported fields
}

Element is the parsed XML subtree passed to an ExtensionReader hook.

func (*Element) Attr

func (e *Element) Attr(local string) string

Attr returns the first attribute with the given local name, regardless of namespace.

func (*Element) AttrNS

func (e *Element) AttrNS(local, namespaceURI string) string

AttrNS returns the attribute with the given local name and namespace URI.

func (*Element) Attributes

func (e *Element) Attributes() []ElementAttribute

Attributes returns the element's attributes in source order.

func (*Element) ChildElements

func (e *Element) ChildElements(local string) iter.Seq[*Element]

ChildElements iterates over direct child elements, optionally filtered by local name. An empty local name includes every element child.

func (*Element) LocalName

func (e *Element) LocalName() string

LocalName returns the element name without its namespace prefix.

func (*Element) NamespaceURI

func (e *Element) NamespaceURI() string

NamespaceURI returns the namespace URI, or an empty string for an unqualified element.

func (*Element) TextContent

func (e *Element) TextContent() string

TextContent concatenates direct text children, including CDATA content.

type ElementAttribute

type ElementAttribute struct {
	Name         string
	NamespaceURI string
	Value        string
}

ElementAttribute is an attribute on a parsed extension element.

type ExtensionReader

type ExtensionReader interface {
	// Namespace returns the URI of the namespace this reader handles.
	Namespace() string

	// ReadResourceElement is invoked for each direct child of <resources>
	// whose namespace matches Namespace().
	ReadResourceElement(res *Resources, elem *Element) error

	// ReadObjectElement is invoked for each direct child of <object> whose
	// namespace matches Namespace().
	ReadObjectElement(obj *Object, elem *Element) error

	// ReadMeshElement is invoked for each direct child of <mesh> whose
	// namespace matches Namespace().
	ReadMeshElement(mesh *Mesh, elem *Element) error

	// ReadBuildElement is invoked for each direct child of <build> whose
	// namespace matches Namespace().
	ReadBuildElement(b *Build, elem *Element) error
}

ExtensionReader is implemented by extension sub-packages and registered via RegisterExtensionReader. The core 3MF reader invokes the appropriate hook when it encounters an element belonging to the extension's namespace at a position where the extension is allowed to contribute.

All hooks have a default no-op implementation; extensions need only implement the ones that apply to them. ExtensionReader is intentionally minimal — it covers the four contexts where 3MF extensions inject new elements: top-level <resources>, individual <object>, individual <mesh>, and the model's <build>.

func LookupExtensionReader

func LookupExtensionReader(ns string) ExtensionReader

LookupExtensionReader returns the registered reader for ns, or nil.

type ExtensionWriter

type ExtensionWriter interface {
	// Namespace returns the URI of the namespace this writer handles.
	Namespace() string

	// WriteResourceElements is invoked once per model, after all core
	// resource elements have been written but while the <resources> element
	// is still open.
	WriteResourceElements(res *Resources, w *Writer) error

	// WriteObjectElements is invoked once per object, after the core
	// <mesh>/<components> child has been written but while the <object>
	// element is still open.
	WriteObjectElements(obj *Object, w *Writer) error

	// WriteMeshElements is invoked once per mesh, after the core
	// <vertices>/<triangles> children have been written but while the
	// <mesh> element is still open.
	WriteMeshElements(mesh *Mesh, w *Writer) error

	// WriteBuildElements is invoked once per build, after the core
	// <item> children have been written but while the <build> element
	// is still open.
	WriteBuildElements(b *Build, w *Writer) error
}

ExtensionWriter is the symmetric write-side hook for an extension. Each method is called by the core writer at the corresponding position in the XML stream so that the extension may emit additional elements.

Implementations must use the supplied *Writer's StartElementNS/AttrNS helpers with the extension's pre-declared prefix; they must not close the elements opened by the core writer.

func LookupExtensionWriter

func LookupExtensionWriter(ns string) ExtensionWriter

LookupExtensionWriter returns the registered writer for ns, or nil.

type Matrix

type Matrix [12]float64

Matrix is a 4x3 affine transform stored in row-major order matching the 3MF wire format ("m00 m01 m02 m10 m11 m12 m20 m21 m22 m30 m31 m32"). The implicit fourth column is (0 0 0 1)^T.

func IdentityMatrix

func IdentityMatrix() Matrix

IdentityMatrix returns the identity transform.

func ParseMatrix

func ParseMatrix(s string) (Matrix, error)

ParseMatrix parses a 3MF transform string ("m00 m01 m02 m10 m11 m12 m20 m21 m22 m30 m31 m32", 12 whitespace-separated floats) and returns the corresponding Matrix. An empty string yields IdentityMatrix().

func (Matrix) IsIdentity

func (m Matrix) IsIdentity() bool

IsIdentity reports whether m equals the identity transform within a tight tolerance.

type Mesh

type Mesh struct {
	// contains filtered or unexported fields
}

Mesh is the geometry attached to an Object.

func NewMesh

func NewMesh(opts ...Option) *Mesh

NewMesh constructs a Mesh from functional options.

func (*Mesh) AppendTriangle

func (m *Mesh) AppendTriangle(t Triangle)

AppendTriangle appends a single triangle.

func (*Mesh) AppendVertex

func (m *Mesh) AppendVertex(v Vertex) uint32

AppendVertex appends a single vertex and returns its zero-based index.

func (*Mesh) Extension

func (m *Mesh) Extension(ns string) any

Extension returns the parsed extension payload that was attached to the mesh for namespace ns, or nil if none was attached. The returned value is the extension-specific Go type — for instance, a *beamlattice.BeamLattice when ns is beamlattice.Namespace.

func (*Mesh) Extensions

func (m *Mesh) Extensions() map[string]any

Extensions returns a copy of the extension namespaces present on the mesh.

func (*Mesh) SetExtension

func (m *Mesh) SetExtension(ns string, v any)

SetExtension attaches an extension payload for namespace ns to the mesh. Passing nil removes any existing payload for that namespace.

func (*Mesh) SetTriangles

func (m *Mesh) SetTriangles(t []Triangle)

SetTriangles replaces the triangle list. The provided slice is retained without copying.

func (*Mesh) SetVertices

func (m *Mesh) SetVertices(v []Vertex)

SetVertices replaces the vertex list. The provided slice is retained without copying.

func (*Mesh) Triangles

func (m *Mesh) Triangles() []Triangle

Triangles returns the mesh triangles. The returned slice is owned by the mesh and must not be mutated by the caller.

func (*Mesh) Vertices

func (m *Mesh) Vertices() []Vertex

Vertices returns the mesh vertices. The returned slice is owned by the mesh and must not be mutated by the caller.

type Metadata

type Metadata struct {
	Name     string
	Value    string
	Type     string
	Preserve bool
}

Metadata is a key/value annotation attached to a Model, Object, or BuildItem. Names use the form "namespace:localname"; the 3MF specification reserves a fixed set of namespace-free names (Title, Designer, etc.) and allows arbitrary additional names when the namespace is declared on the owning element.

func NewMetadata

func NewMetadata(opts ...Option) *Metadata

NewMetadata constructs a Metadata from functional options.

type Model

type Model struct {
	// contains filtered or unexported fields
}

Model is the in-memory representation of a single 3MF model part (3dmodel.model). A Package may hold multiple Models when the Production extension is in use; the primary Model is reached via Package.Model().

func NewModel

func NewModel(opts ...Option) *Model

NewModel constructs a Model from functional options. The model's Resources and Build are always non-nil after construction so callers can append to them directly.

func ReadModel

func ReadModel(ctx context.Context, data []byte) (*Model, error)

ReadModel parses a 3dmodel.model XML payload into a *Model.

func (*Model) AppendMetadata

func (m *Model) AppendMetadata(md *Metadata)

AppendMetadata appends a metadata entry.

func (*Model) Build

func (m *Model) Build() *Build

Build returns the build list (never nil).

func (*Model) Extension

func (m *Model) Extension(ns string) any

Extension returns an arbitrary extension payload attached at the model level, or nil.

func (*Model) Extensions

func (m *Model) Extensions() map[string]any

Extensions returns a copy of the attached extension payloads.

func (*Model) Language

func (m *Model) Language() string

Language returns the xml:lang attribute, or "".

func (*Model) Metadata

func (m *Model) Metadata() []*Metadata

Metadata returns the model's metadata entries.

func (*Model) RequireExtension

func (m *Model) RequireExtension(ns, prefix string)

RequireExtension declares that namespace ns is required by this model and should be prefixed with prefix when serialized.

func (*Model) RequiredExtensions

func (m *Model) RequiredExtensions() map[string]string

RequiredExtensions returns a copy of the map URI -> declared prefix.

func (*Model) Resources

func (m *Model) Resources() *Resources

Resources returns the resource list (never nil).

func (*Model) SetExtension

func (m *Model) SetExtension(ns string, v any)

SetExtension attaches an extension payload. Passing nil removes it.

func (*Model) SetLanguage

func (m *Model) SetLanguage(s string)

SetLanguage sets the xml:lang attribute.

func (*Model) SetThumbnail

func (m *Model) SetThumbnail(s string)

SetThumbnail sets the in-package thumbnail path.

func (*Model) SetUnit

func (m *Model) SetUnit(u Unit)

SetUnit sets the unit attribute on <model>.

func (*Model) Thumbnail

func (m *Model) Thumbnail() string

Thumbnail returns the in-package thumbnail path, or "".

func (*Model) Unit

func (m *Model) Unit() Unit

Unit returns the unit attribute on <model>.

type Object

type Object struct {
	// contains filtered or unexported fields
}

Object is a 3MF resource that holds either a mesh or a list of components (or, in the case of certain extensions, alternative geometry such as a beam lattice or implicit function reference).

func NewObject

func NewObject(opts ...Option) *Object

NewObject constructs an Object from functional options.

func (*Object) AppendComponent

func (o *Object) AppendComponent(c *Component)

AppendComponent appends a single component.

func (*Object) Components

func (o *Object) Components() []*Component

Components returns the components participating in this object. The returned slice is owned by the object.

func (*Object) Extension

func (o *Object) Extension(ns string) any

Extension returns an extension payload attached to this object, keyed by namespace URI.

func (*Object) Extensions

func (o *Object) Extensions() map[string]any

Extensions returns a copy of the extension namespaces attached.

func (*Object) ID

func (o *Object) ID() uint32

ID returns the object's id attribute, unique within its model part.

func (*Object) Mesh

func (o *Object) Mesh() *Mesh

Mesh returns the mesh geometry attached to this object, or nil if the object is a components-only or extension-defined object.

func (*Object) Name

func (o *Object) Name() string

Name returns the human-readable name attribute, or "".

func (*Object) PID

func (o *Object) PID() (uint32, bool)

PID returns the object-level property-group id and whether one was set.

func (*Object) PIndex

func (o *Object) PIndex() uint32

PIndex returns the index into the property group named by PID. Only meaningful when PID is set.

func (*Object) PartNumber

func (o *Object) PartNumber() string

PartNumber returns the part-number attribute, or "".

func (*Object) SetComponents

func (o *Object) SetComponents(cs []*Component)

SetComponents replaces the component list.

func (*Object) SetExtension

func (o *Object) SetExtension(ns string, v any)

SetExtension attaches an extension payload. Passing nil removes it.

func (*Object) SetID

func (o *Object) SetID(id uint32)

SetID overrides the object id.

func (*Object) SetMesh

func (o *Object) SetMesh(m *Mesh)

SetMesh attaches a mesh to the object, replacing any existing components.

func (*Object) SetName

func (o *Object) SetName(s string)

SetName sets the human-readable name attribute.

func (*Object) SetPID

func (o *Object) SetPID(pid uint32)

SetPID sets the object-level property-group id.

func (*Object) SetPIndex

func (o *Object) SetPIndex(idx uint32)

SetPIndex sets the per-object property index.

func (*Object) SetPartNumber

func (o *Object) SetPartNumber(s string)

SetPartNumber sets the part-number attribute.

func (*Object) SetThumbnail

func (o *Object) SetThumbnail(s string)

SetThumbnail sets the in-package thumbnail path.

func (*Object) SetType

func (o *Object) SetType(t ObjectType)

SetType sets the ObjectType.

func (*Object) SetUUID

func (o *Object) SetUUID(s string)

SetUUID sets the Production-extension UUID.

func (*Object) Thumbnail

func (o *Object) Thumbnail() string

Thumbnail returns the in-package thumbnail path, or "".

func (*Object) Type

func (o *Object) Type() ObjectType

Type returns the ObjectType (defaults to ObjectTypeModel).

func (*Object) UUID

func (o *Object) UUID() string

UUID returns the Production-extension UUID, or "".

type ObjectType

type ObjectType int

ObjectType identifies the role of an Object inside a 3MF model.

const (
	ObjectTypeModel ObjectType = iota
	ObjectTypeSolidSupport
	ObjectTypeSupport
	ObjectTypeSurface
	ObjectTypeOther
)

func ParseObjectType

func ParseObjectType(s string) (ObjectType, error)

ParseObjectType returns the ObjectType corresponding to s. An empty string returns ObjectTypeModel (the default per the spec). Unknown strings return an error.

func (ObjectType) String

func (t ObjectType) String() string

type Option

type Option = option.Interface

Option is the type passed to the New* constructors in this package and to the extension sub-packages. It is a type alias for github.com/lestrrat-go/option/v3.Interface.

func WithAttachment

func WithAttachment(a Attachment) Option

WithAttachment attaches an extra OPC part.

func WithBaseMaterials

func WithBaseMaterials(b *BaseMaterials) Option

WithBaseMaterials appends a BaseMaterials resource to a new Model.

func WithBuildItem

func WithBuildItem(b *BuildItem) Option

WithBuildItem appends a BuildItem to a new Model.

func WithBuildObjectID

func WithBuildObjectID(id uint32) Option

WithBuildObjectID sets a BuildItem's ObjectID directly (useful when the target object lives in a different model part referenced by WithItemPath).

func WithComponent

func WithComponent(c *Component) Option

WithComponent appends a single Component to a new Object.

func WithComponentObjectRef

func WithComponentObjectRef(o *Object) Option

WithComponentObjectRef sets the referenced Object on a Component. The component's ObjectID is taken from the object's id.

func WithComponentPath

func WithComponentPath(p string) Option

WithComponentPath sets the Production-extension path attribute on a Component.

func WithComponentTransform

func WithComponentTransform(m Matrix) Option

WithComponentTransform sets the affine transform on a Component.

func WithComponentUUID

func WithComponentUUID(u string) Option

WithComponentUUID sets the Production-extension UUID on a Component.

func WithComponents

func WithComponents(cs []*Component) Option

WithComponents attaches a slice of Components to a new Object.

func WithExtension

func WithExtension(namespace string, value any) Option

WithExtension attaches an extension payload identified by its namespace URI to the surrounding Mesh, Object, Build, or Model value. Extension packages (materials, beamlattice, etc.) typically wrap this option with a more strongly typed helper.

func WithItemMetadata

func WithItemMetadata(m *Metadata) Option

WithItemMetadata appends a Metadata entry to a BuildItem.

func WithItemPartNumber

func WithItemPartNumber(s string) Option

WithItemPartNumber sets the optional part-number on a BuildItem.

func WithItemPath

func WithItemPath(p string) Option

WithItemPath sets the Production-extension path attribute on a BuildItem.

func WithItemTransform

func WithItemTransform(m Matrix) Option

WithItemTransform sets the affine transform on a BuildItem.

func WithItemUUID

func WithItemUUID(s string) Option

WithItemUUID sets the Production-extension UUID on a BuildItem.

func WithLanguage

func WithLanguage(s string) Option

WithLanguage sets the xml:lang attribute on a new Model.

func WithMesh

func WithMesh(m *Mesh) Option

WithMesh attaches a Mesh to a new Object.

func WithMetadataName

func WithMetadataName(s string) Option

WithMetadataName sets the name attribute on a new Metadata.

func WithMetadataPreserve

func WithMetadataPreserve(b bool) Option

WithMetadataPreserve sets the preserve attribute on a new Metadata.

func WithMetadataType

func WithMetadataType(s string) Option

WithMetadataType sets the type attribute on a new Metadata.

func WithMetadataValue

func WithMetadataValue(s string) Option

WithMetadataValue sets the text body of a new Metadata.

func WithModel

func WithModel(m *Model) Option

WithModel attaches a primary Model to a new Package.

func WithModelMetadata

func WithModelMetadata(md *Metadata) Option

WithModelMetadata appends a Metadata entry to a new Model.

func WithModelPath

func WithModelPath(p string) Option

WithModelPath overrides the in-package path of the primary 3MF model part. Defaults to DefaultModelPath ("/3D/3dmodel.model").

func WithObject

func WithObject(o *Object) Option

WithObject appends an Object resource to a new Model.

func WithObjectID

func WithObjectID(id uint32) Option

WithObjectID sets the id attribute on a new Object.

func WithObjectName

func WithObjectName(s string) Option

WithObjectName sets the human-readable name attribute on a new Object.

func WithObjectPID

func WithObjectPID(pid uint32) Option

WithObjectPID sets the object-level property-group id.

func WithObjectPIndex

func WithObjectPIndex(idx uint32) Option

WithObjectPIndex sets the object-level property index.

func WithObjectPartNumber

func WithObjectPartNumber(s string) Option

WithObjectPartNumber sets the part-number attribute on a new Object.

func WithObjectRef

func WithObjectRef(o *Object) Option

WithObjectRef wires a BuildItem to an existing Object by reference; the item's ObjectID is taken from the object's id at construction time.

func WithObjectThumbnail

func WithObjectThumbnail(s string) Option

WithObjectThumbnail sets the thumbnail path on a new Object.

func WithObjectType

func WithObjectType(t ObjectType) Option

WithObjectType sets the type attribute on a new Object.

func WithObjectUUID

func WithObjectUUID(s string) Option

WithObjectUUID sets the Production-extension UUID on a new Object.

func WithObjects

func WithObjects(objs ...*Object) []Option

WithObjects appends multiple Object resources to a new Model.

func WithPackageThumbnail

func WithPackageThumbnail(t Thumbnail) Option

WithPackageThumbnail attaches a package-level thumbnail.

func WithRequiredExtension

func WithRequiredExtension(namespace, prefix string) Option

WithRequiredExtension instructs the writer to declare a namespace prefix for the given extension namespace URI on the root model element and to list it in the requiredextensions attribute.

func WithResources

func WithResources(r *Resources) Option

WithResources replaces the Resources of a new Model.

func WithThumbnail

func WithThumbnail(s string) Option

WithThumbnail sets the in-package thumbnail path on a new Model.

func WithTriangles

func WithTriangles(t []Triangle) Option

WithTriangles supplies a slice of triangles to NewMesh.

func WithUnit

func WithUnit(u Unit) Option

WithUnit sets the unit attribute on a new Model.

func WithVertices

func WithVertices(v []Vertex) Option

WithVertices supplies a slice of vertices to NewMesh.

type Package

type Package struct {
	// contains filtered or unexported fields
}

Package is a 3MF package: an OPC container plus a primary in-memory Model. When the Production extension is in use, additional model parts are kept around in OPC.Parts so that AdditionalModel(path) can decode them on demand and writes can faithfully round-trip the package.

func NewPackage

func NewPackage(opts ...Option) *Package

NewPackage constructs an empty Package with the given primary Model and optional package-level metadata (thumbnail, attachments, etc.).

func Open

func Open(filePath string) (*Package, error)

Open reads a 3MF package from the file at path.

func ReadPackage

func ReadPackage(r io.ReaderAt, size int64) (*Package, error)

ReadPackage parses a 3MF package from r (which must implement io.ReaderAt because the ZIP format requires random access). size is the total size of the package in bytes.

func (*Package) AddAttachment

func (p *Package) AddAttachment(a Attachment)

AddAttachment is a convenience that registers an attachment plus an optional package-level relationship.

func (*Package) AddPart

func (p *Package) AddPart(name, contentType string, data []byte)

AddPart writes raw bytes into the package at the given absolute part name, with the given content type.

func (*Package) AdditionalModel

func (p *Package) AdditionalModel(name string) (*Model, error)

AdditionalModel decodes the secondary 3MF model part at the given absolute part name (Production extension). Results are cached.

func (*Package) Model

func (p *Package) Model() *Model

Model returns the primary Model of the package (never nil).

func (*Package) ModelPath

func (p *Package) ModelPath() string

ModelPath returns the in-package path of the primary 3MF model part.

func (*Package) OPC

func (p *Package) OPC() *opc.Package

OPC returns the underlying OPC package. Modifying it directly is fine but callers should ensure consistency with the primary Model.

func (*Package) Part

func (p *Package) Part(name string) []byte

Part returns the raw bytes of the part at the given absolute name, or nil when no such part exists.

func (*Package) Save

func (p *Package) Save(filePath string) error

Save writes p to the file at filePath, creating the file if necessary.

func (*Package) SetModel

func (p *Package) SetModel(m *Model)

SetModel replaces the primary Model.

func (*Package) WriteTo

func (p *Package) WriteTo(w io.Writer) (int64, error)

WriteTo serializes the package as a ZIP archive to w.

type Resources

type Resources struct {
	// contains filtered or unexported fields
}

Resources is the top-level resource list of a 3MF model part. It holds Objects, BaseMaterials, and extension-supplied resources (color groups, texture groups, slice stacks, etc.) accessed via Extension/SetExtension.

func (*Resources) AppendBaseMaterials

func (r *Resources) AppendBaseMaterials(b *BaseMaterials)

AppendBaseMaterials appends a base-materials resource.

func (*Resources) AppendObject

func (r *Resources) AppendObject(o *Object)

AppendObject appends an object resource.

func (*Resources) BaseMaterials

func (r *Resources) BaseMaterials() []*BaseMaterials

BaseMaterials returns the BaseMaterials resources in this list.

func (*Resources) ExtensionResources

func (r *Resources) ExtensionResources(ns string) any

ExtensionResources returns the extension-specific resource value for namespace ns, or nil.

func (*Resources) FindBaseMaterials

func (r *Resources) FindBaseMaterials(id uint32) *BaseMaterials

FindBaseMaterials returns the BaseMaterials with the given id, or nil.

func (*Resources) FindObject

func (r *Resources) FindObject(id uint32) *Object

FindObject returns the Object with the given id, or nil if none matches. O(n) — for tight loops, build a map.

func (*Resources) Objects

func (r *Resources) Objects() []*Object

Objects returns all Object resources in this list.

func (*Resources) SetExtensionResources

func (r *Resources) SetExtensionResources(ns string, v any)

SetExtensionResources attaches an extension-specific resource value. Passing nil removes it.

type Thumbnail

type Thumbnail struct {
	Path        string // typically "/Metadata/thumbnail.png"
	ContentType string // typically ContentTypePNG
	Data        []byte
}

Thumbnail attaches a package-level thumbnail image (referenced from the package's _rels/.rels).

type Triangle

type Triangle struct {
	V1, V2, V3 uint32

	// PID is the resource id of a property group (BaseMaterials, ColorGroup,
	// etc.) that this triangle references. A value of zero means no override.
	PID uint32

	// P1, P2, P3 are per-vertex indices into the property group named by PID.
	// When PID is zero these are ignored.
	P1, P2, P3 uint32

	// HasPID is true when an explicit PID was set on this triangle (so a
	// zero PID can still be distinguished from the default).
	HasPID bool

	// HasPIndices is true when the per-vertex P1/P2/P3 indices were set.
	// Some triangles set only PID, in which case all three vertices share
	// the same P1 value.
	HasPIndices bool
}

Triangle is a face of a mesh referencing three Vertices by index. The per-vertex property indices PIndices and the per-triangle property identifier PID encode 3MF material/property references; both default to zero, meaning "inherit from the object".

type Unit

type Unit int

Unit identifies the unit of measure used by a 3MF model. The 3MF core specification fixes the set of legal values; any other string is rejected when parsing.

const (
	UnitUnknown Unit = iota
	UnitMicron
	UnitMillimeter
	UnitCentimeter
	UnitInch
	UnitFoot
	UnitMeter
)

func ParseUnit

func ParseUnit(s string) (Unit, error)

ParseUnit returns the Unit corresponding to s, which must be one of the canonical spellings defined by the 3MF core specification.

func (Unit) String

func (u Unit) String() string

String returns the canonical 3MF spelling of the unit.

type Vertex

type Vertex struct {
	X, Y, Z float64
}

Vertex is a 3D coordinate in the model's local unit system.

type Writer

type Writer struct {
	// contains filtered or unexported fields
}

Writer is the streaming XML writer surface that the core serializer and the extension sub-packages share. It tracks namespace prefixes that the core writer has pre-declared on the root <model> element so that extension writers can emit prefix-qualified attributes and elements without triggering a duplicate xmlns declaration.

Extension implementations use the methods on this type to write elements, attributes, and text without accessing the internal XML encoder.

func NewWriter

func NewWriter(w io.Writer) *Writer

NewWriter wraps an io.Writer and returns a *Writer ready for use. Callers typically prefer the higher-level WriteModel function.

func (*Writer) Attr

func (w *Writer) Attr(name, value string) error

Attr writes a plain attribute on the currently open element.

func (*Writer) AttrNS

func (w *Writer) AttrNS(prefix, localName, value string) error

AttrNS writes an attribute whose qualified name is prefix:localName. The prefix is expected to have been declared via DeclarePrefix; this method does not emit any xmlns declaration.

func (*Writer) DeclarePrefix

func (w *Writer) DeclarePrefix(prefix, uri string)

DeclarePrefix records that prefix is bound to uri on the root element. Subsequent calls to Attr / Element with this prefix will emit a prefix-qualified name without re-declaring the namespace. DeclarePrefix does not itself write any output — the caller must emit the xmlns:prefix attribute, typically via the helpers used while writing the root element.

func (*Writer) EndDocument

func (w *Writer) EndDocument() error

EndDocument flushes the document and reports unclosed elements.

func (*Writer) EndElement

func (w *Writer) EndElement() error

EndElement closes the currently open element.

func (*Writer) PrefixFor

func (w *Writer) PrefixFor(uri string) string

PrefixFor returns the prefix declared for uri, or "" when none has been declared.

func (*Writer) StartDocument

func (w *Writer) StartDocument(version, encoding, standalone string) error

StartDocument writes the XML declaration.

func (*Writer) StartElement

func (w *Writer) StartElement(name string) error

StartElement opens an element with the given local name (no namespace).

func (*Writer) StartElementNS

func (w *Writer) StartElementNS(prefix, localName string) error

StartElementNS opens an element with the given prefix and local name. The prefix must have been declared via DeclarePrefix.

func (*Writer) WriteString

func (w *Writer) WriteString(s string) error

WriteString writes escaped text content.

Directories

Path Synopsis
Package beamlattice implements the 3MF Beam Lattice Extension.
Package beamlattice implements the 3MF Beam Lattice Extension.
internal
xmltree
Package xmltree provides the small XML tree used by 3MF extension readers.
Package xmltree provides the small XML tree used by 3MF extension readers.
xmlutil
Package xmlutil contains small helpers shared by the core reader/writer and the extension sub-packages.
Package xmlutil contains small helpers shared by the core reader/writer and the extension sub-packages.
Package materials implements the 3MF Materials and Properties Extension.
Package materials implements the 3MF Materials and Properties Extension.
Package opc implements just enough of the Open Packaging Conventions (ECMA-376 Part 2) to support reading and writing 3MF (.3mf) packages.
Package opc implements just enough of the Open Packaging Conventions (ECMA-376 Part 2) to support reading and writing 3MF (.3mf) packages.
Package production implements the 3MF Production Extension.
Package production implements the 3MF Production Extension.
Package securecontent implements the metadata side of the 3MF Secure Content Extension.
Package securecontent implements the metadata side of the 3MF Secure Content Extension.
Package slice implements the 3MF Slice Extension.
Package slice implements the 3MF Slice Extension.
Package volumetric implements the 3MF Volumetric Extension.
Package volumetric implements the 3MF Volumetric Extension.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL