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.
Render images and 3D models in the browser views
3b2bcc30534f24b4628b6365e69dcb9065115065 · Keenan Nemetz · 13d ago · parent 87bab8e1
Render images and 3D models in the browser views A blob whose name is an image is served as that image, so the <img> a README already emitted works and the source view can show it. An SVG keeps its source view and previews on request. The instance introduction resolves assets/, so a landing-page picture is no longer a broken link. A changed image or model shows both sides in the commit, compare, and change request diffs, where git only says "binary". The 3D viewer is a vendored three.js bundle, loaded only when a page has a model, with a download fallback for a reader without JavaScript or WebGL. closes: 01M7XQ9AKKKFNEX0F679JRRYQD
server/web/static/models/model-viewer.js +273
| @@ -0,0 +1,273 @@ | |||
| 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 | // | ||
| 9 | // A viewer is a canvas and two controls: orbit and zoom (OrbitControls) and a | ||
| 10 | // wireframe toggle. The model is centred and scaled to a unit sphere, so a part | ||
| 11 | // exported in millimetres and one in metres frame the same way. | ||
| 12 | |||
| 13 | import { | ||
| 14 | WebGLRenderer, Scene, PerspectiveCamera, HemisphereLight, DirectionalLight, | ||
| 15 | Box3, Vector3, Group, Mesh, MeshStandardMaterial, SRGBColorSpace, | ||
| 16 | OrbitControls, STLLoader, OBJLoader, GLTFLoader, ThreeMFLoader, | ||
| 17 | } from './three.bundle.js'; | ||
| 18 | |||
| 19 | const FORMATS = new Set(['stl', 'obj', 'gltf', 'glb', '3mf']); | ||
| 20 | |||
| 21 | // extension is the URL's file extension, ignoring a query or fragment the raw | ||
| 22 | // link may carry. | ||
| 23 | const extension = (url) => { | ||
| 24 | const clean = (url || '').split(/[?#]/)[0]; | ||
| 25 | const dot = clean.lastIndexOf('.'); | ||
| 26 | return dot < 0 ? '' : clean.slice(dot + 1).toLowerCase(); | ||
| 27 | }; | ||
| 28 | |||
| 29 | // formatOf prefers the server's data-format and falls back to the URL, so an | ||
| 30 | // element a future surface writes without the attribute still draws. | ||
| 31 | const formatOf = (host) => { | ||
| 32 | const named = (host.dataset.format || '').toLowerCase(); | ||
| 33 | if (FORMATS.has(named)) return named; | ||
| 34 | const ext = extension(host.dataset.model); | ||
| 35 | return FORMATS.has(ext) ? ext : ''; | ||
| 36 | }; | ||
| 37 | |||
| 38 | const loaderFor = (format) => { | ||
| 39 | switch (format) { | ||
| 40 | case 'stl': return new STLLoader(); | ||
| 41 | case 'obj': return new OBJLoader(); | ||
| 42 | case 'gltf': | ||
| 43 | case 'glb': return new GLTFLoader(); | ||
| 44 | case '3mf': return new ThreeMFLoader(); | ||
| 45 | default: return null; | ||
| 46 | } | ||
| 47 | }; | ||
| 48 | |||
| 49 | const button = (label, onClick) => { | ||
| 50 | const element = document.createElement('button'); | ||
| 51 | element.type = 'button'; | ||
| 52 | element.className = 'model-tool'; | ||
| 53 | element.textContent = label; | ||
| 54 | element.addEventListener('click', onClick); | ||
| 55 | return element; | ||
| 56 | }; | ||
| 57 | |||
| 58 | // disposeTree frees the geometry, materials and textures a loaded model owns. | ||
| 59 | // A viewer that is swapped out of the page must give its GPU memory back. | ||
| 60 | const disposeTree = (node) => { | ||
| 61 | node.traverse((child) => { | ||
| 62 | if (child.geometry && child.geometry.dispose) child.geometry.dispose(); | ||
| 63 | const materials = child.material == null ? [] | ||
| 64 | : (Array.isArray(child.material) ? child.material : [child.material]); | ||
| 65 | for (const material of materials) { | ||
| 66 | if (!material) continue; | ||
| 67 | for (const value of Object.values(material)) { | ||
| 68 | if (value && value.isTexture && value.dispose) value.dispose(); | ||
| 69 | } | ||
| 70 | if (material.dispose) material.dispose(); | ||
| 71 | } | ||
| 72 | }); | ||
| 73 | }; | ||
| 74 | |||
| 75 | export const upgrade = (host) => { | ||
| 76 | if (!host || host.dataset.modelReady) return; | ||
| 77 | // An HTMX swap can replace a pane before the module has finished loading. | ||
| 78 | if (!host.isConnected) return; | ||
| 79 | host.dataset.modelReady = 'loading'; | ||
| 80 | |||
| 81 | const url = host.dataset.model || ''; | ||
| 82 | const format = formatOf(host); | ||
| 83 | const fallback = host.querySelector('.model-fallback'); | ||
| 84 | |||
| 85 | const status = document.createElement('p'); | ||
| 86 | status.className = 'model-status muted'; | ||
| 87 | status.textContent = 'Loading model…'; | ||
| 88 | host.append(status); | ||
| 89 | |||
| 90 | const fail = (message) => { | ||
| 91 | host.dataset.modelReady = 'failed'; | ||
| 92 | status.textContent = message; | ||
| 93 | }; | ||
| 94 | |||
| 95 | const loader = format ? loaderFor(format) : null; | ||
| 96 | if (!url || !loader) { | ||
| 97 | fail('This file cannot be previewed here.'); | ||
| 98 | return; | ||
| 99 | } | ||
| 100 | |||
| 101 | const canvas = document.createElement('canvas'); | ||
| 102 | canvas.className = 'model-canvas'; | ||
| 103 | canvas.setAttribute('role', 'img'); | ||
| 104 | canvas.setAttribute('aria-label', '3D preview of ' + (host.dataset.title || 'this model')); | ||
| 105 | host.prepend(canvas); | ||
| 106 | |||
| 107 | let renderer; | ||
| 108 | try { | ||
| 109 | renderer = new WebGLRenderer({ canvas, antialias: true, alpha: true }); | ||
| 110 | } catch (_) { | ||
| 111 | canvas.remove(); | ||
| 112 | fail('This browser cannot draw a 3D preview.'); | ||
| 113 | return; | ||
| 114 | } | ||
| 115 | renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2)); | ||
| 116 | renderer.outputColorSpace = SRGBColorSpace; | ||
| 117 | |||
| 118 | const scene = new Scene(); | ||
| 119 | const camera = new PerspectiveCamera(38, 1, 0.01, 100); | ||
| 120 | const controls = new OrbitControls(camera, canvas); | ||
| 121 | controls.enableDamping = false; | ||
| 122 | controls.screenSpacePanning = true; | ||
| 123 | controls.minDistance = 0.8; | ||
| 124 | controls.maxDistance = 30; | ||
| 125 | |||
| 126 | // A sky/ground hemisphere plus two directional lights: an untextured mesh | ||
| 127 | // still shows its form, and the pair is cheap enough for several viewers on | ||
| 128 | // one diff page. | ||
| 129 | scene.add(new HemisphereLight(0xffffff, 0x30343c, 2.2)); | ||
| 130 | const key = new DirectionalLight(0xffffff, 2.1); | ||
| 131 | key.position.set(2.5, 3, 2); | ||
| 132 | scene.add(key); | ||
| 133 | const fill = new DirectionalLight(0xffffff, 0.7); | ||
| 134 | fill.position.set(-2.5, -1.5, -2); | ||
| 135 | scene.add(fill); | ||
| 136 | |||
| 137 | let width = 0; | ||
| 138 | let height = 0; | ||
| 139 | let root = null; | ||
| 140 | let disposed = false; | ||
| 141 | |||
| 142 | const render = () => { | ||
| 143 | if (!disposed) renderer.render(scene, camera); | ||
| 144 | }; | ||
| 145 | |||
| 146 | // fitDistance is the camera distance that puts a unit sphere inside the | ||
| 147 | // narrower of the two field-of-view angles, so a narrow pane does not crop | ||
| 148 | // the model. | ||
| 149 | const fitDistance = () => { | ||
| 150 | const vertical = (camera.fov * Math.PI) / 180; | ||
| 151 | const horizontal = 2 * Math.atan(Math.tan(vertical / 2) * Math.max(camera.aspect, 0.0001)); | ||
| 152 | return 1.15 / Math.sin(Math.min(vertical, horizontal) / 2); | ||
| 153 | }; | ||
| 154 | |||
| 155 | const fit = () => { | ||
| 156 | const direction = camera.position.clone().sub(controls.target); | ||
| 157 | if (direction.lengthSq() === 0) direction.set(1.1, 0.75, 1.4); | ||
| 158 | direction.normalize().multiplyScalar(fitDistance()); | ||
| 159 | camera.position.copy(controls.target).add(direction); | ||
| 160 | camera.lookAt(controls.target); | ||
| 161 | camera.updateProjectionMatrix(); | ||
| 162 | controls.update(); | ||
| 163 | render(); | ||
| 164 | }; | ||
| 165 | |||
| 166 | const resize = () => { | ||
| 167 | if (disposed) return; | ||
| 168 | const rect = host.getBoundingClientRect(); | ||
| 169 | const w = Math.max(1, Math.round(rect.width)); | ||
| 170 | const h = Math.max(1, Math.round(rect.height)); | ||
| 171 | if (w === width && h === height) return; | ||
| 172 | width = w; | ||
| 173 | height = h; | ||
| 174 | camera.aspect = w / h; | ||
| 175 | camera.updateProjectionMatrix(); | ||
| 176 | renderer.setSize(w, h, false); | ||
| 177 | if (root) fit(); | ||
| 178 | else render(); | ||
| 179 | }; | ||
| 180 | |||
| 181 | // place centres the loaded model at the origin, scales its bounding sphere to | ||
| 182 | // a unit radius, and frames it. The controls' target is the origin, so orbit | ||
| 183 | // and zoom stay around what is actually drawn. | ||
| 184 | const place = () => { | ||
| 185 | if (!root) return; | ||
| 186 | // Reset before measuring: a previous place() left the root scaled, and | ||
| 187 | // measuring that would compound the scale instead of replacing it. | ||
| 188 | root.scale.setScalar(1); | ||
| 189 | root.position.set(0, 0, 0); | ||
| 190 | const box = new Box3().setFromObject(root); | ||
| 191 | if (box.isEmpty()) throw new Error('empty model'); | ||
| 192 | const size = box.getSize(new Vector3()); | ||
| 193 | const center = box.getCenter(new Vector3()); | ||
| 194 | // The half-diagonal is the box's bounding-sphere radius, so the whole box | ||
| 195 | // stays inside the frame whatever angle the reader orbits to. | ||
| 196 | const radius = size.length() / 2; | ||
| 197 | if (!(radius > 0)) throw new Error('empty model'); | ||
| 198 | const scale = 1 / radius; | ||
| 199 | root.scale.setScalar(scale); | ||
| 200 | root.position.copy(center).multiplyScalar(-scale); | ||
| 201 | controls.target.set(0, 0, 0); | ||
| 202 | camera.position.set(1.1, 0.75, 1.4); | ||
| 203 | fit(); | ||
| 204 | }; | ||
| 205 | |||
| 206 | const setWireframe = (on) => { | ||
| 207 | if (!root) return; | ||
| 208 | root.traverse((node) => { | ||
| 209 | if (!node.isMesh || !node.material) return; | ||
| 210 | const materials = Array.isArray(node.material) ? node.material : [node.material]; | ||
| 211 | for (const material of materials) { | ||
| 212 | if (material) material.wireframe = on; | ||
| 213 | } | ||
| 214 | }); | ||
| 215 | render(); | ||
| 216 | }; | ||
| 217 | |||
| 218 | const observer = typeof ResizeObserver === 'function' ? new ResizeObserver(resize) : null; | ||
| 219 | if (observer) observer.observe(host); | ||
| 220 | else window.addEventListener('resize', resize); | ||
| 221 | resize(); | ||
| 222 | |||
| 223 | const dispose = () => { | ||
| 224 | if (disposed) return; | ||
| 225 | disposed = true; | ||
| 226 | if (observer) observer.disconnect(); | ||
| 227 | else window.removeEventListener('resize', resize); | ||
| 228 | host.removeEventListener('vole:dispose', dispose); | ||
| 229 | controls.dispose(); | ||
| 230 | if (root) disposeTree(root); | ||
| 231 | renderer.dispose(); | ||
| 232 | if (renderer.forceContextLoss) renderer.forceContextLoss(); | ||
| 233 | }; | ||
| 234 | host.addEventListener('vole:dispose', dispose); | ||
| 235 | |||
| 236 | loader.load(url, (loaded) => { | ||
| 237 | if (disposed) return; | ||
| 238 | let object = loaded; | ||
| 239 | if (format === 'stl') { | ||
| 240 | if (!loaded.attributes.normal) loaded.computeVertexNormals(); | ||
| 241 | object = new Mesh(loaded, new MeshStandardMaterial({ | ||
| 242 | color: 0x9aa6b2, metalness: 0.05, roughness: 0.6, | ||
| 243 | })); | ||
| 244 | } else if (format === 'gltf' || format === 'glb') { | ||
| 245 | object = loaded.scene || (loaded.scenes && loaded.scenes[0]) || loaded; | ||
| 246 | } | ||
| 247 | root = new Group(); | ||
| 248 | root.add(object); | ||
| 249 | scene.add(root); | ||
| 250 | try { | ||
| 251 | place(); | ||
| 252 | } catch (_) { | ||
| 253 | fail('This model is empty.'); | ||
| 254 | return; | ||
| 255 | } | ||
| 256 | status.remove(); | ||
| 257 | if (fallback) fallback.remove(); | ||
| 258 | |||
| 259 | const tools = document.createElement('div'); | ||
| 260 | tools.className = 'model-tools'; | ||
| 261 | const reset = button('Reset view', place); | ||
| 262 | const wireframe = button('Wireframe', () => { | ||
| 263 | const on = !wireframe.classList.contains('active'); | ||
| 264 | wireframe.classList.toggle('active', on); | ||
| 265 | setWireframe(on); | ||
| 266 | }); | ||
| 267 | tools.append(reset, wireframe); | ||
| 268 | host.append(tools); | ||
| 269 | resize(); | ||
| 270 | }, undefined, () => { | ||
| 271 | fail('This model could not be loaded. Download it to open it in a 3D application.'); | ||
| 272 | }); | ||
| 273 | }; | ||