-
Notifications
You must be signed in to change notification settings - Fork 1
/
Shape.ts
4424 lines (3727 loc) · 165 KB
/
Shape.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
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
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
*
* Shape.ts - Defines a Shape in Archiyou (and Opencascade )
* Inherites very basic properties from Obj ( like name, id, position, rotation)
* Wraps all other shapes like: Vertex, Edge, Wire, Face, Shell, Solid, Compound Solid and Compound
* We follow the inheritance from OC; Shape is main class, subclasses are Vertex, Edge etc that inherit the properties
* Subclasses overload the Shape interface methods (move,bbox,overlaps etc) and add some specific methods for accessing the geometry directly if needed
*
* OC lib TopoDS_Shape: https://dev.opencascade.org/doc/occt-7.4.0/refman/html/class_topo_d_s___shape.html
* Creation of different Shapes: https://dev.opencascade.org/doc/occt-7.4.0/refman/html/class_b_rep_builder_a_p_i___make_shape.html
* see https://github.com/CadQuery/cadquery/blob/master/cadquery/occ_impl/shapes.py:361 for inspiration
*/
import { MESHING_MAX_DEVIATION, MESHING_ANGULAR_DEFLECTION, MESHING_MINIMUM_POINTS, MESHING_TOLERANCE, MESHING_EDGE_MIN_LENGTH,
DEFAULT_WORKPLANE, SHAPE_ARRAY_DEFAULT_OFFSET, SHAPE_EXTRUDE_DEFAULT_AMOUNT, SHAPE_SWEEP_DEFAULT_SOLID,
SHAPE_SWEEP_DEFAULT_AUTOROTATE, SHAPE_SCALE_DEFAULT_FACTOR, SHAPE_ALIGNMENT_DEFAULT, SHAPE_SHELL_AMOUNT} from './internal'
import { isPointLike, SelectionString, isSelectionString, CoordArray, isAnyShape,isAnyShapeOrCollection,isColorInput,isPivot,isAxis,isMainAxis,isAnyShapeCollection, isPointLikeOrAnyShapeOrCollection,isLinearShape, isSide} from './internal' // types
import { PointLike,PointLikeOrAnyShape,Coord,AnyShape,AnyShapeOrCollection,ColorInput,Pivot,Axis,MainAxis,AnyShapeCollection,PointLikeOrAnyShapeOrCollection,LinearShape, ShapeType, Side } from './internal' // types
import { Obj, Vector, Point, Bbox, Vertex, Edge, Wire, Face, Shell, Solid, ShapeCollection } from './internal'
import { Link, Selection, SelectionShapeTargetSetting, SelectorSetting, SelectorPointRange, SelectorAxisCoord, SelectorBbox,SelectorIndex } from './internal' // InternalModels
import { ShapeAttributes, isShapeAttributes } from './internal' // attributes
import { ObjStyle } from './internal'
import { MeshShape, FaceMesh, EdgeMesh, VertexMesh } from './internal' // see: ExportModels
import { Selector } from './internal' // see: Selectors
import { toRad, isNumeric, roundToTolerance } from './internal' // utils
import { checkInput, addResultShapesToScene, protectOC } from './decorators'; // Import directly to avoid error in ts-node
import { Alignment, isAlignment, isShapeType, AnyShapeOrCollectionOrSelectionString, MeshingQualitySettings } from './internal'
import { Annotation, DimensionOptions, DimensionLine } from './internal'
import { Obbox } from './internal'
// this can disable TS errors when subclasses are not initialized yet
type IVertex = Vertex
type IEdge = Edge
type ISolid = Solid
type IWire = Wire
type IDimensionLine = DimensionLine
export class Shape
{
_oc:any; // avoids TS errors in filling CLASSNAME_TO_SHAPE_ENUM
_geom:any;
_obj:Obj; // Obj container this Shape belongs to
_parent:Shape; // With selecting subshapes we keep the reference to parent
_ocShape:any = null; // instance of OC Shape subclass: Vertex, Edge, Wire etc. - NOTE: we have to set a value here: otherwise it will not be set
_ocId:string = null;
_isTmp:boolean = false; // Flag to signify if a Shape is temporary (for example for construction)
attributes:ShapeAttributes = {}; // data attributes that can be added to Shapes (NOT STYLING)
annotations:Array<Annotation> = []; // array of annotations associated with this Shape
//// SETTINGS ////
CLASSNAME_TO_SHAPE_ENUM_STATIC: {[key:string]:string} = {
// NOTE: these will be really initialized if _oc is present!
'Vertex' : 'TopAbs_VERTEX',
'Edge' : 'TopAbs_EDGE',
'Wire' : 'TopAbs_WIRE',
'Face' : 'TopAbs_FACE',
'Shell' : 'TopAbs_SHELL',
'Solid' : 'TopAbs_SOLID',
'CompSolid' : 'TopAbs_COMPSOLID',
'Compound' : 'TopAbs_COMPOUND',
};
CLASSNAME_TO_SHAPE_ENUM: {[key:string]:any} = {}; // to be filled.
OC_SHAPE_ENUM_TO_CLASSNAME: {[key:string]:string} = {}; // set with CLASSNAME_TO_SHAPE_ENUM
//// CREATION METHODS ////
constructor()
{
this._setShapeEnumToClassName(); // Some groundwork
}
/** Update _OcShape from Shape properties */
_updateOcShape()
{
// override by different classes where needed, for example in Vertex
}
/** Update properties from current OC Shape */
_updateFromOcShape(ocShape?:any) // TODO: TopoDS_Shape
{
// Can be overriden by subclass
}
/** Do an effort to create a Shape */
fromAll(value:any):AnyShape
{
// Overrides by subclasses
if (value === null || value === undefined)
{
return null;
}
// already a Shape
if (Shape.isShape(value))
{
return value; // original Shape
}
else if (isPointLike(value))
{
return new Point(value as PointLike)._toVertex(); // Vertex
}
else if (value instanceof Bbox)
{
return (value as Bbox).box(); // Solid
}
else {
console.warn(`_convertToShape: Could not convert "${value}" to a Shape! Returned null`);
}
}
/** Class method for ease of use */
static fromAll(value:any):AnyShape
{
return new Shape().fromAll(value);
}
//// MANAGING ATTRIBUTES ////
attribute(key?:string, value?:any):any|AnyShape
{
// NOTE: this is an awkward repetition of these attributes (see typeguards): TODO: better
const SHAPE_ATTRIBUTE_KEYS = ['hidden','outline', 'visible'];
// getter
if (typeof key === 'string' && value === undefined)
{
return this.attributes[key]
}
const attr = {};
attr[key] = value;
if(!key || value === undefined){ throw new Error(`Shape::attribute: Please use attribute(key:string,value) to set attribute!`) }
if(!isShapeAttributes(attr)){ console.warn(`Shape::attribute: Unofficial attribute. Use any of these "${SHAPE_ATTRIBUTE_KEYS.join('", "')}", or know what you are doing!`) }
this.attributes[key] = value;
return this;
}
/** Get attributes of Shape */
attrs():ShapeAttributes
{
return this.attributes;
}
/** Copy attributes from other Shape */
@checkInput('AnyShape', 'auto')
_copyAttributes(from:Shape)
{
this.attributes = { ...from.attrs() }
}
//// CURSOR ////
getCursor()
{
// This method is overloaded on subshape
console.warn(`Shape::getCursor: **** NOT IMPLEMENTED **** Shape: "${this.type()}"`);
}
/** Check and fix Shape after operation: can get overloaded in subclasses */
checkAndFix():AnyShape
{
// This is a very generic fixer algoritm
// OC docs: https://dev.opencascade.org/doc/occt-7.5.0/refman/html/class_shape_fix___shape.html
// NOTE: this might be very slow: use only when really needed!
try
{
let ocFixer = new this._oc.ShapeFix_Shape_2(this._ocShape);
ocFixer.Perform( new this._oc.Message_ProgressRange_1() );
let ocShape = ocFixer.Shape();
if (ocShape && !ocShape.IsNull())
{
// success
this._ocShape = this._makeSpecificOcShape(ocFixer.Shape(), this.type());
}
}
catch(e)
{
console.warn(`Shape::checkAndFix: Failed to check and fix Shape of type ${this.type()}: ${e}!`);
}
finally
{
return this;
}
}
/** Unify Shapes that are lying on the same plane and can be combined */
_unifyDomain():AnyShape
{
// OC docs: https://dev.opencascade.org/doc/occt-7.4.0/refman/html/class_shape_upgrade___unify_same_domain.html
let fusor = new this._oc.ShapeUpgrade_UnifySameDomain_2(this._ocShape, true, true, true); // unify edges, unify faces, concat bsplines
fusor.Build();
let fusedOcShape = new Shape()._fromOcShape(fusor.Shape()) as AnyShape;
this._ocShape = fusedOcShape._ocShape;
return this;
}
/** Make Shape from OC Shape if given, otherwise update properties based on current _ocShape */
/* !!!! Important: This method is not consistent with _fromOcWire, _fromOcSolid etc because it does not affect original
So: this does NOT update current Shape with an Oc Shape. For now we do that manually in every operator
*/
_fromOcShape(ocShape:any):AnyShapeOrCollection
{
ocShape = ocShape || this._ocShape;
if (ocShape == null || ocShape.IsNull())
{
console.error('Shape::_fromOcShape: No valid OC Shape given!')
return null;
}
let shapeType = this._getShapeTypeFromOcShape(ocShape);
let newShape:any;
switch(shapeType)
{
// NOTE: We round every new Shape to the global tolerance - that's done in _fromOC<<TYPE>> methods
case 'Vertex':
newShape = new Vertex()._fromOcVertex(this._makeSpecificOcShape(ocShape, shapeType));
break;
case 'Edge':
newShape = new Edge()._fromOcEdge(this._makeSpecificOcShape(ocShape, shapeType));
break;
case 'Wire':
newShape = new Wire()._fromOcWire(this._makeSpecificOcShape(ocShape, shapeType));
break;
case 'Face':
newShape = new Face()._fromOcFace(this._makeSpecificOcShape(ocShape, shapeType));
break;
case 'Shell':
newShape = new Shell()._fromOcShell(this._makeSpecificOcShape(ocShape, shapeType));
break;
case 'Solid':
newShape = new Solid()._fromOcSolid(this._makeSpecificOcShape(ocShape, shapeType));
break;
case 'Compound':
case 'CompSolid':
let shapeOrCollection = this._extractShapesFromOcCompound(ocShape);
newShape = (ShapeCollection.isShapeCollection(shapeOrCollection)) ? (shapeOrCollection as ShapeCollection).collapse() : shapeOrCollection;
break;
default:
console.warn(`Shape::_fromOcShape: Unknown OC Shape. Found type "${shapeType}"`);
newShape = null;
}
// Removed: Check downgrade to avoid Shells with only one Face, or Wires with only one Edge
// Too slow: apply checkDowngrade() after operations where it these kind of Shapes can be created
return newShape;
}
//// OPERATIONS ON SHAPE AND RELATED OBJECT ////
/** For now we don't have a sense of a pivot and thus clear position of an object, we calculate its center
We can override this in the individual subclasses.
TODO: For example an position of a Wire is probably more intuitive as its start Vertex
*/
position():Point
{
return this.center();
}
/** Return this Shape wrapped with a Obj instance for adding it to the scene */
object(forceNew:boolean=false):Obj
{
// don't make Obj if already exists
if (!forceNew && this._obj)
{
return this._obj;
}
// wrap in Obj and return
let obj = new Obj(this);
this._obj = obj;
return this._obj;
}
/** Set color on the Object of this Shape */
@checkInput('ColorInput', 'auto')
color(value:string|number):this
{
this.object().color(value);
return this;
}
/** Set dashed lines on the Object of this Shape */
dashed():this
{
this.object().dashed();
return this;
}
/** Set stroke width of lines of Shape */
@checkInput(Number, 'auto')
strokeWidth(n:number):this
{
this.object().strokeWidth(n);
return this;
}
/** Get the color of this Shape as defined in its Obj container */
getColor():number
{
return this?._obj?.getColor();
}
_getColorRGBA():[number,number,number,number]
{
return this?._obj?._getColorRGBA()
}
/** check if Shape is co-planar and return the normal of the workingplane if so! */
workPlaneNormal():Vector
{
if (this.edges().length < 2 )
{
console.warn(`Shape::workPlanNormal:: This Shape has only 1 Edge or less, so it's not possible to determine a workplane!`);
return null;
}
let allEdgesClosed = new Wire().fromEdges(this.edges()).close().edges();
let prevEdgeVec = allEdgesClosed[0].direction();
let prevNormal;
let normal;
for (let i = 1; i < allEdgesClosed.length - 1; i++)
{
try { // protect against cross products of same Vectors or zero length Vectors
let nextEdgeVec = allEdgesClosed[i+1].direction();
normal = prevEdgeVec.crossed(nextEdgeVec).normalized().round().abs();
if(prevNormal)
{
if (!normal.equals(prevNormal))
{
// immediately when a normal is not the same: quit - there is no clear workplane
return null;
}
}
prevNormal = normal;
}
catch(e){
// TODO
}
}
return normal;
}
/**
* Some operations on Shape actually create new Shape types: For example Shape.intersections(other)
* To Updating those in place we use the Obj container of the Shape
*/
@checkInput('AnyShapeOrCollection', 'auto')
replaceShape(newShapes:AnyShapeOrCollection):AnyShapeOrCollection
{
// if it's not in the Scene add it
if(!this._obj)
{
this.addToScene();
}
this._obj._updateShapes(newShapes);
return newShapes;
}
/** We can delete a Shape from the Scene by removing it's Obj container */
removeFromScene()
{
if(this._obj)
{
this._geom.removeObj(this._obj);
}
}
isEmpty():boolean
{
if (!this._ocShape){ return true };
return this._ocShape.IsNull();
}
_setShapeEnumToClassName()
{
// see: http://jcae.sourceforge.net/occjava-doc/index.html?org/jcae/opencascade/jni/TopAbs_ShapeEnum.html
// really initialize the values
for ( const [ key,value] of Object.entries(this.CLASSNAME_TO_SHAPE_ENUM_STATIC))
{
this.CLASSNAME_TO_SHAPE_ENUM[key] = this._oc.TopAbs_ShapeEnum[value];
}
Object.entries(this.CLASSNAME_TO_SHAPE_ENUM).forEach(([className, ocShapeEnum]) => this.OC_SHAPE_ENUM_TO_CLASSNAME[ocShapeEnum.value as string] = className); // TS fix
}
//// TRANSFORMATION METHODS ////
/** Convert Shape to Wire (private) */
_toWire():IWire // Cannot use Wire because it's not initialized
{
let wire:Wire;
switch(this.type())
{
case 'Edge':
wire = this._toWire();
break;
case 'Wire':
wire = this as any as Wire; // avoid TS errors
break;
case 'Face':
wire = this.wires()[0];
break;
default:
console.warn(`Shape::lofted: Cannot convert to wire this Shape of type ${this.type()}`);
}
return wire;
}
/** Try to convert the current Shape to a Wire */
@addResultShapesToScene
toWire():IWire // Cannot use Wire because it's not initialized
{
return this._toWire() as Wire
}
//// COMPUTED PROPERTIES ////
/** To have consistent API between Shape and ShapeCollection instances */
isShape(obj:any):boolean
{
return true;
}
/** To have consistent API between Shape and ShapeCollection instances */
isShapeCollection():boolean
{
return false;
}
/* Test if a given object is a single Shape */
static isShape(obj:any)
{
return (!obj) ? false : obj.hasOwnProperty('_ocShape');
}
/** Create hash for this Shape: can be used to check if an Shape is the same instance (NOTE: not that is has equal geometry!) */
_hashcode():string
{
let h = (this._ocShape) ? this._ocShape.HashCode(2147483647) : null;
return h;
}
ocGeom():any
{
/** as implemented by subclass */
return null;
}
type(): ShapeType
{
// fall back on name of Class: this might not be accurate: but better than nothing
let type = (this._ocShape) ?
this._shapeTypeEnumLookup(this._ocShape.ShapeType().value) :
this.constructor.name;
return type as ShapeType;
}
_getShapeTypeFromOcShape(ocShape:any):string // TODO: OC typing
{
if(!ocShape.ShapeType)
{
console.error(`Shape::_getShapeTypeFromOcShape: Please supply a ocShape!`);
return null;
}
let shapeType:string = this._shapeTypeEnumLookup(ocShape.ShapeType().value) ;
return shapeType;
}
/** Returns subType of current Shape: For example Edge::Line */
subType(): string
{
const SUBTYPE_METHOD_BY_TYPE = {
'Edge' : 'edgeType', // methods of specific children of Shape, like Edges, Faces etc.
'Wire' : 'wireType',
'Face' : 'faceType',
'Solid' : 'solidType',
}
let shapeType = this.type();
if (!SUBTYPE_METHOD_BY_TYPE[shapeType])
{
console.error(`Shape::subType: Shape of type "${shapeType}" has not subType!`);
return null;
}
else {
let subTypeFunc = this[SUBTYPE_METHOD_BY_TYPE[shapeType]];
if (subTypeFunc)
{
return this[SUBTYPE_METHOD_BY_TYPE[shapeType]](); // needs to be bounded on Shape
}
return null;
}
}
/** is this Shape 2D */
is2D():boolean
{
if (!this.isEmpty() && this.valid())
{
return this.bbox().is2D();
}
else {
return null;
}
}
/** is this Shape 2D on XY plane (used for SVG export for example) */
is2DXY():boolean
{
// will be overriden by specific classes if they can be 2D
console.warn(`Shape::is2DXY(): Shape can not be 2D: "${this.type()}"`)
return false;
}
/** Test if a Shape is valid */
valid(ocShape?:any)
{
try {
ocShape = ocShape || this._ocShape;
let ocChecker = new this._oc.BRepCheck_Analyzer(ocShape, true, false);
const result = ocChecker.IsValid_2();
ocChecker.delete();
return result;
}
catch (e)
{
return false;
}
}
/** For compatibility with ShapeCollection */
count():number
{
return 1;
}
/** Length of a Shape (depending on specific class) */
length():number
{
// overloaded by appropriate subclasses
return null;
}
/** The top surface area of Shape - for example the area of a Box is the top part */
area():number
{
/* OC docs:
- https://dev.opencascade.org/doc/refman/html/class_g_prop___g_props.html
- https://dev.opencascade.org/content/calculate-surface-and-volume-topodsshape
*/
let ocSystem = new this._oc.GProp_GProps_1();
this._oc.BRepGProp.SurfaceProperties_1(this._ocShape, ocSystem, false, false);
return ocSystem.Mass();
}
/** The total surface Area of a Shape - for example the total surface area of Sphere is 4πr2 */
surface():number
{
// overloaded by appropriate subclasses
// NOTE: this distinction is not made in OC - area() gives all surface
// - either select specific Faces or remove
return null;
}
/** Calculate the volume of this Shape */
volume():number
{
let ocSystem = new this._oc.GProp_GProps_1();
this._oc.BRepGProp.VolumeProperties_1(this._ocShape, ocSystem, false, false, false);
return ocSystem.Mass();
}
/** Get all Vertices of this Shape */
vertices(): AnyShapeCollection
{
let vertices = new ShapeCollection();
let shapeEdges = this.edges(); // test if this Shape has any Edges
if (shapeEdges.length == 0)
{
vertices.add(this._getEntities("Vertex")); // This can result in different starting vertices
}
else
{
// !!!! IMPORTANT: have beginning of sequence for vertices() and edges() the same!
let vertexPresent = {}; // hash
shapeEdges.forEach( e =>
{
// always start with first
if(vertices.length == 0)
{
let sv = e.start();
vertices.add(sv);
vertexPresent[sv._hashcode()] = true;
}
let vertex = e.end();
if (!vertexPresent[vertex._hashcode()])
{
vertices.add(vertex);
vertexPresent[vertex._hashcode()] = true;
}
})
}
return vertices;
}
/** Get all Edges of this Shape */
edges(): AnyShapeCollection
{
return this._getEntities("Edge");
}
/** Get all Wires of this Shape */
wires():AnyShapeCollection
{
// TODO
return this._getEntities("Wire");
}
/** Get all Faces of this Shape */
faces():AnyShapeCollection
{
let faces = this._getEntities("Face");
return faces;
}
/** Get all Shells of this Shape */
shells():AnyShapeCollection
{
return this._getEntities("Shell");
}
/** Get all Solids of this Shape */
solids():AnyShapeCollection
{
return this._getEntities("Solid");
}
/** Calculate and set Bounding Box of Shape */
bbox():Bbox
{
// OC docs: https://dev.opencascade.org/doc/refman/html/class_b_rep_bnd_lib.html
if(this._ocShape)
{
let newBbox = new Bbox();
this._oc.BRepBndLib.AddOptimal(this._ocShape, newBbox._ocBbox, true, false); // useTriangulation, useShapeTolerance
newBbox.updateFromOcBbox();
return newBbox;
}
}
_getOBbox():Obbox
{
let ocOBbox = new this._oc.Bnd_OBB_1();
this._oc.BRepBndLib.prototype.constructor.AddOBB(this._ocShape, ocOBbox, true, false, false); // useTriangulation, isOptimal, theIsShapeToleranceUsed
let obbox:Obbox = {
center: new Point()._fromOcPoint(ocOBbox.Position().Location()),
width: roundToTolerance(ocOBbox.XHSize())*2,
depth: roundToTolerance(ocOBbox.YHSize())*2,
height: roundToTolerance(ocOBbox.ZHSize())*2,
xDirection: new Point()._fromOcXYZ(ocOBbox.XDirection()).toVector(),
yDirection: new Point()._fromOcXYZ(ocOBbox.YDirection()).toVector(),
zDirection: new Point()._fromOcXYZ(ocOBbox.ZDirection()).toVector(),
}
return obbox;
}
/** Calculate Orientated Bounding Box of Shape (returning a Solid or Face) */
obbox():AnyShape
{
/**
OC docs:
- Bnd_OBB: https://dev.opencascade.org/doc/refman/html/class_bnd___o_b_b.html
- BRepBndLib: https://dev.opencascade.org/doc/refman/html/class_b_rep_bnd_lib.html
*/
if(this._ocShape)
{
let obbox = this._getOBbox();
// TODO
return null;
}
}
/** Calculate center of this Shape */
center():Point // TODO: Point output?
{
// this gets overloaded in specific Shape type classes
return null;
}
/** Get max coordinate of Bbox of this Shape */
max(axis:string):number
{
axis = axis.replace('-', ''); // ignore sign
if(this._checkAxis(axis))
{
return this.bbox().max()[axis.toLowerCase()]; // NOTE: bbox.max returns a Vector
}
return null;
}
/** Get min coordinate of Bbox of this Shape */
min(axis:string):number
{
axis = axis.replace('-', ''); // ignore sign
if(this._checkAxis(axis))
{
return this.bbox().min()[axis.toLowerCase()];
}
return null;
}
//// BASIC OPERATIONS ////
/** Round geometry to globally set (in OC) tolerance */
round():Shape
{
/* docs:
- https://dev.opencascade.org/doc/refman/html/class_shape_fix___shape_tolerance.html
- https://dev.opencascade.org/doc/refman/html/class_shape_fix___shape.html
- https://opencascade.blogspot.com/2009/02/topology-and-geometry-in-open-cascade_09.html
- https://dev.opencascade.org/content/shape-tolerance
*/
try
{
let ocShapeFix = new this._oc.ShapeFix_Shape_2(this._ocShape);
ocShapeFix.SetPrecision(this._oc.SHAPE_TOLERANCE);
ocShapeFix.Perform(new this._oc.Message_ProgressRange_1());
this._ocShape = this._makeSpecificOcShape(ocShapeFix.Shape());
return this;
}
catch(e)
{
console.warn(`Shape.round(): Failed rounding this Shape. Returned original!`);
return this;
}
}
/** Copy the Shape and add it to the Scene (private) */
_copy()
{
const newShape = this.copy(false);
return newShape;
}
/** Copy the Shape and add it to the Scene */
// @addResultShapesToScene
copy(addToScene:boolean=true):AnyShape
{
// OC docs: https://dev.opencascade.org/doc/refman/html/class_b_rep_builder_a_p_i___copy.html
// Copying does take 10-15ms for even simple geometries like Boxes!
let ocBuilderCopy = new this._oc.BRepBuilderAPI_Copy_1();
ocBuilderCopy.Perform(this._ocShape, true, false); // TopoDS_Shape &S, copyGeom=Standard_True, copyMesh=Standard_False
let newShape = new Shape()._fromOcShape(ocBuilderCopy.Shape()) as AnyShape;
newShape._copyAttributes(this);
newShape._parent = this._parent; // also take over _parent
if(addToScene)
{
newShape.addToScene();
}
return newShape;
}
/** Move Shape to a position by offsetting all Geometry with a Vector */
// This is a good candidate for variable class return
@checkInput('PointLike','Vector') // this automatically transforms Types
move(vector:PointLike, ...args):AnyShape // also allows flattened input move(10,20,30)
{
this._ocShape.Move( (vector as Vector)._toOcLocation(), true );
if (this._updateFromOcShape)
{
// For example in Vertex: Needed to get data from OC into class properties
this._updateFromOcShape();
}
if (this.type() == 'Wire')
{
// checking is important: Wires for example will have Edges unordered
// !!!! checking takes a lot time (10-15ms), don't use it for simple operations like move
this.checkAndFix();
}
// bring annotation along
this._updateAnnotations();
return this;
}
/** Aliass for move along x-direction */
@checkInput(Number, 'auto')
moveX(distance:number):this
{
this.move(distance)
return this;
}
/** Aliass for move along x-direction */
@checkInput(Number, 'auto')
moveY(distance:number):this
{
this.move(0,distance,0)
return this;
}
/** Aliass for move along x-direction */
@checkInput(Number, 'auto')
moveZ(distance:number):this
{
this.move(0,0,distance)
return this;
}
/** Move a copy of the Shape */
@addResultShapesToScene
@checkInput('PointLike','Vector')
moved(v:PointLike, ...args):AnyShape
{
// move a copy
return this._copy().move(v as Vector); // return specific Shape class
}
/** Move Shape to a specific location using the pivot as center */
@checkInput('PointLike','Vector')
moveTo(to:PointLike, ...args):AnyShape
{
let moveVec = (to as Vector).subtracted(this.center());
this.move(moveVec);
return this;
}
/** Move copy of the Shape to a Point in space */
@checkInput('PointLike','Vector')
movedTo(to:PointLike, ...args):AnyShape
{
let moveVec = (to as Vector).subtracted(this.center()); // auto convert to Vector
let newShape = (this.copy() as AnyShape).move(moveVec);
return newShape;
}
/** Center Shape so that the center of the Shape is at the origin */
moveToOrigin():AnyShape
{
return this.moveTo(0,0,0);
}
/** Resize Shape with a given factor
TODO: different scaling factors per axis? scale(0.5,1,2)
*/
@checkInput([[Number,SHAPE_SCALE_DEFAULT_FACTOR], ['PointLike', null]],[Number, 'Point'])
scale(factor?:number, pivot?:PointLike):AnyShape
{
/* OC docs:
- gp_Trsf https://dev.opencascade.org/doc/occt-7.5.0/refman/html/classgp___trsf.html
- BRepBuilderAPI_Transform: https://dev.opencascade.org/doc/occt-7.5.0/refman/html/class_b_rep_builder_a_p_i___transform.html
*/
let ocTransform = new this._oc.gp_Trsf_1();
pivot = pivot as Point || this.center();
ocTransform.SetScale(pivot._toOcPoint(), factor);
let ocBuilder = new this._oc.BRepBuilderAPI_Transform_2(this._ocShape, ocTransform, true);
this._ocShape = ocBuilder.Shape(); //
return this;
}
/** Same as scale but returning a copy of Shape */
@checkInput([[Number,SHAPE_SCALE_DEFAULT_FACTOR], ['PointLike', null]],[Number, 'Point'])
scaled(factor?:number, pivot?:PointLike):AnyShape
{
return (this.copy() as AnyShape).scale(factor,pivot);
}
/**
* Rotation around X,Y,Z axis with a given pivot (default: center)
* NOTE: because the order of these rotations if very important we don't call it just rotate.
* Use rotateX, rotateY and rotateZ to rotate around the main axis
*/
@checkInput([ [Number,0],[Number,0], [Number,0], ['Pivot', 'center']], [Number,Number,Number,'auto']) // IMPORTANT: not able to directly convert Pivot to Vector because pivot needs current Shape (can that be accessed in decorator?)
rotateEuler(degX:number, degY?:number, degZ?:number, pivot?:Pivot):AnyShape
{
// Due to our algoritm in Vector.rotationTo we work with YZX Euler angles, so we apply the rotations in this order.
return this.rotateY(degY, pivot).rotateZ(degZ,pivot).rotateX(degX,pivot);
}
/** Same as rotateEuler but makes a copy */
@checkInput([ [Number,0],[Number,0], [Number,0], ['Pivot', 'center']], [Number,Number,Number,'auto'])
rotatedEuler(degX:number, degY:number = 0, degZ:number = 0, pivot:Pivot):AnyShape
{
return this.copy().rotateEuler(degX, degY, degZ, pivot);
}
/**
* Rotate sequencely around the x,y and z axis.
* !!!! IMPORTANT: this is not the same as supplying the independant angles around the axis!
*/
@checkInput('PointLike', 'Vector')
rotate(r:PointLike, ...args) // allows flattened notation rotate(180,0,-90)
{
r = r as Vector; // automatically converted to Vector
return this.rotateX(r.x).rotateY(r.y).rotateZ(r.z);
}
/** Rotate this Shape around the x-axis with a given angle and pivot (default: center) */
@checkInput([Number,['Pivot','center']], [Number, 'auto'])
rotateX(deg:number, pivot?:Pivot):AnyShape
{
return this.rotateAround(deg, [1,0,0], pivot);
}
/** Rotate this Shape around the y-axis with a given angle and pivot (default: center) */
@checkInput([Number,['Pivot','center']], [Number, 'auto'])
rotateY(deg:number, pivot?:Pivot):AnyShape
{
return this.rotateAround(deg, [0,1,0], pivot);
}
/** Rotate this Shape around the y-axis with a given angle and pivot (default: center) */
@checkInput([Number,['Pivot','center']], [Number, 'auto'])
rotateZ(deg:number, pivot?:Pivot):AnyShape
{
return this.rotateAround(deg, [0,0,1], pivot);
}
/** Rotates a Shape a given angle along a axis (default: Z) */
@checkInput([Number,['PointLike',[0,0,1]],['Pivot','center'] ], [Number, Vector, 'auto'])
rotateAround(angle:number, axis?:PointLike, pivot?:Pivot):AnyShape
{
/* !!!! IMPORTANT: OC uses righthand rotation from given Vector
- Rotating around x-axis in positive direction is from Y to Z axis
- Rotating around y-axis in positive direction goes from Z to X (counterintuitive!)
- Rotation around z-axis is from X to Y axis
*/
/* OC docs:
- gp_Trsf - https://dev.opencascade.org/doc/refman/html/classgp___trsf.html
- gp_Pnt - https://dev.opencascade.org/doc/refman/html/classgp___pnt.html
- gp_Vec - https://dev.opencascade.org/doc/refman/html/classgp___vec.html
- gp_Dir - https://dev.opencascade.org/doc/refman/html/classgp___dir.html
- gp_Ax1 - https://dev.opencascade.org/doc/refman/html/classgp___ax1.html
- TopLoc_Location - https://dev.opencascade.org/doc/refman/html/class_top_loc___location.html
*/
let pivotVec:Vector;
let axisVec = axis as Vector; // automatically converted
if (typeof pivot === 'string' || pivot == null)
{
pivotVec = this.pointAtSide(pivot as string).toVector();
}
else {
pivotVec = new Vector(pivot);
}
let ocTransformation = new this._oc.gp_Trsf_1();
ocTransformation.SetRotation_1(
new this._oc.gp_Ax1_2(
pivotVec._toOcPoint(),
axisVec._toOcDir()