Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

phoneViewer.ts

332 lines11.4 KB

1import {
2 AmbientLight,
3 Box3,
4 CanvasTexture,
5 DirectionalLight,
6 LinearFilter,
7 Matrix4,
8 PerspectiveCamera,
9 Quaternion,
10 Scene,
11 SRGBColorSpace,
12 Vector3,
13 WebGLRenderer,
14} from "three";
15import {
16 createDeviceModelSlot,
17 type DeviceModelSource,
18 type DeviceAccessorySource,
19} from "./model.ts";
20import { createImportedPhoneScene, loadDeviceModel } from "./modelScene.ts";
21import { createPhoneScene, phoneDisplayLayout } from "./phoneScene.ts";
22import { createRenderScheduler } from "./renderScheduler.ts";
23import { createDeviceMotion } from "./deviceMotion.ts";
24import { createDeviceFraming } from "./deviceFraming.ts";
25import { nearestDeviceView } from "./deviceViewSnap.ts";
26import type { DeviceScreenSize } from "./stream.ts";
27import { IOS_PHONE_SHAPE, type DeviceShapeProfile } from "./shapeProfile.ts";
28​
29export interface PhoneViewer {
30 readonly setModel: (source: DeviceModelSource | null) => void;
31 readonly setAccessory: (source: DeviceAccessorySource | null) => void;
32 readonly frameUpdated: () => void;
33 readonly setScreen: (screen: DeviceScreenSize | null, profile?: DeviceShapeProfile) => void;
34 readonly resize: (width: number, height: number, pixelRatio: number) => void;
35 readonly screenPoint: (
36 x: number,
37 y: number,
38 captured?: boolean,
39 ) => { x: number; y: number } | null;
40 readonly orbit: (deltaX: number, deltaY: number) => void;
41 readonly setInteractionActive: (active: boolean, mode: "touch" | "orbit") => void;
42 readonly resetPose: () => void;
43 readonly dispose: () => void;
45​
46/** Owns only presentation resources. The caller retains the decoded canvas and the stream connection. */
47export function createPhoneViewer(options: {
48 readonly canvas: HTMLCanvasElement;
49 readonly source: HTMLCanvasElement;
50 readonly onUnavailable: () => void;
51 readonly onModelError?: (cause: unknown) => void;
52 readonly onFramingAspect?: (aspect: number) => void;
53 readonly profile?: DeviceShapeProfile;
54 readonly model?: DeviceModelSource | null;
55 readonly accessory?: DeviceAccessorySource | null;
56}): PhoneViewer {
57 const renderer = new WebGLRenderer({
58 canvas: options.canvas,
59 alpha: true,
60 antialias: true,
61 powerPreference: "low-power",
62 });
63 renderer.outputColorSpace = SRGBColorSpace;
64 const makeTexture = () => {
65 const next = new CanvasTexture(options.source);
66 next.colorSpace = SRGBColorSpace;
67 next.minFilter = LinearFilter;
68 next.magFilter = LinearFilter;
69 next.generateMipmaps = false;
70 return next;
71 };
72 let texture = makeTexture();
73 let textureWidth = options.source.width;
74 let textureHeight = options.source.height;
75 const scene = new Scene();
76 const camera = new PerspectiveCamera(32, 1, 0.1, 30);
77 camera.position.z = 5.5;
78 const ambient = new AmbientLight(0xffffff, 2.4);
79 const key = new DirectionalLight(0xe4edff, 5);
80 key.position.set(-3, 4, 5);
81 const rim = new DirectionalLight(0xffffff, 4);
82 rim.position.set(3, 1, -3);
83 const fill = new DirectionalLight(0x9facd4, 2);
84 fill.position.set(-2, -2, -4);
85 scene.add(ambient, key, rim, fill);
86​
87 let screen: DeviceScreenSize | null = null;
88 let layout = phoneDisplayLayout(screen, options.source.width, options.source.height);
89 let profile = options.profile ?? IOS_PHONE_SHAPE;
90 let imported: Awaited<ReturnType<typeof loadDeviceModel>> | null = null;
91 let modelSource = options.model ?? null;
92 let accessory: Awaited<ReturnType<typeof loadDeviceModel>> | null = null;
93 let accessoryBounds: Box3 | null = null;
94 let phone = createPhoneScene(texture, layout, profile);
95 scene.add(phone.root);
96 let disposed = false;
97 const rest = new Quaternion();
98 const motion = createDeviceMotion({
99 choose: (rotation) =>
100 nearestDeviceView(rotation, [{ rotation: new Quaternion(), yawLimit: Math.PI / 3 }])!
101 .rotation,
102 });
103 motion.setPose(rest, performance.now(), true);
104 const framing = createDeviceFraming();
105 const reducedMotion = () =>
106 globalThis.matchMedia?.("(prefers-reduced-motion: reduce)").matches ?? false;
107 let viewport = { width: 0, height: 0, pixelRatio: 1 };
108 let drawingBuffer = { width: 0, height: 0, pixelRatio: 0 };
109​
110 let framingAspect: number | null = null;
111 const fit = (immediate = false) => {
112 if (!viewport.width || !viewport.height) return;
113 camera.aspect = viewport.width / viewport.height;
114 const bounds = new Box3(
115 new Vector3(-phone.width / 2, -phone.height / 2, 0),
116 new Vector3(phone.width / 2, phone.height / 2, 0),
117 );
118 if (imported && accessoryBounds) bounds.union(accessoryBounds);
119 bounds.applyMatrix4(new Matrix4().makeRotationZ(layout.rotation));
120 const size = bounds.getSize(new Vector3());
121 const aspect = size.x / size.y;
122 if (aspect !== framingAspect) {
123 framingAspect = aspect;
124 options.onFramingAspect?.(aspect);
125 }
126 phone.root.updateMatrixWorld(true);
127 framing.setBounds(
128 new Box3().setFromObject(phone.root),
129 (camera.fov * Math.PI) / 360,
130 camera.aspect,
131 performance.now(),
132 immediate,
133 );
134 applyCamera();
135 };
136 const applyCamera = () => {
137 camera.position.set(framing.center.x, framing.center.y, framing.distance());
138 camera.lookAt(framing.center.x, framing.center.y, 0);
139 camera.updateProjectionMatrix();
140 };
141 const applyPose = () => {
142 phone.root.quaternion.copy(motion.rotation);
143 phone.orientation.rotation.z = layout.rotation;
144 };
145 const scheduler = createRenderScheduler(() => {
146 if (disposed || !viewport.width || !viewport.height) return;
147 try {
148 if (
149 drawingBuffer.width !== viewport.width ||
150 drawingBuffer.height !== viewport.height ||
151 drawingBuffer.pixelRatio !== viewport.pixelRatio
152 ) {
153 // Canvas allocation clears the previous image. Commit it with the redraw,
154 // rather than exposing an empty buffer between ResizeObserver and the next frame.
155 renderer.setDrawingBufferSize(viewport.width, viewport.height, viewport.pixelRatio);
156 drawingBuffer = viewport;
157 }
158 const now = performance.now();
159 if (motion.advance(now, reducedMotion())) {
160 applyPose();
161 fit(reducedMotion());
162 }
163 framing.advance(now, reducedMotion());
164 applyCamera();
165 renderer.render(scene, camera);
166 if (motion.needsFrame() || framing.needsFrame()) scheduler.invalidate();
167 } catch {
168 options.onUnavailable();
169 }
170 });
171 const updateLayout = (nextProfile = profile) => {
172 const next = phoneDisplayLayout(screen, options.source.width, options.source.height);
173 const resized =
174 textureWidth !== options.source.width || textureHeight !== options.source.height;
175 if (
176 resized ||
177 nextProfile !== profile ||
178 next.aspect !== layout.aspect ||
179 next.rawLandscape !== layout.rawLandscape ||
180 next.rotation !== layout.rotation
181 ) {
182 // The model and renderer survive framebuffer rotation and native resolution changes.
183 if (resized) {
184 const previous = texture;
185 texture = makeTexture();
186 textureWidth = options.source.width;
187 textureHeight = options.source.height;
188 phone.setDisplay(texture, next);
189 previous.dispose();
190 }
191 if (!imported && (nextProfile !== profile || next.aspect !== layout.aspect)) {
192 scene.remove(phone.root);
193 phone.dispose();
194 phone = createPhoneScene(texture, next, nextProfile);
195 scene.add(phone.root);
196 } else {
197 phone.setDisplay(texture, next);
198 }
199 layout = next;
200 profile = nextProfile;
201 applyPose();
202 fit(true);
203 }
204 applyPose();
205 };
206 const modelSlot = createDeviceModelSlot({
207 load: loadDeviceModel,
208 onError: options.onModelError,
209 install(model) {
210 // Validate and prepare the next scene before releasing the visible one.
211 const next = disposed
212 ? null
213 : model
214 ? createImportedPhoneScene(model.asset, texture, layout)
215 : createPhoneScene(texture, layout, profile);
216 scene.remove(phone.root);
217 phone.dispose();
218 imported = model;
219 if (!next) return;
220 phone = next;
221 scene.add(phone.root);
222 if (accessory) {
223 if (imported) phone.orientation.add(accessory.asset);
224 else accessory.asset.removeFromParent();
225 }
226 applyPose();
227 fit(true);
228 scheduler.invalidate();
229 },
230 });
231 const accessorySlot = createDeviceModelSlot({
232 load: loadDeviceModel,
233 onError: options.onModelError,
234 install(model) {
235 const bounds = model ? new Box3().setFromObject(model.asset) : null;
236 if (
237 bounds &&
238 (bounds.isEmpty() ||
239 ![...bounds.min.toArray(), ...bounds.max.toArray()].every(Number.isFinite))
240 )
241 throw new Error("Device accessory has invalid bounds");
242 accessory?.asset.removeFromParent();
243 accessory = model;
244 accessoryBounds = bounds;
245 if (disposed) return;
246 if (imported && accessory) phone.orientation.add(accessory.asset);
247 fit(true);
248 scheduler.invalidate();
249 },
250 });
251 const setAccessory = (source: DeviceAccessorySource | null) => {
252 accessorySlot.set(source?.modelId === modelSource?.id ? source : null);
253 };
254 const contextLost = (event: Event) => {
255 event.preventDefault();
256 options.onUnavailable();
257 };
258 options.canvas.addEventListener("webglcontextlost", contextLost);
259 applyPose();
260 modelSlot.set(options.model ?? null);
261 setAccessory(options.accessory ?? null);
262 return {
263 setModel(source) {
264 if (source?.id !== modelSource?.id || source?.url !== modelSource?.url)
265 accessorySlot.set(null);
266 modelSource = source;
267 modelSlot.set(source);
268 },
269 setAccessory,
270 frameUpdated() {
271 if (disposed) return;
272 updateLayout();
273 texture.needsUpdate = true;
274 scheduler.invalidate();
275 },
276 setScreen(next, nextProfile = profile) {
277 if (disposed) return;
278 screen = next;
279 updateLayout(nextProfile);
280 scheduler.invalidate();
281 },
282 resize(width, height, pixelRatio) {
283 if (disposed) return;
284 if (![width, height, pixelRatio].every(Number.isFinite) || width <= 0 || height <= 0) return;
285 const ratio = Math.min(2, Math.max(1, pixelRatio));
286 if (viewport.width === width && viewport.height === height && viewport.pixelRatio === ratio)
287 return;
288 viewport = { width, height, pixelRatio: ratio };
289 fit(true);
290 scheduler.invalidate();
291 },
292 screenPoint(x, y, captured = false) {
293 if (disposed) return null;
294 applyPose();
295 return phone.screenPoint(x, y, camera, captured);
296 },
297 orbit(deltaX, deltaY) {
298 if (disposed) return;
299 motion.orbit(deltaX * viewport.width, deltaY * viewport.height, performance.now());
300 scheduler.invalidate();
301 },
302 setInteractionActive(active, mode) {
303 if (disposed) return;
304 const now = performance.now();
305 if (mode === "orbit") motion.dragActive(active, now);
306 else {
307 motion.hold(active, now);
308 framing.hold(active, now);
309 }
310 scheduler.invalidate();
311 },
312 resetPose() {
313 if (disposed) return;
314 motion.reset(rest, performance.now());
315 scheduler.invalidate();
316 },
317 dispose() {
318 if (disposed) return;
319 disposed = true;
320 scheduler.dispose();
321 const hadImported = imported !== null;
322 accessorySlot.dispose();
323 modelSlot.dispose();
324 options.canvas.removeEventListener("webglcontextlost", contextLost);
325 scene.remove(phone.root);
326 if (!hadImported) phone.dispose();
327 texture.dispose();
328 renderer.dispose();
329 renderer.forceContextLoss();
330 },
331 };