vole
Site
Clone
Read only, no credentials:
https://rodent.software/vole.git
Write over SSH with a registered key:
git clone ssh://git@rodent.software/vole.git
Self-hosted forge that lives in your Git repo.
Blame · server/web/static/models/model-viewer.js
Line attribution on main · 658 line(s)
|
3b2bcc30
Keenan Nemetz
13d ago
|
1 | // The 3D preview for model blobs and model diffs. |
| 2 | // | |
| 3 | // app.js imports this module only when the page contains a [data-model] | |
| 4 | // element, so a page with no model downloads neither this file nor the three.js | |
| 5 | // bundle it imports. The host element is rendered by the server with a download | |
| 6 | // link inside, so a reader without JavaScript or without WebGL still has the | |
| 7 | // file. | |
| 8 | // | |
|
d4764b08
Keenan Nemetz
9d ago
|
9 | // A viewer is a canvas, a pointer, a few buttons and a small orientation cube. |
|
f865b269
Keenan Nemetz
9d ago
|
10 | // A drag turns the model the way a turntable turns what stands on it: sideways |
| 11 | // spins it about its own up axis, up and down tips it over the top, and the two | |
| 12 | // mix without ever rolling it. The wheel or a pinch zooms, and the buttons | |
| 13 | // repeat the zoom, reset the view and toggle a wireframe, so a reader who only | |
| 14 | // clicks can still move around. The cube puts a named side of the model toward | |
|
7d989146
Keenan Nemetz
8d ago
|
15 | // the reader. Two viewers in one diff turn and zoom together unless the reader |
| 16 | // unlinks them. The model is centred and scaled to a unit sphere, so a part | |
| 17 | // exported in millimetres and one in metres frame the same way. | |
|
3b2bcc30
Keenan Nemetz
13d ago
|
18 | |
| 19 | import { | |
| 20 | WebGLRenderer, Scene, PerspectiveCamera, HemisphereLight, DirectionalLight, | |
|
32eefb58
Keenan Nemetz
9d ago
|
21 | Box3, Vector3, Matrix4, Quaternion, Group, Mesh, MeshStandardMaterial, |
| 22 | SRGBColorSpace, | |
|
3b2bcc30
Keenan Nemetz
13d ago
|
23 | OrbitControls, STLLoader, OBJLoader, GLTFLoader, ThreeMFLoader, |
| 24 | } from './three.bundle.js'; | |
| 25 | ||
| 26 | const FORMATS = new Set(['stl', 'obj', 'gltf', 'glb', '3mf']); | |
| 27 | ||
|
d4764b08
Keenan Nemetz
9d ago
|
28 | // VIEW_FACES is the cube's six face names and labels. The order is the DOM |
| 29 | // order; the buttons are laid out in CSS, not in this order. | |
| 30 | const VIEW_FACES = [ | |
| 31 | ['front', 'Front'], | |
| 32 | ['back', 'Back'], | |
| 33 | ['right', 'Right'], | |
| 34 | ['left', 'Left'], | |
| 35 | ['top', 'Top'], | |
| 36 | ['bottom', 'Bottom'], | |
| 37 | ]; | |
| 38 | ||
|
3b2bcc30
Keenan Nemetz
13d ago
|
39 | // extension is the URL's file extension, ignoring a query or fragment the raw |
| 40 | // link may carry. | |
| 41 | const extension = (url) => { | |
| 42 | const clean = (url || '').split(/[?#]/)[0]; | |
| 43 | const dot = clean.lastIndexOf('.'); | |
| 44 | return dot < 0 ? '' : clean.slice(dot + 1).toLowerCase(); | |
| 45 | }; | |
| 46 | ||
| 47 | // formatOf prefers the server's data-format and falls back to the URL, so an | |
| 48 | // element a future surface writes without the attribute still draws. | |
| 49 | const formatOf = (host) => { | |
| 50 | const named = (host.dataset.format || '').toLowerCase(); | |
| 51 | if (FORMATS.has(named)) return named; | |
| 52 | const ext = extension(host.dataset.model); | |
| 53 | return FORMATS.has(ext) ? ext : ''; | |
| 54 | }; | |
| 55 | ||
| 56 | const loaderFor = (format) => { | |
| 57 | switch (format) { | |
| 58 | case 'stl': return new STLLoader(); | |
| 59 | case 'obj': return new OBJLoader(); | |
| 60 | case 'gltf': | |
| 61 | case 'glb': return new GLTFLoader(); | |
| 62 | case '3mf': return new ThreeMFLoader(); | |
| 63 | default: return null; | |
| 64 | } | |
| 65 | }; | |
| 66 | ||
|
0be96824
Keenan Nemetz
11d ago
|
67 | // button makes one control. label is what a reader sees, and title is the same |
| 68 | // action in words: it is the tooltip, the accessible name for a symbol, and what | |
| 69 | // a screen reader announces. | |
| 70 | const button = (label, title, onClick) => { | |
|
3b2bcc30
Keenan Nemetz
13d ago
|
71 | const element = document.createElement('button'); |
| 72 | element.type = 'button'; | |
| 73 | element.className = 'model-tool'; | |
| 74 | element.textContent = label; | |
|
0be96824
Keenan Nemetz
11d ago
|
75 | element.title = title; |
| 76 | element.setAttribute('aria-label', title); | |
|
3b2bcc30
Keenan Nemetz
13d ago
|
77 | element.addEventListener('click', onClick); |
| 78 | return element; | |
| 79 | }; | |
| 80 | ||
|
32eefb58
Keenan Nemetz
9d ago
|
81 | // pressed shows a button that holds a mode. The attribute carries the same state |
| 82 | // to a screen reader, so the drawn and announced states cannot drift apart. | |
| 83 | const pressed = (element, on) => { | |
| 84 | element.classList.toggle('active', on); | |
| 85 | element.setAttribute('aria-pressed', on ? 'true' : 'false'); | |
| 86 | }; | |
| 87 | ||
| 88 | // reduceMotion reports the reader's preference, so a snap can arrive at its view | |
| 89 | // at once instead of turning there. | |
| 90 | const reduceMotion = () => typeof matchMedia === 'function' | |
| 91 | && matchMedia('(prefers-reduced-motion: reduce)').matches; | |
| 92 | ||
| 93 | // The two sides of a diff are one file before and after, drawn in one | |
| 94 | // .media-diff. Each is framed the same way, so an orientation means the same | |
|
7d989146
Keenan Nemetz
8d ago
|
95 | // thing in both, and a reader comparing them wants them turned and zoomed |
| 96 | // together. Viewers that share a container publish their view to the rest | |
| 97 | // unless the reader unlinks them to look at each side on its own. | |
|
32eefb58
Keenan Nemetz
9d ago
|
98 | const pairs = new WeakMap(); |
| 99 | ||
| 100 | // pairFor is the shared turn for a host's container, or null when the container | |
| 101 | // holds one model and there is nothing to turn with. | |
| 102 | const pairFor = (host) => { | |
| 103 | const container = host.closest('.media-diff'); | |
| 104 | if (!container || container.querySelectorAll('[data-model]').length < 2) return null; | |
| 105 | let pair = pairs.get(container); | |
| 106 | if (!pair) { | |
|
7d989146
Keenan Nemetz
8d ago
|
107 | pair = { linked: true, turn: null, distance: 0, viewers: new Set() }; |
|
32eefb58
Keenan Nemetz
9d ago
|
108 | pairs.set(container, pair); |
| 109 | } | |
| 110 | return pair; | |
| 111 | }; | |
| 112 | ||
|
3b2bcc30
Keenan Nemetz
13d ago
|
113 | // disposeTree frees the geometry, materials and textures a loaded model owns. |
| 114 | // A viewer that is swapped out of the page must give its GPU memory back. | |
| 115 | const disposeTree = (node) => { | |
| 116 | node.traverse((child) => { | |
| 117 | if (child.geometry && child.geometry.dispose) child.geometry.dispose(); | |
| 118 | const materials = child.material == null ? [] | |
| 119 | : (Array.isArray(child.material) ? child.material : [child.material]); | |
| 120 | for (const material of materials) { | |
| 121 | if (!material) continue; | |
| 122 | for (const value of Object.values(material)) { | |
| 123 | if (value && value.isTexture && value.dispose) value.dispose(); | |
| 124 | } | |
| 125 | if (material.dispose) material.dispose(); | |
| 126 | } | |
| 127 | }); | |
| 128 | }; | |
| 129 | ||
| 130 | export const upgrade = (host) => { | |
| 131 | if (!host || host.dataset.modelReady) return; | |
| 132 | // An HTMX swap can replace a pane before the module has finished loading. | |
| 133 | if (!host.isConnected) return; | |
| 134 | host.dataset.modelReady = 'loading'; | |
| 135 | ||
| 136 | const url = host.dataset.model || ''; | |
| 137 | const format = formatOf(host); | |
| 138 | const fallback = host.querySelector('.model-fallback'); | |
| 139 | ||
| 140 | const status = document.createElement('p'); | |
| 141 | status.className = 'model-status muted'; | |
| 142 | status.textContent = 'Loading model…'; | |
| 143 | host.append(status); | |
| 144 | ||
| 145 | const fail = (message) => { | |
| 146 | host.dataset.modelReady = 'failed'; | |
| 147 | status.textContent = message; | |
| 148 | }; | |
| 149 | ||
| 150 | const loader = format ? loaderFor(format) : null; | |
| 151 | if (!url || !loader) { | |
| 152 | fail('This file cannot be previewed here.'); | |
| 153 | return; | |
| 154 | } | |
| 155 | ||
| 156 | const canvas = document.createElement('canvas'); | |
| 157 | canvas.className = 'model-canvas'; | |
| 158 | canvas.setAttribute('role', 'img'); | |
| 159 | canvas.setAttribute('aria-label', '3D preview of ' + (host.dataset.title || 'this model')); | |
| 160 | host.prepend(canvas); | |
| 161 | ||
| 162 | let renderer; | |
| 163 | try { | |
| 164 | renderer = new WebGLRenderer({ canvas, antialias: true, alpha: true }); | |
| 165 | } catch (_) { | |
| 166 | canvas.remove(); | |
| 167 | fail('This browser cannot draw a 3D preview.'); | |
| 168 | return; | |
| 169 | } | |
| 170 | renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2)); | |
| 171 | renderer.outputColorSpace = SRGBColorSpace; | |
| 172 | ||
| 173 | const scene = new Scene(); | |
|
6064a745
Keenan Nemetz
11d ago
|
174 | // The placed model lives under this group, and a drag turns the group. The |
| 175 | // camera keeps its line to the model, so the turn has no pole to stop at. | |
| 176 | const spin = new Group(); | |
| 177 | scene.add(spin); | |
|
3b2bcc30
Keenan Nemetz
13d ago
|
178 | const camera = new PerspectiveCamera(38, 1, 0.01, 100); |
| 179 | const controls = new OrbitControls(camera, canvas); | |
| 180 | controls.enableDamping = false; | |
| 181 | controls.screenSpacePanning = true; | |
|
6064a745
Keenan Nemetz
11d ago
|
182 | // An orbit clamps its polar angle to [0, π], so a vertical drag stops after |
| 183 | // half a turn. The pointer handler below turns the model itself instead, which | |
| 184 | // has no such stop; OrbitControls is kept for the zoom, the pan and the | |
| 185 | // distance limits the buttons share. | |
| 186 | controls.enableRotate = false; | |
|
3b2bcc30
Keenan Nemetz
13d ago
|
187 | controls.minDistance = 0.8; |
| 188 | controls.maxDistance = 30; | |
| 189 | ||
| 190 | // A sky/ground hemisphere plus two directional lights: an untextured mesh | |
| 191 | // still shows its form, and the pair is cheap enough for several viewers on | |
| 192 | // one diff page. | |
| 193 | scene.add(new HemisphereLight(0xffffff, 0x30343c, 2.2)); | |
| 194 | const key = new DirectionalLight(0xffffff, 2.1); | |
| 195 | key.position.set(2.5, 3, 2); | |
| 196 | scene.add(key); | |
| 197 | const fill = new DirectionalLight(0xffffff, 0.7); | |
| 198 | fill.position.set(-2.5, -1.5, -2); | |
| 199 | scene.add(fill); | |
| 200 | ||
| 201 | let width = 0; | |
| 202 | let height = 0; | |
| 203 | let root = null; | |
| 204 | let disposed = false; | |
|
d4764b08
Keenan Nemetz
9d ago
|
205 | // Assigned once the cube exists; render is also called during the initial |
| 206 | // resize, before a model has loaded. | |
| 207 | let drawCube = () => {}; | |
|
3b2bcc30
Keenan Nemetz
13d ago
|
208 | |
| 209 | const render = () => { | |
|
d4764b08
Keenan Nemetz
9d ago
|
210 | if (!disposed) { |
| 211 | renderer.render(scene, camera); | |
| 212 | drawCube(); | |
| 213 | } | |
|
3b2bcc30
Keenan Nemetz
13d ago
|
214 | }; |
| 215 | ||
|
0be96824
Keenan Nemetz
11d ago
|
216 | // OrbitControls moves the camera and fires change; it does not draw. This |
|
6064a745
Keenan Nemetz
11d ago
|
217 | // viewer renders on demand, so without this the wheel would zoom a picture |
|
7d989146
Keenan Nemetz
8d ago
|
218 | // that never changes. A change is also the moment a zoom belongs to a linked |
| 219 | // sibling, so the handler below publishes it. adopting and placing mark a | |
| 220 | // camera move this viewer did not ask for, which must not travel back out. | |
| 221 | let adopting = false; | |
| 222 | let placing = false; | |
| 223 | let publishTurn = () => {}; | |
| 224 | let publishZoom = () => {}; | |
| 225 | const onViewChange = () => { | |
| 226 | render(); | |
| 227 | if (!adopting && !placing) publishZoom(); | |
| 228 | }; | |
| 229 | controls.addEventListener('change', onViewChange); | |
|
0be96824
Keenan Nemetz
11d ago
|
230 | |
|
32eefb58
Keenan Nemetz
9d ago
|
231 | // The turn a diff pair shares. adopt takes a sibling's turn and cancels any |
| 232 | // snap in flight, so two animations cannot fight over the same quaternion. | |
| 233 | let snap = 0; | |
| 234 | const adoptTurn = (turn) => { | |
| 235 | if (snap) { cancelAnimationFrame(snap); snap = 0; } | |
| 236 | spin.quaternion.copy(turn); | |
|
d4764b08
Keenan Nemetz
9d ago
|
237 | // The sibling's turn is not this viewer's named view any more. |
| 238 | markView(''); | |
|
32eefb58
Keenan Nemetz
9d ago
|
239 | render(); |
| 240 | }; | |
|
7d989146
Keenan Nemetz
8d ago
|
241 | // adoptZoom copies a sibling's camera distance but keeps this viewer's own |
| 242 | // line to its target, so two panes framed at different sizes still share the | |
| 243 | // zoom rather than jumping to a position that only fits one of them. The | |
| 244 | // controls report the copy as a change; adopting suppresses the publish that | |
| 245 | // would send it straight back. | |
| 246 | const adoptZoom = (distance) => { | |
| 247 | if (!(distance > 0)) return; | |
| 248 | const offset = camera.position.clone().sub(controls.target); | |
| 249 | if (offset.lengthSq() === 0) offset.set(1.1, 0.75, 1.4); | |
| 250 | adopting = true; | |
| 251 | camera.position.copy(controls.target).add(offset.setLength(distance)); | |
| 252 | controls.update(); | |
| 253 | adopting = false; | |
| 254 | }; | |
|
32eefb58
Keenan Nemetz
9d ago
|
255 | const pair = pairFor(host); |
|
7d989146
Keenan Nemetz
8d ago
|
256 | const member = { adopt: adoptTurn, zoom: adoptZoom }; |
|
32eefb58
Keenan Nemetz
9d ago
|
257 | if (pair) pair.viewers.add(member); |
| 258 | ||
|
7d989146
Keenan Nemetz
8d ago
|
259 | // publish hands this viewer's turn and zoom to its siblings. A pair starts |
| 260 | // linked; the Sync button turns the link off. The two halves stay separate so | |
| 261 | // a drag or a view snap publishes only the turn, and the controls publish | |
| 262 | // only the zoom. | |
| 263 | publishTurn = () => { | |
|
32eefb58
Keenan Nemetz
9d ago
|
264 | if (!pair || !pair.linked) return; |
| 265 | pair.turn = spin.quaternion.clone(); | |
| 266 | for (const other of pair.viewers) { | |
| 267 | if (other !== member) other.adopt(pair.turn); | |
| 268 | } | |
| 269 | }; | |
|
7d989146
Keenan Nemetz
8d ago
|
270 | publishZoom = () => { |
| 271 | if (!pair || !pair.linked) return; | |
| 272 | pair.distance = camera.position.distanceTo(controls.target); | |
| 273 | for (const other of pair.viewers) { | |
| 274 | if (other !== member) other.zoom(pair.distance); | |
| 275 | } | |
| 276 | }; | |
| 277 | const publish = () => { | |
| 278 | publishTurn(); | |
| 279 | publishZoom(); | |
| 280 | }; | |
|
32eefb58
Keenan Nemetz
9d ago
|
281 | |
|
d4764b08
Keenan Nemetz
9d ago
|
282 | // viewButtons lets the cube and its accessible list show which view the |
| 283 | // model is at. A drag off a view clears both, so neither claims an angle the | |
| 284 | // model has left. | |
|
32eefb58
Keenan Nemetz
9d ago
|
285 | const viewButtons = new Map(); |
| 286 | const markView = (name) => { | |
|
d4764b08
Keenan Nemetz
9d ago
|
287 | for (const [view, controls] of viewButtons) { |
| 288 | pressed(controls.accessible, view === name); | |
| 289 | controls.face.classList.toggle('active', view === name); | |
| 290 | } | |
|
32eefb58
Keenan Nemetz
9d ago
|
291 | }; |
| 292 | ||
|
f865b269
Keenan Nemetz
9d ago
|
293 | // A drag turns the model, not the camera, the way a turntable turns what is |
| 294 | // standing on it: a horizontal drag spins the model about its own up (Y) axis, | |
| 295 | // so the side facing the reader follows the pointer left and right, and a | |
| 296 | // vertical drag tips it about the screen's horizontal axis. Spin about the | |
| 297 | // model's own up rather than the scene's vertical is what keeps a drag free of | |
| 298 | // roll: that axis cannot move itself, so the model's up stays in the plane the | |
| 299 | // reader sees as vertical however the two axes are mixed inside one diagonal | |
| 300 | // drag, and a tip can carry the model over the top and out upside down with no | |
| 301 | // pole to stop at. This is the arrangement Blender calls a turntable. Spinning | |
| 302 | // about the scene's vertical after a tip does roll, because then the tipped up | |
| 303 | // axis sweeps sideways. A drag across the width, or up the height, of the | |
| 304 | // canvas is one full turn. | |
|
6064a745
Keenan Nemetz
11d ago
|
305 | const pointers = new Set(); |
| 306 | let turning = null; | |
| 307 | let turnX = 0; | |
| 308 | let turnY = 0; | |
| 309 | const screenRight = new Vector3(); | |
|
f865b269
Keenan Nemetz
9d ago
|
310 | const upAxis = new Vector3(0, 1, 0); |
| 311 | const spinAxis = new Vector3(); | |
| 312 | // extractBasis wants three vectors; only the right one is read. | |
| 313 | const scratchUp = new Vector3(); | |
| 314 | const scratchOut = new Vector3(); | |
|
6064a745
Keenan Nemetz
11d ago
|
315 | |
| 316 | const endTurn = (event) => { | |
| 317 | pointers.delete(event.pointerId); | |
| 318 | if (canvas.hasPointerCapture(event.pointerId)) canvas.releasePointerCapture(event.pointerId); | |
| 319 | if (turning === event.pointerId) turning = null; | |
| 320 | }; | |
| 321 | ||
| 322 | canvas.addEventListener('pointerdown', (event) => { | |
| 323 | pointers.add(event.pointerId); | |
| 324 | canvas.setPointerCapture(event.pointerId); | |
| 325 | // A second pointer is a pinch, which belongs to OrbitControls' zoom: it | |
| 326 | // cancels the turn instead of turning while the fingers spread. | |
| 327 | if (!root || event.button !== 0 || pointers.size !== 1) { | |
| 328 | turning = null; | |
| 329 | return; | |
| 330 | } | |
| 331 | turning = event.pointerId; | |
| 332 | turnX = event.clientX; | |
| 333 | turnY = event.clientY; | |
|
32eefb58
Keenan Nemetz
9d ago
|
334 | markView(''); |
|
6064a745
Keenan Nemetz
11d ago
|
335 | }); |
| 336 | ||
| 337 | canvas.addEventListener('pointermove', (event) => { | |
| 338 | if (turning !== event.pointerId) return; | |
| 339 | const dx = event.clientX - turnX; | |
| 340 | const dy = event.clientY - turnY; | |
| 341 | turnX = event.clientX; | |
| 342 | turnY = event.clientY; | |
| 343 | if (dx === 0 && dy === 0) return; | |
| 344 | camera.updateMatrixWorld(); | |
|
f865b269
Keenan Nemetz
9d ago
|
345 | camera.matrixWorld.extractBasis(screenRight, scratchUp, scratchOut); |
| 346 | // spinAxis is the model's own up axis in world space. It always lies in the | |
| 347 | // camera's vertical plane and the camera's right is perpendicular to that | |
| 348 | // plane, so the two axes below are always square to each other and neither | |
| 349 | // drag can turn into the other. | |
| 350 | spinAxis.copy(upAxis).applyQuaternion(spin.quaternion); | |
| 351 | spin.rotateOnWorldAxis(spinAxis, dx * (2 * Math.PI) / Math.max(1, canvas.clientWidth)); | |
| 352 | spin.rotateOnWorldAxis(screenRight, dy * (2 * Math.PI) / Math.max(1, canvas.clientHeight)); | |
|
6064a745
Keenan Nemetz
11d ago
|
353 | render(); |
|
7d989146
Keenan Nemetz
8d ago
|
354 | publishTurn(); |
|
6064a745
Keenan Nemetz
11d ago
|
355 | }); |
| 356 | ||
| 357 | canvas.addEventListener('pointerup', endTurn); | |
| 358 | canvas.addEventListener('pointercancel', endTurn); | |
| 359 | ||
|
32eefb58
Keenan Nemetz
9d ago
|
360 | // A view puts a named side of the model toward the reader. The camera stays |
| 361 | // where it is and the model turns to meet it, so a view is the turn that maps | |
| 362 | // the model's own axes onto the screen's: front sets +z at the reader with +y | |
| 363 | // up, top puts +y there with +x to the right, right puts +x there with +y up. | |
| 364 | // The targets are built from the camera's basis when asked for, so they hold | |
| 365 | // whatever the zoom. | |
| 366 | const viewTurn = (name) => { | |
| 367 | camera.updateMatrixWorld(); | |
| 368 | const right = new Vector3(); | |
| 369 | const up = new Vector3(); | |
| 370 | const out = new Vector3(); | |
| 371 | camera.matrixWorld.extractBasis(right, up, out); | |
|
d4764b08
Keenan Nemetz
9d ago
|
372 | const neg = (v) => v.clone().negate(); |
| 373 | let x = right; | |
| 374 | let y = up; | |
| 375 | let z = out; | |
| 376 | switch (name) { | |
| 377 | case 'back': x = neg(right); z = neg(out); break; | |
| 378 | case 'right': x = out; z = neg(right); break; | |
| 379 | case 'left': x = neg(out); z = right; break; | |
| 380 | case 'top': y = out; z = neg(up); break; | |
| 381 | case 'bottom': y = neg(out); z = up; break; | |
| 382 | default: break; | |
| 383 | } | |
| 384 | return new Quaternion().setFromRotationMatrix( | |
| 385 | new Matrix4().makeBasis(x, y, z)); | |
|
32eefb58
Keenan Nemetz
9d ago
|
386 | }; |
| 387 | ||
| 388 | // turnTo eases to a view and publishes each frame the way a drag does, so a | |
| 389 | // linked pair arrives together. | |
| 390 | const turnTo = (target) => { | |
| 391 | if (snap) cancelAnimationFrame(snap); | |
| 392 | snap = 0; | |
| 393 | const from = spin.quaternion.clone(); | |
| 394 | if (reduceMotion() || from.angleTo(target) < 0.001) { | |
| 395 | spin.quaternion.copy(target); | |
| 396 | render(); | |
|
7d989146
Keenan Nemetz
8d ago
|
397 | publishTurn(); |
|
32eefb58
Keenan Nemetz
9d ago
|
398 | return; |
| 399 | } | |
| 400 | const start = performance.now(); | |
| 401 | const step = (now) => { | |
| 402 | const progress = Math.min(1, (now - start) / 220); | |
| 403 | // A smoothstep leaves and arrives at rest, so the view settles instead of | |
| 404 | // stopping dead at it. | |
| 405 | spin.quaternion.copy(from).slerp(target, progress * progress * (3 - 2 * progress)); | |
| 406 | render(); | |
|
7d989146
Keenan Nemetz
8d ago
|
407 | publishTurn(); |
|
32eefb58
Keenan Nemetz
9d ago
|
408 | snap = progress < 1 ? requestAnimationFrame(step) : 0; |
| 409 | }; | |
| 410 | snap = requestAnimationFrame(step); | |
| 411 | }; | |
| 412 | ||
|
3b2bcc30
Keenan Nemetz
13d ago
|
413 | // fitDistance is the camera distance that puts a unit sphere inside the |
| 414 | // narrower of the two field-of-view angles, so a narrow pane does not crop | |
| 415 | // the model. | |
| 416 | const fitDistance = () => { | |
| 417 | const vertical = (camera.fov * Math.PI) / 180; | |
| 418 | const horizontal = 2 * Math.atan(Math.tan(vertical / 2) * Math.max(camera.aspect, 0.0001)); | |
| 419 | return 1.15 / Math.sin(Math.min(vertical, horizontal) / 2); | |
| 420 | }; | |
| 421 | ||
| 422 | const fit = () => { | |
| 423 | const direction = camera.position.clone().sub(controls.target); | |
| 424 | if (direction.lengthSq() === 0) direction.set(1.1, 0.75, 1.4); | |
| 425 | direction.normalize().multiplyScalar(fitDistance()); | |
| 426 | camera.position.copy(controls.target).add(direction); | |
| 427 | camera.lookAt(controls.target); | |
| 428 | camera.updateProjectionMatrix(); | |
|
7d989146
Keenan Nemetz
8d ago
|
429 | // Framing is this viewer's own doing, not a zoom the reader asked to share. |
| 430 | // Keep it off the pair while it moves the camera; a reset publishes the | |
| 431 | // result once place has finished. | |
| 432 | placing = true; | |
| 433 | try { | |
| 434 | controls.update(); | |
| 435 | } finally { | |
| 436 | placing = false; | |
| 437 | } | |
|
3b2bcc30
Keenan Nemetz
13d ago
|
438 | render(); |
| 439 | }; | |
| 440 | ||
| 441 | const resize = () => { | |
| 442 | if (disposed) return; | |
| 443 | const rect = host.getBoundingClientRect(); | |
| 444 | const w = Math.max(1, Math.round(rect.width)); | |
| 445 | const h = Math.max(1, Math.round(rect.height)); | |
| 446 | if (w === width && h === height) return; | |
| 447 | width = w; | |
| 448 | height = h; | |
| 449 | camera.aspect = w / h; | |
| 450 | camera.updateProjectionMatrix(); | |
| 451 | renderer.setSize(w, h, false); | |
| 452 | if (root) fit(); | |
| 453 | else render(); | |
| 454 | }; | |
| 455 | ||
| 456 | // place centres the loaded model at the origin, scales its bounding sphere to | |
|
6064a745
Keenan Nemetz
11d ago
|
457 | // a unit radius, and frames it. The controls' target is the origin, so zoom |
| 458 | // stays around what is actually drawn, and the turn is about the model's own | |
| 459 | // centre rather than a corner. | |
|
3b2bcc30
Keenan Nemetz
13d ago
|
460 | const place = () => { |
| 461 | if (!root) return; | |
|
32eefb58
Keenan Nemetz
9d ago
|
462 | // A snap still in flight would overwrite the reset on its next frame. |
| 463 | if (snap) { cancelAnimationFrame(snap); snap = 0; } | |
|
6064a745
Keenan Nemetz
11d ago
|
464 | // Reset the turn and the scale before measuring: the box is measured in world |
| 465 | // space, and a previous turn would measure the model at an angle. The world | |
| 466 | // matrix is recomputed here because the measurement below reads the parent's | |
| 467 | // stored matrix rather than rebuilding it. | |
| 468 | spin.quaternion.identity(); | |
| 469 | spin.updateMatrixWorld(); | |
|
3b2bcc30
Keenan Nemetz
13d ago
|
470 | root.scale.setScalar(1); |
| 471 | root.position.set(0, 0, 0); | |
| 472 | const box = new Box3().setFromObject(root); | |
| 473 | if (box.isEmpty()) throw new Error('empty model'); | |
| 474 | const size = box.getSize(new Vector3()); | |
| 475 | const center = box.getCenter(new Vector3()); | |
| 476 | // The half-diagonal is the box's bounding-sphere radius, so the whole box | |
|
6064a745
Keenan Nemetz
11d ago
|
477 | // stays inside the frame whatever angle the reader turns it to. |
|
3b2bcc30
Keenan Nemetz
13d ago
|
478 | const radius = size.length() / 2; |
| 479 | if (!(radius > 0)) throw new Error('empty model'); | |
| 480 | const scale = 1 / radius; | |
| 481 | root.scale.setScalar(scale); | |
| 482 | root.position.copy(center).multiplyScalar(-scale); | |
| 483 | controls.target.set(0, 0, 0); | |
| 484 | camera.position.set(1.1, 0.75, 1.4); | |
| 485 | fit(); | |
| 486 | }; | |
| 487 | ||
| 488 | const setWireframe = (on) => { | |
| 489 | if (!root) return; | |
| 490 | root.traverse((node) => { | |
| 491 | if (!node.isMesh || !node.material) return; | |
| 492 | const materials = Array.isArray(node.material) ? node.material : [node.material]; | |
| 493 | for (const material of materials) { | |
| 494 | if (material) material.wireframe = on; | |
| 495 | } | |
| 496 | }); | |
| 497 | render(); | |
| 498 | }; | |
| 499 | ||
|
0be96824
Keenan Nemetz
11d ago
|
500 | // zoomBy moves the camera along its line to the orbit target. The buttons and |
| 501 | // the wheel have to stop in the same place, so the distance is clamped to the | |
| 502 | // limits OrbitControls enforces rather than left to grow without bound. update() | |
| 503 | // fires change, and the change listener above draws the result. | |
| 504 | const zoomBy = (factor) => { | |
| 505 | const offset = camera.position.clone().sub(controls.target); | |
| 506 | const distance = Math.min( | |
| 507 | Math.max(offset.length() * factor, controls.minDistance), | |
| 508 | controls.maxDistance, | |
| 509 | ); | |
| 510 | camera.position.copy(controls.target).add(offset.setLength(distance)); | |
| 511 | controls.update(); | |
| 512 | }; | |
| 513 | ||
|
3b2bcc30
Keenan Nemetz
13d ago
|
514 | const observer = typeof ResizeObserver === 'function' ? new ResizeObserver(resize) : null; |
| 515 | if (observer) observer.observe(host); | |
| 516 | else window.addEventListener('resize', resize); | |
| 517 | resize(); | |
| 518 | ||
| 519 | const dispose = () => { | |
| 520 | if (disposed) return; | |
| 521 | disposed = true; | |
|
32eefb58
Keenan Nemetz
9d ago
|
522 | if (snap) cancelAnimationFrame(snap); |
| 523 | if (pair) pair.viewers.delete(member); | |
|
3b2bcc30
Keenan Nemetz
13d ago
|
524 | if (observer) observer.disconnect(); |
| 525 | else window.removeEventListener('resize', resize); | |
| 526 | host.removeEventListener('vole:dispose', dispose); | |
|
7d989146
Keenan Nemetz
8d ago
|
527 | controls.removeEventListener('change', onViewChange); |
|
3b2bcc30
Keenan Nemetz
13d ago
|
528 | controls.dispose(); |
| 529 | if (root) disposeTree(root); | |
| 530 | renderer.dispose(); | |
| 531 | if (renderer.forceContextLoss) renderer.forceContextLoss(); | |
| 532 | }; | |
| 533 | host.addEventListener('vole:dispose', dispose); | |
| 534 | ||
| 535 | loader.load(url, (loaded) => { | |
| 536 | if (disposed) return; | |
| 537 | let object = loaded; | |
| 538 | if (format === 'stl') { | |
| 539 | if (!loaded.attributes.normal) loaded.computeVertexNormals(); | |
| 540 | object = new Mesh(loaded, new MeshStandardMaterial({ | |
| 541 | color: 0x9aa6b2, metalness: 0.05, roughness: 0.6, | |
| 542 | })); | |
| 543 | } else if (format === 'gltf' || format === 'glb') { | |
| 544 | object = loaded.scene || (loaded.scenes && loaded.scenes[0]) || loaded; | |
| 545 | } | |
| 546 | root = new Group(); | |
| 547 | root.add(object); | |
|
6064a745
Keenan Nemetz
11d ago
|
548 | spin.add(root); |
|
3b2bcc30
Keenan Nemetz
13d ago
|
549 | try { |
| 550 | place(); | |
| 551 | } catch (_) { | |
| 552 | fail('This model is empty.'); | |
| 553 | return; | |
| 554 | } | |
|
7d989146
Keenan Nemetz
8d ago
|
555 | // The other side may already have been turned or zoomed while this one |
| 556 | // loaded. | |
| 557 | if (pair && pair.linked) { | |
| 558 | if (pair.turn) adoptTurn(pair.turn); | |
| 559 | if (pair.distance) adoptZoom(pair.distance); | |
| 560 | } | |
|
3b2bcc30
Keenan Nemetz
13d ago
|
561 | status.remove(); |
| 562 | if (fallback) fallback.remove(); | |
| 563 | ||
| 564 | const tools = document.createElement('div'); | |
| 565 | tools.className = 'model-tools'; | |
|
6064a745
Keenan Nemetz
11d ago
|
566 | // The pointer turns the model and the wheel or a pinch zooms, and these two |
| 567 | // repeat the zoom for a reader who only clicks. | |
|
0be96824
Keenan Nemetz
11d ago
|
568 | const zoomOut = button('\u2212', 'Zoom out', () => zoomBy(1.25)); |
| 569 | const zoomIn = button('+', 'Zoom in', () => zoomBy(0.8)); | |
|
32eefb58
Keenan Nemetz
9d ago
|
570 | const reset = button('Reset view', 'Reset view', () => { |
| 571 | markView(''); | |
| 572 | place(); | |
| 573 | publish(); | |
| 574 | }); | |
|
0be96824
Keenan Nemetz
11d ago
|
575 | const wireframe = button('Wireframe', 'Toggle wireframe', () => { |
|
3b2bcc30
Keenan Nemetz
13d ago
|
576 | const on = !wireframe.classList.contains('active'); |
|
32eefb58
Keenan Nemetz
9d ago
|
577 | pressed(wireframe, on); |
|
3b2bcc30
Keenan Nemetz
13d ago
|
578 | setWireframe(on); |
| 579 | }); | |
|
0be96824
Keenan Nemetz
11d ago
|
580 | tools.append(zoomOut, zoomIn, reset, wireframe); |
|
32eefb58
Keenan Nemetz
9d ago
|
581 | // A diff holds two viewers of the same file, and a reader comparing them |
|
7d989146
Keenan Nemetz
8d ago
|
582 | // wants one angle and one zoom in both. The button turns that link off; |
| 583 | // linking again makes this viewer's view the shared one, so neither jumps | |
| 584 | // on the next drag. | |
|
32eefb58
Keenan Nemetz
9d ago
|
585 | if (pair) { |
|
7d989146
Keenan Nemetz
8d ago
|
586 | const sync = button('Sync', 'Turn and zoom both models together', () => { |
|
32eefb58
Keenan Nemetz
9d ago
|
587 | pair.linked = !pair.linked; |
| 588 | pressed(sync, pair.linked); | |
| 589 | publish(); | |
| 590 | }); | |
| 591 | pressed(sync, pair.linked); | |
| 592 | tools.append(sync); | |
| 593 | } | |
| 594 | ||
|
d4764b08
Keenan Nemetz
9d ago
|
595 | // The orientation cube is the pointer control; its faces are decorative |
| 596 | // buttons for the mouse, while the visually hidden list below it is the | |
| 597 | // keyboard and screen-reader control for all six views. | |
| 598 | const cube = document.createElement('div'); | |
| 599 | cube.className = 'model-cube'; | |
| 600 | cube.setAttribute('aria-hidden', 'true'); | |
| 601 | const stage = document.createElement('div'); | |
| 602 | stage.className = 'model-cube-stage'; | |
| 603 | ||
|
32eefb58
Keenan Nemetz
9d ago
|
604 | const views = document.createElement('div'); |
| 605 | views.className = 'model-views'; | |
|
d4764b08
Keenan Nemetz
9d ago
|
606 | for (const [view, label] of VIEW_FACES) { |
| 607 | const face = document.createElement('button'); | |
| 608 | face.type = 'button'; | |
| 609 | face.className = 'model-cube-face ' + view; | |
| 610 | face.textContent = label; | |
| 611 | face.title = label + ' view'; | |
| 612 | face.tabIndex = -1; | |
| 613 | face.addEventListener('click', () => { | |
|
32eefb58
Keenan Nemetz
9d ago
|
614 | markView(view); |
| 615 | turnTo(viewTurn(view)); | |
| 616 | }); | |
|
d4764b08
Keenan Nemetz
9d ago
|
617 | stage.append(face); |
| 618 | ||
| 619 | const accessible = button(label, label + ' view', () => { | |
| 620 | markView(view); | |
| 621 | turnTo(viewTurn(view)); | |
| 622 | }); | |
| 623 | views.append(accessible); | |
| 624 | viewButtons.set(view, { accessible, face }); | |
|
32eefb58
Keenan Nemetz
9d ago
|
625 | } |
|
d4764b08
Keenan Nemetz
9d ago
|
626 | cube.append(stage); |
| 627 | ||
| 628 | // The cube is the model's axes as the main camera sees them. three.js uses | |
| 629 | // y up; CSS uses y down, so F maps between the two. V is world -> camera, | |
| 630 | // S is the model's turn, and F*V*S*F is the rotation CSS should apply to | |
| 631 | // the cube's local (CSS-axis) geometry. | |
| 632 | const flip = new Matrix4().makeScale(1, -1, 1); | |
| 633 | const view = new Matrix4(); | |
| 634 | const model = new Matrix4(); | |
| 635 | const rotation = new Matrix4(); | |
| 636 | const cubeRight = new Vector3(); | |
| 637 | const cubeUp = new Vector3(); | |
| 638 | const cubeOut = new Vector3(); | |
| 639 | drawCube = () => { | |
| 640 | camera.updateMatrixWorld(); | |
| 641 | camera.matrixWorld.extractBasis(cubeRight, cubeUp, cubeOut); | |
| 642 | view.makeBasis(cubeRight, cubeUp, cubeOut).transpose(); | |
| 643 | model.makeRotationFromQuaternion(spin.quaternion); | |
| 644 | rotation.multiplyMatrices(flip, view) | |
| 645 | .multiply(model) | |
| 646 | .multiply(flip); | |
| 647 | const e = rotation.elements; | |
| 648 | stage.style.transform = 'matrix3d(' | |
| 649 | + e.map((value) => value.toFixed(6)).join(',') + ')'; | |
| 650 | }; | |
| 651 | drawCube(); | |
|
32eefb58
Keenan Nemetz
9d ago
|
652 | |
|
d4764b08
Keenan Nemetz
9d ago
|
653 | host.append(tools, cube, views); |
|
3b2bcc30
Keenan Nemetz
13d ago
|
654 | resize(); |
| 655 | }, undefined, () => { | |
| 656 | fail('This model could not be loaded. Download it to open it in a 3D application.'); | |
| 657 | }); | |
| 658 | }; |