@buerli.io/headless 0.4.1 → 0.5.0-beta.2

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.
@@ -0,0 +1,35 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __importDefault = (this && this.__importDefault) || function (mod) {
26
+ return (mod && mod.__esModule) ? mod : { "default": mod };
27
+ };
28
+ Object.defineProperty(exports, "__esModule", { value: true });
29
+ exports.createPolyline = exports.history = exports.solid = void 0;
30
+ const history_1 = __importDefault(require("./history"));
31
+ exports.history = history_1.default;
32
+ const solid_1 = __importStar(require("./solid"));
33
+ exports.solid = solid_1.default;
34
+ Object.defineProperty(exports, "createPolyline", { enumerable: true, get: function () { return solid_1.createPolyline; } });
35
+ //#endregion Re-export type definitions
@@ -0,0 +1,435 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ Object.defineProperty(exports, "__esModule", { value: true });
26
+ exports.createPolyline = void 0;
27
+ /* eslint-disable max-lines */
28
+ const classcad_1 = require("@buerli.io/classcad");
29
+ const core_1 = require("@buerli.io/core");
30
+ const three_1 = require("three");
31
+ const BufferGeometryUtils_ = __importStar(require("three/examples/jsm/utils/BufferGeometryUtils"));
32
+ const solidAPI = classcad_1.ccAPI.solid;
33
+ let BufferGeometryUtils = BufferGeometryUtils_;
34
+ if (BufferGeometryUtils.BufferGeometryUtils) {
35
+ BufferGeometryUtils = BufferGeometryUtils.BufferGeometryUtils;
36
+ }
37
+ const toCCVec = (args) => ({ x: args[0], y: args[1], z: args[2] });
38
+ const toCCNbrVec = (args) => ({ x: args[0], y: args[1], z: args[2] });
39
+ const toArray = (v) => (Array.isArray(v) ? v : v.toArray());
40
+ const toEuler = (v) => toArray(v);
41
+ const makeVec = (v) => toCCVec(toArray(v));
42
+ const makeNbrVec = (v) => toCCNbrVec(toArray(v));
43
+ const makeEuler = (v) => toCCVec(toEuler(v));
44
+ const makeNbrEuler = (v) => toCCNbrVec(toEuler(v));
45
+ /**
46
+ * Returns the entity of solid from structure tree
47
+ * @param drawingId Id of current drawing
48
+ * @param solid Solid to get entity from
49
+ */
50
+ const getEntity = async (drawingId, solid) => {
51
+ const rSolid = await solid;
52
+ const cDrawing = (0, core_1.getDrawing)(drawingId);
53
+ const object = cDrawing.structure.tree[rSolid];
54
+ if (object != undefined) {
55
+ const entities = object.geometryIdList;
56
+ if (entities != undefined && entities.length > 0) {
57
+ return cDrawing.geometry.cache[entities[0]];
58
+ }
59
+ else {
60
+ console.warn(`There is no cached entry for ${rSolid}!`, cDrawing.geometry.cache);
61
+ return null;
62
+ }
63
+ }
64
+ else {
65
+ console.warn(`There is no cached entry for ${rSolid}!`, cDrawing.geometry.cache);
66
+ return null;
67
+ }
68
+ };
69
+ /**
70
+ * Returns the adjacent points of the fillet arc. These are the points where fillet arc tangentially touches the lines.
71
+ * @param info contains all information for the fillet, like start- and endpoints of adjacent lines and control point
72
+ * @param radius radius of the fillet arc
73
+ */
74
+ const getTouchPoints = (info, radius) => {
75
+ const controlPos = info.control;
76
+ const linearTolerance = 1e-3;
77
+ const dirs = [];
78
+ const maxDists = [];
79
+ for (let i = 0; i < 2; i++) {
80
+ const startPos = info.lineStarts[i];
81
+ const endPos = info.lineEnds[i];
82
+ const dir = endPos.clone().sub(startPos).normalize();
83
+ const maxDist = endPos.distanceTo(controlPos);
84
+ dirs.push(dir);
85
+ maxDists.push(maxDist);
86
+ }
87
+ if (radius + linearTolerance >= Math.min(maxDists[0], maxDists[1])) {
88
+ return null; // too large fillet
89
+ }
90
+ // Calculate distance from controlpt to touchpoint
91
+ const scalar = Math.abs(radius / Math.tan(getIncludingAngle(info) / 2));
92
+ return dirs.map(dir => dir
93
+ .clone()
94
+ .multiplyScalar(scalar)
95
+ .add(controlPos));
96
+ };
97
+ /**
98
+ * 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
99
+ * @param info Info contains information about lines
100
+ */
101
+ const getIncludingAngle = (info) => {
102
+ // First line (line to point)
103
+ const line1 = info.lineEnds[0]
104
+ .clone()
105
+ .sub(info.lineStarts[0])
106
+ .normalize();
107
+ // Second line (line from point)
108
+ const line2 = info.lineEnds[1]
109
+ .clone()
110
+ .sub(info.lineStarts[1])
111
+ .normalize();
112
+ // Angle, measured from first line to second line counterclockwise.
113
+ // If angle exceeds 180°, measuring is clockwise but negative angle
114
+ const angle = Math.atan2(line1.x * line2.y - line1.y * line2.x, line1.x * line2.x + line1.y * line2.y);
115
+ return angle;
116
+ };
117
+ /**
118
+ * 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.
119
+ * @param info
120
+ */
121
+ const getIncludingBulgeAngle = (info) => {
122
+ // angle of first line, control point and second line
123
+ const angle = getIncludingAngle(info);
124
+ // Opposite angle of the angle which was calculated from control point and its adjacent lines
125
+ const oppositeAngle = Math.PI - Math.abs(angle);
126
+ const sign = angle / Math.abs(angle);
127
+ return oppositeAngle * sign * -1; // -1 because of bulges definition
128
+ };
129
+ /**
130
+ * Creates a polyline from the given fillet points
131
+ * @param fPts points of the polyline with its associated fillet radius
132
+ * @example
133
+ * // Creates a polyline with three points
134
+ * const fp0 = { point: new THREE.Vector3(20, 20, 0), radius: 4 }
135
+ * const fp1 = { point: new THREE.Vector3(40, 0, 0), radius: 2 }
136
+ * const fp2 = { point: new THREE.Vector3(0, 0, 0), radius: 2 }
137
+ * const polyline = createPolyline([fp0, fp1, fp2])
138
+ */
139
+ function createPolyline(fPts) {
140
+ const newVertices = [];
141
+ const newBulges = [];
142
+ for (let i = 0; i < fPts.length; i++) {
143
+ // if fillet point has radius, calculate fillet info, touchpoints and bulge
144
+ if (fPts[i].radius > 0) {
145
+ const j = i - 1 < 0 ? fPts.length - 1 : i - 1;
146
+ const k = i + 1 > fPts.length - 1 ? 0 : i + 1;
147
+ const filletInfo = {
148
+ control: fPts[i].point,
149
+ lineStarts: [fPts[i].point, fPts[i].point],
150
+ lineEnds: [fPts[j].point, fPts[k].point],
151
+ };
152
+ const touchPts = getTouchPoints(filletInfo, fPts[i].radius); // returns two points
153
+ if (touchPts != undefined && (touchPts === null || touchPts === void 0 ? void 0 : touchPts.length) > 0) {
154
+ const angle = getIncludingBulgeAngle(filletInfo);
155
+ const bulge = Math.tan(angle / 4);
156
+ newVertices.push(...touchPts);
157
+ newBulges.push(bulge); // bulge for first point
158
+ newBulges.push(0); // bulge for second point
159
+ }
160
+ }
161
+ else {
162
+ newVertices.push(fPts[i].point);
163
+ newBulges.push(0);
164
+ }
165
+ }
166
+ return { points: newVertices, bulges: newBulges };
167
+ }
168
+ exports.createPolyline = createPolyline;
169
+ /**
170
+ * 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.
171
+ * @param curves THREE.Shape.curves
172
+ */
173
+ const makeCCData = (curves) => {
174
+ return curves.map((curve) => {
175
+ switch (curve.type) {
176
+ // [pStart, p1, p2, p3]
177
+ case 'CubicBezierCurve':
178
+ return [curve.type, curve.v0.toArray(), curve.v1.toArray(), curve.v2.toArray(), curve.v3.toArray()];
179
+ // [pStart, p1, p2]
180
+ case 'QuadraticBezierCurve':
181
+ return [curve.type, curve.v0.toArray(), curve.v1.toArray(), curve.v2.toArray()];
182
+ // [p1, p2]
183
+ case 'LineCurve':
184
+ return [curve.type, curve.v1.toArray(), curve.v2.toArray()];
185
+ // [...points]
186
+ case 'SplineCurve':
187
+ return [curve.type, curve.points.map((point) => point.toArray())];
188
+ // [pA, radius, angles, clockwise, rotation]
189
+ case 'EllipseCurve':
190
+ case 'ArcCurve':
191
+ const { aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation } = curve;
192
+ return [
193
+ curve.type,
194
+ [aX, aY],
195
+ [xRadius, yRadius],
196
+ [(aStartAngle / Math.PI) * 180, (aEndAngle / Math.PI) * 180],
197
+ aClockwise,
198
+ aRotation,
199
+ ];
200
+ default:
201
+ return undefined;
202
+ }
203
+ });
204
+ };
205
+ class CAD {
206
+ constructor() {
207
+ this.drawingId = null;
208
+ this.queue = Promise.resolve(0);
209
+ this.queue = Promise.resolve(0);
210
+ }
211
+ resolve(callback, ...args) {
212
+ return (this.queue = this.queue
213
+ .then(() => Promise.all(args).then(callback))
214
+ .catch(e => {
215
+ // catch is necessary to avoid error promises in the queue
216
+ }));
217
+ }
218
+ init(callback) {
219
+ const promise = new Promise(async (resolve, reject) => {
220
+ const drawingId = await classcad_1.ccAPI.base.createCCDrawing('solid');
221
+ if (!drawingId)
222
+ throw new Error('Drawing could not be created');
223
+ this.drawingId = drawingId;
224
+ await solidAPI.init(drawingId);
225
+ const publicApi = {
226
+ box: (length, width, height) => {
227
+ return this.resolve(async () => {
228
+ return solidAPI.createBox(drawingId, length, width, height);
229
+ });
230
+ },
231
+ clearSolids: () => {
232
+ return this.resolve(async () => {
233
+ return solidAPI.clearSolids(drawingId);
234
+ });
235
+ },
236
+ clearSolid: (target) => {
237
+ return this.resolve(async ([rTarget]) => {
238
+ return solidAPI.clearSolid(drawingId, rTarget);
239
+ }, target);
240
+ },
241
+ cone: (length, diameter1, diameter2) => {
242
+ return this.resolve(async () => {
243
+ return solidAPI.createCone(drawingId, length, diameter1, diameter2);
244
+ });
245
+ },
246
+ copy: (target) => {
247
+ return this.resolve(async ([rTarget]) => {
248
+ return solidAPI.copy(drawingId, rTarget);
249
+ }, target);
250
+ },
251
+ createBufferGeometry: async (solid) => {
252
+ await this.queue;
253
+ this.queue = Promise.resolve(0);
254
+ const rSolid = await solid;
255
+ await classcad_1.ccAPI.baseModeler.requestVisualisationOfObject(drawingId, rSolid);
256
+ const entity = await getEntity(drawingId, rSolid);
257
+ if (entity != null) {
258
+ return BufferGeometryUtils.mergeBufferGeometries(entity.meshes.map(m => m.geometry));
259
+ }
260
+ },
261
+ createScene: async (solid) => {
262
+ await this.queue;
263
+ this.queue = Promise.resolve(0);
264
+ const rSolid = await solid;
265
+ await classcad_1.ccAPI.baseModeler.requestVisualisationOfObject(drawingId, rSolid);
266
+ const entity = await getEntity(drawingId, rSolid);
267
+ const group = new three_1.Scene();
268
+ group.userData = { id: rSolid };
269
+ group.name = 'Solid';
270
+ if (entity != null) {
271
+ for (const mesh of entity.meshes) {
272
+ group.add(new three_1.Mesh(mesh.geometry, new three_1.MeshStandardMaterial({
273
+ color: mesh.color,
274
+ transparent: mesh.opacity < 1,
275
+ opacity: mesh.opacity,
276
+ })));
277
+ }
278
+ }
279
+ return group;
280
+ },
281
+ cylinder: (length, diameter) => {
282
+ return this.resolve(async () => {
283
+ return solidAPI.createCylinder(drawingId, length, diameter);
284
+ });
285
+ },
286
+ edgeLoops: (breps) => {
287
+ return this.resolve(async ([rBreps]) => {
288
+ return solidAPI.edgeLoops(drawingId, rBreps);
289
+ }, breps);
290
+ },
291
+ export: (solidIds) => {
292
+ return this.resolve(async ([rSolidIds]) => {
293
+ return solidAPI.export(drawingId, 'stp', rSolidIds);
294
+ }, solidIds);
295
+ },
296
+ extendSolidAtPlane: (target, point, normal, distance) => {
297
+ return this.resolve(async ([rTarget]) => {
298
+ return solidAPI.solidExtendAtPlane(drawingId, rTarget, makeNbrVec(point), makeNbrVec(normal), distance);
299
+ }, target);
300
+ },
301
+ extrude: (height, region) => {
302
+ return this.resolve(async () => {
303
+ if (region instanceof three_1.Shape) {
304
+ const curveArray = makeCCData(region.curves);
305
+ return solidAPI.createExtrudeRegion(drawingId, makeNbrVec(height), curveArray);
306
+ }
307
+ else {
308
+ return solidAPI.createExtrude(drawingId, makeNbrVec(height), region.points, region.bulges);
309
+ }
310
+ });
311
+ },
312
+ fillet: (radius, edges) => {
313
+ return this.resolve(async ([rEdges]) => {
314
+ return solidAPI.createFillet(drawingId, radius, rEdges);
315
+ }, edges);
316
+ },
317
+ import: (data) => {
318
+ return this.resolve(async () => {
319
+ return solidAPI.import(drawingId, data, 'stp');
320
+ });
321
+ },
322
+ intersect: (solidId, keepSolid, ...bodies) => {
323
+ return this.resolve(async ([rSolidId, ...rBodies]) => {
324
+ for (const rBody of rBodies) {
325
+ solidAPI.intersect(drawingId, rSolidId, keepSolid, rBody);
326
+ }
327
+ return rSolidId;
328
+ }, solidId, ...bodies);
329
+ },
330
+ load: (data) => {
331
+ return this.resolve(async () => {
332
+ const productId = await solidAPI.load(drawingId, data, 'ofb', true);
333
+ if (productId !== null) {
334
+ const drawing = (0, core_1.getDrawing)(drawingId);
335
+ const solids = drawing.structure.tree[productId].solids;
336
+ if (solids !== undefined) {
337
+ return solids.map(innerId => drawing.graphic.containers[innerId].owner);
338
+ }
339
+ }
340
+ return [];
341
+ });
342
+ },
343
+ mirror: (target, point, normal) => {
344
+ return this.resolve(async ([rTarget]) => {
345
+ return solidAPI.mirror(drawingId, rTarget, makeNbrVec(point), makeNbrEuler(normal));
346
+ }, target);
347
+ },
348
+ moveTo: (target, position) => {
349
+ return this.resolve(async ([rTarget]) => {
350
+ return solidAPI.moveTo(drawingId, rTarget, makeNbrVec(position));
351
+ }, target);
352
+ },
353
+ offset: (target, offsetDistance) => {
354
+ return this.resolve(async ([rTarget]) => {
355
+ return solidAPI.offset(drawingId, rTarget, offsetDistance);
356
+ }, target);
357
+ },
358
+ pick: (target, type, ...points) => {
359
+ return this.resolve(async ([rTarget]) => {
360
+ const pts = points.map(pt => makeNbrVec(pt));
361
+ const breps = await solidAPI.pick(drawingId, rTarget, type, ...pts);
362
+ if (breps !== null) {
363
+ return Array.isArray(breps) ? breps : [breps];
364
+ }
365
+ }, target);
366
+ },
367
+ revolve: (position, direction, angle, region) => {
368
+ return this.resolve(async () => {
369
+ if (region instanceof three_1.Shape) {
370
+ const curveArray = makeCCData(region.curves);
371
+ return solidAPI.createRevolveRegion(drawingId, makeNbrVec(position), makeNbrVec(direction), angle, curveArray);
372
+ }
373
+ else {
374
+ return solidAPI.createRevolve(drawingId, makeNbrVec(position), makeNbrVec(direction), (angle / Math.PI) * 180, region.points, region.bulges);
375
+ }
376
+ });
377
+ },
378
+ rotateTo: (target, point) => {
379
+ return this.resolve(async ([rTarget]) => {
380
+ return solidAPI.rotateTo(drawingId, rTarget, makeNbrEuler(point));
381
+ }, target);
382
+ },
383
+ save: () => {
384
+ return this.resolve(async () => {
385
+ return solidAPI.save(drawingId, 'ofb');
386
+ });
387
+ },
388
+ scale: (target, pointOrFactor) => {
389
+ return this.resolve(async ([rTarget]) => {
390
+ const lPointOrFactor = typeof pointOrFactor === 'number' ? pointOrFactor : makeNbrVec(pointOrFactor);
391
+ return solidAPI.scale(drawingId, rTarget, lPointOrFactor);
392
+ }, target);
393
+ },
394
+ setFacetingParams: (distanceTol, angleTol) => {
395
+ return this.resolve(async () => {
396
+ return classcad_1.ccAPI.common.setFacetingParameters(drawingId, distanceTol, angleTol);
397
+ });
398
+ },
399
+ slice: (target, point, normal) => {
400
+ return this.resolve(async ([rTarget]) => {
401
+ return solidAPI.slice(drawingId, rTarget, makeNbrVec(point), makeNbrVec(normal));
402
+ }, target);
403
+ },
404
+ sphere: (radius) => {
405
+ return this.resolve(async () => {
406
+ return solidAPI.createSphere(drawingId, radius);
407
+ });
408
+ },
409
+ subtract: (solidId, keepSolid, ...bodies) => {
410
+ return this.resolve(async ([rSolidId, ...rBodies]) => {
411
+ for (const rBody of rBodies) {
412
+ solidAPI.subtract(drawingId, rSolidId, keepSolid, rBody);
413
+ }
414
+ return rSolidId;
415
+ }, solidId, ...bodies);
416
+ },
417
+ union: (solidId, keepSolid, ...bodies) => {
418
+ return this.resolve(async ([rSolidId, ...rBodies]) => {
419
+ for (const rBody of rBodies) {
420
+ solidAPI.union(drawingId, rSolidId, keepSolid, rBody);
421
+ }
422
+ return rSolidId;
423
+ }, solidId, ...bodies);
424
+ },
425
+ };
426
+ callback(publicApi);
427
+ resolve(drawingId);
428
+ });
429
+ return () => promise.then(drawingId => core_1.api.getState().api.removeDrawing(drawingId));
430
+ }
431
+ destroy() {
432
+ this.drawingId && core_1.api.getState().api.removeDrawing(this.drawingId);
433
+ }
434
+ }
435
+ exports.default = CAD;
@@ -0,0 +1,32 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.waitForSelect = void 0;
7
+ const core_1 = require("@buerli.io/core");
8
+ const uuid_1 = require("uuid");
9
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
10
+ // @ts-ignore
11
+ const flat_promise_1 = __importDefault(require("flat-promise"));
12
+ async function waitForSelect(length, filter, onChange) {
13
+ const id = (0, uuid_1.v4)();
14
+ const activeDrawingId = core_1.api.getState().drawing.active;
15
+ const selApi = activeDrawingId && (0, core_1.getDrawing)(activeDrawingId).api.selection;
16
+ // Set up selection API
17
+ const { promise, resolve } = (0, flat_promise_1.default)();
18
+ const change = (selId, items, diff) => {
19
+ selApi && selApi.setItems(selId, items);
20
+ if (onChange)
21
+ onChange(resolve, items, diff);
22
+ };
23
+ const unsub = selApi && selApi.createSelector(id, filter, false, [], length, change, change);
24
+ // Wait for user interaction
25
+ selApi && selApi.activateSelector(id);
26
+ const result = await promise;
27
+ // Unsubscribe from all selections
28
+ unsub && unsub();
29
+ selApi && selApi.activateSelector(null);
30
+ return result;
31
+ }
32
+ exports.waitForSelect = waitForSelect;