@classcad/client 0.0.0-stage → 3.0.0-beta.20261119090857

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.
Files changed (108) hide show
  1. package/README.md +20 -2
  2. package/bin/buerli-classcad.cjs +23 -0
  3. package/build/cjs/BuerliCadFacade.js +718 -0
  4. package/build/cjs/cclass/utils/assembly.js +687 -0
  5. package/build/cjs/cclass/utils/base.js +136 -0
  6. package/build/cjs/cclass/utils/index.js +99 -0
  7. package/build/cjs/cclass/utils/part.js +153 -0
  8. package/build/cjs/classcadEngine.js +33 -0
  9. package/build/cjs/createApi.js +71 -0
  10. package/build/cjs/createUnwrappedApi.js +43 -0
  11. package/build/cjs/facade.js +103 -0
  12. package/build/cjs/globals.js +157 -0
  13. package/build/cjs/index.js +102 -0
  14. package/build/cjs/io/AwvNodeClient.js +290 -0
  15. package/build/cjs/io/SocketIOClient.js +339 -0
  16. package/build/cjs/io/Transaction.js +134 -0
  17. package/build/cjs/io/WASMClient.js +433 -0
  18. package/build/cjs/io/WSClient.js +646 -0
  19. package/build/cjs/io/engineKey.js +202 -0
  20. package/build/cjs/re-export.js +35 -0
  21. package/build/cjs/session/host.js +479 -0
  22. package/build/cjs/session/identity.js +38 -0
  23. package/build/cjs/session/selection.js +283 -0
  24. package/build/cjs/session/share.js +229 -0
  25. package/build/cjs/session/types.js +23 -0
  26. package/build/cjs/test/SocketIOClient.spec.js +178 -0
  27. package/build/cjs/types/ComClient.js +10 -0
  28. package/build/cjs/utils/createRecursiveBufferGeometry.js +55 -0
  29. package/build/cjs/utils/createRecursiveScene.js +140 -0
  30. package/build/cjs/utils/getDifferentColoredMeshesFromEntity.js +24 -0
  31. package/build/cjs/utils/index.js +20 -0
  32. package/build/cjs/utils/polyline.js +65 -0
  33. package/build/cjs/utils/waitForSelect.js +29 -0
  34. package/build/esm/BuerliCadFacade.js +714 -0
  35. package/build/esm/cclass/utils/assembly.js +665 -0
  36. package/build/esm/cclass/utils/base.js +127 -0
  37. package/build/esm/cclass/utils/index.js +62 -0
  38. package/build/esm/cclass/utils/part.js +144 -0
  39. package/build/esm/classcadEngine.js +30 -0
  40. package/build/esm/createApi.js +66 -0
  41. package/build/esm/createUnwrappedApi.js +39 -0
  42. package/build/esm/facade.js +98 -0
  43. package/build/esm/globals.js +150 -0
  44. package/build/esm/index.js +80 -0
  45. package/build/esm/io/AwvNodeClient.js +286 -0
  46. package/build/esm/io/SocketIOClient.js +332 -0
  47. package/build/esm/io/Transaction.js +130 -0
  48. package/build/esm/io/WASMClient.js +429 -0
  49. package/build/esm/io/WSClient.js +642 -0
  50. package/build/esm/io/engineKey.js +196 -0
  51. package/build/esm/re-export.js +3 -0
  52. package/build/esm/session/host.js +474 -0
  53. package/build/esm/session/identity.js +34 -0
  54. package/build/esm/session/selection.js +277 -0
  55. package/build/esm/session/share.js +221 -0
  56. package/build/esm/session/types.js +20 -0
  57. package/build/esm/test/SocketIOClient.spec.js +178 -0
  58. package/build/esm/types/ComClient.js +7 -0
  59. package/build/esm/utils/createRecursiveBufferGeometry.js +51 -0
  60. package/build/esm/utils/createRecursiveScene.js +136 -0
  61. package/build/esm/utils/getDifferentColoredMeshesFromEntity.js +20 -0
  62. package/build/esm/utils/index.js +4 -0
  63. package/build/esm/utils/polyline.js +60 -0
  64. package/build/esm/utils/waitForSelect.js +23 -0
  65. package/build/types/BuerliCadFacade.d.ts +410 -0
  66. package/build/types/cclass/utils/assembly.d.ts +180 -0
  67. package/build/types/cclass/utils/base.d.ts +55 -0
  68. package/build/types/cclass/utils/index.d.ts +46 -0
  69. package/build/types/cclass/utils/part.d.ts +46 -0
  70. package/build/types/classcadEngine.d.ts +40 -0
  71. package/build/types/createApi.d.ts +65 -0
  72. package/build/types/createUnwrappedApi.d.ts +36 -0
  73. package/build/types/facade.d.ts +9 -0
  74. package/build/types/globals.d.ts +79 -0
  75. package/build/types/index.d.ts +82 -0
  76. package/build/types/io/AwvNodeClient.d.ts +182 -0
  77. package/build/types/io/SocketIOClient.d.ts +84 -0
  78. package/build/types/io/Transaction.d.ts +56 -0
  79. package/build/types/io/WASMClient.d.ts +239 -0
  80. package/build/types/io/WSClient.d.ts +242 -0
  81. package/build/types/io/engineKey.d.ts +137 -0
  82. package/build/types/re-export.d.ts +6 -0
  83. package/build/types/session/host.d.ts +108 -0
  84. package/build/types/session/identity.d.ts +46 -0
  85. package/build/types/session/selection.d.ts +164 -0
  86. package/build/types/session/share.d.ts +131 -0
  87. package/build/types/session/types.d.ts +113 -0
  88. package/build/types/test/SocketIOClient.spec.d.ts +0 -0
  89. package/build/types/types/ComClient.d.ts +307 -0
  90. package/build/types/utils/createRecursiveBufferGeometry.d.ts +8 -0
  91. package/build/types/utils/createRecursiveScene.d.ts +24 -0
  92. package/build/types/utils/getDifferentColoredMeshesFromEntity.d.ts +14 -0
  93. package/build/types/utils/index.d.ts +4 -0
  94. package/build/types/utils/polyline.d.ts +43 -0
  95. package/build/types/utils/waitForSelect.d.ts +4 -0
  96. package/doc/api/advanced/connection.md +488 -0
  97. package/doc/api/clients.md +2045 -0
  98. package/doc/api/engine-keys.md +230 -0
  99. package/doc/api/index.md +58 -0
  100. package/doc/api/modeling.md +682 -0
  101. package/doc/api/other.md +33 -0
  102. package/doc/api/session-sharing.md +706 -0
  103. package/package.json +59 -4
  104. package/test/classcadEngine.test.cjs +44 -0
  105. package/test/connect.test.cjs +81 -0
  106. package/test/engineKey.test.cjs +80 -0
  107. package/test/onClient.test.cjs +82 -0
  108. package/typedoc.json +8 -0
@@ -0,0 +1,718 @@
1
+ "use strict";
2
+ var _a;
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.BuerliCadFacade = void 0;
5
+ const three_1 = require("three");
6
+ const sdkjs_1 = require("@classcad/sdkjs");
7
+ const createUnwrappedApi_1 = require("./createUnwrappedApi");
8
+ const globals_1 = require("./globals");
9
+ const ComClient_1 = require("./types/ComClient");
10
+ const utils_1 = require("./utils");
11
+ /**
12
+ * Only for internal usage!
13
+ *
14
+ * Connects the drawing to ClassCAD
15
+ * This function is not part of the api itself, since it should only be used internally!
16
+ */
17
+ const connect = async (drawingId) => {
18
+ const client = globals_1.Globals.clientCache[drawingId];
19
+ if (!client) {
20
+ throw new Error("Client not ready. Did you create a valid cc drawing by calling 'createCCDrawing'?");
21
+ }
22
+ await client.connect();
23
+ (0, sdkjs_1.showMessage)({ type: 'success', text: `Connected to ClassCAD`, drawingId: drawingId });
24
+ };
25
+ /**
26
+ * Only for internal usage!
27
+ *
28
+ * Makes the drawing's client with the factory given to init, hands it to the onClient callbacks and connects it.
29
+ * Rejects with what kept the client from connecting.
30
+ */
31
+ const connectClient = async (drawingId) => {
32
+ globals_1.Globals.clientCache[drawingId] = globals_1.Globals.factory(drawingId);
33
+ (0, globals_1.clientMade)(globals_1.Globals.clientCache[drawingId], drawingId);
34
+ await connect(drawingId);
35
+ };
36
+ const assertFactory = () => {
37
+ if (!globals_1.Globals.factory) {
38
+ throw new Error('Client factory not initialized. Did you init @classcad/client by calling the function init?');
39
+ }
40
+ };
41
+ /**
42
+ * A drawing connected to ClassCAD: its API, and helpers that turn the model into three.js objects.
43
+ *
44
+ * `connect()` creates a drawing in the buerli store and connects it with a client from the factory given to
45
+ * {@link init}. Then `api` is the drawing's ClassCAD API, unwrapped: `await api.v1.part.create(…)` resolves to the
46
+ * new part's id and rejects when the engine reports an error; warnings are logged. `createBufferGeometry` and
47
+ * `createScene` make three.js geometry of what was built, `tree` and `graphic` read the drawing as the store holds
48
+ * it. The static `utils` do the facade's work for any drawing, by its id.
49
+ *
50
+ * @example
51
+ * ```ts
52
+ * import * as THREE from 'three'
53
+ * import { init, BuerliCadFacade, WASMClient } from '@classcad/client'
54
+ *
55
+ * init(drawingId => new WASMClient(drawingId, { token: 'ccpk_…' }))
56
+ *
57
+ * // A parametric flange: one facade per drawing
58
+ * export async function flange(diameter: number, thickness: number) {
59
+ * const facade = new BuerliCadFacade()
60
+ * await facade.connect('Flange')
61
+ * const { part } = facade.api.v1
62
+ * const flange = (await part.create({ name: 'Flange' }))!
63
+ * await part.cylinder({ id: flange, diameter, height: thickness })
64
+ * const geometries = (await facade.createBufferGeometry(flange)) ?? []
65
+ * const meshes = geometries.map(geometry => new THREE.Mesh(geometry, new THREE.MeshStandardMaterial()))
66
+ * // Done with it: the drawing leaves the store
67
+ * await facade.destroy()
68
+ * return meshes
69
+ * }
70
+ * ```
71
+ * @category Modeling
72
+ */
73
+ class BuerliCadFacade {
74
+ /** The id of the drawing the facade connected. Throws before `connect()`. */
75
+ get drawingId() {
76
+ if (!this._drawingId) {
77
+ throw new Error('Drawing ID not set. Did you call connect() first?');
78
+ }
79
+ return this._drawingId;
80
+ }
81
+ /**
82
+ * The drawing's ClassCAD API ({@link ClassCADApi}): calls resolve to their result and reject on an error.
83
+ * Throws before `connect()` and after `disconnect()`.
84
+ */
85
+ get api() {
86
+ if (!this._api) {
87
+ throw new Error('API not initialized. Did you call connect() first?');
88
+ }
89
+ return this._api;
90
+ }
91
+ /**
92
+ * Disconnects from ClassCAD and removes the drawing from the buerli store. The facade can `connect()` again.
93
+ *
94
+ * A failing disconnect does not keep the drawing from being removed.
95
+ */
96
+ async destroy() {
97
+ // Make sure disconnect does not prevent the drawing from being removed!
98
+ try {
99
+ await this.disconnect();
100
+ }
101
+ catch (error) { }
102
+ sdkjs_1.api.getState().api.removeDrawing(this.drawingId);
103
+ this._drawingId = undefined;
104
+ }
105
+ /**
106
+ * Creates a drawing, connects it to ClassCAD with a client from the factory given to {@link init}, and makes its
107
+ * `api` available.
108
+ *
109
+ * Rejects when the facade is connected already, when `init` has not been called, and when connecting fails: then
110
+ * with the error that kept the client from connecting (a token the key service refuses, an engine that cannot be
111
+ * reached), and the drawing it made is removed again.
112
+ *
113
+ * @param drawingName - The drawing's name in the store; by default `Drawing #<n>`.
114
+ * @returns The id of the new drawing.
115
+ */
116
+ async connect(drawingName) {
117
+ if (this._drawingId) {
118
+ // Prefer throwing here since calling connect() twice should be considered a bug
119
+ throw new Error('Drawing already connected. Did you call connect() twice?');
120
+ }
121
+ assertFactory();
122
+ const drawing = await sdkjs_1.api.getState().api.createDrawing(drawingName);
123
+ try {
124
+ await connectClient(drawing.id);
125
+ }
126
+ catch (error) {
127
+ // A drawing that did not connect leaves the store (its client is disconnected with it)
128
+ sdkjs_1.api.getState().api.removeDrawing(drawing.id);
129
+ throw error;
130
+ }
131
+ this._drawingId = drawing.id;
132
+ // Initialize the API with the drawingId, unwrap the API to get a more JS centric version
133
+ this._api = (0, createUnwrappedApi_1.createUnwrappedApi)(drawing.id);
134
+ return drawing.id;
135
+ }
136
+ /**
137
+ * Disconnects from ClassCAD. The drawing stays in the buerli store, reset (without its model), and keeps its
138
+ * client; `api` is not available until {@link BuerliCadFacade.reconnect}.
139
+ */
140
+ async disconnect() {
141
+ await _a.utils.disconnect(this.drawingId);
142
+ this._api = undefined;
143
+ }
144
+ /**
145
+ * Disconnects, connects the drawing's client again and recalculates the model (`v1.common.recalc`); then `api` is
146
+ * available again.
147
+ */
148
+ async reconnect() {
149
+ await _a.utils.reconnect(this.drawingId);
150
+ // Initialize the API with the drawingId
151
+ this._api = (0, createUnwrappedApi_1.createUnwrappedApi)(this.drawingId);
152
+ }
153
+ /**
154
+ * The structure tree (id -> node) of the drawing, as held by the buerli store.
155
+ * The tree is kept up to date by the regular structure broadcast; pass
156
+ * `refresh: true` to explicitly request it from ClassCAD first.
157
+ *
158
+ * @param opts - Options.
159
+ * @param opts.refresh - Loads the tree from ClassCAD before reading it.
160
+ * @returns The structure tree, keyed by object id.
161
+ * @example
162
+ * ```ts
163
+ * import { ccUtils, ScgClassType } from '@classcad/client'
164
+ *
165
+ * // The parts of a loaded model, by name
166
+ * const tree = await facade.tree({ refresh: true })
167
+ * const parts = Object.values(tree).filter(node => ccUtils.base.isA(node.class, ScgClassType.CCPart))
168
+ * const wheel = parts.find(node => node.name === 'Wheel')
169
+ * console.log(parts.map(node => node.name), wheel?.id)
170
+ * ```
171
+ */
172
+ async tree(opts) {
173
+ var _b, _c;
174
+ if (opts === null || opts === void 0 ? void 0 : opts.refresh) {
175
+ await _a.utils.fetchTree(this.drawingId);
176
+ }
177
+ return (_c = (_b = (0, sdkjs_1.getDrawing)(this.drawingId)) === null || _b === void 0 ? void 0 : _b.structure.tree) !== null && _c !== void 0 ? _c : {};
178
+ }
179
+ /**
180
+ * The current graphic (tessellation) of the drawing as `{ containers }`, as
181
+ * held by the buerli store. Pass `recalc: true` to recalculate first.
182
+ *
183
+ * Note that graphic element ids are payload-local - they rotate on every
184
+ * re-tessellation. The stable join between graphic and structure tree is
185
+ * `container.owner === <CC_Solid id>`.
186
+ *
187
+ * @param opts - Options.
188
+ * @param opts.recalc - Recalculates the model before reading the graphic.
189
+ * @returns The graphic containers, or `null` if the drawing is not available.
190
+ * @example
191
+ * ```ts
192
+ * import * as THREE from 'three'
193
+ *
194
+ * // Frames the camera on the model: the bounds of every body
195
+ * const graphic = await facade.graphic()
196
+ * const bounds = new THREE.Box3()
197
+ * for (const container of graphic?.containers ?? []) {
198
+ * if (!container.meshes?.length) continue
199
+ * bounds.expandByPoint(new THREE.Vector3().fromArray(container.properties.min))
200
+ * bounds.expandByPoint(new THREE.Vector3().fromArray(container.properties.max))
201
+ * }
202
+ * const center = bounds.getCenter(new THREE.Vector3())
203
+ * const size = bounds.getSize(new THREE.Vector3()).length()
204
+ * camera.position.copy(center).add(new THREE.Vector3(0, -size, size))
205
+ * camera.lookAt(center)
206
+ * ```
207
+ */
208
+ async graphic(opts) {
209
+ var _b;
210
+ if (opts === null || opts === void 0 ? void 0 : opts.recalc) {
211
+ await this.api.v1.common.recalc();
212
+ }
213
+ const containers = (_b = (0, sdkjs_1.getDrawing)(this.drawingId)) === null || _b === void 0 ? void 0 : _b.graphic.containers;
214
+ return containers ? { containers: Object.values(containers) } : null;
215
+ }
216
+ /**
217
+ * Creates the buffer geometry of any product (part or assembly).
218
+ *
219
+ * Each part, and each instance of a part in an assembly, becomes one geometry: its bodies merged, placed where it
220
+ * is in the model. Bodies the store has no graphic for yet are requested from ClassCAD first. Rejects when an id is
221
+ * not in the drawing's tree.
222
+ *
223
+ * @param objectId - The product, its instance or a solid; or several of them.
224
+ * @returns The geometries, or undefined when there is no id or nothing to show.
225
+ * @example
226
+ * ```ts
227
+ * import * as THREE from 'three'
228
+ *
229
+ * // A cylinder with diameter 20 and height 30, as a mesh of one's own
230
+ * const part = (await facade.api.v1.part.create({ name: 'Pin' }))!
231
+ * await facade.api.v1.part.cylinder({ id: part, diameter: 20, height: 30 })
232
+ * const [geometry] = (await facade.createBufferGeometry(part)) ?? []
233
+ * if (geometry) scene.add(new THREE.Mesh(geometry, new THREE.MeshStandardMaterial({ color: 'orange' })))
234
+ * ```
235
+ */
236
+ async createBufferGeometry(objectId) {
237
+ if (!objectId)
238
+ return undefined;
239
+ const cDrawing = (0, sdkjs_1.getDrawing)(this.drawingId);
240
+ const structureTree = cDrawing.structure.tree;
241
+ const ids = Array.isArray(objectId) ? objectId : [objectId];
242
+ const bufferGeomArray = [];
243
+ for (const id of ids) {
244
+ const obj = structureTree[id];
245
+ if (obj) {
246
+ await (0, utils_1.createRecursiveBufferGeometry)(obj, this.drawingId, bufferGeomArray);
247
+ }
248
+ else {
249
+ throw new Error('Object does not exist!');
250
+ }
251
+ }
252
+ if (bufferGeomArray.length > 0) {
253
+ return bufferGeomArray;
254
+ }
255
+ return undefined;
256
+ }
257
+ /**
258
+ * Creates the threeJS scene of any product (part or assembly).
259
+ *
260
+ * Assemblies and instances become groups placed as in the model, parts become groups of their bodies. A body is
261
+ * one mesh per color (`meshPerGeometry: false`, default) or one mesh per face. Bodies the store has no graphic
262
+ * for yet are requested from ClassCAD first. Rejects when an id is not in the drawing's tree.
263
+ *
264
+ * @param objectId - The product, its instance or a solid, or several of them; by default the drawing's root.
265
+ * @param options - Options.
266
+ * @param options.meshPerGeometry - Makes a mesh for each face (its `userData.id` is the face's graphic id) instead
267
+ * of merging a body's faces of one color into one mesh.
268
+ * @param options.structureOnly - Makes the nodes without geometry and materials.
269
+ * @returns The scene, its nodes and their materials.
270
+ * @example
271
+ * ```ts
272
+ * import * as THREE from 'three'
273
+ *
274
+ * // The whole assembly in a three.js scene, a node per instance
275
+ * const { scene: model, nodes } = await facade.createScene(assembly)
276
+ * scene.add(model)
277
+ * // The nodes by the id of the object they show, and by name
278
+ * nodes[`${wheel}`].rotation.z = Math.PI / 4
279
+ * ```
280
+ */
281
+ async createScene(objectId, options) {
282
+ const cDrawing = (0, sdkjs_1.getDrawing)(this.drawingId);
283
+ const structureTree = cDrawing.structure.tree;
284
+ const ids = objectId ? (Array.isArray(objectId) ? objectId : [objectId]) : [cDrawing.structure.root];
285
+ const scene = new three_1.Scene();
286
+ const result = {
287
+ nodes: {},
288
+ materials: {},
289
+ };
290
+ for (const id of ids) {
291
+ const obj = structureTree[id];
292
+ if (obj) {
293
+ await (0, utils_1.createRecursiveScene)(obj, this.drawingId, scene, result, options);
294
+ }
295
+ else {
296
+ throw new Error('Object does not exist!');
297
+ }
298
+ }
299
+ return Object.assign({ scene }, result);
300
+ }
301
+ /**
302
+ * Adds the curves of a three.js `Shape` to a shape curve of the model, in one batch of API calls.
303
+ *
304
+ * Lines, arcs and ellipses, quadratic and cubic Bézier curves and splines (as interpolation curves) are added, in
305
+ * the XY plane; other curves and the shape's holes are not.
306
+ *
307
+ * @param owner - The shape curve, from `v1.curve.shape`.
308
+ * @param shape - The outline.
309
+ * @example
310
+ * ```ts
311
+ * import * as THREE from 'three'
312
+ *
313
+ * // A disc, extruded from a three.js outline
314
+ * const part = (await facade.api.v1.part.create({ name: 'Disc' }))!
315
+ * const ei = (await facade.api.v1.part.entityInjection({ id: part }))!
316
+ * const outline = new THREE.Shape()
317
+ * outline.absarc(0, 0, 40, 0, Math.PI * 2, false)
318
+ * const curve = (await facade.api.v1.curve.shape({ id: ei }))!
319
+ * await facade.createThreeShape(curve, outline)
320
+ * await facade.api.v1.solid.extrusion({ id: ei, curves: [curve], direction: [0, 0, 5] })
321
+ * ```
322
+ */
323
+ async createThreeShape(owner, shape) {
324
+ const jobs = [];
325
+ for (const curve of shape.curves) {
326
+ switch (curve.type) {
327
+ case 'CubicBezierCurve':
328
+ const c1 = curve;
329
+ const p11 = [c1.v0.x, c1.v0.y, 0];
330
+ const p12 = [c1.v1.x, c1.v1.y, 0];
331
+ const p13 = [c1.v2.x, c1.v2.y, 0];
332
+ const p14 = [c1.v3.x, c1.v3.y, 0];
333
+ jobs.push({ api: 'v1/curve/bezierCurve', param: { id: owner, points: [p11, p12, p13, p14] } });
334
+ break;
335
+ case 'QuadraticBezierCurve':
336
+ const c2 = curve;
337
+ const p21 = [c2.v0.x, c2.v0.y, 0];
338
+ const p22 = [c2.v1.x, c2.v1.y, 0];
339
+ const p23 = [c2.v2.x, c2.v2.y, 0];
340
+ jobs.push({ api: 'v1/curve/bezierCurve', param: { id: owner, points: [p21, p22, p23] } });
341
+ break;
342
+ case 'LineCurve':
343
+ const c3 = curve;
344
+ const p31 = [c3.v1.x, c3.v1.y, 0];
345
+ const p32 = [c3.v2.x, c3.v2.y, 0];
346
+ jobs.push({ api: 'v1/curve/line', param: { id: owner, startPos: p31, endPos: p32 } });
347
+ break;
348
+ case 'SplineCurve':
349
+ const c4 = curve;
350
+ const p41 = c4.points.map((p) => [p.x, p.y, 0]);
351
+ jobs.push({ api: 'v1/curve/interpolationCurve', param: { id: owner, points: p41 } });
352
+ break;
353
+ case 'EllipseCurve':
354
+ case 'ArcCurve':
355
+ const c5 = curve;
356
+ jobs.push({
357
+ api: 'v1/curve/ellipticArc',
358
+ param: {
359
+ id: owner,
360
+ centerPos: [c5.aX, c5.aY, 0],
361
+ startAngle: c5.aStartAngle,
362
+ endAngle: c5.aEndAngle,
363
+ radius1: c5.xRadius,
364
+ radius2: c5.yRadius,
365
+ },
366
+ });
367
+ break;
368
+ default:
369
+ break;
370
+ }
371
+ }
372
+ await this.api.common.batch({ jobs });
373
+ }
374
+ /**
375
+ * Adds a polyline through the given points to a shape curve of the model, its corners rounded where a radius is
376
+ * given (`v1.curve.polyline2d`).
377
+ *
378
+ * A corner with a radius above 0 becomes an arc of that radius. A corner whose arc does not fit between its
379
+ * neighbours is left out.
380
+ *
381
+ * @param owner - The shape curve, from `v1.curve.shape`.
382
+ * @param fPts - The corners, each with the radius to round it with (0 for a sharp corner).
383
+ * @param close - Closes the polyline. Default `true`.
384
+ * @example
385
+ * ```ts
386
+ * import * as THREE from 'three'
387
+ *
388
+ * // A plate with two rounded corners, extruded from a polyline
389
+ * const part = (await facade.api.v1.part.create({ name: 'Plate' }))!
390
+ * const ei = (await facade.api.v1.part.entityInjection({ id: part }))!
391
+ * const curve = (await facade.api.v1.curve.shape({ id: ei }))!
392
+ * await facade.createPolyline(curve, [
393
+ * { point: new THREE.Vector3(0, 0, 0), radius: 0 },
394
+ * { point: new THREE.Vector3(100, 0, 0), radius: 10 },
395
+ * { point: new THREE.Vector3(100, 50, 0), radius: 10 },
396
+ * { point: new THREE.Vector3(0, 50, 0), radius: 0 },
397
+ * ])
398
+ * await facade.api.v1.solid.extrusion({ id: ei, curves: [curve], direction: [0, 0, 8] })
399
+ * ```
400
+ */
401
+ async createPolyline(owner, fPts, close = true) {
402
+ const newVertices = [];
403
+ const bulges = [];
404
+ for (let i = 0; i < fPts.length; i++) {
405
+ // if fillet point has radius, calculate fillet info, touchpoints and bulge
406
+ if (fPts[i].radius > 0) {
407
+ const j = i - 1 < 0 ? fPts.length - 1 : i - 1;
408
+ const k = i + 1 > fPts.length - 1 ? 0 : i + 1;
409
+ const filletInfo = {
410
+ control: fPts[i].point,
411
+ lineStarts: [fPts[i].point, fPts[i].point],
412
+ lineEnds: [fPts[j].point, fPts[k].point],
413
+ };
414
+ const touchPts = (0, utils_1.getTouchPoints)(filletInfo, fPts[i].radius); // returns two points
415
+ if (touchPts != undefined && (touchPts === null || touchPts === void 0 ? void 0 : touchPts.length) > 0) {
416
+ const angle = (0, utils_1.getIncludingBulgeAngle)(filletInfo);
417
+ const bulge = Math.tan(angle / 4);
418
+ newVertices.push(...touchPts);
419
+ bulges.push(bulge); // bulge for first point
420
+ bulges.push(0); // bulge for second point
421
+ }
422
+ }
423
+ else {
424
+ newVertices.push(fPts[i].point);
425
+ bulges.push(0);
426
+ }
427
+ }
428
+ const points = newVertices.map(v => [v.x, v.y, v.z]);
429
+ await this.api.curve.polyline2d({ id: owner, points: points, bulges, close });
430
+ }
431
+ /**
432
+ * Lets the user pick geometry of the given types in the 3D view, and resolves with what was picked.
433
+ *
434
+ * The drawing's geometry must be shown for selection, for example by `BuerliGeometry` of `@classcad/react` with
435
+ * `selection`. With a count it resolves once that many items are picked; with a function, that function is
436
+ * called at the first pick with one that ends the selection. Each item carries the picked element's ids, and in
437
+ * `userData` its geometry in world coordinates and its positions (`matchingPoints`).
438
+ *
439
+ * @param types - The kinds of geometry that can be picked.
440
+ * @param countOrResolver - How many items to pick (default 1), or a function that gets the function that ends the
441
+ * selection.
442
+ * @returns The picked items.
443
+ * @example
444
+ * ```ts
445
+ * import { ScgGraphicType } from '@classcad/client'
446
+ *
447
+ * // A box whose edges the user picks to round them; the drawing is shown with <BuerliGeometry selection />
448
+ * const part = (await facade.api.v1.part.create({ name: 'Block' }))!
449
+ * await facade.api.v1.part.box({ id: part, length: 60, width: 40, height: 20 })
450
+ * const edges = await facade.selectGeometry([ScgGraphicType.LINE, ScgGraphicType.ARC], 2)
451
+ * await facade.api.v1.part.fillet({ id: part, references: edges.map(edge => edge.graphicId!), radius: 4 })
452
+ * ```
453
+ * @example
454
+ * ```ts
455
+ * import { ScgGraphicType } from '@classcad/client'
456
+ *
457
+ * // As many faces as the user likes, until "Done"
458
+ * const faces = await facade.selectGeometry([ScgGraphicType.PLANE, ScgGraphicType.CYLINDER], finish => {
459
+ * doneButton.onclick = () => finish()
460
+ * })
461
+ * ```
462
+ */
463
+ async selectGeometry(types, countOrResolver) {
464
+ const drId = this.drawingId;
465
+ const filter = (scope, data) => scope === sdkjs_1.BuerliScope && types.some(type => type === data);
466
+ let selections;
467
+ if (typeof countOrResolver === 'function') {
468
+ // Callback-based selection: user controls when to stop
469
+ let resolveSelectionFn = null;
470
+ let currentItems = [];
471
+ let isCallbackInvoked = false;
472
+ selections = (await (0, utils_1.waitForSelect)(drId, Infinity, filter, (resolveSelection, items, diff) => {
473
+ // Store the resolve function and update current items on every change
474
+ resolveSelectionFn = resolveSelection;
475
+ currentItems = items;
476
+ // Invoke the user's resolver function only once, on the first call
477
+ if (!isCallbackInvoked) {
478
+ isCallbackInvoked = true;
479
+ countOrResolver(() => {
480
+ if (resolveSelectionFn) {
481
+ resolveSelectionFn(currentItems);
482
+ }
483
+ });
484
+ }
485
+ }));
486
+ }
487
+ else {
488
+ // Count-based selection: wait for exact count
489
+ const lCount = countOrResolver ? (countOrResolver < 1 ? 1 : countOrResolver) : 1;
490
+ selections = (await (0, utils_1.waitForSelect)(drId, lCount, filter, (resolveSelection, items, diff) => {
491
+ if (items.length > lCount - 1) {
492
+ resolveSelection(items);
493
+ }
494
+ }));
495
+ }
496
+ const interactionInfos = [];
497
+ for (const selection of selections) {
498
+ // Get matching points from selected geometry and add to userData. TODO: Only if in part mode useful?
499
+ const points = (await this.api.part.getGeometryPositions({ elems: [selection.data.graphicId] }))[0].positions;
500
+ const matrix = (0, sdkjs_1.getDrawing)(drId).api.structure.calculateGlobalTransformation(selection.data.productId);
501
+ const clone = selection.data.geometry.clone().applyMatrix4(matrix);
502
+ // TODO: Should the transform code be moved to something else than Measure? It's helpful for more cases than just measuring.
503
+ const transformedData = sdkjs_1.Measure.transform([selection.data], drId)[0];
504
+ const interactionInfo = (0, sdkjs_1.createInfo)({
505
+ objectId: selection.data.container.ownerId,
506
+ prodRefId: selection.data.productId,
507
+ containerId: selection.data.container.id,
508
+ graphicId: selection.data.graphicId,
509
+ // objectPath: ?, TODO: Add path to the root in expanded tree, as soon as available
510
+ userData: Object.assign(Object.assign({}, transformedData), { geometry: clone, matchingPoints: points }),
511
+ });
512
+ interactionInfos.push(interactionInfo);
513
+ }
514
+ return interactionInfos;
515
+ }
516
+ }
517
+ exports.BuerliCadFacade = BuerliCadFacade;
518
+ _a = BuerliCadFacade;
519
+ /**
520
+ * The facade's work for any drawing, by its id: connect, disconnect, undo, emission config, middleware commands.
521
+ *
522
+ * For drawings an app connects without a facade, and for the drawings of react-cad and Buerligons.
523
+ */
524
+ BuerliCadFacade.utils = {
525
+ /**
526
+ * Creates a drawing and connects it: makes its client with the factory given to {@link init}, calls the
527
+ * {@link onClient} callbacks, connects the client.
528
+ *
529
+ * Rejects when `init` has not been called. When connecting fails, the error is logged and shown as a message,
530
+ * and it resolves to null.
531
+ *
532
+ * @param drawingName - The drawing's name in the store; by default `Drawing #<n>`.
533
+ * @returns The new drawing's id, or null when it could not connect.
534
+ */
535
+ connect: async (drawingName) => {
536
+ assertFactory();
537
+ try {
538
+ const drawing = await sdkjs_1.api.getState().api.createDrawing(drawingName);
539
+ if (drawing) {
540
+ await connectClient(drawing.id);
541
+ return drawing.id;
542
+ }
543
+ return null;
544
+ }
545
+ catch (error) {
546
+ console.error(error);
547
+ (0, sdkjs_1.showMessage)({ type: 'error', text: `Connection to ClassCAD failed` });
548
+ return null;
549
+ }
550
+ },
551
+ /**
552
+ * Disconnects the drawing's client and resets the drawing: it stays in the store, without its model.
553
+ *
554
+ * Rejects when the drawing has no client.
555
+ *
556
+ * @param drawingId - The drawing.
557
+ */
558
+ disconnect: async (drawingId) => {
559
+ const client = globals_1.Globals.clientCache[drawingId];
560
+ if (!client) {
561
+ throw new Error("Client not ready. Did you create a valid cc drawing by calling 'createCCDrawing'?");
562
+ }
563
+ await client.disconnect();
564
+ (0, sdkjs_1.getDrawing)(drawingId).api.reset();
565
+ (0, sdkjs_1.getDrawing)(drawingId).api.cad.setConnected(false);
566
+ },
567
+ /**
568
+ * Disconnects the drawing, connects its client again and recalculates the model (`v1.common.recalc`).
569
+ *
570
+ * @param drawingId - The drawing.
571
+ */
572
+ reconnect: async (drawingId) => {
573
+ await _a.utils.disconnect(drawingId);
574
+ await connect(drawingId);
575
+ await (0, createUnwrappedApi_1.createUnwrappedApi)(drawingId).v1.common.recalc();
576
+ },
577
+ /**
578
+ * Loads the drawing's structure tree from the engine into the store.
579
+ *
580
+ * @param drawingId - The drawing.
581
+ */
582
+ fetchTree: async (drawingId) => {
583
+ const comClient = globals_1.Globals.clientCache[drawingId];
584
+ await comClient.requestTree();
585
+ },
586
+ /**
587
+ * Effective per-connection emission config of the drawing's client (see {@link IComClient.getEmissionConfig}).
588
+ *
589
+ * @param drawingId - The drawing.
590
+ */
591
+ getEmissionConfig: async (drawingId) => {
592
+ const comClient = globals_1.Globals.clientCache[drawingId];
593
+ return comClient.getEmissionConfig();
594
+ },
595
+ /**
596
+ * Merges `partial` into the per-connection emission config and returns the effective flags.
597
+ *
598
+ * @param drawingId - The drawing.
599
+ * @param partial - The flags to change; the others stay as they are.
600
+ */
601
+ setEmissionConfig: async (drawingId, partial) => {
602
+ const comClient = globals_1.Globals.clientCache[drawingId];
603
+ return comClient.setEmissionConfig(partial);
604
+ },
605
+ /**
606
+ * Runs `fn` with a temporary emission config and restores the previous one
607
+ * afterwards (also when `fn` throws). This is the "own config for a
608
+ * script" pattern: e.g. switch every graphic category off while a script
609
+ * issues hundreds of commands, then restore the app's config and fetch
610
+ * tree + graphic once. On engines without GetEmissionConfig/SetEmissionConfig
611
+ * ({@link EMISSION_CONFIG_UNSUPPORTED}) `fn` simply runs with the fixed config.
612
+ *
613
+ * Only the flags in `partial` are restored. Resolves to what `fn` resolves to. {@link EmissionConfig} has an
614
+ * example.
615
+ *
616
+ * @param drawingId - The drawing.
617
+ * @param partial - The flags to change while `fn` runs, e.g. `{ sendGraphic_Kernel: false }`.
618
+ * @param fn - The work to do with them.
619
+ */
620
+ withEmissionConfig: async (drawingId, partial, fn) => {
621
+ const comClient = globals_1.Globals.clientCache[drawingId];
622
+ let previous = null;
623
+ try {
624
+ previous = await comClient.getEmissionConfig();
625
+ await comClient.setEmissionConfig(partial);
626
+ }
627
+ catch (e) {
628
+ if ((e === null || e === void 0 ? void 0 : e.name) !== ComClient_1.EMISSION_CONFIG_UNSUPPORTED)
629
+ throw e;
630
+ previous = null;
631
+ }
632
+ try {
633
+ return await fn();
634
+ }
635
+ finally {
636
+ if (previous) {
637
+ // Restore only the flags we changed, taken from the previous snapshot.
638
+ const restore = {};
639
+ for (const key of Object.keys(partial)) {
640
+ ;
641
+ restore[key] = previous[key];
642
+ }
643
+ await comClient.setEmissionConfig(restore);
644
+ }
645
+ }
646
+ },
647
+ /**
648
+ * Steps back in the drawing's undo history, to `state` when given ({@link AwvNodeClient.undo}).
649
+ *
650
+ * Messages of the engine are logged as warnings; an error is logged, not thrown.
651
+ *
652
+ * @param drawingId - The drawing.
653
+ * @param state - The state to go back to, a name from the drawing's `cad.states.stack`.
654
+ */
655
+ undo: async (drawingId, state) => {
656
+ const comClient = globals_1.Globals.clientCache[drawingId];
657
+ try {
658
+ const res = await comClient.undo({ state });
659
+ const errStr = (res.messages || [])
660
+ .map(e => `undo > State: ${e.level}, Code: ${e.code}, Message: ${e.message}`)
661
+ .join('\n');
662
+ if (errStr) {
663
+ console.warn(errStr);
664
+ }
665
+ }
666
+ catch (error) {
667
+ console.error(error);
668
+ }
669
+ },
670
+ /**
671
+ * Steps forward in the drawing's undo history, to `state` when given ({@link AwvNodeClient.redo}).
672
+ *
673
+ * Messages of the engine are logged as warnings; an error is logged, not thrown.
674
+ *
675
+ * @param drawingId - The drawing.
676
+ * @param state - The state to go forward to, a name from the drawing's `cad.states.stack`.
677
+ */
678
+ redo: async (drawingId, state) => {
679
+ const comClient = globals_1.Globals.clientCache[drawingId];
680
+ try {
681
+ const res = await comClient.redo({ state });
682
+ const errStr = (res.messages || [])
683
+ .map(e => `redo > State: ${e.level}, Code: ${e.code}, Message: ${e.message}`)
684
+ .join('\n');
685
+ if (errStr) {
686
+ console.warn(errStr);
687
+ }
688
+ }
689
+ catch (error) {
690
+ console.error(error);
691
+ }
692
+ },
693
+ /**
694
+ * Sends a command of the server's own ({@link AwvNodeClient.executeMiddleware}) and resolves to the reply.
695
+ *
696
+ * Messages of the reply are logged as warnings; on an error it is logged and the call resolves to undefined.
697
+ *
698
+ * @param drawingId - The drawing.
699
+ * @param middlewareCommand - The command's name.
700
+ * @param data - Fields sent along with the command.
701
+ */
702
+ callMiddleware: async (drawingId, middlewareCommand, data) => {
703
+ const comClient = globals_1.Globals.clientCache[drawingId];
704
+ try {
705
+ const res = await comClient.executeMiddleware(middlewareCommand, data);
706
+ const errStr = (res.messages || [])
707
+ .map(e => `${middlewareCommand} > Level: ${e.level}, Code: ${e.code}, Message: ${e.message}`)
708
+ .join('\n');
709
+ if (errStr) {
710
+ console.warn(errStr);
711
+ }
712
+ return res;
713
+ }
714
+ catch (error) {
715
+ console.error(error);
716
+ }
717
+ },
718
+ };