-
Notifications
You must be signed in to change notification settings - Fork 1
/
Obj.ts
538 lines (453 loc) · 16.1 KB
/
Obj.ts
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
/**
*
* Archiyou Obj is the abstract object container for one or more Shapes (Shape or ShapeCollection)
* and builds the whole Scenegraph. Scene is also just a Obj
* All coordinates of underlying shapes are in world coordinates (not local Object coordinates);
* We only use position and rotation (and its transformations: move and rotate ) to transform them
*
*/
import chroma from 'chroma-js' // direct import like in documentation does not work - fix with @types/chroma
import { Point, Vector, Shape, Vertex, Edge, Wire, Face, Shell, Solid, ShapeCollection, Geom, isObjStyle, isBaseStyle} from './internal'
import { AnyShape, isAnyShape } from './internal' // types
import { checkInput } from './decorators'; // decorators - use direct import to avoid error in jest / ts-node
import { v4 as uuidv4 } from 'uuid' // fix TS warning with @types/uuid
import { MeshShape, MeshShapeBuffer } from './internal' // ExportModels.MeshShape
import { SceneGraphNode, SceneGraphNodeDetails, BaseStyle, ObjStyle } from './internal' // InternalModels
import { isNumeric, ColorHexToInt } from './internal'
import { PointLike, isPointLike, AnyShapeOrCollection, MeshingQualitySettings } from './internal';
export class Obj
{
//// SETTINGS ////
DEFAULT_OBJ_STYLE:ObjStyle = { point : {}, line: {}, fill: {} }
DEFAULT_BASE_STYLE:BaseStyle = {
color: null, // null: let viewer decide
opacity: null,
size: null,
dashed: null,
}
_oc:any; // holds a reference to loaded opencascade.js: needs to be public
_geom:Geom; // reference to Geom API instance
_id:string;
_name:string;
_shapeType:string; // for introspection: type of Shape
// NOTE: removed _position and _rotation for now
_isLayer:boolean = false;
_visible:boolean = true;
_style:ObjStyle = null;
_shapes:ShapeCollection = new ShapeCollection(); // one or more Shapes: ShapeCollection offers the same API as Shape
_parent:Obj = null; // parent Obj of this Obj instance
_children:Array<Obj> = []; // Obj children of current Obj: this enables a branching scene graph
constructor(shapes:AnyShapeOrCollection=null)
{
if (shapes)
{
if (isAnyShape(shapes))
{
this.addShape(shapes);
}
else {
// ShapeCollection
this._shapes.concat(shapes)
}
}
this._id = uuidv4();
this._setProps();
}
/** Try to get as many properties for easy introspection */
_setProps()
{
this.shapeType();
this.isLayer();
}
/** Set this Obj as a child of another */
setParent(parent:Obj)
{
// TODO
}
/** Get or set style
* NOTE: We don't use get/setters because we want to be able to return Obj for setter
*/
style(newStyle:any):Obj
{
this._style = this._compileStyle(newStyle);
return this;
}
/** set Color for Obj/Layer. Shortcut of style */
color(newColor:string|number|Array<number>):Obj
{
return this.style( { color: newColor });
}
/** set Lines dashed */
dashed():Obj
{
return this.style({ line: { dashed: true }});
}
/** set strokeWidth */
strokeWidth(n:number):Obj
{
return this.style({ line: { width: n }});
}
/** Get current Obj color or the one that is defined by one of the parents up the hierarchy */
getColor():number
{
let foundColor = (this._style && this._style.fill) ? this._style.fill.color: null;
if (!foundColor)
{
if (this._parent)
{
return this._parent.getColor(); // go up the hierarchy of parents
}
else {
// we cannot look futher
return null;
}
}
else {
if (isNumeric(foundColor))
{
return foundColor as number;
}
else {
// convert string hex to number
return ColorHexToInt(foundColor);
}
}
}
/** Internal: get RGBA values of current color in range [0-1] for RGB and A*/
_getColorRGBA():[number,number,number,number]
{
const c = this.getColor();
return (c !== null) ?
chroma(c).rgba(true).map((v,i) => (i < 3) ? v/255 : v ) as [number,number,number,number]
: null
}
/** Compile different parameters into a ObjStyle instance */
_compileStyle(newStyle:ObjStyle|BaseStyle):ObjStyle // NOTE: needs be to be any, not Object
{
let newObjStyle = { ...this.DEFAULT_OBJ_STYLE, ...(this._style || {}) };
// given newStyle is a full/fragmented config ObjStyle in format { line: { BaseStyle }, point : ..., fill: ... }
if( isObjStyle(newStyle))
{
// newStyle can have fragmented form: { line : dashed }: Make sure we keep original structure
Object.keys(newStyle).forEach(k => {
newObjStyle[k] = { ...newObjStyle[k], ...newStyle[k] }
})
}
// or a simplified BaseStyle
else if( isBaseStyle(newStyle))
{
// base style over all geometries
newObjStyle.point = { ...newObjStyle.point, ...newStyle };
newObjStyle.line = { ...newObjStyle.line, ...newStyle };
newObjStyle.fill = { ...newObjStyle.fill, ...newStyle };
}
const s = this._checkObjStyle(newObjStyle as ObjStyle);
return s;
}
/** Check and normalize ObjStyle values (mostly colors) in place */
_checkObjStyle(style:ObjStyle):ObjStyle
{
// check base styles per geomType in place
Object.entries(style).forEach(([geomType, geomStyle]) =>
{
// Normalize colors with Chroma
if (geomStyle?.color)
{
if( chroma.valid(geomStyle.color) )
{
geomStyle.color = chroma(geomStyle.color).num();
}
else if ( geomStyle.color == 'random' )
{
geomStyle.color = chroma.random().num();
}
else {
console.warn(`Obj::_checkObjStyle: Got a unknown color value ${geomStyle.color}: Defaulted to base color`);
geomStyle.color = null;
}
}
});
return style
}
// ==== basic transformations: most are overloaded by subclasses ====
@checkInput(isPointLike, Vector)
move(v:PointLike)
{
let moveVec = v as Vector;
this._shapes.move(moveVec);
}
rotate(t:any)
{
// TODO
}
/** get/setter method for name property */
name(name?:string):string|Obj
{
if(!name)
{
return this._name;
}
else {
if(typeof name == 'string')
{
this._name = name;
return this;
}
}
}
get id()
{
return this._id;
}
// ==== Visibility and Styling ====
hide():any
{
this._visible = false;
return this;
}
show():any
{
this._visible = true;
return this;
}
// ==== Managing children Objs ====
add(o:Obj):Obj
{
if(!(o instanceof Obj))
{
console.warn(`Obj::add: Can only add Obj type. Got ${typeof o}!`);
}
else
{
this._children.push(o);
o._parent = this;
this._setProps(); // changed structure so recalculate
}
return this;
}
/** Remove an object from children */
remove(o:Obj)
{
this._children.forEach(curObj =>
{
if (curObj === o)
{
let i = this._children.indexOf(o);
this._children.splice(i, 1);
}
})
}
has(o:Obj):boolean
{
if(o instanceof Obj)
{
return this._children.includes(o);
}
else
{
// block all non-Obj
console.warn(`Obj::has: Cannot check of presence of this type ${typeof o}: Only Obj allowed as children in Obj!`);
return true;
}
}
/** Gets the direct children of this Obj */
children():Array<Obj>
{
return this._children;
}
/** Alias for children() */
nodes():Array<Obj>
{
return this.children();
}
/** Recursively get all Objs in this Obj container */
descendants():Array<Obj>
{
let children = this._children;
for(let c = 0; c < children.length; c++)
{
let childChildren = children[c].descendants();
children = children.concat(childChildren);
}
return children;
}
/** Return Obj ShapeCollection: NOTE: use allShapes() to also get the Shapes of children.
For example layers don't have Shapes of their own!
!!!! IMPORTANT: returns reference. So don't change the return value !!!!*/
shapes():ShapeCollection
{
return this._shapes; // all children of ShapeCollection _shapes
}
/** Get all shapes of this Obj including its descendant Obj's returned as grouped ShapeCollection */
allShapesCollection():ShapeCollection
{
let collection = this.shapes().shallowCopy(); // IMPORTANT: don't change reference this._shapes
this.children().forEach((child,i) =>
{
// add as layers
if(child.isLayer())
{
const groupShapes = new ShapeCollection(child.allShapes());
collection.addGroup( child?.name() as string || `obj${i}`, groupShapes);
}
else {
collection.add(child.shapes())
}
});
return collection;
}
/** Get all Shapes within this Obj and its children Objs */
allShapes():Array<AnyShape>
{
// NOTE: shapes is a ShapeCollection, to get its Shapes use getShapes()
let shapes:Array<AnyShape> = this.shapes().getShapes();
this.descendants().forEach(obj =>
{
shapes = shapes.concat( obj.shapes().getShapes())
});
return shapes;
}
getObjByName(name?:string): Obj
{
if(!name || (typeof name !== 'string')) return null;
let obj = this.descendants().find( d => d.name() == name );
return obj;
}
isEmpty():Obj
{
this._shapes = new ShapeCollection();
this._children = [];
return this;
}
// ==== Managing Shapes ====
/** Add a Shape to this object */
@checkInput('AnyShape', 'auto')
addShape(shape:AnyShape):Obj
{
this._shapes.push(shape);
this._setProps();
return this;
}
/** Remove all Shapes */
clearShapes():Obj
{
this._shapes = new ShapeCollection();
return this;
}
/** Get type of Shape(s) in this Object */
shapeType():string
{
let shapeCollapsed = this._shapes.collapse(); // will be null if empty ShapeCollection, single Shape if only one or ShapeCollection
this._shapeType = (shapeCollapsed == null) ? 'container' : shapeCollapsed.type();
return this._shapeType;
}
/** Does this Obj contain multiple Shapes */
isLayer():boolean
{
this._isLayer = this._children.length > 0;
return this._isLayer;
}
/**
* Sometimes a Shape changes - it can then change its own reference inside a Obj container
* @param newShape Can be both a Shape and ShapeCollection - that will be converted by ShapeCollection()
*
* */
_updateShapes(newShape:Shape|Vertex|Edge|Wire|Face|Shell|Solid|ShapeCollection)
{
if ( new Shape().isShape(newShape) )
{
// console.geom(`Obj::_updateShapes: from type "${this._shapes.type()}" to "${newShape.type()}"`);
this._shapes = new ShapeCollection(newShape);
this._shapes.setObj(this); // place reference of current Obj into new Shape
}
}
// ==== Output all mesh data from Shape in this Obj and its children ====
toMeshShapes(quality?:MeshingQualitySettings):Array<MeshShape>
{
let meshes = (this._visible && this._shapes != null) ? this._shapes.toMeshShapes(quality) : [];
// recurse to children Objs
if (this._children.length > 0)
{
this._children.forEach( childObj => {
meshes = meshes.concat( childObj.toMeshShapes()); // recurve into the scene graph Objs to get the Mesh Data out of the Shapes
});
}
return meshes;
}
toMeshShapeBuffer(quality:MeshingQualitySettings ): MeshShapeBuffer
{
let allShapes = new ShapeCollection(this.allShapes());
allShapes = allShapes.filter( s => s?._obj._visible); // filter out hidden Obj
return allShapes.toMeshShapeBuffer(quality);
}
/** Turn Obj containing shape/shapeCollection of other Objs into a graph which we can use to show in a menu */
toGraph():SceneGraphNode
{
const OUTPUT_SHAPE_STATS = false; // NOTE: outputting statistics takes almost 300ms! Can we do these calculations more efficient?
// set current node information
let curNode:SceneGraphNode = { name : null, type: null, nodes: [], details: { color: this.getColor() } };
if (this.isLayer()) // It's a layer not having any geometry but having children that might
{
curNode.name = this._name || `Unnamed Layer`;
curNode.type = 'layer'
curNode.nodes = this.children().map(child => child.toGraph() );
}
else
{
// is an Obj
curNode.name = this._name || `Unnamed Obj`;
curNode.type = 'object';
let shapeDetails:SceneGraphNodeDetails = { visible: this._visible, color : this.getColor() };
curNode.details = shapeDetails; // set details also on Obj
// big overview (but heavy to calculate)
if (OUTPUT_SHAPE_STATS)
{
// If this Object has only one Shape in its ShapeCollection ._shapes then output more details of it!
if(this._shapes.length == 1 && Shape.isShape(this._shapes.first()))
{
let singleShape = this._shapes.first() as Shape;
shapeDetails = { ...shapeDetails,
...{
subType : singleShape.subType(),
numVertices : singleShape.vertices().length,
numEdges : singleShape.edges().length,
numWires : singleShape.wires().length,
numFaces : singleShape.faces().length,
}}
}
}
// end node = single child of current node
curNode.nodes = [ { name: this.shapeType(),
type: this.shapeType(),
nodes: null,
details: shapeDetails,
} ]
}
return curNode;
}
/** Output all properties of this Obj including that of its Shapes into a { key value } row */
toData():Object
{
return {
id : this._id,
name : this._name,
isLayer: this._isLayer,
visible : this._visible,
style : this._style,
color: (this._style) ? (this._style as any).color : null, // TODO
parentId: ( this._parent ) ? this._parent._id : null,
childrenIds: ( this._children ) ? this._children.map(child => child._id) : [],
shapeIds : [] // TODO
}
}
toString():string
{
let shapeStrings = [];
this.shapes().forEach(s =>
{
shapeStrings.push(s.toString())
}
);
return `<Obj id="${this.id}, name="${this._name}", shapes: ${shapeStrings}>`;
}
}