// Convert Three.js ES6 modules to work with global THREE object // OrbitControls adapted for global THREE class OrbitControls extends THREE.EventDispatcher { constructor(object, domElement) { super(); this.object = object; this.domElement = domElement !== undefined ? domElement : document; this.enabled = true; this.target = new THREE.Vector3(); this.minDistance = 0; this.maxDistance = Infinity; this.minZoom = 0; this.maxZoom = Infinity; this.minPolarAngle = 0; this.maxPolarAngle = Math.PI; this.minAzimuthAngle = -Infinity; this.maxAzimuthAngle = Infinity; this.enableDamping = false; this.dampingFactor = 0.05; this.enableZoom = true; this.zoomSpeed = 1.0; this.enableRotate = true; this.rotateSpeed = 1.0; this.enablePan = true; this.panSpeed = 1.0; this.screenSpacePanning = true; this.keyPanSpeed = 7.0; this.autoRotate = false; this.autoRotateSpeed = 2.0; this.enableKeys = true; this.keys = { LEFT: 37, UP: 38, RIGHT: 39, BOTTOM: 40 }; this.mouseButtons = { LEFT: THREE.MOUSE.ROTATE, MIDDLE: THREE.MOUSE.DOLLY, RIGHT: THREE.MOUSE.PAN }; this.touches = { ONE: THREE.TOUCH.ROTATE, TWO: THREE.TOUCH.DOLLY_PAN }; this.target0 = this.target.clone(); this.position0 = this.object.position.clone(); this.zoom0 = this.object.zoom; this.changeEvent = { type: 'change' }; this.startEvent = { type: 'start' }; this.endEvent = { type: 'end' }; this.state = { NONE: -1, ROTATE: 0, DOLLY: 1, PAN: 2, TOUCH_ROTATE: 3, TOUCH_PAN: 4, TOUCH_DOLLY_PAN: 5, TOUCH_DOLLY_ROTATE: 6 }; this.stateKey = this.state.NONE; this.EPS = 0.000001; this.spherical = new THREE.Spherical(); this.sphericalDelta = new THREE.Spherical(); this.scale = 1; this.panOffset = new THREE.Vector3(); this.zoomChanged = false; this.rotateStart = new THREE.Vector2(); this.rotateEnd = new THREE.Vector2(); this.rotateDelta = new THREE.Vector2(); this.panStart = new THREE.Vector2(); this.panEnd = new THREE.Vector2(); this.panDelta = new THREE.Vector2(); this.dollyStart = new THREE.Vector2(); this.dollyEnd = new THREE.Vector2(); this.dollyDelta = new THREE.Vector2(); this.init(); } init() { this.domElement.addEventListener('contextmenu', this.onContextMenu.bind(this), false); this.domElement.addEventListener('mousedown', this.onMouseDown.bind(this), false); this.domElement.addEventListener('wheel', this.onMouseWheel.bind(this), false); this.domElement.addEventListener('touchstart', this.onTouchStart.bind(this), false); this.domElement.addEventListener('touchend', this.onTouchEnd.bind(this), false); this.domElement.addEventListener('touchmove', this.onTouchMove.bind(this), false); this.domElement.addEventListener('keydown', this.onKeyDown.bind(this), false); this.update(); } update() { const offset = new THREE.Vector3(); const quat = new THREE.Quaternion().setFromUnitVectors(this.object.up, new THREE.Vector3(0, 1, 0)); const quatInverse = quat.clone().invert(); const lastPosition = new THREE.Vector3(); const lastQuaternion = new THREE.Quaternion(); const position = this.object.position; offset.copy(position).sub(this.target); offset.applyQuaternion(quat); this.spherical.setFromVector3(offset); if (this.autoRotate && this.stateKey === this.state.NONE) { this.rotateLeft(this.getAutoRotationAngle()); } if (this.enableDamping) { this.spherical.theta += this.sphericalDelta.theta * this.dampingFactor; this.spherical.phi += this.sphericalDelta.phi * this.dampingFactor; } else { this.spherical.theta += this.sphericalDelta.theta; this.spherical.phi += this.sphericalDelta.phi; } this.spherical.theta = Math.max(this.minAzimuthAngle, Math.min(this.maxAzimuthAngle, this.spherical.theta)); this.spherical.phi = Math.max(this.minPolarAngle, Math.min(this.maxPolarAngle, this.spherical.phi)); this.spherical.makeSafe(); this.spherical.radius *= this.scale; this.spherical.radius = Math.max(this.minDistance, Math.min(this.maxDistance, this.spherical.radius)); if (this.enableDamping === true) { this.target.addScaledVector(this.panOffset, this.dampingFactor); } else { this.target.add(this.panOffset); } offset.setFromSpherical(this.spherical); offset.applyQuaternion(quatInverse); position.copy(this.target).add(offset); this.object.lookAt(this.target); if (this.enableDamping === true) { this.sphericalDelta.theta *= (1 - this.dampingFactor); this.sphericalDelta.phi *= (1 - this.dampingFactor); this.panOffset.multiplyScalar(1 - this.dampingFactor); } else { this.sphericalDelta.set(0, 0, 0); this.panOffset.set(0, 0, 0); } this.scale = 1; if (this.zoomChanged || lastPosition.distanceToSquared(this.object.position) > this.EPS || 8 * (1 - lastQuaternion.dot(this.object.quaternion)) > this.EPS) { this.dispatchEvent(this.changeEvent); lastPosition.copy(this.object.position); lastQuaternion.copy(this.object.quaternion); this.zoomChanged = false; return true; } return false; } dispose() { this.domElement.removeEventListener('contextmenu', this.onContextMenu.bind(this), false); this.domElement.removeEventListener('mousedown', this.onMouseDown.bind(this), false); this.domElement.removeEventListener('wheel', this.onMouseWheel.bind(this), false); this.domElement.removeEventListener('touchstart', this.onTouchStart.bind(this), false); this.domElement.removeEventListener('touchend', this.onTouchEnd.bind(this), false); this.domElement.removeEventListener('touchmove', this.onTouchMove.bind(this), false); this.domElement.removeEventListener('keydown', this.onKeyDown.bind(this), false); } getAutoRotationAngle() { return 2 * Math.PI / 60 / 60 * this.autoRotateSpeed; } getZoomScale() { return Math.pow(0.95, this.zoomSpeed); } rotateLeft(angle) { this.sphericalDelta.theta -= angle; } rotateUp(angle) { this.sphericalDelta.phi -= angle; } panLeft(distance, objectMatrix) { const v = new THREE.Vector3(); v.setFromMatrixColumn(objectMatrix, 0); v.multiplyScalar(-distance); this.panOffset.add(v); } panUp(distance, objectMatrix) { const v = new THREE.Vector3(); if (this.screenSpacePanning === true) { v.setFromMatrixColumn(objectMatrix, 1); } else { v.setFromMatrixColumn(objectMatrix, 0); v.crossVectors(this.object.up, v); } v.multiplyScalar(distance); this.panOffset.add(v); } pan(deltaX, deltaY) { const element = this.domElement; if (this.object.isPerspectiveCamera) { const position = this.object.position; const offset = position.clone().sub(this.target); let targetDistance = offset.length(); targetDistance *= Math.tan((this.object.fov / 2) * Math.PI / 180.0); this.panLeft(2 * deltaX * targetDistance / element.clientHeight, this.object.matrix); this.panUp(2 * deltaY * targetDistance / element.clientHeight, this.object.matrix); } else if (this.object.isOrthographicCamera) { this.panLeft(deltaX * (this.object.right - this.object.left) / this.object.zoom / element.clientWidth, this.object.matrix); this.panUp(deltaY * (this.object.top - this.object.bottom) / this.object.zoom / element.clientHeight, this.object.matrix); } } dollyOut(dollyScale) { if (this.object.isPerspectiveCamera) { this.scale /= dollyScale; } else if (this.object.isOrthographicCamera) { this.object.zoom = Math.max(this.minZoom, Math.min(this.maxZoom, this.object.zoom * dollyScale)); this.object.updateProjectionMatrix(); this.zoomChanged = true; } } dollyIn(dollyScale) { if (this.object.isPerspectiveCamera) { this.scale *= dollyScale; } else if (this.object.isOrthographicCamera) { this.object.zoom = Math.max(this.minZoom, Math.min(this.maxZoom, this.object.zoom / dollyScale)); this.object.updateProjectionMatrix(); this.zoomChanged = true; } } onMouseDown(event) { if (this.enabled === false) return; event.preventDefault(); switch (event.button) { case 0: if (event.ctrlKey || event.metaKey || event.shiftKey) { if (this.enablePan === false) return; this.panStart.set(event.clientX, event.clientY); this.stateKey = this.state.PAN; } else { if (this.enableRotate === false) return; this.rotateStart.set(event.clientX, event.clientY); this.stateKey = this.state.ROTATE; } break; case 1: if (this.enableZoom === false) return; this.dollyStart.set(event.clientX, event.clientY); this.stateKey = this.state.DOLLY; break; case 2: if (this.enablePan === false) return; this.panStart.set(event.clientX, event.clientY); this.stateKey = this.state.PAN; break; } if (this.stateKey !== this.state.NONE) { document.addEventListener('mousemove', this.onMouseMove.bind(this), false); document.addEventListener('mouseup', this.onMouseUp.bind(this), false); this.dispatchEvent(this.startEvent); } } onMouseMove(event) { if (this.enabled === false) return; event.preventDefault(); switch (this.stateKey) { case this.state.ROTATE: if (this.enableRotate === false) return; this.rotateEnd.set(event.clientX, event.clientY); this.rotateDelta.subVectors(this.rotateEnd, this.rotateStart).multiplyScalar(this.rotateSpeed); const element = this.domElement; this.rotateLeft(2 * Math.PI * this.rotateDelta.x / element.clientHeight); this.rotateUp(2 * Math.PI * this.rotateDelta.y / element.clientHeight); this.rotateStart.copy(this.rotateEnd); this.update(); break; case this.state.DOLLY: if (this.enableZoom === false) return; this.dollyEnd.set(event.clientX, event.clientY); this.dollyDelta.subVectors(this.dollyEnd, this.dollyStart); if (this.dollyDelta.y > 0) { this.dollyOut(this.getZoomScale()); } else if (this.dollyDelta.y < 0) { this.dollyIn(this.getZoomScale()); } this.dollyStart.copy(this.dollyEnd); this.update(); break; case this.state.PAN: if (this.enablePan === false) return; this.panEnd.set(event.clientX, event.clientY); this.panDelta.subVectors(this.panEnd, this.panStart).multiplyScalar(this.panSpeed); this.pan(this.panDelta.x, this.panDelta.y); this.panStart.copy(this.panEnd); this.update(); break; } } onMouseUp(event) { if (this.enabled === false) return; document.removeEventListener('mousemove', this.onMouseMove.bind(this), false); document.removeEventListener('mouseup', this.onMouseUp.bind(this), false); this.dispatchEvent(this.endEvent); this.stateKey = this.state.NONE; } onMouseWheel(event) { if (this.enabled === false || this.enableZoom === false || (this.stateKey !== this.state.NONE && this.stateKey !== this.state.ROTATE)) return; event.preventDefault(); this.dispatchEvent(this.startEvent); if (event.deltaY < 0) { this.dollyIn(this.getZoomScale()); } else if (event.deltaY > 0) { this.dollyOut(this.getZoomScale()); } this.update(); this.dispatchEvent(this.endEvent); } onTouchStart(event) { if (this.enabled === false) return; event.preventDefault(); switch (event.touches.length) { case 1: if (this.enableRotate === false) return; this.rotateStart.set(event.touches[0].pageX, event.touches[0].pageY); this.stateKey = this.state.TOUCH_ROTATE; break; case 2: if (this.enableZoom === false && this.enablePan === false) return; const dx = event.touches[0].pageX - event.touches[1].pageX; const dy = event.touches[0].pageY - event.touches[1].pageY; const distance = Math.sqrt(dx * dx + dy * dy); this.dollyStart.set(0, distance); const x = 0.5 * (event.touches[0].pageX + event.touches[1].pageX); const y = 0.5 * (event.touches[0].pageY + event.touches[1].pageY); this.panStart.set(x, y); this.stateKey = this.state.TOUCH_DOLLY_PAN; break; } if (this.stateKey !== this.state.NONE) { this.dispatchEvent(this.startEvent); } } onTouchMove(event) { if (this.enabled === false) return; event.preventDefault(); switch (this.stateKey) { case this.state.TOUCH_ROTATE: if (this.enableRotate === false) return; this.rotateEnd.set(event.touches[0].pageX, event.touches[0].pageY); this.rotateDelta.subVectors(this.rotateEnd, this.rotateStart).multiplyScalar(this.rotateSpeed); const element = this.domElement; this.rotateLeft(2 * Math.PI * this.rotateDelta.x / element.clientHeight); this.rotateUp(2 * Math.PI * this.rotateDelta.y / element.clientHeight); this.rotateStart.copy(this.rotateEnd); break; case this.state.TOUCH_DOLLY_PAN: if (this.enableZoom === false && this.enablePan === false) return; const dx = event.touches[0].pageX - event.touches[1].pageX; const dy = event.touches[0].pageY - event.touches[1].pageY; const distance = Math.sqrt(dx * dx + dy * dy); this.dollyEnd.set(0, distance); this.dollyDelta.set(0, Math.pow(this.dollyEnd.y / this.dollyStart.y, this.zoomSpeed)); this.dollyOut(this.dollyDelta.y); this.dollyStart.copy(this.dollyEnd); const x = 0.5 * (event.touches[0].pageX + event.touches[1].pageX); const y = 0.5 * (event.touches[0].pageY + event.touches[1].pageY); this.panEnd.set(x, y); this.panDelta.subVectors(this.panEnd, this.panStart).multiplyScalar(this.panSpeed); this.pan(this.panDelta.x, this.panDelta.y); this.panStart.copy(this.panEnd); break; } this.update(); } onTouchEnd(event) { if (this.enabled === false) return; this.dispatchEvent(this.endEvent); this.stateKey = this.state.NONE; } onKeyDown(event) { if (this.enabled === false || this.enableKeys === false) return; switch (event.keyCode) { case this.keys.UP: this.pan(0, this.keyPanSpeed); this.update(); break; case this.keys.BOTTOM: this.pan(0, -this.keyPanSpeed); this.update(); break; case this.keys.LEFT: this.pan(this.keyPanSpeed, 0); this.update(); break; case this.keys.RIGHT: this.pan(-this.keyPanSpeed, 0); this.update(); break; } } onContextMenu(event) { if (this.enabled === false) return; event.preventDefault(); } reset() { this.target.copy(this.target0); this.object.position.copy(this.position0); this.object.zoom = this.zoom0; this.object.updateProjectionMatrix(); this.dispatchEvent(this.changeEvent); this.update(); this.stateKey = this.state.NONE; } } // STLLoader adapted for global THREE class STLLoader extends THREE.Loader { constructor(manager) { super(manager); } load(url, onLoad, onProgress, onError) { const scope = this; const loader = new THREE.FileLoader(this.manager); loader.setPath(this.path); loader.setResponseType('arraybuffer'); loader.setRequestHeader(this.requestHeader); loader.setWithCredentials(this.withCredentials); loader.load(url, function (text) { try { onLoad(scope.parse(text)); } catch (e) { if (onError) { onError(e); } else { console.error(e); } scope.manager.itemError(url); } }, onProgress, onError); } parse(data) { const binData = this.ensureBinary(data); return this.isBinary(binData) ? this.parseBinary(binData) : this.parseASCII(this.ensureString(data)); } isBinary(data) { const reader = new DataView(data); const face_size = (32 / 8 * 3) + ((32 / 8 * 3) * 3) + (16 / 8); const n_faces = reader.getUint32(80, true); const expect = 80 + (32 / 8) + (n_faces * face_size); if (expect === reader.byteLength) { return true; } const fileLength = reader.byteLength; if (80 + (32 / 8) + (n_faces * face_size) === fileLength) { return true; } if (fileLength % 50 === 0) { return false; } return true; } parseBinary(data) { const reader = new DataView(data); const faces = reader.getUint32(80, true); let r, g, b, hasColors = false, colors; let defaultR, defaultG, defaultB, alpha; for (let index = 0; index < 80 - 10; index++) { if ((reader.getUint32(index, false) == 0x434F4C4F /*COLO*/) && (reader.getUint8(index + 4) == 0x52 /*'R'*/) && (reader.getUint8(index + 5) == 0x3D /*'='*/)) { hasColors = true; colors = new Float32Array(faces * 3 * 3); defaultR = reader.getUint8(index + 6) / 255; defaultG = reader.getUint8(index + 7) / 255; defaultB = reader.getUint8(index + 8) / 255; alpha = reader.getUint8(index + 9) / 255; } } const dataOffset = 84; const faceLength = 12 * 4 + 2; const geometry = new THREE.BufferGeometry(); const vertices = new Float32Array(faces * 3 * 3); const normals = new Float32Array(faces * 3 * 3); for (let face = 0; face < faces; face++) { const start = dataOffset + face * faceLength; const normalX = reader.getFloat32(start, true); const normalY = reader.getFloat32(start + 4, true); const normalZ = reader.getFloat32(start + 8, true); if (hasColors) { const packedColor = reader.getUint16(start + 48, true); if ((packedColor & 0x8000) === 0) { r = (packedColor & 0x1F) / 31; g = ((packedColor >> 5) & 0x1F) / 31; b = ((packedColor >> 10) & 0x1F) / 31; } else { r = defaultR; g = defaultG; b = defaultB; } } for (let i = 1; i <= 3; i++) { const vertexstart = start + i * 12; const componentIdx = (face * 3 * 3) + ((i - 1) * 3); vertices[componentIdx] = reader.getFloat32(vertexstart, true); vertices[componentIdx + 1] = reader.getFloat32(vertexstart + 4, true); vertices[componentIdx + 2] = reader.getFloat32(vertexstart + 8, true); normals[componentIdx] = normalX; normals[componentIdx + 1] = normalY; normals[componentIdx + 2] = normalZ; if (hasColors) { colors[componentIdx] = r; colors[componentIdx + 1] = g; colors[componentIdx + 2] = b; } } } geometry.setAttribute('position', new THREE.BufferAttribute(vertices, 3)); geometry.setAttribute('normal', new THREE.BufferAttribute(normals, 3)); if (hasColors) { geometry.setAttribute('color', new THREE.BufferAttribute(colors, 3)); geometry.hasColors = true; geometry.alpha = alpha; } return geometry; } parseASCII(data) { const geometry = new THREE.BufferGeometry(); const patternSolid = /solid([\s\S]*?)endsolid/g; const patternFace = /facet([\s\S]*?)endfacet/g; const patternFloat = /[\s]+([+-]?(?:\d*)(?:\.\d*)?(?:[eE][+-]?\d+)?)(?=[\s]+|$)/g; const vertices = []; const normals = []; const normal = new THREE.Vector3(); let result; let groupCount = 0; let startVertex = 0; let endVertex = 0; while ((result = patternSolid.exec(data)) !== null) { startVertex = endVertex; const solid = result[0]; while ((result = patternFace.exec(solid)) !== null) { let vertexCountPerFace = 0; let normalCountPerFace = 0; const text = result[0]; while ((result = patternFloat.exec(text)) !== null) { if (normalCountPerFace < 3) { normal.setComponent(normalCountPerFace, parseFloat(result[1])); normalCountPerFace++; } else { vertices.push(parseFloat(result[1])); if (vertexCountPerFace % 3 === 0) { normals.push(normal.x, normal.y, normal.z); } vertexCountPerFace++; } } } endVertex = startVertex + (vertices.length - startVertex) / 3; groupCount++; } geometry.setAttribute('position', new THREE.Float32BufferAttribute(vertices, 3)); geometry.setAttribute('normal', new THREE.Float32BufferAttribute(normals, 3)); return geometry; } ensureBinary(buf) { if (typeof buf === 'string') { const array_buffer = new Uint8Array(buf.length); for (let i = 0; i < buf.length; i++) { array_buffer[i] = buf.charCodeAt(i) & 0xff; } return array_buffer.buffer || array_buffer; } else { return buf; } } ensureString(buf) { if (typeof buf !== 'string') { return new TextDecoder().decode(buf); } else { return buf; } } } // Attach to THREE global object THREE.OrbitControls = OrbitControls; THREE.STLLoader = STLLoader;