@buerli.io/headless 0.10.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,462 +1,472 @@
1
- var __asyncValues = (this && this.__asyncValues) || function (o) {
2
- if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
3
- var m = o[Symbol.asyncIterator], i;
4
- return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
5
- function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
6
- function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
7
- };
8
- /* eslint-disable max-lines */
9
- import { ccAPI } from '@buerli.io/classcad';
10
- import { api, getDrawing } from '@buerli.io/core';
11
- import { Group, Mesh, MeshStandardMaterial, Scene, Shape } from 'three';
12
- import { mergeBufferGeometries } from 'three-stdlib';
13
- import { getDifferentColoredMeshesFromEntity } from './utils/meshes';
14
- const solidAPI = ccAPI.solid;
15
- const toCCVec = (args) => ({ x: args[0], y: args[1], z: args[2] });
16
- const toCCNbrVec = (args) => ({ x: args[0], y: args[1], z: args[2] });
17
- const toArray = (v) => (Array.isArray(v) ? v : v.toArray());
18
- const toEuler = (v) => toArray(v);
19
- const makeVec = (v) => toCCVec(toArray(v));
20
- const makeNbrVec = (v) => toCCNbrVec(toArray(v));
21
- const makeEuler = (v) => toCCVec(toEuler(v));
22
- const makeNbrEuler = (v) => toCCNbrVec(toEuler(v));
23
- /**
24
- * Returns the entity of solid from structure tree
25
- * @param drawingId Id of current drawing
26
- * @param solid Solid to get entity from
27
- */
28
- const getEntity = async (drawingId, solid) => {
29
- const rSolid = await solid;
30
- const cDrawing = getDrawing(drawingId);
31
- const object = cDrawing.structure.tree[rSolid];
32
- if (object != undefined) {
33
- const entities = object.geometryIdList;
34
- if (entities != undefined && entities.length > 0) {
35
- return cDrawing.geometry.cache[entities[0]];
36
- }
37
- else {
38
- console.warn(`There is no cached entry for ${rSolid}!`, cDrawing.geometry.cache);
39
- return null;
40
- }
41
- }
42
- else {
43
- console.warn(`There is no cached entry for ${rSolid}!`, cDrawing.geometry.cache);
44
- return null;
45
- }
46
- };
47
- /**
48
- * Returns the adjacent points of the fillet arc. These are the points where fillet arc tangentially touches the lines.
49
- * @param info contains all information for the fillet, like start- and endpoints of adjacent lines and control point
50
- * @param radius radius of the fillet arc
51
- */
52
- const getTouchPoints = (info, radius) => {
53
- const controlPos = info.control;
54
- const linearTolerance = 1e-3;
55
- const dirs = [];
56
- const maxDists = [];
57
- for (let i = 0; i < 2; i++) {
58
- const startPos = info.lineStarts[i];
59
- const endPos = info.lineEnds[i];
60
- const dir = endPos.clone().sub(startPos).normalize();
61
- const maxDist = endPos.distanceTo(controlPos);
62
- dirs.push(dir);
63
- maxDists.push(maxDist);
64
- }
65
- if (radius + linearTolerance >= Math.min(maxDists[0], maxDists[1])) {
66
- return null; // too large fillet
67
- }
68
- // Calculate distance from controlpt to touchpoint
69
- const scalar = Math.abs(radius / Math.tan(getIncludingAngle(info) / 2));
70
- return dirs.map(dir => dir
71
- .clone()
72
- .multiplyScalar(scalar)
73
- .add(controlPos));
74
- };
75
- /**
76
- * Calculates the including angle between two lines. The angle is measured from first to second line counterclockwise. If angle exceeds 180°, measuring is clockwise but negative angle
77
- * @param info Info contains information about lines
78
- */
79
- const getIncludingAngle = (info) => {
80
- // First line (line to point)
81
- const line1 = info.lineEnds[0]
82
- .clone()
83
- .sub(info.lineStarts[0])
84
- .normalize();
85
- // Second line (line from point)
86
- const line2 = info.lineEnds[1]
87
- .clone()
88
- .sub(info.lineStarts[1])
89
- .normalize();
90
- // Angle, measured from first line to second line counterclockwise.
91
- // If angle exceeds 180°, measuring is clockwise but negative angle
92
- const angle = Math.atan2(line1.x * line2.y - line1.y * line2.x, line1.x * line2.x + line1.y * line2.y);
93
- return angle;
94
- };
95
- /**
96
- * Calculates and returns the including angle between the touchpoints of the fillet. Attention: It is the angle of touchpoints and center of fillet arc and not the one between touchpoints and control point.
97
- * @param info
98
- */
99
- const getIncludingBulgeAngle = (info) => {
100
- // angle of first line, control point and second line
101
- const angle = getIncludingAngle(info);
102
- // Opposite angle of the angle which was calculated from control point and its adjacent lines
103
- const oppositeAngle = Math.PI - Math.abs(angle);
104
- const sign = angle / Math.abs(angle);
105
- return oppositeAngle * sign * -1; // -1 because of bulges definition
106
- };
107
- /**
108
- * Creates a polyline from the given fillet points
109
- * @param fPts points of the polyline with its associated fillet radius
110
- * @example
111
- * // Creates a polyline with three points
112
- * const fp0 = { point: new THREE.Vector3(20, 20, 0), radius: 4 }
113
- * const fp1 = { point: new THREE.Vector3(40, 0, 0), radius: 2 }
114
- * const fp2 = { point: new THREE.Vector3(0, 0, 0), radius: 2 }
115
- * const polyline = createPolyline([fp0, fp1, fp2])
116
- */
117
- export function createPolyline(fPts) {
118
- const newVertices = [];
119
- const newBulges = [];
120
- for (let i = 0; i < fPts.length; i++) {
121
- // if fillet point has radius, calculate fillet info, touchpoints and bulge
122
- if (fPts[i].radius > 0) {
123
- const j = i - 1 < 0 ? fPts.length - 1 : i - 1;
124
- const k = i + 1 > fPts.length - 1 ? 0 : i + 1;
125
- const filletInfo = {
126
- control: fPts[i].point,
127
- lineStarts: [fPts[i].point, fPts[i].point],
128
- lineEnds: [fPts[j].point, fPts[k].point],
129
- };
130
- const touchPts = getTouchPoints(filletInfo, fPts[i].radius); // returns two points
131
- if (touchPts != undefined && (touchPts === null || touchPts === void 0 ? void 0 : touchPts.length) > 0) {
132
- const angle = getIncludingBulgeAngle(filletInfo);
133
- const bulge = Math.tan(angle / 4);
134
- newVertices.push(...touchPts);
135
- newBulges.push(bulge); // bulge for first point
136
- newBulges.push(0); // bulge for second point
137
- }
138
- }
139
- else {
140
- newVertices.push(fPts[i].point);
141
- newBulges.push(0);
142
- }
143
- }
144
- return { points: newVertices, bulges: newBulges };
145
- }
146
- /**
147
- * Creates the specific curve array from THREE.Shape.curves to draw the region in ClassCAD. It contains the type and all necessary points and control points in a multidimensional array.
148
- * @param curves THREE.Shape.curves
149
- */
150
- const makeCCData = (curves) => {
151
- return curves.map((curve) => {
152
- switch (curve.type) {
153
- // [pStart, p1, p2, p3]
154
- case 'CubicBezierCurve':
155
- return [curve.type, curve.v0.toArray(), curve.v1.toArray(), curve.v2.toArray(), curve.v3.toArray()];
156
- // [pStart, p1, p2]
157
- case 'QuadraticBezierCurve':
158
- return [curve.type, curve.v0.toArray(), curve.v1.toArray(), curve.v2.toArray()];
159
- // [p1, p2]
160
- case 'LineCurve':
161
- return [curve.type, curve.v1.toArray(), curve.v2.toArray()];
162
- // [...points]
163
- case 'SplineCurve':
164
- return [curve.type, curve.points.map((point) => point.toArray())];
165
- // [pA, radius, angles, clockwise, rotation]
166
- case 'EllipseCurve':
167
- case 'ArcCurve':
168
- const { aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation } = curve;
169
- return [
170
- curve.type,
171
- [aX, aY],
172
- [xRadius, yRadius],
173
- [(aStartAngle / Math.PI) * 180, (aEndAngle / Math.PI) * 180],
174
- aClockwise,
175
- aRotation,
176
- ];
177
- default:
178
- return undefined;
179
- }
180
- });
181
- };
182
- export default class CAD {
183
- constructor() {
184
- this.drawingId = null;
185
- this.queue = Promise.resolve(0);
186
- this.queue = Promise.resolve(0);
187
- }
188
- resolve(callback, ...args) {
189
- return (this.queue = this.queue
190
- .then(() => Promise.all(args).then(callback))
191
- .catch(e => {
192
- // catch is necessary to avoid error promises in the queue
193
- }));
194
- }
195
- init(callback) {
196
- const promise = new Promise(async (resolve, reject) => {
197
- const drawingId = await ccAPI.base.createCCDrawing('solid');
198
- if (!drawingId)
199
- throw new Error('Drawing could not be created');
200
- this.drawingId = drawingId;
201
- await solidAPI.init(drawingId);
202
- const publicApi = {
203
- box: (length, width, height) => {
204
- return this.resolve(async () => {
205
- return solidAPI.createBox(drawingId, length, width, height);
206
- });
207
- },
208
- clearSolids: () => {
209
- return this.resolve(async () => {
210
- return solidAPI.clearSolids(drawingId);
211
- });
212
- },
213
- clearSolid: (target) => {
214
- return this.resolve(async ([rTarget]) => {
215
- return solidAPI.clearSolid(drawingId, rTarget);
216
- }, target);
217
- },
218
- cone: (length, diameter1, diameter2) => {
219
- return this.resolve(async () => {
220
- return solidAPI.createCone(drawingId, length, diameter1, diameter2);
221
- });
222
- },
223
- copy: (target) => {
224
- return this.resolve(async ([rTarget]) => {
225
- return solidAPI.copy(drawingId, rTarget);
226
- }, target);
227
- },
228
- createBufferGeometry: async (solid) => {
229
- await this.queue;
230
- this.queue = Promise.resolve(0);
231
- const rSolid = await solid;
232
- await ccAPI.baseModeler.requestVisualisationOfObject(drawingId, rSolid);
233
- const entity = await getEntity(drawingId, rSolid);
234
- if (entity != null) {
235
- return mergeBufferGeometries(entity.meshes.map(m => m.geometry));
236
- }
237
- },
238
- createScene: async (solids, options) => {
239
- var e_1, _a;
240
- await this.queue;
241
- this.queue = Promise.resolve(0);
242
- const scene = new Scene();
243
- scene.name = 'Scene'; // Default name for the scene
244
- const part = new Group();
245
- part.name = 'Part'; // Default name for the part
246
- const _solids = [];
247
- const meshes = [];
248
- try {
249
- for (var solids_1 = __asyncValues(solids), solids_1_1; solids_1_1 = await solids_1.next(), !solids_1_1.done;) {
250
- const solid = solids_1_1.value;
251
- await ccAPI.baseModeler.requestVisualisationOfObject(drawingId, solid);
252
- const cDrawing = getDrawing(drawingId);
253
- const solidObject = cDrawing.structure.tree[solid];
254
- if (solidObject) {
255
- const _solid = new Group();
256
- _solid.name = solidObject.name;
257
- _solid.userData = { id: solidObject.id }; // add solid id to the userData
258
- const entities = solidObject.geometryIdList;
259
- if (entities && entities.length > 0) {
260
- const entity = cDrawing.geometry.cache[entities[0]];
261
- if (entity && entity.meshes.length > 0) {
262
- if (options === null || options === void 0 ? void 0 : options.meshPerGeometry) {
263
- // Create a mesh for each geometry element
264
- entity.meshes.forEach(m => {
265
- const mesh = new Mesh();
266
- mesh.userData = { id: m.graphicId }; // add graphic id to the userData
267
- mesh.geometry = m.geometry;
268
- mesh.material = new MeshStandardMaterial({
269
- color: m.color ? m.color : entity.color,
270
- transparent: m.opacity ? m.opacity < 1 : entity.opacity < 1,
271
- opacity: m.opacity ? m.opacity : entity.opacity,
272
- });
273
- _solid.add(mesh);
274
- meshes.push(mesh);
275
- });
276
- }
277
- else {
278
- // Merge all geometries into one mesh, sort them by color
279
- const colorMeshesMap = getDifferentColoredMeshesFromEntity(entity);
280
- Object.keys(colorMeshesMap).forEach(key => {
281
- const mesh = new Mesh();
282
- mesh.geometry = mergeBufferGeometries(colorMeshesMap[key].meshes.map(m => m.geometry));
283
- mesh.material = new MeshStandardMaterial({
284
- color: colorMeshesMap[key].color,
285
- transparent: colorMeshesMap[key].opacity < 1,
286
- opacity: colorMeshesMap[key].opacity,
287
- });
288
- _solid.add(mesh); // Add mesh to solid of the scene
289
- meshes.push(mesh); // Collect mesh to return later
290
- });
291
- }
292
- part.add(_solid); // Add solid to part of the scene
293
- _solids.push(_solid); // Collect solid to return later
294
- }
295
- }
296
- }
297
- }
298
- }
299
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
300
- finally {
301
- try {
302
- if (solids_1_1 && !solids_1_1.done && (_a = solids_1.return)) await _a.call(solids_1);
303
- }
304
- finally { if (e_1) throw e_1.error; }
305
- }
306
- scene.add(part); // Add part to the scene
307
- return { scene, part, solids: _solids, meshes };
308
- },
309
- cylinder: (length, diameter) => {
310
- return this.resolve(async () => {
311
- return solidAPI.createCylinder(drawingId, length, diameter);
312
- });
313
- },
314
- edgeLoops: (breps) => {
315
- return this.resolve(async ([rBreps]) => {
316
- return solidAPI.edgeLoops(drawingId, rBreps);
317
- }, breps);
318
- },
319
- export: (solidIds) => {
320
- return this.resolve(async ([rSolidIds]) => {
321
- return solidAPI.export(drawingId, 'stp', rSolidIds);
322
- }, solidIds);
323
- },
324
- extendSolidAtPlane: (target, point, normal, distance) => {
325
- return this.resolve(async ([rTarget]) => {
326
- return solidAPI.solidExtendAtPlane(drawingId, rTarget, makeNbrVec(point), makeNbrVec(normal), distance);
327
- }, target);
328
- },
329
- extrude: (height, region) => {
330
- return this.resolve(async () => {
331
- if (region instanceof Shape) {
332
- const curveArray = makeCCData(region.curves);
333
- return solidAPI.createExtrudeRegion(drawingId, makeNbrVec(height), curveArray);
334
- }
335
- else {
336
- return solidAPI.createExtrude(drawingId, makeNbrVec(height), region.points, region.bulges);
337
- }
338
- });
339
- },
340
- fillet: (radius, edges) => {
341
- return this.resolve(async ([rEdges]) => {
342
- return solidAPI.createFillet(drawingId, radius, rEdges);
343
- }, edges);
344
- },
345
- import: (data) => {
346
- return this.resolve(async () => {
347
- return solidAPI.import(drawingId, data, 'stp');
348
- });
349
- },
350
- intersect: (solidId, keepSolid, ...bodies) => {
351
- return this.resolve(async ([rSolidId, ...rBodies]) => {
352
- for (const rBody of rBodies) {
353
- solidAPI.intersect(drawingId, rSolidId, keepSolid, rBody);
354
- }
355
- return rSolidId;
356
- }, solidId, ...bodies);
357
- },
358
- load: (data) => {
359
- return this.resolve(async () => {
360
- const productId = await solidAPI.load(drawingId, data, 'ofb', true);
361
- if (productId !== null) {
362
- const drawing = getDrawing(drawingId);
363
- const solids = drawing.structure.tree[productId].solids;
364
- if (solids !== undefined) {
365
- return solids.map(innerId => drawing.graphic.containers[innerId].owner);
366
- }
367
- }
368
- return [];
369
- });
370
- },
371
- mirror: (target, point, normal) => {
372
- return this.resolve(async ([rTarget]) => {
373
- return solidAPI.mirror(drawingId, rTarget, makeNbrVec(point), makeNbrEuler(normal));
374
- }, target);
375
- },
376
- moveTo: (target, position) => {
377
- return this.resolve(async ([rTarget]) => {
378
- return solidAPI.moveTo(drawingId, rTarget, makeNbrVec(position));
379
- }, target);
380
- },
381
- offset: (target, offsetDistance) => {
382
- return this.resolve(async ([rTarget]) => {
383
- return solidAPI.offset(drawingId, rTarget, offsetDistance);
384
- }, target);
385
- },
386
- pick: (target, type, ...points) => {
387
- return this.resolve(async ([rTarget]) => {
388
- const pts = points.map(pt => makeNbrVec(pt));
389
- const breps = await solidAPI.pick(drawingId, rTarget, type, ...pts);
390
- if (breps !== null) {
391
- return Array.isArray(breps) ? breps : [breps];
392
- }
393
- }, target);
394
- },
395
- revolve: (position, direction, angle, region) => {
396
- return this.resolve(async () => {
397
- if (region instanceof Shape) {
398
- const curveArray = makeCCData(region.curves);
399
- return solidAPI.createRevolveRegion(drawingId, makeNbrVec(position), makeNbrVec(direction), angle, curveArray);
400
- }
401
- else {
402
- return solidAPI.createRevolve(drawingId, makeNbrVec(position), makeNbrVec(direction), (angle / Math.PI) * 180, region.points, region.bulges);
403
- }
404
- });
405
- },
406
- rotateTo: (target, point) => {
407
- return this.resolve(async ([rTarget]) => {
408
- return solidAPI.rotateTo(drawingId, rTarget, makeNbrEuler(point));
409
- }, target);
410
- },
411
- save: () => {
412
- return this.resolve(async () => {
413
- return solidAPI.save(drawingId, 'ofb');
414
- });
415
- },
416
- scale: (target, pointOrFactor) => {
417
- return this.resolve(async ([rTarget]) => {
418
- const lPointOrFactor = typeof pointOrFactor === 'number' ? pointOrFactor : makeNbrVec(pointOrFactor);
419
- return solidAPI.scale(drawingId, rTarget, lPointOrFactor);
420
- }, target);
421
- },
422
- setFacetingParams: (distanceTol, angleTol) => {
423
- return this.resolve(async () => {
424
- return ccAPI.common.setFacetingParameters(drawingId, distanceTol, angleTol);
425
- });
426
- },
427
- slice: (target, point, normal) => {
428
- return this.resolve(async ([rTarget]) => {
429
- return solidAPI.slice(drawingId, rTarget, makeNbrVec(point), makeNbrVec(normal));
430
- }, target);
431
- },
432
- sphere: (radius) => {
433
- return this.resolve(async () => {
434
- return solidAPI.createSphere(drawingId, radius);
435
- });
436
- },
437
- subtract: (solidId, keepSolid, ...bodies) => {
438
- return this.resolve(async ([rSolidId, ...rBodies]) => {
439
- for (const rBody of rBodies) {
440
- solidAPI.subtract(drawingId, rSolidId, keepSolid, rBody);
441
- }
442
- return rSolidId;
443
- }, solidId, ...bodies);
444
- },
445
- union: (solidId, keepSolid, ...bodies) => {
446
- return this.resolve(async ([rSolidId, ...rBodies]) => {
447
- for (const rBody of rBodies) {
448
- solidAPI.union(drawingId, rSolidId, keepSolid, rBody);
449
- }
450
- return rSolidId;
451
- }, solidId, ...bodies);
452
- },
453
- };
454
- callback(publicApi);
455
- resolve(drawingId);
456
- });
457
- return () => promise.then(drawingId => api.getState().api.removeDrawing(drawingId));
458
- }
459
- destroy() {
460
- this.drawingId && api.getState().api.removeDrawing(this.drawingId);
461
- }
462
- }
1
+ var __asyncValues = (this && this.__asyncValues) || function (o) {
2
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
3
+ var m = o[Symbol.asyncIterator], i;
4
+ return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
5
+ function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
6
+ function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
7
+ };
8
+ /* eslint-disable max-lines */
9
+ import { ccAPI } from '@buerli.io/classcad';
10
+ import { api, getDrawing } from '@buerli.io/core';
11
+ import { Group, Mesh, MeshStandardMaterial, Scene, Shape } from 'three';
12
+ import { mergeBufferGeometries } from 'three-stdlib';
13
+ import { getDifferentColoredMeshesFromEntity } from './utils/meshes';
14
+ const solidAPI = ccAPI.solid;
15
+ const toCCVec = (args) => ({ x: args[0], y: args[1], z: args[2] });
16
+ const toCCNbrVec = (args) => ({ x: args[0], y: args[1], z: args[2] });
17
+ const toArray = (v) => (Array.isArray(v) ? v : v.toArray());
18
+ const toEuler = (v) => toArray(v);
19
+ const makeVec = (v) => toCCVec(toArray(v));
20
+ const makeNbrVec = (v) => toCCNbrVec(toArray(v));
21
+ const makeEuler = (v) => toCCVec(toEuler(v));
22
+ const makeNbrEuler = (v) => toCCNbrVec(toEuler(v));
23
+ /**
24
+ * Returns the entity of solid from structure tree
25
+ * @param drawingId Id of current drawing
26
+ * @param solid Solid to get entity from
27
+ */
28
+ const getEntity = async (drawingId, _solid) => {
29
+ const rSolid = await _solid;
30
+ const cDrawing = getDrawing(drawingId);
31
+ const object = cDrawing.structure.tree[rSolid];
32
+ if (object != undefined) {
33
+ const entities = object.geometryIdList;
34
+ if (entities != undefined && entities.length > 0) {
35
+ return cDrawing.geometry.cache[entities[0]];
36
+ }
37
+ else {
38
+ console.warn(`There is no cached entry for ${rSolid}!`, cDrawing.geometry.cache);
39
+ return null;
40
+ }
41
+ }
42
+ else {
43
+ console.warn(`There is no cached entry for ${rSolid}!`, cDrawing.geometry.cache);
44
+ return null;
45
+ }
46
+ };
47
+ /**
48
+ * Returns the adjacent points of the fillet arc. These are the points where fillet arc tangentially touches the lines.
49
+ * @param info contains all information for the fillet, like start- and endpoints of adjacent lines and control point
50
+ * @param radius radius of the fillet arc
51
+ */
52
+ const getTouchPoints = (info, radius) => {
53
+ const controlPos = info.control;
54
+ const linearTolerance = 1e-3;
55
+ const dirs = [];
56
+ const maxDists = [];
57
+ for (let i = 0; i < 2; i++) {
58
+ const startPos = info.lineStarts[i];
59
+ const endPos = info.lineEnds[i];
60
+ const dir = endPos.clone().sub(startPos).normalize();
61
+ const maxDist = endPos.distanceTo(controlPos);
62
+ dirs.push(dir);
63
+ maxDists.push(maxDist);
64
+ }
65
+ if (radius + linearTolerance >= Math.min(maxDists[0], maxDists[1])) {
66
+ return null; // too large fillet
67
+ }
68
+ // Calculate distance from controlpt to touchpoint
69
+ const scalar = Math.abs(radius / Math.tan(getIncludingAngle(info) / 2));
70
+ return dirs.map(dir => dir
71
+ .clone()
72
+ .multiplyScalar(scalar)
73
+ .add(controlPos));
74
+ };
75
+ /**
76
+ * Calculates the including angle between two lines. The angle is measured from first to second line counterclockwise. If angle exceeds 180°, measuring is clockwise but negative angle
77
+ * @param info Info contains information about lines
78
+ */
79
+ const getIncludingAngle = (info) => {
80
+ // First line (line to point)
81
+ const line1 = info.lineEnds[0]
82
+ .clone()
83
+ .sub(info.lineStarts[0])
84
+ .normalize();
85
+ // Second line (line from point)
86
+ const line2 = info.lineEnds[1]
87
+ .clone()
88
+ .sub(info.lineStarts[1])
89
+ .normalize();
90
+ // Angle, measured from first line to second line counterclockwise.
91
+ // If angle exceeds 180°, measuring is clockwise but negative angle
92
+ const angle = Math.atan2(line1.x * line2.y - line1.y * line2.x, line1.x * line2.x + line1.y * line2.y);
93
+ return angle;
94
+ };
95
+ /**
96
+ * Calculates and returns the including angle between the touchpoints of the fillet. Attention: It is the angle of touchpoints and center of fillet arc and not the one between touchpoints and control point.
97
+ * @param info
98
+ */
99
+ const getIncludingBulgeAngle = (info) => {
100
+ // angle of first line, control point and second line
101
+ const angle = getIncludingAngle(info);
102
+ // Opposite angle of the angle which was calculated from control point and its adjacent lines
103
+ const oppositeAngle = Math.PI - Math.abs(angle);
104
+ const sign = angle / Math.abs(angle);
105
+ return oppositeAngle * sign * -1; // -1 because of bulges definition
106
+ };
107
+ /**
108
+ * Creates a polyline from the given fillet points
109
+ * @param fPts points of the polyline with its associated fillet radius
110
+ * @example
111
+ * // Creates a polyline with three points
112
+ * const fp0 = { point: new THREE.Vector3(20, 20, 0), radius: 4 }
113
+ * const fp1 = { point: new THREE.Vector3(40, 0, 0), radius: 2 }
114
+ * const fp2 = { point: new THREE.Vector3(0, 0, 0), radius: 2 }
115
+ * const polyline = createPolyline([fp0, fp1, fp2])
116
+ */
117
+ export function createPolyline(fPts) {
118
+ const newVertices = [];
119
+ const newBulges = [];
120
+ for (let i = 0; i < fPts.length; i++) {
121
+ // if fillet point has radius, calculate fillet info, touchpoints and bulge
122
+ if (fPts[i].radius > 0) {
123
+ const j = i - 1 < 0 ? fPts.length - 1 : i - 1;
124
+ const k = i + 1 > fPts.length - 1 ? 0 : i + 1;
125
+ const filletInfo = {
126
+ control: fPts[i].point,
127
+ lineStarts: [fPts[i].point, fPts[i].point],
128
+ lineEnds: [fPts[j].point, fPts[k].point],
129
+ };
130
+ const touchPts = getTouchPoints(filletInfo, fPts[i].radius); // returns two points
131
+ if (touchPts != undefined && (touchPts === null || touchPts === void 0 ? void 0 : touchPts.length) > 0) {
132
+ const angle = getIncludingBulgeAngle(filletInfo);
133
+ const bulge = Math.tan(angle / 4);
134
+ newVertices.push(...touchPts);
135
+ newBulges.push(bulge); // bulge for first point
136
+ newBulges.push(0); // bulge for second point
137
+ }
138
+ }
139
+ else {
140
+ newVertices.push(fPts[i].point);
141
+ newBulges.push(0);
142
+ }
143
+ }
144
+ return { points: newVertices, bulges: newBulges };
145
+ }
146
+ /**
147
+ * Creates the specific curve array from THREE.Shape.curves to draw the region in ClassCAD. It contains the type and all necessary points and control points in a multidimensional array.
148
+ * @param curves THREE.Shape.curves
149
+ */
150
+ const makeCCData = (curves) => {
151
+ return curves.map((curve) => {
152
+ switch (curve.type) {
153
+ // [pStart, p1, p2, p3]
154
+ case 'CubicBezierCurve':
155
+ return [curve.type, curve.v0.toArray(), curve.v1.toArray(), curve.v2.toArray(), curve.v3.toArray()];
156
+ // [pStart, p1, p2]
157
+ case 'QuadraticBezierCurve':
158
+ return [curve.type, curve.v0.toArray(), curve.v1.toArray(), curve.v2.toArray()];
159
+ // [p1, p2]
160
+ case 'LineCurve':
161
+ return [curve.type, curve.v1.toArray(), curve.v2.toArray()];
162
+ // [...points]
163
+ case 'SplineCurve':
164
+ return [curve.type, curve.points.map((point) => point.toArray())];
165
+ // [pA, radius, angles, clockwise, rotation]
166
+ case 'EllipseCurve':
167
+ case 'ArcCurve':
168
+ const { aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation } = curve;
169
+ return [
170
+ curve.type,
171
+ [aX, aY],
172
+ [xRadius, yRadius],
173
+ [(aStartAngle / Math.PI) * 180, (aEndAngle / Math.PI) * 180],
174
+ aClockwise,
175
+ aRotation,
176
+ ];
177
+ default:
178
+ return undefined;
179
+ }
180
+ });
181
+ };
182
+ export class Solid {
183
+ constructor() {
184
+ this.drawingId = null;
185
+ this.queue = Promise.resolve(0);
186
+ this.queue = Promise.resolve(0);
187
+ }
188
+ resolve(callback, ...args) {
189
+ return (this.queue = this.queue
190
+ .then(() => Promise.all(args).then(callback))
191
+ .catch(e => {
192
+ // catch is necessary to avoid error promises in the queue
193
+ }));
194
+ }
195
+ init(callback) {
196
+ const promise = new Promise(async (resolve, reject) => {
197
+ const drawingId = await ccAPI.base.createCCDrawing('solid');
198
+ if (!drawingId)
199
+ throw new Error('Drawing could not be created');
200
+ this.drawingId = drawingId;
201
+ await solidAPI.init(drawingId);
202
+ const publicApi = {
203
+ getDrawingId: () => drawingId,
204
+ getDrawing: () => getDrawing(drawingId),
205
+ getState: () => api.getState(),
206
+ setFacetingParameters: (distanceTol, angleTol) => this.resolve(async () => ccAPI.common.setFacetingParameters(drawingId, distanceTol, angleTol)),
207
+ box: (length, width, height) => {
208
+ return this.resolve(async () => {
209
+ return solidAPI.createBox(drawingId, length, width, height);
210
+ });
211
+ },
212
+ clearSolids: () => {
213
+ return this.resolve(async () => {
214
+ return solidAPI.clearSolids(drawingId);
215
+ });
216
+ },
217
+ clearSolid: (target) => {
218
+ return this.resolve(async ([rTarget]) => {
219
+ return solidAPI.clearSolid(drawingId, rTarget);
220
+ }, target);
221
+ },
222
+ cone: (length, diameter1, diameter2) => {
223
+ return this.resolve(async () => {
224
+ return solidAPI.createCone(drawingId, length, diameter1, diameter2);
225
+ });
226
+ },
227
+ copy: (target) => {
228
+ return this.resolve(async ([rTarget]) => {
229
+ return solidAPI.copy(drawingId, rTarget);
230
+ }, target);
231
+ },
232
+ createBufferGeometry: async (_solid) => {
233
+ await this.queue;
234
+ this.queue = Promise.resolve(0);
235
+ const rSolid = await _solid;
236
+ await ccAPI.baseModeler.requestVisualisationOfObject(drawingId, rSolid);
237
+ const entity = await getEntity(drawingId, rSolid);
238
+ if (entity != null) {
239
+ return mergeBufferGeometries(entity.meshes.map(m => m.geometry));
240
+ }
241
+ },
242
+ createScene: async (solids, options) => {
243
+ var e_1, _a;
244
+ await this.queue;
245
+ this.queue = Promise.resolve(0);
246
+ const scene = new Scene();
247
+ scene.name = 'Scene'; // Default name for the scene
248
+ const part = new Group();
249
+ part.name = 'Part'; // Default name for the part
250
+ const _solids = [];
251
+ const meshes = [];
252
+ try {
253
+ for (var solids_1 = __asyncValues(solids), solids_1_1; solids_1_1 = await solids_1.next(), !solids_1_1.done;) {
254
+ const _solid = solids_1_1.value;
255
+ await ccAPI.baseModeler.requestVisualisationOfObject(drawingId, _solid);
256
+ const cDrawing = getDrawing(drawingId);
257
+ const solidObject = cDrawing.structure.tree[_solid];
258
+ if (solidObject) {
259
+ const _solidGroup = new Group();
260
+ _solidGroup.name = solidObject.name;
261
+ _solidGroup.userData = { id: solidObject.id }; // add solid id to the userData
262
+ const entities = solidObject.geometryIdList;
263
+ if (entities && entities.length > 0) {
264
+ const entity = cDrawing.geometry.cache[entities[0]];
265
+ if (entity && entity.meshes.length > 0) {
266
+ if (options === null || options === void 0 ? void 0 : options.meshPerGeometry) {
267
+ // Create a mesh for each geometry element
268
+ entity.meshes.forEach(m => {
269
+ const mesh = new Mesh();
270
+ mesh.userData = { id: m.graphicId }; // add graphic id to the userData
271
+ mesh.geometry = m.geometry;
272
+ mesh.material = new MeshStandardMaterial({
273
+ color: m.color ? m.color : entity.color,
274
+ transparent: m.opacity ? m.opacity < 1 : entity.opacity < 1,
275
+ opacity: m.opacity ? m.opacity : entity.opacity,
276
+ });
277
+ _solidGroup.add(mesh);
278
+ meshes.push(mesh);
279
+ });
280
+ }
281
+ else {
282
+ // Merge all geometries into one mesh, sort them by color
283
+ const colorMeshesMap = getDifferentColoredMeshesFromEntity(entity);
284
+ Object.keys(colorMeshesMap).forEach(key => {
285
+ const mesh = new Mesh();
286
+ mesh.geometry = mergeBufferGeometries(colorMeshesMap[key].meshes.map(m => m.geometry));
287
+ mesh.material = new MeshStandardMaterial({
288
+ color: colorMeshesMap[key].color,
289
+ transparent: colorMeshesMap[key].opacity < 1,
290
+ opacity: colorMeshesMap[key].opacity,
291
+ });
292
+ _solidGroup.add(mesh); // Add mesh to solid of the scene
293
+ meshes.push(mesh); // Collect mesh to return later
294
+ });
295
+ }
296
+ part.add(_solidGroup); // Add solid to part of the scene
297
+ _solids.push(_solidGroup); // Collect solid to return later
298
+ }
299
+ }
300
+ }
301
+ }
302
+ }
303
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
304
+ finally {
305
+ try {
306
+ if (solids_1_1 && !solids_1_1.done && (_a = solids_1.return)) await _a.call(solids_1);
307
+ }
308
+ finally { if (e_1) throw e_1.error; }
309
+ }
310
+ scene.add(part); // Add part to the scene
311
+ return { scene, part, solids: _solids, meshes };
312
+ },
313
+ cylinder: (length, diameter) => {
314
+ return this.resolve(async () => {
315
+ return solidAPI.createCylinder(drawingId, length, diameter);
316
+ });
317
+ },
318
+ edgeLoops: (breps) => {
319
+ return this.resolve(async ([rBreps]) => {
320
+ return solidAPI.edgeLoops(drawingId, rBreps);
321
+ }, breps);
322
+ },
323
+ export: (solidIds) => {
324
+ return this.resolve(async ([rSolidIds]) => {
325
+ return solidAPI.export(drawingId, 'stp', rSolidIds);
326
+ }, solidIds);
327
+ },
328
+ extendSolidAtPlane: (target, point, normal, distance) => {
329
+ return this.resolve(async ([rTarget]) => {
330
+ return solidAPI.solidExtendAtPlane(drawingId, rTarget, makeNbrVec(point), makeNbrVec(normal), distance);
331
+ }, target);
332
+ },
333
+ extrude: (height, region) => {
334
+ return this.resolve(async () => {
335
+ if (region instanceof Shape) {
336
+ const curveArray = makeCCData(region.curves);
337
+ return solidAPI.createExtrudeRegion(drawingId, makeNbrVec(height), curveArray);
338
+ }
339
+ else {
340
+ return solidAPI.createExtrude(drawingId, makeNbrVec(height), region.points, region.bulges);
341
+ }
342
+ });
343
+ },
344
+ fillet: (radius, edges) => {
345
+ return this.resolve(async ([rEdges]) => {
346
+ return solidAPI.createFillet(drawingId, radius, rEdges);
347
+ }, edges);
348
+ },
349
+ import: (data) => {
350
+ return this.resolve(async () => {
351
+ return solidAPI.import(drawingId, data, 'stp');
352
+ });
353
+ },
354
+ intersect: (solidId, keepSolid, ...bodies) => {
355
+ return this.resolve(async ([rSolidId, ...rBodies]) => {
356
+ for (const rBody of rBodies) {
357
+ solidAPI.intersect(drawingId, rSolidId, keepSolid, rBody);
358
+ }
359
+ return rSolidId;
360
+ }, solidId, ...bodies);
361
+ },
362
+ load: (data) => {
363
+ return this.resolve(async () => {
364
+ const productId = await solidAPI.load(drawingId, data, 'ofb', true);
365
+ if (productId !== null) {
366
+ const drawing = getDrawing(drawingId);
367
+ const solids = drawing.structure.tree[productId].solids;
368
+ if (solids !== undefined) {
369
+ return solids.map(innerId => drawing.graphic.containers[innerId].owner);
370
+ }
371
+ }
372
+ return [];
373
+ });
374
+ },
375
+ mirror: (target, point, normal) => {
376
+ return this.resolve(async ([rTarget]) => {
377
+ return solidAPI.mirror(drawingId, rTarget, makeNbrVec(point), makeNbrEuler(normal));
378
+ }, target);
379
+ },
380
+ moveTo: (target, position) => {
381
+ return this.resolve(async ([rTarget]) => {
382
+ return solidAPI.moveTo(drawingId, rTarget, makeNbrVec(position));
383
+ }, target);
384
+ },
385
+ offset: (target, offsetDistance) => {
386
+ return this.resolve(async ([rTarget]) => {
387
+ return solidAPI.offset(drawingId, rTarget, offsetDistance);
388
+ }, target);
389
+ },
390
+ pick: (target, type, ...points) => {
391
+ return this.resolve(async ([rTarget]) => {
392
+ const pts = points.map(pt => makeNbrVec(pt));
393
+ const breps = await solidAPI.pick(drawingId, rTarget, type, ...pts);
394
+ if (breps !== null) {
395
+ return Array.isArray(breps) ? breps : [breps];
396
+ }
397
+ }, target);
398
+ },
399
+ revolve: (position, direction, angle, region) => {
400
+ return this.resolve(async () => {
401
+ if (region instanceof Shape) {
402
+ const curveArray = makeCCData(region.curves);
403
+ return solidAPI.createRevolveRegion(drawingId, makeNbrVec(position), makeNbrVec(direction), angle, curveArray);
404
+ }
405
+ else {
406
+ return solidAPI.createRevolve(drawingId, makeNbrVec(position), makeNbrVec(direction), (angle / Math.PI) * 180, region.points, region.bulges);
407
+ }
408
+ });
409
+ },
410
+ rotateTo: (target, point) => {
411
+ return this.resolve(async ([rTarget]) => {
412
+ return solidAPI.rotateTo(drawingId, rTarget, makeNbrEuler(point));
413
+ }, target);
414
+ },
415
+ save: () => {
416
+ return this.resolve(async () => {
417
+ return solidAPI.save(drawingId, 'ofb');
418
+ });
419
+ },
420
+ scale: (target, pointOrFactor) => {
421
+ return this.resolve(async ([rTarget]) => {
422
+ const lPointOrFactor = typeof pointOrFactor === 'number' ? pointOrFactor : makeNbrVec(pointOrFactor);
423
+ return solidAPI.scale(drawingId, rTarget, lPointOrFactor);
424
+ }, target);
425
+ },
426
+ setFacetingParams: (distanceTol, angleTol) => {
427
+ return this.resolve(async () => {
428
+ return ccAPI.common.setFacetingParameters(drawingId, distanceTol, angleTol);
429
+ });
430
+ },
431
+ slice: (target, point, normal) => {
432
+ return this.resolve(async ([rTarget]) => {
433
+ return solidAPI.slice(drawingId, rTarget, makeNbrVec(point), makeNbrVec(normal));
434
+ }, target);
435
+ },
436
+ sphere: (radius) => {
437
+ return this.resolve(async () => {
438
+ return solidAPI.createSphere(drawingId, radius);
439
+ });
440
+ },
441
+ subtract: (solidId, keepSolid, ...bodies) => {
442
+ return this.resolve(async ([rSolidId, ...rBodies]) => {
443
+ for (const rBody of rBodies) {
444
+ solidAPI.subtract(drawingId, rSolidId, keepSolid, rBody);
445
+ }
446
+ return rSolidId;
447
+ }, solidId, ...bodies);
448
+ },
449
+ union: (solidId, keepSolid, ...bodies) => {
450
+ return this.resolve(async ([rSolidId, ...rBodies]) => {
451
+ for (const rBody of rBodies) {
452
+ solidAPI.union(drawingId, rSolidId, keepSolid, rBody);
453
+ }
454
+ return rSolidId;
455
+ }, solidId, ...bodies);
456
+ },
457
+ };
458
+ callback(publicApi);
459
+ resolve(drawingId);
460
+ });
461
+ return () => promise.then(drawingId => api.getState().api.removeDrawing(drawingId));
462
+ }
463
+ destroy() {
464
+ this.drawingId && api.getState().api.removeDrawing(this.drawingId);
465
+ }
466
+ }
467
+ export class solid extends Solid {
468
+ constructor() {
469
+ super();
470
+ console.warn("Warning: 'solid' is deprecated, use 'Solid' instead, 'solid' will be removed in a future release.");
471
+ }
472
+ }