-
Notifications
You must be signed in to change notification settings - Fork 10
/
core.go
633 lines (571 loc) · 16.1 KB
/
core.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
// © Copyright 2021 HP Development Company, L.P.
// SPDX-License Identifier: BSD-2-Clause
package go3mf
import (
"encoding/xml"
"image/color"
"io"
"sort"
"sync"
"github.com/hpinc/go3mf/spec"
)
const (
// Namespace is the canonical name of this extension.
Namespace = "http://schemas.microsoft.com/3dmanufacturing/core/2015/02"
// RelType3DModel is the canonical 3D model relationship type.
RelType3DModel = "http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel"
// RelTypeThumbnail is the canonical thumbnail relationship type.
RelTypeThumbnail = "http://schemas.openxmlformats.org/package/2006/relationships/metadata/thumbnail"
// RelTypePrintTicket is the canonical print ticket relationship type.
RelTypePrintTicket = "http://schemas.microsoft.com/3dmanufacturing/2013/01/printticket"
// RelTypeMustPreserve is the canonical must preserve relationship type.
RelTypeMustPreserve = "http://schemas.openxmlformats.org/package/2006/relationships/mustpreserve"
// DefaultModelPath is the recommended root model part name.
DefaultModelPath = "/3D/3dmodel.model"
// DefaultPrintTicketName is the recommended print ticket part name.
DefaultPrintTicketName = "/3D/Metadata/Model_PT.xml"
// Default3DTexturesDir is the recommended directory for 3D textures.
Default3DTexturesDir = "/3D/Textures/"
// Default3DOtherDir is the recommended directory for non-standard parts.
Default3DOtherDir = "/3D/Other/"
// DefaultMetadataDir is the recommended directory for standard metadata.
DefaultMetadataDir = "/Metadata/"
// ContentType3DModel is the 3D model content type.
ContentType3DModel = "application/vnd.ms-package.3dmanufacturing-3dmodel+xml"
// ContentTypePrintTicket is the print ticket content type.
ContentTypePrintTicket = "application/vnd.ms-printing.printticket+xml"
)
// Units define the allowed model units.
type Units uint8
// Supported units.
const (
UnitMillimeter Units = iota
UnitMicrometer
UnitCentimeter
UnitInch
UnitFoot
UnitMeter
)
func (u Units) String() string {
return map[Units]string{
UnitMillimeter: "millimeter",
UnitMicrometer: "micron",
UnitCentimeter: "centimeter",
UnitInch: "inch",
UnitFoot: "foot",
UnitMeter: "meter",
}[u]
}
// ObjectType defines the allowed object types.
type ObjectType int8
// Supported object types.
const (
ObjectTypeModel ObjectType = iota
ObjectTypeOther
ObjectTypeSupport
ObjectTypeSolidSupport
ObjectTypeSurface
)
func (o ObjectType) String() string {
return map[ObjectType]string{
ObjectTypeModel: "model",
ObjectTypeOther: "other",
ObjectTypeSupport: "support",
ObjectTypeSolidSupport: "solidsupport",
ObjectTypeSurface: "surface",
}[o]
}
// Asset defines build resource.
type Asset interface {
XMLName() xml.Name
Identify() uint32
}
// Metadata item is an in memory representation of the 3MF metadata,
// and can be attached to any 3MF model node.
type Metadata struct {
Name xml.Name
Value string
Type string
Preserve bool
}
// Attachment defines the Model Attachment.
type Attachment struct {
Stream io.Reader
Path string
ContentType string
}
// Relationship defines a dependency between
// the owner of the relationsip and the attachment
// referenced by path. ID is optional, if not set a random
// value will be used when encoding.
type Relationship struct {
Path string
Type string
ID string
}
// Build contains one or more items to manufacture as part of processing the job.
type Build struct {
Items []*Item
AnyAttr spec.AnyAttr
}
// The Resources element acts as the root element of a library of constituent
// pieces of the overall 3D object definition.
type Resources struct {
Assets []Asset
Objects []*Object
AnyAttr spec.AnyAttr
}
// UnusedID returns the lowest unused ID.
func (rs *Resources) UnusedID() uint32 {
if len(rs.Assets) == 0 && len(rs.Objects) == 0 {
return 1
}
ids := make([]int, len(rs.Assets)+len(rs.Objects)+1)
ids[0] = 0
for i, r := range rs.Assets {
id := r.Identify()
ids[i+1] = int(id)
}
for i, o := range rs.Objects {
ids[len(rs.Assets)+i+1] = int(o.ID)
}
sort.Ints(ids)
lowest := 0
for i, id := range ids {
if id != i {
lowest = i
break
}
}
if lowest == 0 {
lowest = ids[len(ids)-1] + 1
}
return uint32(lowest)
}
// FindObject returns the resource with the target ID.
func (rs *Resources) FindObject(id uint32) (*Object, bool) {
for _, value := range rs.Objects {
if value.ID == id {
return value, true
}
}
return nil, false
}
// FindAsset returns the resource with the target ID.
func (rs *Resources) FindAsset(id uint32) (Asset, bool) {
for _, value := range rs.Assets {
if rID := value.Identify(); rID == id {
return value, true
}
}
return nil, false
}
type Extension struct {
Namespace string
LocalName string
IsRequired bool
}
// ChildModel repreents de content of a non-root model file.
//
// It is not supported by the core spec but a common concept
// for multiple official specs.
// The relationships are usually managed by the extensions themself,
// but they are usefull to reference custom attachments.
type ChildModel struct {
Resources Resources
Relationships []Relationship
Any spec.Any
}
// A Model is an in memory representation of the 3MF file.
//
// If path is empty, the default path '/3D/3dmodel.model' will be used.
// The relationships are usually managed by the extensions themself,
// but they are usefull to reference custom attachments.
// Childs keys cannot be an empty string.
// RootRelationships are the OPC root relationships.
type Model struct {
Path string
Language string
Units Units
Thumbnail string
Resources Resources
Build Build
Attachments []Attachment
Extensions []Extension // space -> spec
Metadata []Metadata
Childs map[string]*ChildModel // path -> child
RootRelationships []Relationship
Relationships []Relationship
Any spec.Any
AnyAttr spec.AnyAttr
}
// PathOrDefault returns Path if not empty, else DefaultModelPath.
func (m *Model) PathOrDefault() string {
if m.Path == "" {
return DefaultModelPath
}
return m.Path
}
// BoundingBox returns the bounding box of the model.
func (m *Model) BoundingBox() Box {
if len(m.Build.Items) == 0 {
return Box{}
}
var wg sync.WaitGroup
var mu sync.Mutex
box := newLimitBox()
wg.Add(len(m.Build.Items))
for i := range m.Build.Items {
go func(i int) {
defer wg.Done()
item := m.Build.Items[i]
if o, ok := m.FindObject(item.ObjectPath(), item.ObjectID); ok {
ibox := o.boundingBox(m, item.ObjectPath())
if ibox != emptyBox {
mu.Lock()
box = box.extend(item.Transform.MulBox(ibox))
mu.Unlock()
}
}
}(i)
}
wg.Wait()
return box
}
// FindResources returns the resource associated with path.
func (m *Model) FindResources(path string) (*Resources, bool) {
if path == "" || path == m.Path || (m.Path == "" && path == DefaultModelPath) {
return &m.Resources, true
}
if child, ok := m.Childs[path]; ok {
return &child.Resources, true
}
return nil, false
}
// FindAsset returns the resource with the target path and ID.
func (m *Model) FindAsset(path string, id uint32) (Asset, bool) {
if rs, ok := m.FindResources(path); ok {
return rs.FindAsset(id)
}
return nil, false
}
// FindObject returns the object with the target path and ID.
func (m *Model) FindObject(path string, id uint32) (*Object, bool) {
if rs, ok := m.FindResources(path); ok {
return rs.FindObject(id)
}
return nil, false
}
// WalkAssets walks the assets of the root and child models, calling fn for asset and stopping
// if fn returns an error.
//
// The child models are first walked in lexical order and then the root model is walked.
// The root model path is always empty, regardless of the defined model path.
func (m *Model) WalkAssets(fn func(string, Asset) error) error {
sortedChilds := m.sortedChilds()
for _, path := range sortedChilds {
c := m.Childs[path]
for _, r := range c.Resources.Assets {
if err := fn(path, r); err != nil {
return err
}
}
}
for _, r := range m.Resources.Assets {
if err := fn("", r); err != nil {
return err
}
}
return nil
}
// WalkObjects walks the objects of the root and child models, calling fn for object and stopping
// if fn returns an error.
//
// The child models are first walked in lexical order and then the root model is walked.
// The root model path is always empty, regardless of the defined model path.
func (m *Model) WalkObjects(fn func(string, *Object) error) error {
sortedChilds := m.sortedChilds()
for _, path := range sortedChilds {
c := m.Childs[path]
for _, r := range c.Resources.Objects {
if err := fn(path, r); err != nil {
return err
}
}
}
for _, r := range m.Resources.Objects {
if err := fn("", r); err != nil {
return err
}
}
return nil
}
// Base defines the Model Base Material Resource.
// A model material resource is an in memory representation of the 3MF
// material resource object.
type Base struct {
Name string
Color color.RGBA
AnyAttr spec.AnyAttr
}
// BaseMaterials defines a slice of Base.
type BaseMaterials struct {
ID uint32
Materials []Base
AnyAttr spec.AnyAttr
}
// Len returns the materials count.
func (r *BaseMaterials) Len() int {
return len(r.Materials)
}
// Identify returns the unique ID of the resource.
func (r *BaseMaterials) Identify() uint32 {
return r.ID
}
// XMLName returns the xml identifier of the resource.
func (BaseMaterials) XMLName() xml.Name {
return xml.Name{Space: Namespace, Local: attrBaseMaterials}
}
type MetadataGroup struct {
Metadata []Metadata
AnyAttr spec.AnyAttr
}
// A Item is an in memory representation of the 3MF build item.
type Item struct {
ObjectID uint32
Transform Matrix
PartNumber string
Metadata MetadataGroup
AnyAttr spec.AnyAttr
}
// ObjectPath search an extension attribute with an ObjectPath
// function that return a non empty path.
// Else returns an empty path.
func (b *Item) ObjectPath() string {
for _, att := range b.AnyAttr {
if ext, ok := att.(objectPather); ok {
path := ext.ObjectPath()
if path != "" {
return path
}
}
}
return ""
}
// HasTransform returns true if the transform is different than the identity.
func (b *Item) HasTransform() bool {
return b.Transform != Matrix{} && b.Transform != Identity()
}
// An Object is an in memory representation of the 3MF model object.
type Object struct {
ID uint32
Name string
PartNumber string
Thumbnail string
PID uint32
PIndex uint32
Type ObjectType
Metadata MetadataGroup
Mesh *Mesh
Components *Components
AnyAttr spec.AnyAttr
}
func (o *Object) boundingBox(m *Model, path string) Box {
if o.Mesh != nil {
return o.Mesh.BoundingBox()
}
if o.Components == nil || len(o.Components.Component) == 0 {
return Box{}
}
box := newLimitBox()
for _, c := range o.Components.Component {
if obj, ok := m.FindObject(c.ObjectPath(path), c.ObjectID); ok {
cbox := obj.boundingBox(m, path)
if cbox != emptyBox {
box = box.extend(c.Transform.MulBox(cbox))
}
}
}
return box
}
// A Components is an in memory representation of the 3MF components.
type Components struct {
Component []*Component
AnyAttr spec.AnyAttr
}
// A Component is an in memory representation of the 3MF component.
type Component struct {
ObjectID uint32
Transform Matrix
AnyAttr spec.AnyAttr
}
// ObjectPath search an extension attribute with an ObjectPath
// function that return a non empty path.
// Else returns the default path.
func (c *Component) ObjectPath(defaultPath string) string {
for _, att := range c.AnyAttr {
if ext, ok := att.(objectPather); ok {
path := ext.ObjectPath()
if path != "" {
return path
}
}
}
return defaultPath
}
// HasTransform returns true if the transform is different than the identity.
func (c *Component) HasTransform() bool {
return c.Transform != Matrix{} && c.Transform != Identity()
}
// Triangle defines a triangle of a mesh.
//
// The 7 elements are: v1,v2,v3,pid,p1,p2,p3.
type Triangle struct {
V1, V2, V3 uint32
PID uint32
P1, P2, P3 uint32
AnyAttr spec.AnyAttr
}
// A Mesh is an in memory representation of the 3MF mesh object.
// Each node and face have an ID, which allows to identify them. Each face have an
// orientation (i.e. the face can look up or look down) and have three nodes.
// The orientation is defined by the order of its nodes.
type Mesh struct {
Vertices Vertices
Triangles Triangles
AnyAttr spec.AnyAttr
Any spec.Any
}
type Vertices struct {
Vertex []Point3D
AnyAttr spec.AnyAttr
}
type Triangles struct {
Triangle []Triangle
AnyAttr spec.AnyAttr
}
// BoundingBox returns the bounding box of the mesh.
func (m *Mesh) BoundingBox() Box {
if len(m.Vertices.Vertex) == 0 {
return Box{}
}
box := newLimitBox()
for _, v := range m.Vertices.Vertex {
box = box.extendPoint(v)
}
return box
}
// MeshBuilder is a helper that creates mesh following a configurable criteria.
// It must be instantiated using NewMeshBuilder.
type MeshBuilder struct {
// True to automatically check if a node with the same coordinates already exists in the mesh
// when calling AddVertex. If it exists, the return value will be the existing node and no node will be added.
// Using this option produces an speed penalty.
CalculateConnectivity bool
// Do not modify the pointer to Mesh once the build process has started.
Mesh *Mesh
vectorTree vectorTree
}
// NewMeshBuilder returns a new MeshBuilder.
func NewMeshBuilder(m *Mesh) *MeshBuilder {
return &MeshBuilder{
Mesh: m,
CalculateConnectivity: true,
vectorTree: vectorTree{},
}
}
// AddVertex adds a node the the mesh at the target position.
func (mb *MeshBuilder) AddVertex(node Point3D) uint32 {
if mb.CalculateConnectivity {
if index, ok := mb.vectorTree.FindVector(node); ok {
return index
}
}
mb.Mesh.Vertices.Vertex = append(mb.Mesh.Vertices.Vertex, node)
index := uint32(len(mb.Mesh.Vertices.Vertex)) - 1
if mb.CalculateConnectivity {
mb.vectorTree.AddVector(node, index)
}
return index
}
// UnknownAsset wraps a spec.UnknownTokens to fulfill
// the Asset interface.
type UnknownAsset struct {
spec.UnknownTokens
id uint32
}
func (u UnknownAsset) Identify() uint32 {
return u.id
}
func newObjectType(s string) (o ObjectType, ok bool) {
o, ok = map[string]ObjectType{
"model": ObjectTypeModel,
"other": ObjectTypeOther,
"support": ObjectTypeSupport,
"solidsupport": ObjectTypeSolidSupport,
"surface": ObjectTypeSurface,
}[s]
return
}
func newUnits(s string) (u Units, ok bool) {
u, ok = map[string]Units{
"millimeter": UnitMillimeter,
"micron": UnitMicrometer,
"centimeter": UnitCentimeter,
"inch": UnitInch,
"foot": UnitFoot,
"meter": UnitMeter,
}[s]
return
}
type objectPather interface {
ObjectPath() string
}
const (
nsXML = "http://www.w3.org/XML/1998/namespace"
nsXMLNs = "http://www.w3.org/2000/xmlns/"
)
const (
attrXML = "xml"
attrXmlns = "xmlns"
attrID = "id"
attrName = "name"
attrObjectID = "objectid"
attrTransform = "transform"
attrUnit = "unit"
attrReqExt = "requiredextensions"
attrLang = "lang"
attrResources = "resources"
attrBuild = "build"
attrObject = "object"
attrBaseMaterials = "basematerials"
attrBase = "base"
attrDisplayColor = "displaycolor"
attrPartNumber = "partnumber"
attrItem = "item"
attrModel = "model"
attrVertices = "vertices"
attrVertex = "vertex"
attrX = "x"
attrY = "y"
attrZ = "z"
attrV1 = "v1"
attrV2 = "v2"
attrV3 = "v3"
attrType = "type"
attrThumbnail = "thumbnail"
attrPID = "pid"
attrPIndex = "pindex"
attrMesh = "mesh"
attrComponents = "components"
attrComponent = "component"
attrTriangles = "triangles"
attrTriangle = "triangle"
attrP1 = "p1"
attrP2 = "p2"
attrP3 = "p3"
attrPreserve = "preserve"
attrMetadata = "metadata"
attrMetadataGroup = "metadatagroup"
attrPath = "path"
)