Branchwell

Jotley / website · jotley.ai / src / app / components / home / phone-scene.ts

1import * as THREE from 'three';
2import { RoomEnvironment } from 'three/examples/jsm/environments/RoomEnvironment.js';
3import { RoundedBoxGeometry } from 'three/examples/jsm/geometries/RoundedBoxGeometry.js';
4
5/**
6 * A procedurally modelled iPhone (Pro-style titanium frame, glass, camera
7 * plateau) whose screen displays native Jotley captures.
8 * Units are centimetres, so the body matches a 6.3" phone (7.15 × 14.96 × 0.83).
9 */
10
11export type PhonePose = { rotateX: number; rotateY: number };
12
13export type PhoneScreen = { image: string; video?: string };
14
15export type PhoneSceneOptions = {
16 screens: PhoneScreen[];
17 poses: PhonePose[];
18 reducedMotion: boolean;
19 /** 0 = phone shows its back, 1 = facing the viewer. Read every frame. */
20 getEntryProgress: () => number;
21};
22
23export type PhoneSceneHandle = {
24 show: (index: number) => void;
25 setActive: (active: boolean) => void;
26 dispose: () => void;
27};
28
29const BODY_W = 7.15;
30const BODY_H = 14.96;
31const BODY_D = 0.83;
32const EDGE = 0.12; // rounded transition between frame and glass
33const SCREEN_ASPECT = 1320 / 2868; // the iPhone captures’ native aspect
34const BEZEL = 0.124;
35const CORNER = 1.154; // corner radius of the glass faces
36
37function roundedRectShape(width: number, height: number, radius: number): THREE.Shape {
38 const x = -width / 2;
39 const y = -height / 2;
40 const r = Math.min(radius, width / 2, height / 2);
41 const shape = new THREE.Shape();
42 shape.moveTo(x + r, y);
43 shape.lineTo(x + width - r, y);
44 shape.quadraticCurveTo(x + width, y, x + width, y + r);
45 shape.lineTo(x + width, y + height - r);
46 shape.quadraticCurveTo(x + width, y + height, x + width - r, y + height);
47 shape.lineTo(x + r, y + height);
48 shape.quadraticCurveTo(x, y + height, x, y + height - r);
49 shape.lineTo(x, y + r);
50 shape.quadraticCurveTo(x, y, x + r, y);
51 return shape;
52}
53
54/** ShapeGeometry with UVs normalised to the shape's bounding box (for textures). */
55function planarShapeGeometry(shape: THREE.Shape, segments = 48): THREE.ShapeGeometry {
56 const geometry = new THREE.ShapeGeometry(shape, segments);
57 geometry.computeBoundingBox();
58 const box = geometry.boundingBox!;
59 const size = new THREE.Vector3();
60 box.getSize(size);
61 const position = geometry.attributes.position;
62 const uv = geometry.attributes.uv;
63 for (let i = 0; i < position.count; i++) {
64 uv.setXY(i, (position.getX(i) - box.min.x) / size.x, (position.getY(i) - box.min.y) / size.y);
65 }
66 uv.needsUpdate = true;
67 return geometry;
68}
69
70/** Soft diagonal glare that slides across the glass as the phone turns. */
71function glareTexture(): THREE.CanvasTexture {
72 const canvas = document.createElement('canvas');
73 canvas.width = 256;
74 canvas.height = 512;
75 const ctx = canvas.getContext('2d')!;
76 const gradient = ctx.createLinearGradient(0, 0, 256, 512);
77 gradient.addColorStop(0, 'rgba(255,255,255,0)');
78 gradient.addColorStop(0.38, 'rgba(255,255,255,0)');
79 gradient.addColorStop(0.47, 'rgba(255,255,255,0.55)');
80 gradient.addColorStop(0.53, 'rgba(255,255,255,0.12)');
81 gradient.addColorStop(0.62, 'rgba(255,255,255,0)');
82 gradient.addColorStop(1, 'rgba(255,255,255,0)');
83 ctx.fillStyle = gradient;
84 ctx.fillRect(0, 0, 256, 512);
85 const texture = new THREE.CanvasTexture(canvas);
86 texture.wrapS = THREE.RepeatWrapping;
87 return texture;
88}
89
90function buildPhone(materials: {
91 frame: THREE.Material;
92 backGlass: THREE.Material;
93 frontGlass: THREE.Material;
94 lensRing: THREE.Material;
95 lensGlass: THREE.Material;
96 lensInner: THREE.Material;
97 plateau: THREE.Material;
98 flash: THREE.Material;
99 screen: THREE.Material;
100 glare: THREE.Material;
101}) {
102 const phone = new THREE.Group();
103 const capW = BODY_W - EDGE * 2;
104 const capH = BODY_H - EDGE * 2;
105 const coreDepth = BODY_D - EDGE * 2;
106
107 // Body: flat titanium sides with softly rounded edges into the glass.
108 const body = new THREE.ExtrudeGeometry(roundedRectShape(capW, capH, CORNER), {
109 depth: coreDepth,
110 bevelEnabled: true,
111 bevelThickness: EDGE,
112 bevelSize: EDGE,
113 bevelSegments: 8,
114 curveSegments: 40,
115 });
116 body.translate(0, 0, -coreDepth / 2);
117 phone.add(new THREE.Mesh(body, [materials.backGlass, materials.frame]));
118
119 const frontZ = coreDepth / 2 + EDGE;
120
121 // Front glass (black border visible around the display).
122 const front = new THREE.Mesh(planarShapeGeometry(roundedRectShape(capW, capH, CORNER)), materials.frontGlass);
123 front.position.z = frontZ + 0.003;
124 phone.add(front);
125
126 // Display. Uniform 1.24mm bezel; the aspect matches the recordings exactly.
127 const screenW = capW - BEZEL * 2;
128 const screenH = screenW / SCREEN_ASPECT;
129 const screenGeometry = planarShapeGeometry(roundedRectShape(screenW, screenH, CORNER - BEZEL));
130 const screen = new THREE.Mesh(screenGeometry, materials.screen);
131 screen.position.z = frontZ + 0.014;
132 phone.add(screen);
133
134 const glare = new THREE.Mesh(screenGeometry, materials.glare);
135 glare.position.z = frontZ + 0.024;
136 phone.add(glare);
137
138 // Back: camera plateau with three lenses, flash and LiDAR.
139 const back = new THREE.Group();
140 back.rotation.y = Math.PI; // build in front-facing coords, then flip to the back
141 back.position.z = -frontZ;
142 phone.add(back);
143
144 const plateauSize = 3.55;
145 const plateauGeometry = new THREE.ExtrudeGeometry(roundedRectShape(plateauSize - 0.1, plateauSize - 0.1, 0.78), {
146 depth: 0.06,
147 bevelEnabled: true,
148 bevelThickness: 0.05,
149 bevelSize: 0.05,
150 bevelSegments: 5,
151 curveSegments: 24,
152 });
153 const plateau = new THREE.Mesh(plateauGeometry, materials.plateau);
154 // `back` is flipped, so its local axes read as seen from behind: the plateau sits top-left.
155 const plateauX = -(capW / 2 - plateauSize / 2 - 0.28);
156 const plateauY = capH / 2 - plateauSize / 2 - 0.28;
157 plateau.position.set(plateauX, plateauY, 0);
158 back.add(plateau);
159
160 const lensRingGeometry = new THREE.CylinderGeometry(0.72, 0.74, 0.22, 48);
161 lensRingGeometry.rotateX(Math.PI / 2);
162 const lensGlassGeometry = new THREE.CircleGeometry(0.6, 48);
163 const lensInnerGeometry = new THREE.CircleGeometry(0.26, 32);
164 const lensSpots: [number, number][] = [
165 [-0.8, 0.8],
166 [-0.8, -0.8],
167 [0.75, 0],
168 ];
169 for (const [dx, dy] of lensSpots) {
170 const lens = new THREE.Group();
171 lens.position.set(plateauX + dx, plateauY + dy, 0.2);
172 const ring = new THREE.Mesh(lensRingGeometry, materials.lensRing);
173 lens.add(ring);
174 const glass = new THREE.Mesh(lensGlassGeometry, materials.lensGlass);
175 glass.position.z = 0.111;
176 lens.add(glass);
177 const inner = new THREE.Mesh(lensInnerGeometry, materials.lensInner);
178 inner.position.z = 0.113;
179 lens.add(inner);
180 back.add(lens);
181 }
182 const flash = new THREE.Mesh(new THREE.CircleGeometry(0.2, 32), materials.flash);
183 flash.position.set(plateauX + 0.78, plateauY + 1.05, 0.125);
184 back.add(flash);
185 const lidar = new THREE.Mesh(new THREE.CircleGeometry(0.2, 32), materials.lensGlass);
186 lidar.position.set(plateauX + 0.78, plateauY - 1.05, 0.125);
187 back.add(lidar);
188
189 // Side buttons: action + volume on the left, side button + camera control on the right.
190 const button = (length: number, x: number, y: number) => {
191 const mesh = new THREE.Mesh(new RoundedBoxGeometry(0.1, length, 0.32, 3, 0.045), materials.frame);
192 mesh.position.set(x, y, 0);
193 phone.add(mesh);
194 };
195 const sideX = BODY_W / 2 + 0.02;
196 button(0.62, -sideX, 4.35);
197 button(1.15, -sideX, 2.75);
198 button(1.15, -sideX, 1.35);
199 button(1.65, sideX, 2.6);
200 button(1.0, sideX, -2.35);
201
202 return { phone, screen };
203}
204
205export async function createPhoneScene(container: HTMLElement, options: PhoneSceneOptions): Promise<PhoneSceneHandle> {
206 const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true, powerPreference: 'high-performance' });
207 renderer.outputColorSpace = THREE.SRGBColorSpace;
208 renderer.toneMapping = THREE.ACESFilmicToneMapping;
209 renderer.toneMappingExposure = 1.05;
210 renderer.domElement.setAttribute('aria-hidden', 'true');
211 container.appendChild(renderer.domElement);
212
213 const scene = new THREE.Scene();
214 const pmrem = new THREE.PMREMGenerator(renderer);
215 const environment = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;
216 scene.environment = environment;
217
218 // A tight near/far range keeps depth precision high enough that the glass layers never z-fight.
219 const camera = new THREE.PerspectiveCamera(28, 1, 4, 120);
220
221 // Key, fill and two brand-coloured rim lights so the titanium edges catch purple.
222 scene.add(new THREE.AmbientLight(0xffffff, 0.25));
223 const key = new THREE.DirectionalLight(0xffffff, 1.6);
224 key.position.set(6, 10, 14);
225 scene.add(key);
226 const rimLeft = new THREE.DirectionalLight(0xa855f7, 3.2);
227 rimLeft.position.set(-14, 4, -6);
228 scene.add(rimLeft);
229 const rimRight = new THREE.DirectionalLight(0x7c3aed, 2.4);
230 rimRight.position.set(14, -6, -8);
231 scene.add(rimRight);
232
233 const textureLoader = new THREE.TextureLoader();
234 const screenTextures = options.screens.map((screen) => {
235 const texture = textureLoader.load(screen.image);
236 texture.colorSpace = THREE.SRGBColorSpace;
237 texture.anisotropy = renderer.capabilities.getMaxAnisotropy();
238 return texture;
239 });
240
241 const screenMaterial = new THREE.MeshBasicMaterial({ map: screenTextures[0], toneMapped: false });
242 // Video textures use a different sRGB decoding path in Three.js.
243 const clips = options.screens.map(({ video: src }) => {
244 if (!src || options.reducedMotion) return null;
245 const video = document.createElement('video');
246 video.crossOrigin = 'anonymous';
247 video.muted = true;
248 video.loop = true;
249 video.playsInline = true;
250 video.preload = 'none';
251 const texture = new THREE.VideoTexture(video);
252 texture.colorSpace = THREE.SRGBColorSpace;
253 // The angled screen shrinks fine text and waveform bars unevenly across the frame.
254 texture.generateMipmaps = true;
255 texture.minFilter = THREE.LinearMipmapLinearFilter;
256 texture.anisotropy = Math.min(8, renderer.capabilities.getMaxAnisotropy());
257 const material = new THREE.MeshBasicMaterial({ map: texture, toneMapped: false });
258 material.onBeforeCompile = (shader) => {
259 // Average subpixel samples before the video color conversion. UV gradients
260 // follow the screen as it rotates, smoothing thin lines without blurring the whole phone.
261 const videoMap = THREE.ShaderChunk.map_fragment.replace(
262 'texture2D( map, vMapUv )',
263 `( texture2D( map, vMapUv + tapX + tapY )
264 + texture2D( map, vMapUv + tapX - tapY )
265 + texture2D( map, vMapUv - tapX + tapY )
266 + texture2D( map, vMapUv - tapX - tapY ) ) * 0.25`
267 );
268 shader.fragmentShader = shader.fragmentShader.replace(
269 '#include <map_fragment>',
270 `#ifdef USE_MAP
271 vec2 tapX = dFdx( vMapUv ) * 0.35;
272 vec2 tapY = dFdy( vMapUv ) * 0.35;
273 #endif
274 ${videoMap}`
275 );
276 };
277 return { src, video, material, texture };
278 });
279 const glareMap = glareTexture();
280 const glareMaterial = new THREE.MeshBasicMaterial({
281 map: glareMap,
282 transparent: true,
283 opacity: 0.09,
284 blending: THREE.AdditiveBlending,
285 depthWrite: false,
286 });
287
288 const frameMaterial = new THREE.MeshPhysicalMaterial({
289 color: 0x5b5266,
290 metalness: 1,
291 roughness: 0.26,
292 clearcoat: 0.4,
293 clearcoatRoughness: 0.2,
294 });
295 const backGlassMaterial = new THREE.MeshPhysicalMaterial({
296 color: 0x2f2a38,
297 metalness: 0.15,
298 roughness: 0.55,
299 clearcoat: 0.6,
300 clearcoatRoughness: 0.45,
301 });
302 const materials = {
303 frame: frameMaterial,
304 backGlass: backGlassMaterial,
305 frontGlass: new THREE.MeshPhysicalMaterial({ color: 0x050407, roughness: 0.08, clearcoat: 1, clearcoatRoughness: 0.04 }),
306 plateau: new THREE.MeshPhysicalMaterial({ color: 0x3a3444, metalness: 0.2, roughness: 0.18, clearcoat: 1, clearcoatRoughness: 0.08 }),
307 lensRing: new THREE.MeshPhysicalMaterial({ color: 0x6d6378, metalness: 1, roughness: 0.18 }),
308 lensGlass: new THREE.MeshPhysicalMaterial({ color: 0x07060b, roughness: 0.04, clearcoat: 1, clearcoatRoughness: 0.02 }),
309 lensInner: new THREE.MeshPhysicalMaterial({ color: 0x1b1530, metalness: 0.6, roughness: 0.1, iridescence: 1, iridescenceIOR: 1.6 }),
310 flash: new THREE.MeshStandardMaterial({ color: 0xf3ead3, roughness: 0.4, emissive: 0x2a2416 }),
311 screen: screenMaterial,
312 glare: glareMaterial,
313 };
314
315 const { phone, screen } = buildPhone(materials);
316 const rig = new THREE.Group();
317 rig.add(phone);
318 scene.add(rig);
319
320 // ---- animation state ----
321 let activeIndex = 0;
322 let shownIndex = 0;
323 let fade = 1; // screen brightness (dips to black while switching screenshots)
324 let switching = false;
325 let running = false;
326 let frame = 0;
327 let last = performance.now();
328 const pointer = { x: 0, y: 0 };
329 const smoothPointer = { x: 0, y: 0 };
330 const rotation = { x: 0, y: options.reducedMotion ? 0 : Math.PI };
331
332 let playingIndex = -1;
333 const syncPlayback = () => {
334 // Save the start of the transcript for when the phone is facing the reader.
335 const nextIndex = running && Math.cos(rotation.y) > 0.75 ? shownIndex : -1;
336 if (nextIndex === playingIndex) return;
337 playingIndex = nextIndex;
338 clips.forEach((clip, index) => {
339 if (!clip) return;
340 const { video, src } = clip;
341 if (index === playingIndex) {
342 if (!video.hasAttribute('src')) video.src = src;
343 void video.play().catch(() => undefined);
344 } else {
345 video.pause();
346 if (video.readyState >= 1) video.currentTime = 0;
347 }
348 });
349 };
350
351 const resize = () => {
352 const width = container.clientWidth;
353 const height = container.clientHeight;
354 if (!width || !height) return;
355 // Supersample angled UI on standard displays while bounding the canvas on larger screens.
356 const pixelRatio = Math.min(Math.max(window.devicePixelRatio, 2.5), 3, Math.sqrt(4_500_000 / (width * height)));
357 renderer.setPixelRatio(pixelRatio);
358 renderer.setSize(width, height, false);
359 camera.aspect = width / height;
360 // Keep the whole phone (plus turning room) in frame for any aspect ratio.
361 const halfFov = THREE.MathUtils.degToRad(camera.fov / 2);
362 const fitHeight = (BODY_H * 1.08) / (2 * Math.tan(halfFov));
363 const fitWidth = (BODY_W * 1.9) / (2 * Math.tan(halfFov) * camera.aspect);
364 camera.position.set(0, 0, Math.max(fitHeight, fitWidth));
365 camera.lookAt(0, 0, 0);
366 camera.updateProjectionMatrix();
367 };
368 const resizeObserver = new ResizeObserver(resize);
369 resizeObserver.observe(container);
370 resize();
371
372 const onPointerMove = (event: PointerEvent) => {
373 pointer.x = (event.clientX / window.innerWidth) * 2 - 1;
374 pointer.y = (event.clientY / window.innerHeight) * 2 - 1;
375 };
376 window.addEventListener('pointermove', onPointerMove, { passive: true });
377
378 const damp = (current: number, target: number, lambda: number, dt: number) =>
379 current + (target - current) * (1 - Math.exp(-lambda * dt));
380
381 const tick = (now: number) => {
382 frame = requestAnimationFrame(tick);
383 const dt = Math.min((now - last) / 1000, 0.05);
384 last = now;
385 const t = now / 1000;
386
387 // Swap screenshots through a quick dip to black, like a screen changing apps.
388 if (activeIndex !== shownIndex && !switching) switching = true;
389 if (switching) {
390 fade = Math.max(0, fade - dt * 7);
391 if (fade === 0) {
392 shownIndex = activeIndex;
393 switching = false;
394 }
395 } else {
396 fade = Math.min(1, fade + dt * 5);
397 }
398 screenMaterial.map = screenTextures[shownIndex];
399 const clip = clips[shownIndex];
400 const visibleMaterial = clip && clip.video.readyState >= 2 && !clip.video.error && !clip.video.paused ? clip.material : screenMaterial;
401 visibleMaterial.color.setScalar(fade);
402 screen.material = visibleMaterial;
403
404 const pose = options.poses[activeIndex] ?? options.poses[0];
405 const entry = options.reducedMotion ? 1 : THREE.MathUtils.smootherstep(options.getEntryProgress(), 0, 1);
406 smoothPointer.x = damp(smoothPointer.x, options.reducedMotion ? 0 : pointer.x, 3, dt);
407 smoothPointer.y = damp(smoothPointer.y, options.reducedMotion ? 0 : pointer.y, 3, dt);
408
409 const targetY = THREE.MathUtils.lerp(Math.PI * 1.02, pose.rotateY, entry) + smoothPointer.x * 0.16;
410 const targetX = pose.rotateX + smoothPointer.y * 0.08;
411 rotation.y = damp(rotation.y, targetY, 3.2, dt);
412 rotation.x = damp(rotation.x, targetX, 3.2, dt);
413 syncPlayback();
414
415 rig.rotation.set(rotation.x, rotation.y, options.reducedMotion ? 0 : Math.sin(t * 0.6) * 0.012);
416 rig.position.y = options.reducedMotion ? 0 : Math.sin(t * 0.9) * 0.14;
417 glareMap.offset.x = rotation.y * 0.35 + 0.1;
418
419 renderer.render(scene, camera);
420 };
421
422 const setActive = (active: boolean) => {
423 if (active === running) return;
424 running = active;
425 if (active) {
426 last = performance.now();
427 frame = requestAnimationFrame(tick);
428 } else {
429 cancelAnimationFrame(frame);
430 }
431 syncPlayback();
432 };
433
434 // Render one frame immediately so the canvas isn't blank before it scrolls in.
435 renderer.render(scene, camera);
436
437 return {
438 show(index: number) {
439 activeIndex = Math.max(0, Math.min(index, options.screens.length - 1));
440 },
441 setActive,
442 dispose() {
443 cancelAnimationFrame(frame);
444 resizeObserver.disconnect();
445 window.removeEventListener('pointermove', onPointerMove);
446 clips.forEach((clip) => {
447 if (!clip) return;
448 clip.video.pause();
449 clip.video.removeAttribute('src');
450 clip.video.load();
451 clip.material.dispose();
452 clip.texture.dispose();
453 });
454 scene.traverse((object) => {
455 if (object instanceof THREE.Mesh) object.geometry.dispose();
456 });
457 Object.values(materials).forEach((material) => material.dispose());
458 [...screenTextures, glareMap, environment].forEach((texture) => texture.dispose());
459 pmrem.dispose();
460 renderer.dispose();
461 renderer.domElement.remove();
462 },
463 };
464}