All files / api draw-helper.ts

95.29% Statements 344/361
82.19% Branches 120/146
98.41% Functions 62/63
95.08% Lines 329/346

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703                                        5x                 5x       3x 3x 1x   3x 3x       2x 2x 1x   2x 4x 2x 2x 2x 2x 4x   2x                 4x   4x     4x 4x 4x     4x   2x 2x   2x   4x 4x 4x       2x                 2x       2x 2x     2x 2x   2x 4x 4x   4x 1x 1x 3x   3x     3x   4x 4x   2x 2x 2x         16x 16x 27x   27x 1x     27x 2x 1x   2x 2x         27x       16x 5x   16x               16x 5x 1x 1x 1x 1x 1x   4x     11x 11x 11x 11x 11x         7x   7x 7x 2x   5x   7x 2x   5x       7x       3x 3x     3x                           6x 2x   6x 6x 4x 4x 4x 4x   6x       3x 3x                     10x 10x 10x 8x 8x 1024x     51x   10x 2x 1x   1x 1x         8x       10x       3x 3x 3x 5x     3x 5x 5x 5x         6x 3x       1x     1x 1x 1x     1x 1x 2x             2x                             1x         14x 1080x             14x 14x   16x 16x 16x 1086x   16x     14x 14x 14x 14x 16x 16x   16x 1080x 1080x 1080x 1080x 1080x 1080x       14x             13x 13x   13x 48x 48x 48x 48x 42x 42x   48x 48x     13x     13x 1x 1x 1x 1x 1x           12x 12x 12x     12x 12x 12x 12x 12x 47x 47x           13x 1x   13x       6x   6x           6x 6x 18x     6x 6x   6x 6x 6x 6x 6x   6x                             18x 54x 54x 54x 54x 54x 54x   18x       8x 8x 8x 8x 8x 8x 8x   8x 8x     8x           8x 8x 8x 8x 8x 8x 8x 8x 8x       7x 7x 7x     7x       7x 3x   4x 4x 4x 4x 4x 4x 3x   1x   1x 1x 1x 1x 1x 1x 1x             1x       7x 42x               7x 7x   7x   7x 7x 168x 84x   7x 7x     7x 1x             1x     7x 1x 12x 12x     12x 12x 12x 12x 12x 12x 12x 48x           48x 12x       12x   1x 1x 1x   7x 1x 6x 6x     6x 6x 6x 6x 6x 6x 6x 24x           24x 6x   6x   1x   1x 1x   7x         31x 31x   31x 135x 204x 204x   204x         204x               31x 11x 6x 6x 6x   1x 2x 1x     24x 124x 24x               25x   25x   25x 25x 372x     25x 25x     25x 25x 25x      
 
import { Context } from "./context";
import * as Inputs from "./inputs";
import { Vector, DrawHelperCore, JSCADText } from "@bitbybit-dev/core";
import { JSCADWorkerManager } from "@bitbybit-dev/core/lib/workers";
import { OCCTWorkerManager } from "@bitbybit-dev/occt-worker";
import {
    BufferAttribute, BufferGeometry, Color, Group, Mesh, MeshPhysicalMaterial,
    Vector3, Float32BufferAttribute, LineBasicMaterial, LineSegments,
    MeshBasicMaterial, SphereGeometry, InstancedMesh, Matrix4
} from "three";
 
export class DrawHelper extends DrawHelperCore {
 
    private usedMaterials: {
        sceneId: number,
        hex: string,
        alpha: number,
        zOffset: number,
        material: MeshPhysicalMaterial
    }[] = [];
 
    constructor(
        private readonly context: Context,
        private readonly solidText: JSCADText,
        public readonly vector: Vector,
        private readonly jscadWorkerManager: JSCADWorkerManager,
        private readonly occWorkerManager: OCCTWorkerManager
    ) {
        super(vector);
    }
 
    async drawShape(inputs: Inputs.OCCT.DrawShapeDto<Inputs.OCCT.TopoDSShapePointer>): Promise<Group> {
        const options = { ...inputs };
        if (inputs.faceMaterial) {
            delete inputs.faceMaterial;
        }
        const decomposedMesh: Inputs.OCCT.DecomposedMeshDto = await this.occWorkerManager.genericCallToWorkerPromise("shapeToMesh", inputs);
        return this.handleDecomposedMesh(inputs, decomposedMesh, options);
    }
 
    async drawShapes(inputs: Inputs.OCCT.DrawShapesDto<Inputs.OCCT.TopoDSShapePointer>): Promise<Group> {
        const options = { ...inputs };
        if (inputs.faceMaterial) {
            delete inputs.faceMaterial;
        }
        const meshes: Inputs.OCCT.DecomposedMeshDto[] = await this.occWorkerManager.genericCallToWorkerPromise("shapesToMeshes", inputs);
        const meshesSolved = await Promise.all(meshes.map(async decomposedMesh => this.handleDecomposedMesh(inputs, decomposedMesh, options)));
        const shapesMeshContainer = new Group();
        shapesMeshContainer.name = "shapesMeshContainer-" + Math.random();
        this.context.scene.add(shapesMeshContainer);
        meshesSolved.forEach(mesh => {
            shapesMeshContainer.add(mesh);
        });
        return shapesMeshContainer;
    }
 
    async drawSolidOrPolygonMesh(inputs: Inputs.JSCAD.DrawSolidMeshDto<Group>): Promise<Group> {
        const res: {
            positions: number[],
            normals: number[],
            indices: number[],
            transforms: [],
        } = await this.jscadWorkerManager.genericCallToWorkerPromise("shapeToMesh", inputs);
        let meshToUpdate;
        Iif (inputs.jscadMesh && inputs.updatable) {
            meshToUpdate = inputs.jscadMesh;
        } else {
            meshToUpdate = new Group();
            meshToUpdate.name = `jscadMesh-${Math.random()}`;
            this.context.scene.add(meshToUpdate);
        }
        let colour;
        if (inputs.mesh.color && inputs.mesh.color.length > 0) {
            // if jscad geometry is colorized and color is baked on geometry it will be used over anything that set in the draw options
            const c = inputs.mesh.color;
            colour = "#" + new Color(c[0], c[1], c[2]).getHexString();
        } else {
            colour = Array.isArray(inputs.colours) ? inputs.colours[0] : inputs.colours;
        }
        const s = this.makeMesh({ ...inputs, colour }, meshToUpdate, res);
        inputs.jscadMesh = s;
        return s;
    }
 
    async drawSolidOrPolygonMeshes(inputs: Inputs.JSCAD.DrawSolidMeshesDto<Group>): Promise<Group> {
        return this.jscadWorkerManager.genericCallToWorkerPromise("shapesToMeshes", inputs).then((res: {
            positions: number[],
            normals: number[],
            indices: number[],
            transforms: [],
            color?: number[]
        }[]) => {
 
            let localOrigin: Group;
            Iif (inputs.jscadMesh && inputs.updatable) {
                localOrigin = inputs.jscadMesh;
                localOrigin.clear();
            } else {
                localOrigin = new Group();
                localOrigin.name = `jscadMeshes-${Math.random()}`;
            }
 
            const colourIsArrayAndMatches = Array.isArray(inputs.colours) && inputs.colours.length === res.length;
            const colorsAreArrays = Array.isArray(inputs.colours);
 
            res.map((r, index) => {
                const meshToUpdate = new Group();
                meshToUpdate.name = `jscadMeshes-${Math.random()}`;
                let colour;
                if (r.color) {
                    const c = r.color;
                    colour = "#" + new Color(c[0], c[1], c[2]).getHexString();
                } else Iif (colourIsArrayAndMatches) {
                    colour = inputs.colours[index];
                } else Iif (colorsAreArrays) {
                    colour = inputs.colours[0];
                } else {
                    colour = inputs.colours;
                }
                const m = this.makeMesh({ ...inputs, colour }, meshToUpdate, r);
                localOrigin.add(m);
            });
            this.context.scene.add(localOrigin);
            inputs.jscadMesh = localOrigin;
            return localOrigin;
        });
    }
 
    drawPolylinesWithColours(inputs: Inputs.Polyline.DrawPolylinesDto<Group>) {
        let colours = inputs.colours;
        const points = inputs.polylines.map((s, index) => {
            const pts = s.points;
            //handle jscad
            if (s.isClosed) {
                pts.push(pts[0]);
            }
            // sometimes polylines can have assigned colors in case of jscad for example. Such colour will overwrite the default provided colour for that polyline.
            if (s.color) {
                if (!Array.isArray(colours)) {
                    colours = [];
                }
                if (Array.isArray(s.color)) {
                    colours[index] = "#" + new Color(s.color[0], s.color[1], s.color[2]).getHexString();
                } else E{
                    colours[index] = s.color;
                }
            }
            return pts;
        });
 
        let lineSegments: LineSegments;
        if (inputs.polylinesMesh && inputs.updatable) {
            lineSegments = inputs.polylinesMesh.children[0] as LineSegments;
        }
        const polylines = this.drawPolylines(
            lineSegments,
            points,
            inputs.updatable,
            inputs.size,
            inputs.opacity,
            colours
        );
        if (inputs.polylinesMesh && inputs.updatable) {
            if (inputs.polylinesMesh.children[0].name !== polylines.name) {
                const group = new Group();
                group.name = `polylines-${Math.random()}`;
                group.add(polylines);
                this.context.scene.add(group);
                return group;
            } else {
                return inputs.polylinesMesh;
            }
        } else {
            const group = new Group();
            group.name = `polylines-${Math.random()}`;
            group.add(polylines);
            this.context.scene.add(group);
            return group;
        }
    }
 
    drawPoint(inputs: Inputs.Point.DrawPointDto<Group>): Group {
        const vectorPoints = [inputs.point];
 
        let colorsHex: string[] = [];
        if (Array.isArray(inputs.colours)) {
            colorsHex = inputs.colours;
        } else {
            colorsHex = [inputs.colours];
        }
        if (inputs.pointMesh && inputs.updatable) {
            this.updatePointsInstances(inputs.pointMesh, vectorPoints);
        } else {
            inputs.pointMesh = this.createPointSpheresMesh(
                `pointMesh-${Math.random()}`, vectorPoints, colorsHex, inputs.opacity, inputs.size, inputs.updatable
            );
        }
        return inputs.pointMesh;
    }
 
    drawPolylineClose(inputs: Inputs.Polyline.DrawPolylineDto<Group>): Group {
        const points = inputs.polyline.points;
        Iif (inputs.polyline.isClosed) {
            points.push(points[0]);
        }
        return this.drawPolyline(
            inputs.polylineMesh,
            points,
            inputs.updatable,
            inputs.size,
            inputs.opacity,
            inputs.colours
        );
    }
 
    drawPolyline(mesh: Group,
        pointsToDraw: Inputs.Base.Point3[],
        updatable: boolean, size: number, opacity: number, colours: string | string[]): Group {
        let lineSegments: LineSegments;
        if (mesh && mesh.children.length > 0) {
            lineSegments = mesh.children[0] as LineSegments;
        }
        const polylines = this.drawPolylines(lineSegments, [pointsToDraw], updatable, size, opacity, colours);
        if (!mesh) {
            mesh = new Group();
            mesh.name = `polyline-${Math.random()}`;
            mesh.add(polylines);
            this.context.scene.add(mesh);
        }
        return mesh;
    }
 
    drawCurve(inputs: Inputs.Verb.DrawCurveDto<Group>): Group {
        const points = inputs.curve.tessellate();
        return this.drawPolyline(
            inputs.curveMesh,
            points,
            inputs.updatable,
            inputs.size,
            inputs.opacity,
            inputs.colours
        );
    }
 
    drawPoints(inputs: Inputs.Point.DrawPointsDto<Group>): Group {
        const vectorPoints = inputs.points;
        let coloursHex: string[] = [];
        if (Array.isArray(inputs.colours)) {
            coloursHex = inputs.colours;
            if (coloursHex.length !== inputs.points.length) {
                coloursHex = inputs.points.map(() => coloursHex[0]);
            }
        } else {
            coloursHex = inputs.points.map(() => inputs.colours as string);
        }
        if (inputs.pointsMesh && inputs.updatable) {
            if (inputs.pointsMesh.children.length === vectorPoints.length) {
                this.updatePointsInstances(inputs.pointsMesh, vectorPoints);
            } else {
                inputs.pointsMesh.remove();
                inputs.pointsMesh = this.createPointSpheresMesh(
                    `pointsMesh-${Math.random()}`, vectorPoints, coloursHex, inputs.opacity, inputs.size, inputs.updatable
                );
            }
        } else {
            inputs.pointsMesh = this.createPointSpheresMesh(
                `pointsMesh-${Math.random()}`, vectorPoints, coloursHex, inputs.opacity, inputs.size, inputs.updatable
            );
        }
        return inputs.pointsMesh;
    }
 
    updatePointsInstances(group: Group, positions: Inputs.Base.Point3[]): void {
        const children = group.children as InstancedMesh[];
        const po = {};
        positions.forEach((pos, index) => {
            po[index] = new Vector3(pos[0], pos[1], pos[2]);
        });
 
        children.forEach((child: InstancedMesh) => {
            const index = child.userData.index;
            const p = po[index];
            child.position.set(p.x, p.y, p.z);
        });
    }
 
    drawCurves(inputs: Inputs.Verb.DrawCurvesDto<Group>): Group {
        const points = inputs.curves.map(s => ({ points: s.tessellate() }));
        return this.drawPolylinesWithColours({ polylines: points, polylinesMesh: inputs.curvesMesh, ...inputs });
    }
 
    drawSurfacesMultiColour(inputs: Inputs.Verb.DrawSurfacesColoursDto<Group>): Group {
        Iif (inputs.surfacesMesh && inputs.updatable) {
            inputs.surfacesMesh.clear();
        } else {
            inputs.surfacesMesh = new Group();
            inputs.surfacesMesh.name = `colouredSurfaces-${Math.random()}`;
            this.context.scene.add(inputs.surfacesMesh);
        }
 
        if (Array.isArray(inputs.colours)) {
            inputs.surfaces.forEach((surface, index) => {
                const srf = this.drawSurface({
                    surface,
                    colours: inputs.colours[index] ? inputs.colours[index] : inputs.colours[0],
                    updatable: inputs.updatable,
                    opacity: inputs.opacity,
                    hidden: inputs.hidden,
                });
                inputs.surfacesMesh.add(srf);
            });
        } else E{
            inputs.surfaces.forEach((surface, index) => {
                const srf = this.drawSurface({
                    surface,
                    colours: inputs.colours,
                    updatable: inputs.updatable,
                    opacity: inputs.opacity,
                    hidden: inputs.hidden,
                });
                inputs.surfacesMesh.add(srf);
            });
        }
 
        return inputs.surfacesMesh;
    }
 
    private createPointSpheresMesh(
        meshName: string, positions: Inputs.Base.Point3[], colors: string[], opacity: number, size: number, updatable: boolean): Group {
        const positionsModel = positions.map((pos, index) => {
            return {
                position: pos,
                color: colors[index],
                index
            };
        });
 
        const colorSet = Array.from(new Set(colors));
        const materialSet = colorSet.map((colour, index) => {
 
            const mat = new MeshBasicMaterial({ name: `mat-${Math.random()}` });
            mat.opacity = opacity;
            mat.color = new Color(colour);
            const positions = positionsModel.filter(s => s.color === colour);
 
            return { hex: colorSet, material: mat, positions };
        });
 
        const pointsGroup = new Group();
        pointsGroup.name = meshName;
        this.context.scene.add(pointsGroup);
        materialSet.forEach(ms => {
            const segments = ms.positions.length > 1000 ? 1 : 6;
            const geom = new SphereGeometry(size, segments, segments);
 
            ms.positions.forEach((pos, index) => {
                const instance = new InstancedMesh(geom, ms.material, 1);
                instance.name = `point-${index}-${Math.random()}`;
                instance.position.set(pos.position[0], pos.position[1], pos.position[2]);
                instance.userData = { index: pos.index };
                instance.visible = true;
                pointsGroup.add(instance);
            });
        });
 
        return pointsGroup;
    }
 
    createOrUpdateSurfacesMesh(
        meshDataConverted: { positions: number[]; indices: number[]; normals: number[]; uvs?: number[] }[],
        group: Group, updatable: boolean, material: MeshPhysicalMaterial, addToScene: boolean, hidden: boolean
    ): Group {
        const createMesh = () => {
            const geometries: BufferGeometry[] = [];
 
            meshDataConverted.forEach(mesh => {
                const geometry = new BufferGeometry();
                geometry.setAttribute("position", new BufferAttribute(Float32Array.from(mesh.positions), 3));
                geometry.setAttribute("normal", new BufferAttribute(Float32Array.from(mesh.normals), 3));
                if (mesh.uvs) {
                    geometry.setAttribute("uv", new BufferAttribute(Uint32Array.from(mesh.uvs), 2));
                    geometry.setAttribute("uv2", new BufferAttribute(Uint32Array.from(mesh.uvs), 2));
                }
                geometry.setIndex(new BufferAttribute(Uint32Array.from(mesh.indices), 1));
                geometries.push(geometry);
            });
 
            return geometries;
        };
 
        if (group && updatable) {
            group.clear();
            const geometries = createMesh();
            geometries.forEach(geometry => {
                if (material) {
                    group.add(new Mesh(geometry, material));
                } else E{
                    group.add(new Mesh(geometry));
                }
            });
        } else {
            let scene = null;
            Eif (addToScene) {
                scene = this.context.scene;
            }
 
            group = new Group();
            group.name = `surface-${Math.random()}`;
            scene.add(group);
            const geometries = createMesh();
            geometries.forEach(geometry => {
                if (material) {
                    group.add(new Mesh(geometry, material));
                } else E{
                    group.add(new Mesh(geometry));
                }
            });
        }
        if (hidden) {
            group.visible = false;
        }
        return group;
    }
 
    drawSurface(inputs: Inputs.Verb.DrawSurfaceDto<Group>): Group {
        const meshData = inputs.surface.tessellate();
 
        const meshDataConverted = {
            positions: [],
            indices: [],
            normals: [],
        };
 
        let countIndices = 0;
        meshData.faces.forEach((faceIndices) => {
            countIndices = this.parseFaces(faceIndices, meshData, meshDataConverted, countIndices);
        });
 
        const pbr = new MeshPhysicalMaterial();
        pbr.name = `pbr-${Math.random()}`;
 
        pbr.color = new Color(Array.isArray(inputs.colours) ? inputs.colours[0] : inputs.colours);
        pbr.metalness = 0.5;
        pbr.roughness = 0.7;
        pbr.opacity = inputs.opacity;
        pbr.alphaTest = 1;
 
        return this.createOrUpdateSurfacesMesh(
            [meshDataConverted],
            inputs.surfaceMesh,
            inputs.updatable,
            pbr,
            true,
            inputs.hidden,
        );
    }
 
    private parseFaces(
        faceIndices: any,
        meshData: any,
        meshDataConverted: { positions: number[]; indices: number[]; normals: number[]; },
        countIndices: number): number {
        faceIndices.reverse().forEach((x) => {
            const vn = meshData.normals[x];
            meshDataConverted.normals.push(vn[0], vn[1], vn[2]);
            const pt = meshData.points[x];
            meshDataConverted.positions.push(pt[0], pt[1], pt[2]);
            meshDataConverted.indices.push(countIndices);
            countIndices++;
        });
        return countIndices;
    }
 
    private makeMesh(inputs: { updatable: boolean, opacity: number, colour: string, hidden: boolean }, meshToUpdate: Group, res: { positions: number[]; normals: number[]; indices: number[]; transforms: []; }) {
        const pbr = new MeshPhysicalMaterial();
        pbr.name = `jscadMaterial-${Math.random()}`;
        pbr.color = new Color(inputs.colour);
        pbr.metalness = 0.4;
        pbr.roughness = 0.6;
        pbr.alphaTest = inputs.opacity;
        pbr.polygonOffsetFactor = 0;
 
        this.createMesh(res.positions, res.indices, res.normals, meshToUpdate, res.transforms, inputs.updatable, pbr);
        Iif (inputs.hidden) {
            meshToUpdate.visible = false;
        }
        return meshToUpdate;
    }
 
    private createMesh(
        positions: number[], indices: number[], normals: number[], jscadMesh: Group, transforms: number[], updatable: boolean, material: MeshPhysicalMaterial
    ): void {
        const geometry = new BufferGeometry();
        geometry.setAttribute("position", new BufferAttribute(Float32Array.from(positions), 3));
        geometry.setIndex(new BufferAttribute(Uint32Array.from(indices), 1));
        geometry.computeVertexNormals();
        const matrix4 = new Matrix4();
        matrix4.fromArray(transforms);
        jscadMesh.clear();
        jscadMesh.add(new Mesh(geometry, material));
        jscadMesh.applyMatrix4(matrix4);
    }
 
    private async handleDecomposedMesh(inputs: Inputs.OCCT.DrawShapeDto<Inputs.OCCT.TopoDSShapePointer>, decomposedMesh: Inputs.OCCT.DecomposedMeshDto, options: Inputs.Draw.DrawOcctShapeOptions) {
        const shapeGroup = new Group();
        shapeGroup.name = "brepMesh-" + Math.random();
        this.context.scene.add(shapeGroup);
        let dummy;
 
        Eif (inputs.drawFaces && decomposedMesh && decomposedMesh.faceList && decomposedMesh.faceList.length) {
 
            let pbr;
 
            if (options.faceMaterial) {
                pbr = options.faceMaterial;
            } else {
                const hex = Array.isArray(inputs.faceColour) ? inputs.faceColour[0] : inputs.faceColour;
                const alpha = inputs.faceOpacity;
                const zOffset = inputs.drawEdges ? 2 : 0;
                const materialCached = this.usedMaterials.find(s => s.sceneId === this.context.scene.id && s.hex === hex && s.alpha === alpha && s.zOffset === zOffset);
                this.usedMaterials = this.usedMaterials.filter(s => s.sceneId === this.context.scene.id);
                if (materialCached) {
                    pbr = materialCached.material;
                } else {
                    const pbmat = new MeshPhysicalMaterial();
 
                    pbmat.color = new Color(hex);
                    pbmat.metalness = 0.4;
                    pbmat.roughness = 0.8;
                    pbmat.alphaTest = alpha;
                    pbmat.polygonOffset = true;
                    pbmat.polygonOffsetFactor = zOffset;
                    this.usedMaterials.push({
                        sceneId: this.context.scene.id,
                        hex,
                        alpha: alpha,
                        zOffset: zOffset,
                        material: pbmat
                    });
                    pbr = pbmat;
                }
            }
 
            const meshData = decomposedMesh.faceList.map(face => {
                return {
                    positions: face.vertex_coord,
                    normals: face.normal_coord,
                    indices: face.tri_indexes,
                    uvs: face.uvs,
                };
            });
 
            const mesh = this.createOrUpdateSurfacesMesh(meshData, dummy, false, pbr, true, false);
            shapeGroup.add(mesh);
        }
        Eif (inputs.drawEdges && decomposedMesh && decomposedMesh.edgeList && decomposedMesh.edgeList.length) {
 
            const polylineEdgePoints = [];
            decomposedMesh.edgeList.forEach(edge => {
                const ev = edge.vertex_coord.filter(s => s !== undefined);
                polylineEdgePoints.push(ev);
            });
            const line = this.drawPolylines(undefined, polylineEdgePoints, false, inputs.edgeWidth, inputs.edgeOpacity, inputs.edgeColour);
            shapeGroup.add(line);
        }
 
        if (inputs.drawVertices && decomposedMesh && decomposedMesh.pointsList && decomposedMesh.pointsList.length) {
            const mesh = this.drawPoints({
                points: decomposedMesh.pointsList,
                opacity: 1,
                size: inputs.vertexSize,
                colours: inputs.vertexColour,
                updatable: false,
            });
            shapeGroup.add(mesh);
        }
 
        if (inputs.drawEdgeIndexes) {
            const promises = decomposedMesh.edgeList.map(async (edge) => {
                let edgeMiddle = edge.middle_point;
                Iif (edgeMiddle === undefined) {
                    edgeMiddle = this.computeEdgeMiddlePos(edge);
                }
                const tdto = new Inputs.JSCAD.TextDto();
                tdto.text = `${edge.edge_index + 1}`;
                tdto.height = inputs.edgeIndexHeight;
                tdto.lineSpacing = 1.5;
                const t = await this.solidText.createVectorText(tdto);
                const texts = t.map(s => {
                    const res = s.map(c => {
                        return [
                            c[0],
                            c[1] + 0.05,
                            0
                        ] as Inputs.Base.Vector3;
                    });
                    const movedOnPosition = res.map(r => this.vector.add({ first: r, second: edgeMiddle }));
                    return movedOnPosition as Inputs.Base.Vector3[];
                });
 
                // texts.forEach(te => textPolylines.push(te));
                return texts;
            });
            const textPolylines = await Promise.all(promises);
            const edgeMesh = this.drawPolylines(undefined, textPolylines.flat(), false, 0.2, 1, inputs.edgeIndexColour);
            shapeGroup.add(edgeMesh);
        }
        if (inputs.drawFaceIndexes) {
            const promises = decomposedMesh.faceList.map(async (face) => {
                let faceMiddle = face.center_point;
                Iif (faceMiddle === undefined) {
                    faceMiddle = this.computeFaceMiddlePos(face.vertex_coord_vec) as Inputs.Base.Point3;
                }
                const tdto = new Inputs.JSCAD.TextDto();
                tdto.text = `${face.face_index}`;
                tdto.height = inputs.faceIndexHeight;
                tdto.lineSpacing = 1.5;
                const t = await this.solidText.createVectorText(tdto);
                const texts = t.map(s => {
                    const res = s.map(c => {
                        return [
                            c[0],
                            c[1] + 0.05,
                            0
                        ] as Inputs.Base.Point3;
                    });
                    const movedOnPosition = res.map(r => this.vector.add({ first: r, second: faceMiddle }));
                    return movedOnPosition as Inputs.Base.Point3[];
                });
                return texts;
            });
            const textPolylines = await Promise.all(promises);
 
            const faceMesh = this.drawPolylines(undefined, textPolylines.flat(), false, 0.2, 1, inputs.faceIndexColour);
            faceMesh.parent = shapeGroup;
        }
        return shapeGroup;
    }
 
    private drawPolylines(lineSegments: LineSegments, polylinesPoints: Inputs.Base.Vector3[][], updatable: boolean,
        size: number, opacity: number, colours: string | string[]) {
        if (polylinesPoints && polylinesPoints.length > 0) {
            const lineVertices = [];
 
            polylinesPoints.forEach(pts => {
                for (let i = 0; i < pts.length - 1; i++) {
                    const c = pts[i];
                    const n = pts[i + 1];
 
                    lineVertices.push(new Vector3(
                        c[0],
                        c[1],
                        c[2]
                    ));
                    lineVertices.push(new Vector3(
                        n[0],
                        n[1],
                        n[2]
                    ));
                }
            });
            let lines: LineSegments;
            if (lineSegments && updatable) {
                if (lineSegments?.userData?.linesForRenderLengths === polylinesPoints.map(l => l.length).toString()) {
                    lineSegments.geometry.clearGroups();
                    lineSegments.geometry.setFromPoints(lineVertices);
                    return lineSegments;
                } else {
                    lines = this.createLineGeometry(lineVertices, colours, size);
                    lines.userData = { linesForRenderLengths: polylinesPoints.map(l => l.length).toString() };
                    return lines;
                }
            } else {
                lines = this.createLineGeometry(lineVertices, colours, size);
                lines.userData = { linesForRenderLengths: polylinesPoints.map(l => l.length).toString() };
                return lines;
            }
        } else E{
            return undefined;
        }
    }
 
    private createLineGeometry(lineVertices: any[], colours: string | string[], size: number) {
        const lineGeometry = new BufferGeometry().setFromPoints(lineVertices);
 
        const color = Array.isArray(colours) ? new Color(colours[0]) : new Color(colours);
 
        const lineColors = [];
        for (let i = 0; i < lineVertices.length; i++) {
            lineColors.push(color.r, color.g, color.b);
        }
 
        lineGeometry.setAttribute("color", new Float32BufferAttribute(lineColors, 3));
        const lineMaterial = new LineBasicMaterial({
            color: 0xffffff, linewidth: size, vertexColors: true
        });
        const line = new LineSegments(lineGeometry, lineMaterial);
        line.name = "lines-" + Math.random();
        return line;
    }
}