Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ dist/
wasm/viro-web.js
wasm/viro-web.wasm
wasm/viro-web.data
wasm/Roboto-*.ttf

# The tinyvio tracking engine, copied in by scripts/copy-slam.sh. Same policy as
# the renderer binaries above: build output of another repo, not tracked here,
Expand Down
16 changes: 16 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,21 @@
# Changelog

## Unreleased

### Added

- **Styled text:** `ViroSceneApi.createStyledText` takes a family list, weight, italic, extrusion depth and an outline or drop shadow, and `ViroWebRenderer.loadTextFace` fetches the Roboto face a weight or italic needs from beside the wasm. The 11 faces ship as `wasm/Roboto-*.ttf`; `viro-web.data` is unchanged. On an older binary `createStyledText` draws plain text.
- **Material alpha, bloom threshold, colour write mask and chroma key:** `ViroSceneApi.setMaterialAlpha`, `setMaterialBloomThreshold`, `setMaterialColorWriteMask` (`ViroColorWriteMask` bits) and `setMaterialChromaKey`. On an older binary they do nothing and `supportsMaterialEffects` is false.
- **Pinch, rotate and fuse:** two touch pointers on the canvas become a pinch and a rotate on the node under their midpoint, as on iOS and Android (`ViroNodeEventHandlers.onPinch`, `onRotate`, and `onFuse` for the screen-centre gaze, with `ViroSceneApi.setNodeTimeToFuse`). They start on the first two-finger move; the first finger's press is cancelled without a click.
- **Node reads:** `ViroSceneApi.getNodeWorldTransform` and `getNodeBoundingBox`, decomposed as native's `getTransformAsync` and `getBoundingBoxAsync` are. `supportsGestures` is false on an older binary.
- **Context loss:** `ViroWebRenderer.isContextLost` and `addContextListener`. After a restore, dispose the renderer and create a new one on the same canvas.

### Fixed

- **The canvas is opaque, as a native view is.** Empty space showed the page behind the canvas; it now shows the scene's clear colour (black).
- **`dispose()` stops the render loop.** A disposed renderer kept drawing, so every remount added another loop.
- **`pointercancel` no longer completes a click.** It was sent as a release and could click the pressed node.

## 1.1.1

Needs the virocore web build of 3.1.1; it ships in this package.
Expand Down
6 changes: 4 additions & 2 deletions THIRD-PARTY-LICENSES.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,10 @@ This software is based in part on the work of the Independent JPEG Group.
## Roboto

The typeface every text geometry renders in, baked into `wasm/viro-web.data`
and therefore redistributed with this package. Roboto is also what Viro renders
text in on Android and Quest, so the three agree.
and therefore redistributed with this package. Its other weights and italics
(`wasm/Roboto-*.ttf`, from Android's system fonts) ship beside the wasm and are
fetched when a text uses them. Roboto is also what Viro renders text in on
Android and Quest, so the three agree.

Copyright the Roboto Project Authors, licensed under the Apache License,
Version 2.0. You may obtain a copy of the licence at
Expand Down
12 changes: 11 additions & 1 deletion scripts/copy-wasm.sh
Original file line number Diff line number Diff line change
Expand Up @@ -19,5 +19,15 @@ fi
mkdir -p "$DEST_DIR"
cp "$SRC_DIR/viro-web.js" "$SRC_DIR/viro-web.wasm" "$SRC_DIR/viro-web.data" "$DEST_DIR/"

# Roboto's other weights and italics, served beside the wasm and fetched only
# when a text asks for one (ViroWebRenderer.loadTextFace), so viro-web.data
# stays one face.
FONTS_DIR="${VIRO_WASM_FONTS:-$SRC_DIR/../../fonts}"
if ! ls "$FONTS_DIR"/Roboto-*.ttf >/dev/null 2>&1; then
echo "ERROR: no Roboto faces at $FONTS_DIR (set VIRO_WASM_FONTS to virocore/wasm/fonts)"
exit 1
fi
cp "$FONTS_DIR"/Roboto-*.ttf "$DEST_DIR/"

echo "Copied into $DEST_DIR:"
ls -lh "$DEST_DIR"/viro-web.*
ls -lh "$DEST_DIR"/viro-web.* "$DEST_DIR"/Roboto-*.ttf
208 changes: 193 additions & 15 deletions src/ViroWebRenderer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import {
type ViroAnimationHandlers,
} from "./sceneApi.js";
import { ViroRendererAbortError } from "./types.js";
import type { ViroWebModule, ViroWebRendererOptions } from "./types.js";
import type { LocateFile, ViroWebModule, ViroWebRendererOptions } from "./types.js";

const MODEL_EXT: Record<ViroModelFormat, string> = {
[ViroModelFormat.GLB]: "glb",
Expand Down Expand Up @@ -73,6 +73,12 @@ function computeSize(
* `create()` gives you an empty scene. Build into it through {@link scene},
* the handle-based API the Viro web bridge's reconciler drives.
*/
/** Context loss notifications; see ViroWebRenderer.isContextLost. */
export interface ViroContextListener {
onLost?: () => void;
onRestored?: () => void;
}

export class ViroWebRenderer {
private disposed = false;
private detachInput?: () => void;
Expand All @@ -81,7 +87,11 @@ export class ViroWebRenderer {
private readonly modelLoadResolvers = new Map<ViroHandle, (success: boolean) => void>();
private readonly animationHandlers = new Map<ViroHandle, ViroAnimationHandlers>();
private readonly abortListeners = new Set<(error: ViroRendererAbortError) => void>();
private readonly textFaces = new Map<string, Promise<boolean>>();
private abortError: ViroRendererAbortError | null = null;
private contextLost = false;
private readonly contextListeners = new Set<ViroContextListener>();
private detachContext?: () => void;

private constructor(
private readonly module: ViroWebModule,
Expand Down Expand Up @@ -196,6 +206,40 @@ export class ViroWebRenderer {
}
}

/**
* Makes the face a text at `weight` (100 to 900) and `italic` draws in ready
* to use. Only the regular face is preloaded; the others are served beside
* the wasm and fetched the first time a text asks for them, and stay in the
* FS after. Resolves false when the face could not be had, in which case
* such a text draws in the regular face.
*/
loadTextFace(weight = 400, italic = false): Promise<boolean> {
const file = this.module.viroTextFaceFile?.(weight, italic);
if (!file || file === "Roboto") return Promise.resolve(true);
let pending = this.textFaces.get(file);
if (!pending) {
const locate = this.module.locateFile as LocateFile | undefined;
const url = locate ? locate(`${file}.ttf`, "") : `${file}.ttf`;
pending = fetch(url)
.then((res) => {
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.arrayBuffer();
})
.then((buf) => {
this.module.FS.writeFile(`/${file}.ttf`, new Uint8Array(buf));
return true;
})
.catch((err) => {
console.warn(`[Viro web] could not load the ${file} face from ${url} (${err}); drawing that text in Roboto`);
// Asked again next time, rather than failing for the rest of the page.
this.textFaces.delete(file);
return false;
});
this.textFaces.set(file, pending);
}
return pending;
}

/**
* Load a radiance .hdr from a URL and apply it as the scene's IBL lighting
* environment. Fetches the bytes, writes them to the WASM FS, then loads +
Expand Down Expand Up @@ -253,6 +297,12 @@ export class ViroWebRenderer {
handlers.onClick?.(intArg, source, position);
} else if (action === ViroEventAction.Hover) {
handlers.onHover?.(intArg === 1, source, position);
} else if (action === ViroEventAction.Pinch) {
handlers.onPinch?.(intArg, position[0], source);
} else if (action === ViroEventAction.Rotate) {
handlers.onRotate?.(intArg, position[0], source);
} else if (action === ViroEventAction.Fuse) {
handlers.onFuse?.(source);
}
}

Expand Down Expand Up @@ -284,37 +334,126 @@ export class ViroWebRenderer {
console.log("[Viro web] renderer build " + buildId);
}
renderer.attachInput();
renderer.attachContextLoss();
return renderer;
}

/**
* Forward canvas pointer events to the renderer as touch actions, converting
* CSS coordinates to the canvas's device-pixel backing store.
*
* A second finger turns the touch into a pinch and a rotate, as on a phone:
* the first finger's press is cancelled without a click, both gestures start
* on the node under the fingers' midpoint, and nothing more reaches the scene
* until every finger has lifted. `pointercancel` cancels the press too, for
* any pointer id (the virtual camera sends one when it takes two fingers).
*/
private attachInput(): void {
const canvas = this.canvas;
const send = (action: number, e: PointerEvent) => {
const m = this.module;
const toCanvas = (clientX: number, clientY: number): [number, number] | null => {
const rect = canvas.getBoundingClientRect();
if (rect.width === 0 || rect.height === 0) return;
const x = (e.clientX - rect.left) * (canvas.width / rect.width);
const y = (e.clientY - rect.top) * (canvas.height / rect.height);
this.module.viroOnTouch(action, x, y);
if (rect.width === 0 || rect.height === 0) return null;
return [(clientX - rect.left) * (canvas.width / rect.width), (clientY - rect.top) * (canvas.height / rect.height)];
};
const send = (action: number, e: PointerEvent) => {
const p = toCanvas(e.clientX, e.clientY);
if (p) m.viroOnTouch(action, p[0], p[1]);
};

const onDown = (e: PointerEvent) => send(0, e);
const onMove = (e: PointerEvent) => send(1, e);
const onUp = (e: PointerEvent) => send(2, e);
const fingers = new Map<number, { x: number; y: number }>();
// Starts on the first move, as iOS and Android recognisers do: two fingers
// that land and lift without moving are no gesture at all.
let gesture: { spread: number; angle: number; started: boolean; at: [number, number] } | null = null;
// Set once a gesture starts and cleared when the last finger lifts.
let held = false;
const pair = () => {
const [a, b] = [...fingers.values()];
return {
mid: toCanvas((a!.x + b!.x) / 2, (a!.y + b!.y) / 2),
spread: Math.hypot(b!.x - a!.x, b!.y - a!.y),
angle: Math.atan2(b!.y - a!.y, b!.x - a!.x),
};
};
const gestureEvent = (state: number, scale: number, radians: number, at: [number, number]) => {
m.viroOnPinch!(state, scale, at[0], at[1]);
m.viroOnRotate!(state, radians, at[0], at[1]);
};
let last = { scale: 1, radians: 0, at: [0, 0] as [number, number] };
const endGesture = () => {
if (gesture?.started) gestureEvent(3, last.scale, last.radians, last.at);
gesture = null;
};

const onDown = (e: PointerEvent) => {
if (e.pointerType === "touch" && typeof m.viroOnPinch === "function") {
fingers.set(e.pointerId, { x: e.clientX, y: e.clientY });
if (fingers.size === 2 && !held) {
held = true;
m.viroOnTouch(3, 0, 0);
const p = pair();
if (p.mid && p.spread > 0) {
gesture = { spread: p.spread, angle: p.angle, started: false, at: p.mid };
last = { scale: 1, radians: 0, at: p.mid };
}
}
if (held) return;
}
send(0, e);
};
const onMove = (e: PointerEvent) => {
if (fingers.has(e.pointerId)) {
fingers.set(e.pointerId, { x: e.clientX, y: e.clientY });
if (held) {
if (gesture && fingers.size >= 2) {
if (!gesture.started) {
gesture.started = true;
gestureEvent(1, 1, 0, gesture.at);
}
const p = pair();
// Screen y points down, so a clockwise turn grows the angle; native
// reports counterclockwise as positive.
let turn = gesture.angle - p.angle;
turn = Math.atan2(Math.sin(turn), Math.cos(turn));
last = { scale: p.spread / gesture.spread, radians: last.radians + turn, at: p.mid ?? last.at };
gesture.angle = p.angle;
gestureEvent(2, last.scale, last.radians, last.at);
}
return;
}
}
send(1, e);
};
const onUp = (e: PointerEvent) => {
fingers.delete(e.pointerId);
if (held) {
if (fingers.size < 2) endGesture();
if (fingers.size === 0) held = false;
return;
}
send(2, e);
};
// Any id ends the press: the virtual camera cancels with the second finger's
// id and then keeps both fingers' events to itself.
const onCancel = (e: PointerEvent) => {
if (held) {
onUp(e);
return;
}
fingers.clear();
m.viroOnTouch(3, 0, 0);
};

canvas.addEventListener("pointerdown", onDown);
canvas.addEventListener("pointermove", onMove);
canvas.addEventListener("pointerup", onUp);
canvas.addEventListener("pointercancel", onUp);
canvas.addEventListener("pointercancel", onCancel);

this.detachInput = () => {
canvas.removeEventListener("pointerdown", onDown);
canvas.removeEventListener("pointermove", onMove);
canvas.removeEventListener("pointerup", onUp);
canvas.removeEventListener("pointercancel", onUp);
canvas.removeEventListener("pointercancel", onCancel);
};
}

Expand All @@ -340,24 +479,63 @@ export class ViroWebRenderer {
/**
* Release references and stop responding to input.
*
* NOTE: the WASM main loop is not stoppable from the C API yet — a proper
* teardown (emscripten_cancel_main_loop + context destroy) is a follow-up.
* Until then a disposed renderer keeps drawing, so an app that mounts and
* unmounts repeatedly accumulates render loops. Create one and keep it.
* Stops the render loop on a binary that can (older ones keep drawing).
*
* Any model load still in flight is settled as failed: its native callback
* would have nowhere to arrive.
*/
dispose(): void {
this.module.viroStopMainLoop?.();
this.detachInput?.();
this.detachInput = undefined;
this.detachContext?.();
this.detachContext = undefined;
this.contextListeners.clear();
for (const resolve of this.modelLoadResolvers.values()) resolve(false);
this.modelLoadResolvers.clear();
this.eventHandlers.clear();
this.animationHandlers.clear();
this.disposed = true;
}

/**
* True once the browser has taken the WebGL context away (a GPU reset, or a
* mobile browser reclaiming memory). Nothing this renderer made comes back
* with the context: when it is restored, dispose this renderer and create a
* new one on the same canvas.
*/
get isContextLost(): boolean {
return this.contextLost;
}

/** Be told when the context is lost and when it is back. Returns an unsubscribe. */
addContextListener(listener: ViroContextListener): () => void {
this.contextListeners.add(listener);
return () => {
this.contextListeners.delete(listener);
};
}

private attachContextLoss(): void {
const canvas = this.canvas;
const onLost = (e: Event) => {
// Without this the browser never restores the context.
e.preventDefault();
this.contextLost = true;
this.module.viroStopMainLoop?.();
for (const l of [...this.contextListeners]) l.onLost?.();
};
const onRestored = () => {
for (const l of [...this.contextListeners]) l.onRestored?.();
};
canvas.addEventListener("webglcontextlost", onLost);
canvas.addEventListener("webglcontextrestored", onRestored);
this.detachContext = () => {
canvas.removeEventListener("webglcontextlost", onLost);
canvas.removeEventListener("webglcontextrestored", onRestored);
};
}

/**
* Set once the WASM runtime has aborted (see ViroWebRendererOptions.onAbort).
* A renderer in that state cannot recover; a new one has to be created.
Expand Down
8 changes: 7 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,24 +4,27 @@
* WebAssembly/WebGL2 build of the Viro renderer (virocore) for the web platform.
*/

export { ViroWebRenderer } from "./ViroWebRenderer.js";
export { ViroWebRenderer, type ViroContextListener } from "./ViroWebRenderer.js";
export { loadViroWebModule } from "./loader.js";
export { loadBundledSlam } from "./slamLoader.js";
export {
ViroSceneApi,
ViroLightingModel,
ViroLightType,
ViroEventAction,
ViroGestureState,
ViroClickState,
ViroTextureChannel,
ViroWrapMode,
ViroFilterMode,
ViroCullMode,
ViroBlendMode,
ViroColorWriteMask,
ViroModelFormat,
ViroEasing,
ViroTrackingState,
ViroTextHorizontalAlignment,
ViroTextOuterStroke,
ViroTextVerticalAlignment,
ViroLineBreakMode,
ViroTextClipMode,
Expand All @@ -37,8 +40,11 @@ export {
VIRO_INVALID_HANDLE,
} from "./sceneApi.js";
export type {
ViroTextStyle,
ViroHandle,
ViroNodeEventHandlers,
ViroNodeTransform,
ViroBoundingBox,
ViroAnimationHandlers,
ViroShaderEntryPoint,
} from "./sceneApi.js";
Expand Down
Loading
Loading