TransformComputation.js 30.9 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852
import { Raycaster, Vector3, Vector2, Matrix4, Plane, Quaternion, Euler, EventDispatcher, MathUtils } from 'three';
import { getMousePosition, getMouseScreenPosition } from '@/utility/jsm/function/getMousePosition';
import { getPointsCenter } from '@/utility/jsm/function/getBoundary';
import { roundTo } from '@/utility/jsm/function/getNumber';
import { createMeasureElement, removeMeasureElement } from './createElement/createElement';

// object axis (if there is no object axis, the defalut is the same as world axis)
const axisLocal = {
    xAxis: new Vector3(1, 0, 0),
    yAxis: new Vector3(0, 1, 0),
    zAxis: new Vector3(0, 0, 1)
};
// world axis
const axisWorld = {
    xAxis: new Vector3(1, 0, 0),
    yAxis: new Vector3(0, 1, 0),
    zAxis: new Vector3(0, 0, 1)
};

class TransformComputation extends EventDispatcher {
    constructor(camera, domElement) {
        super();
        this._camera = camera;
        this._domElement = domElement;

        this.raycaster = new Raycaster();
        this.raycaster.firstHitOnly = true;
        this.mode = null;

        //
        this.isRotateAroundCenter = true;
        this.isStickToBase = false;

        this.activeMeshes = [];
        this.adjustMatrix = new Matrix4();

        this.worldPosition = new Vector3();
        this.worldQuaternion = new Quaternion();
        this.worldScale = new Vector3(1, 1, 1);
        //
        this.ismoving = false;
        this.enabled = true;

        this._controlItemExchanged = {
            x: true,
            y: true,
            z: true
        };

        this.selectPoint = null;
        // 紀錄多選模型總共的旋轉中心位置
        this.allMeshRotateCenter = new Vector3();
        this.preAllMeshRotateCenter = new Vector3();
        this.preSelectPoint = null;

        // 紀錄多選模型每一次操作的旋轉中心位置
        this.singleAllMeshRotateCenter = new Vector3();
        this.preSingleAllMeshRotateCenter = new Vector3();
        //
        this.currV = new Vector3();
        this.newV = new Vector3();

        //
        this._pointerIntersectionPlane = new Plane();
        this._intersectPlanePoint = new Vector3();
        this._preintersectPlanePoint = new Vector3();
        this._startintersectPlanePoint = new Vector3();

        this.pointerdownToUpMatrix = new Matrix4();

        this.allMeshfinalRotateAngle = {
            // 多選模型的顯示旋轉角度,物件切換時歸零
            X: 0,
            Y: 0,
            Z: 0
        };
        this.singleRotateAngle = {
            // 單一模型的每一次的旋轉角度顯示提示,mousedown、物件切換時歸零
            X: 0,
            Y: 0,
            Z: 0
        };
        this.everyRotateAngle = {
            // 最後記錄在單一模型屬性裡面的旋轉角度,mouseup、物件切換時歸零,下次選擇模型時會顯示在 UI 上
            X: 0,
            Y: 0,
            Z: 0
        };

        this.workerStop = false;

        this._updateIntersectPlane();
        this.addEvents();
    }

    addEvents = () => {
        this._domElement.addEventListener('pointerup', this.onPointerup);
        this._domElement.addEventListener('pointermove', this.onPointermove);
    };

    removeEvents = () => {
        this._domElement.removeEventListener('pointerup', this.onPointerup);
        this._domElement.removeEventListener('pointermove', this.onPointermove);
    };

    dispose = () => {
        this.removeEvents();
        this._camera = null;
        this._domElement = null;
        this.mode = null;
    };

    setActiveMeshes = (objects) => {
        this.activeMeshes = objects;
        this.updateAllMeshRotateCenter();
        this.singleRotateAngle = {
            X: 0,
            Y: 0,
            Z: 0
        };
        this.allMeshfinalRotateAngle = {
            X: 0,
            Y: 0,
            Z: 0
        };
    };

    updateAllMeshRotateCenter = () => {
        if (this.activeMeshes.length === 0) return;
        const centers = [];
        this.activeMeshes.forEach((el) => {
            centers.push(el.rotateCenter);
        });
        const center = getPointsCenter(centers);
        this.allMeshRotateCenter.copy(center);
        this.singleAllMeshRotateCenter.copy(center);
        this.preAllMeshRotateCenter.copy(this.allMeshRotateCenter);
        this.preSingleAllMeshRotateCenter.copy(this.singleAllMeshRotateCenter);
    };

    onPointerdown = (e, selecteditems) => {
        if (!this.enabled) return;
        this.ismoving = true;

        this.mode = selecteditems.name;
        const { _domElement, _camera } = this;
        const vec2d = getMousePosition(e, _domElement);
        const mouse = new Vector2(vec2d.x, vec2d.y);
        this._camera.near = 1; // raycaster only can work on camera near plane is positive
        this.raycaster.setFromCamera(mouse, _camera);
        const res = this.raycaster.intersectObject(selecteditems);
        if (res.length > 0) {
            this.selectPoint = res[0].point;
            this.preSelectPoint = res[0].point.clone();
        }
        this.currV.set(mouse.x, mouse.y, 0).unproject(_camera);
        this.pointerdownToUpMatrix = new Matrix4();

        this.raycaster.ray.intersectPlane(this._pointerIntersectionPlane, this._preintersectPlanePoint);
        this.raycaster.ray.intersectPlane(this._pointerIntersectionPlane, this._startintersectPlanePoint);

        this.singleRotateAngle = {
            X: 0,
            Y: 0,
            Z: 0
        };

        this.updateAllMeshRotateCenter();
    };

    onPointerup = (e) => {
        if (!this.enabled) return;
        if (!this.ismoving) return;
        this.doStickBottom();
        this.ismoving = false;
        removeMeasureElement();
        // TODO: send EventListener to enabled mouse control
        this.everyRotateAngle = {
            X: 0,
            Y: 0,
            Z: 0
        };
        this.preSingleAllMeshRotateCenter.copy(this.singleAllMeshRotateCenter);
    };

    onPointermove = (e) => {
        e.preventDefault();
        if (!this.enabled) return;
        if (!this.ismoving) return;

        // TODO: record undo redo
        const { _domElement, _camera } = this;
        const vec2d = getMousePosition(e, _domElement);
        const mouse = new Vector2(vec2d.x, vec2d.y);
        this._camera.near = 1; // raycaster only can work on camera near plane is positive
        this.raycaster.setFromCamera(mouse, _camera);

        this.newV.set(mouse.x, mouse.y, 0).unproject(_camera);
        this.raycaster.ray.intersectPlane(this._pointerIntersectionPlane, this._intersectPlanePoint);

        this.adjustMatrix = new Matrix4();

        const rotateCenter = new Vector3();

        const centers = [];
        this.activeMeshes.forEach((el) => {
            centers.push(el.rotateCenter);
        });
        const center = getPointsCenter(centers);
        this.allMeshRotateCenter.copy(center);
        this.singleAllMeshRotateCenter.copy(center);

        if (this.isRotateAroundCenter) {
            rotateCenter.copy(center);
        }

        this.activeMeshes.forEach((el) => {
            if (!this.isRotateAroundCenter) {
                rotateCenter.copy(el.rotateCenter);
            }
            this.selectPoint.copy(this.preSelectPoint);
            switch (this.mode) {
                case 'translate-x':
                case 'translate-xn':
                    this.translation('x');
                    break;
                case 'translate-y':
                case 'translate-yn':
                    this.translation('y');
                    break;
                case 'translate-z':
                case 'translate-zn':
                    this.translation('z');
                    break;
                case 'rotate-x':
                    this.rotation('x', rotateCenter);
                    break;
                case 'rotate-y':
                    this.rotation('y', rotateCenter);
                    break;
                case 'rotate-z':
                    this.rotation('z', rotateCenter);
                    break;
                default:
                    break;
            }
            this.updateMatrix(el, this.adjustMatrix);
        });
        if (this.mode.includes('rotate')) this.updateMeshFinalAngle();
        //
        this.selectPoint.applyMatrix4(this.adjustMatrix);
        this.pointerdownToUpMatrix.premultiply(this.adjustMatrix);

        if (this.isRotateAroundCenter || this.mode.includes('translate')) {
            this.allMeshRotateCenter.applyMatrix4(this.adjustMatrix);
            this.singleAllMeshRotateCenter.applyMatrix4(this.adjustMatrix);
        }
        //
        this.currV = this.newV.clone();
        this.createElement();
        // create element of object transform value
        this._preintersectPlanePoint = this._intersectPlanePoint.clone();
        this._camera.near = -10000;
        this._updateIntersectPlane();

        this.changeEvent();
    };

    updateMeshFinalAngle = () => {
        this.activeMeshes.forEach((el) => {
            el.finalRotateAngle.X += this.everyRotateAngle.X;
            el.finalRotateAngle.Y += this.everyRotateAngle.Y;
            el.finalRotateAngle.Z += this.everyRotateAngle.Z;
        });
    };

    changeEvent = () => {
        const center =
            this.activeMeshes.length === 1
                ? this.activeMeshes[0].rotateCenter.clone().sub(this.activeMeshes[0].geometry.originCenter)
                : this.allMeshRotateCenter.clone().sub(this.preAllMeshRotateCenter);

        const counts = this.activeMeshes.length;

        const angle = {
            X: this.allMeshfinalRotateAngle.X / counts,
            Y: this.allMeshfinalRotateAngle.Y / counts,
            Z: this.allMeshfinalRotateAngle.Z / counts
        };

        const displayAngle = this.activeMeshes.length === 1 ? this.activeMeshes[0].finalRotateAngle : angle;

        this.dispatchEvent({
            type: 'change',
            message: {
                objects: this.activeMeshes,
                mode: this.mode,
                pointerdownToUpMatrix: this.pointerdownToUpMatrix,
                isPointerupAfter: false,
                center,
                displayAngle,
                isTransformMoving: true
            }
        });
    };

    updateMatrix = (mesh, matrix) => {
        mesh.matrix.premultiply(matrix);
        mesh.matrixAutoUpdate = false;
        mesh.matrixWorldNeedsUpdate = true;
        mesh.rotateCenter.applyMatrix4(matrix);
    };

    doStickBottom = () => {
        if (this.activeMeshes.length === 0) return;
        if (this.mode !== 'rotate-x' && this.mode !== 'rotate-y' && this.mode !== 'rotate-z') {
            this.dispatchEvent({
                type: 'end',
                message: {
                    ismoving: false
                }
            });
            return;
        }
        let count = 0;
        const callback = (max, min, object) => {
            if (this.isStickToBase) {
                object.matrix.elements[14] -= min.z;
                object.rotateCenter.z -= min.z;
            }
            const update = () => {
                count++;
                if (count === this.activeMeshes.length) {
                    const centers = [];
                    this.activeMeshes.forEach((el) => {
                        centers.push(el.rotateCenter);
                    });
                    this.allMeshRotateCenter = getPointsCenter(centers);
                    const center =
                        this.activeMeshes.length === 1
                            ? object.rotateCenter.clone().sub(object.geometry.originCenter)
                            : this.allMeshRotateCenter.clone().sub(this.preAllMeshRotateCenter);
                    this.dispatchEvent({
                        type: 'end',
                        message: {
                            center,
                            ismoving: true
                        }
                    });
                }
            };

            if (object.BoxHelper) {
                const offset = new Vector3(0, 0, 0);
                if (this.isStickToBase) {
                    offset.set(0, 0, -min.z);
                }
                object.BoxHelper.setFromObjectByOffset(object, offset, update);
            }
        };
        this._updateIntersectPlane();
        this.activeMeshes.forEach((el) => {
            if (el.BoxHelper) el.BoxHelper.setFromObject(el, callback);
        });
    };

    translation = (vectortype) => {
        const { _camera } = this;
        const scalar = _camera.type === 'OrthographicCamera' ? 1 : 80;
        const deltaV = this.newV.clone().sub(this.currV).multiplyScalar(scalar);
        const deltaVNormalize = deltaV.clone().normalize();
        const localxAxis = axisLocal.xAxis.clone().applyQuaternion(this.worldQuaternion).normalize();
        const localyAxis = axisLocal.yAxis.clone().applyQuaternion(this.worldQuaternion).normalize();
        const localzAxis = axisLocal.zAxis.clone().applyQuaternion(this.worldQuaternion).normalize();
        let sign = 1;
        let dot = 0;
        switch (vectortype) {
            case 'x':
                dot = deltaVNormalize.dot(localxAxis);
                break;
            case 'y':
                dot = deltaVNormalize.dot(localyAxis);
                break;
            case 'z':
                dot = deltaVNormalize.dot(localzAxis);
                break;
            default:
                break;
        }
        // if dot value > 0 , the mouse move vector is the same as object axis; otherwise, it will move reverse vector
        sign = Math.sign(dot);
        const value = Math.abs(dot);
        // if the dot value is too small, it means the mouse move vecotr is perpendicular to object axis, it will not able to move
        if (value < 0.2) {
            deltaV.set(0, 0, 0);
        } else {
            deltaV.set(Math.abs(deltaV.x), Math.abs(deltaV.y), Math.abs(deltaV.z));
        }
        const length = deltaV.length();
        deltaV.set(length, length, length).multiplyScalar(sign); // enlarge move value
        this.doTranslate(vectortype, deltaV);
        this.translation_delta = deltaV;
    };

    doTranslate = (vectortype, delta) => {
        const localxAxis = axisLocal.xAxis.clone().applyQuaternion(this.worldQuaternion).normalize();
        const localyAxis = axisLocal.yAxis.clone();
        localyAxis.z = 0.0;
        localyAxis.applyQuaternion(this.worldQuaternion).normalize();
        const localzAxis = axisLocal.zAxis.clone().applyQuaternion(this.worldQuaternion).normalize();
        // move along to object axis
        switch (vectortype) {
            case 'x':
                delta = localxAxis.multiplyScalar(delta.x);
                break;
            case 'y':
                delta = localyAxis.multiplyScalar(delta.y);
                break;
            case 'z':
                delta = localzAxis.multiplyScalar(delta.z);
                break;
            default:
                break;
        }
        const deltaMatrix = new Matrix4().makeTranslation(delta.x, delta.y, delta.z);
        this.adjustMatrix = deltaMatrix.clone();
    };

    /**
     * MAY BE CORRECT:
     *       https://stackoverflow.com/questions/36107867/three-js-setfromrotationmatrix-strange-behavior-when-rotation-is-over-90-degrees
     *       https://github.com/mrdoob/three.js/issues/16811
     *
     * TODO: There is a 'Gimbal lock' problem due to use the 'Euler' to compute the rotation matrix,
     *       so use the draggedEulerVector and draggedEulerAngleValue to identify the rotation direction.
     *       But it may be unnecessary, it need to use the 'Quaternion' to do rotate action.
     */
    rotation = (vectortype, center) => {
        // current rotate axis
        const localxAxis = axisLocal.xAxis.clone().applyQuaternion(this.worldQuaternion).normalize();
        const localyAxis = axisLocal.yAxis.clone().applyQuaternion(this.worldQuaternion).normalize();
        const localzAxis = axisLocal.zAxis.clone().applyQuaternion(this.worldQuaternion).normalize();
        const scalar = this._camera.type === 'OrthographicCamera' ? 1 : 80;

        const draggedVector = new Quaternion().setFromUnitVectors(
            this._preintersectPlanePoint.clone().sub(this.allMeshRotateCenter).normalize(), // the vector of the position of the first time to pick the move control item to rotation center
            this._intersectPlanePoint.clone().sub(this.allMeshRotateCenter).normalize() // the vector of the updated position after the first position to rotation center
        );

        const deltaV = this.newV.clone().sub(this.currV).multiplyScalar(scalar);

        // The position of the first time to pick the move control item , it will be updated by current mouse position
        const draggedPosition = this.selectPoint.clone().add(deltaV);
        const draggedAngleValue = new Quaternion().setFromUnitVectors(
            this.selectPoint.clone().sub(this.allMeshRotateCenter),
            draggedPosition.clone().sub(this.allMeshRotateCenter)
        );

        const draggedEulerVector = new Euler().setFromQuaternion(draggedVector);
        const draggedEulerAngleValue = new Euler().setFromQuaternion(draggedAngleValue);

        let exchanged = true;
        // rotate along object axis
        let rotationAxis = new Vector3();
        switch (vectortype) {
            case 'x':
                rotationAxis = localxAxis;
                exchanged = this._controlItemExchanged.x;
                break;
            case 'y':
                rotationAxis = localyAxis;
                exchanged = this._controlItemExchanged.y;
                break;
            case 'z':
                rotationAxis = localzAxis;
                exchanged = this._controlItemExchanged.z;
                break;
            default:
                break;
        }

        let _eulerAngle = new Vector3(
            Math.sign(draggedEulerVector.x) * Math.abs(draggedEulerAngleValue.x),
            Math.sign(draggedEulerVector.y) * Math.abs(draggedEulerAngleValue.y),
            Math.sign(draggedEulerVector.z) * Math.abs(draggedEulerAngleValue.z)
        ).dot(rotationAxis);

        if (Number.isNaN(_eulerAngle) || _eulerAngle === 0) {
            return;
        }

        this.rotate_delta = _eulerAngle;

        if (exchanged) {
            const angle = Math.abs(_eulerAngle);
            if (angle < 0.02) _eulerAngle = Math.sign(_eulerAngle) * 0.025;
            else if (angle < 0.04) _eulerAngle = Math.sign(_eulerAngle) * 0.02;
        }

        const rotationAngle = _eulerAngle; // radian
        this.doRotate(vectortype, rotationAngle, center);
    };

    doRotate = (vectortype, angle, center) => {
        // current object axis
        const localxAxis = axisLocal.xAxis.clone().applyQuaternion(this.worldQuaternion).normalize();
        const localyAxis = axisLocal.yAxis.clone().applyQuaternion(this.worldQuaternion).normalize();
        const localzAxis = axisLocal.zAxis.clone().applyQuaternion(this.worldQuaternion).normalize();

        let rotationAxis = new Vector3(0, 0, 1);
        const deltaMatrix = new Matrix4();
        // the rotation axis is object axis
        switch (vectortype) {
            case 'x':
                rotationAxis = localxAxis;
                this.singleRotateAngle.X += angle;
                this.allMeshfinalRotateAngle.X += angle;
                this.everyRotateAngle.X = angle;
                break;
            case 'y':
                rotationAxis = localyAxis;
                this.singleRotateAngle.Y += angle;
                this.allMeshfinalRotateAngle.Y += angle;
                this.everyRotateAngle.Y = angle;
                break;
            case 'z':
                rotationAxis = localzAxis;
                this.singleRotateAngle.Z += angle;
                this.allMeshfinalRotateAngle.Z += angle;
                this.everyRotateAngle.Z = angle;
                break;
            default:
                break;
        }
        deltaMatrix.makeRotationAxis(rotationAxis, angle);
        const rotationCenterMatrix = new Matrix4().makeTranslation(center.x, center.y, center.z); // rotation matrix according to rotation center
        const transformMatrix = new Matrix4()
            .multiply(rotationCenterMatrix)
            .multiply(deltaMatrix)
            .multiply(rotationCenterMatrix.clone().invert());

        this.adjustMatrix = transformMatrix.clone();
    };

    _updateControlItemExchanged = (isChanged) => {
        this._controlItemExchanged =
            isChanged === undefined
                ? {
                      x: true,
                      y: true,
                      z: true
                  }
                : isChanged;
    };

    _updateIntersectPlane = () => {
        const camera = this._camera;
        const eyeVector = new Vector3(
            camera.matrixWorld.elements[8],
            camera.matrixWorld.elements[9],
            camera.matrixWorld.elements[10]
        );
        this._pointerIntersectionPlane.setFromNormalAndCoplanarPoint(eyeVector, this.allMeshRotateCenter);
    };

    // create the transform value tip when object moving
    createElement = () => {
        let text = null;
        let action = '';
        let offset = 0;
        let angle = 0;
        let axisText = '';

        switch (this.mode) {
            case 'rotate-x':
            case 'translate-x':
            case 'translate-xn':
                axisText = 'X';
                break;
            case 'rotate-y':
            case 'translate-y':
            case 'translate-yn':
                axisText = 'Y';
                break;
            case 'rotate-z':
            case 'translate-z':
            case 'translate-zn':
                axisText = 'Z';
                break;
            default:
                break;
        }

        switch (this.mode) {
            case 'translate-x':
            case 'translate-y':
            case 'translate-z':
            case 'translate-xn':
            case 'translate-yn':
            case 'translate-zn':
                offset = this.computeDistance();
                text = Math.abs(offset) > 0.0001 ? `${roundTo(offset).toFixed(2)} mm` : null;
                action = `${axisText}`;
                break;
            case 'rotate-x':
            case 'rotate-y':
            case 'rotate-z':
                angle = this.computeAngle();
                text = Math.abs(angle) > 0.000001 ? roundTo(angle, 0) + '\u00B0' : null;
                action = `${axisText}`;
                break;
            default:
                break;
        }
        if (text) {
            const { _camera, _domElement } = this;
            if (!_camera) return;
            if (!_domElement) return;
            const centerScreen = this.allMeshRotateCenter.clone().project(_camera);
            const client = getMouseScreenPosition(centerScreen, _domElement);
            createMeasureElement(client, `${action} ${text}`);
        }
    };

    computeDistance = () => {
        let distance = this.singleAllMeshRotateCenter.distanceTo(this.preSingleAllMeshRotateCenter);
        const vector = this.singleAllMeshRotateCenter.clone().sub(this.preSingleAllMeshRotateCenter);
        let localAxis = null;
        switch (this.mode) {
            case 'translate-x':
            case 'translate-xn':
                localAxis = axisLocal.xAxis.clone().applyQuaternion(this.worldQuaternion).normalize();
                break;
            case 'translate-y':
            case 'translate-yn':
                localAxis = axisLocal.yAxis.clone().applyQuaternion(this.worldQuaternion).normalize();
                break;
            case 'translate-z':
            case 'translate-zn':
                localAxis = axisLocal.zAxis.clone().applyQuaternion(this.worldQuaternion).normalize();
                break;
            default:
                break;
        }
        distance *= vector.dot(localAxis) > 0 ? 1 : -1;
        return distance;
    };

    computeAngle = () => {
        const eulerAngle = new Euler().setFromRotationMatrix(this.pointerdownToUpMatrix);
        let angle = 0;

        const counts = this.activeMeshes.length;
        eulerAngle.x = this.singleRotateAngle.X / counts;
        eulerAngle.y = this.singleRotateAngle.Y / counts;
        eulerAngle.z = this.singleRotateAngle.Z / counts;

        switch (this.mode) {
            case 'rotate-x':
                angle = MathUtils.radToDeg(eulerAngle.x);
                break;
            case 'rotate-y':
                angle = MathUtils.radToDeg(eulerAngle.y);
                break;
            case 'rotate-z':
                angle = MathUtils.radToDeg(eulerAngle.z);
                break;
            default:
                break;
        }
        angle %= 360;
        if (roundTo(angle, 0) === 360) {
            angle = 0;
        }
        return angle;
    };

    // 從 Transform Component UI 按鈕觸發的物件移動
    updateObjectTransformFromModal = (val) => {
        if (this.workerStop) return;

        this.dispatchEvent({
            type: 'transform-from-ui-start'
        });

        const { translate, rotate, isReset } = val;
        const tx = translate.X;
        const ty = translate.Y;
        const tz = translate.Z;

        const eulerx = rotate.X;
        const eulery = rotate.Y;
        const eulerz = rotate.Z;

        const localxAxis = axisLocal.xAxis.clone().applyQuaternion(this.worldQuaternion).normalize();
        const localyAxis = axisLocal.yAxis.clone().applyQuaternion(this.worldQuaternion).normalize();
        const localzAxis = axisLocal.zAxis.clone().applyQuaternion(this.worldQuaternion).normalize();

        const xrMatrix = new Matrix4().makeRotationAxis(localxAxis, eulerx, 3);
        const yrMatrix = new Matrix4().makeRotationAxis(localyAxis, eulery, 3);
        const zrMatrix = new Matrix4().makeRotationAxis(localzAxis, eulerz, 3);

        let rotateMatrix = new Matrix4();
        let translateMatrix = new Matrix4();

        if (Math.abs(eulerx) > 0) {
            rotateMatrix = xrMatrix.clone();
        } else if (Math.abs(eulery) > 0) {
            rotateMatrix = yrMatrix.clone();
        } else if (Math.abs(eulerz) > 0) {
            rotateMatrix = zrMatrix.clone();
        }

        const xtMatrix = new Matrix4().makeTranslation(tx, 0, 0);
        const ytMatrix = new Matrix4().makeTranslation(0, ty, 0);
        const ztMatrix = new Matrix4().makeTranslation(0, 0, tz);

        if (Math.abs(tx) > 0) {
            translateMatrix = xtMatrix.clone();
        } else if (Math.abs(ty) > 0) {
            translateMatrix = ytMatrix.clone();
        } else if (Math.abs(tz) > 0) {
            translateMatrix = ztMatrix.clone();
        }

        const rotateCenter = new Vector3();

        if (this.isRotateAroundCenter) {
            const centers = [];
            this.activeMeshes.forEach((el) => {
                centers.push(el.rotateCenter);
            });
            const center = getPointsCenter(centers);
            this.allMeshRotateCenter.copy(center);
            this.singleAllMeshRotateCenter.copy(center);
            rotateCenter.copy(center);
        }

        let count = 0;

        let isdispatch = true;

        for (let i = 0; i < this.activeMeshes.length; i++) {
            const el = this.activeMeshes[i];
            if (!this.isRotateAroundCenter) {
                rotateCenter.copy(el.rotateCenter);
            }
            const rotationCenterMatrix = new Matrix4().makeTranslation(rotateCenter.x, rotateCenter.y, rotateCenter.z);
            const transformMatrix = new Matrix4()
                .multiply(translateMatrix)
                .multiply(rotationCenterMatrix)
                .multiply(rotateMatrix)
                .multiply(rotationCenterMatrix.clone().invert());

            if (isReset) {
                const scaleMatrix = el.scaleMatrix ? el.scaleMatrix : new Matrix4();
                el.matrix.identity().multiply(scaleMatrix);
                el.rotateCenter.copy(el.geometry.originCenter);

                el.finalRotateAngle.X = 0;
                el.finalRotateAngle.Y = 0;
                el.finalRotateAngle.Z = 0;
            } else {
                el.matrix.premultiply(transformMatrix);

                el.finalRotateAngle.X += eulerx;
                el.finalRotateAngle.Y += eulery;
                el.finalRotateAngle.Z += eulerz;

                if (this.isStickToBase && (Math.abs(eulerx) > 0 || Math.abs(eulery) > 0 || Math.abs(eulerz) > 0)) {
                    this.workerStop = true;

                    const callback = (max, min) => {
                        el.matrix.elements[14] -= min.z;
                        el.rotateCenter.z -= min.z;
                        this._updateIntersectPlane();
                        this.workerStop = false;

                        const update = () => {
                            count++;
                            if (count === this.activeMeshes.length) {
                                const centers = [];
                                this.activeMeshes.forEach((elements) => {
                                    centers.push(elements.rotateCenter);
                                });
                                this.allMeshRotateCenter = getPointsCenter(centers);
                                const center =
                                    this.activeMeshes.length === 1
                                        ? el.rotateCenter.clone().sub(el.geometry.originCenter)
                                        : new Vector3();
                                this.dispatchEvent({
                                    type: 'end',
                                    message: {
                                        center,
                                        ismoving: true
                                    }
                                });
                            }
                        };

                        if (el.BoxHelper) {
                            el.BoxHelper.setFromObjectByOffset(el, new Vector3(0, 0, -min.z), update);
                        }
                    };

                    if (el.BoxHelper) {
                        el.BoxHelper.setFromObject(el, callback);
                    }

                    isdispatch = false;
                }
                this.allMeshRotateCenter.applyMatrix4(transformMatrix);
                this.singleAllMeshRotateCenter.applyMatrix4(transformMatrix);
            }
        }

        if (isReset) {
            const centers = [];
            this.activeMeshes.forEach((el) => {
                centers.push(el.rotateCenter);
            });
            const center = getPointsCenter(centers);
            this.allMeshRotateCenter.copy(center);
            this.singleAllMeshRotateCenter.copy(center);
            this.preAllMeshRotateCenter.copy(this.allMeshRotateCenter);
            this.preSingleAllMeshRotateCenter.copy(this.singleAllMeshRotateCenter);
        }

        this._updateIntersectPlane();

        if (isdispatch) {
            this.dispatchEvent({
                type: 'end',
                message: {}
            });
        }
    };

    setOrientBottomEnabled = (val) => {
        this.isStickToBase = val;
    };

    _setRotateAroundCenterChecked = (val) => {
        this.isRotateAroundCenter = val;
    };

    _setStickToBaseChecked = (val) => {
        this.isStickToBase = val;
    };
}

export default TransformComputation;