const WEARABLE_VENDOR = '{{VENDOR}}';
const WEARABLE_SHAPE = '{{SHAPE}}';
const DEFAULT_PHYS_W = {{WIDTH}};
const DEFAULT_PHYS_H = {{HEIGHT}};
const DEFAULT_DPR = {{DPR}};
const DEFAULT_WASM_PATH = '{{WASM_PATH}}';
function computeSafeArea(shape, lw, lh) {
if (shape === 'round') {
const d = Math.min(lw, lh);
const margin = Math.max(0, d * (1 - Math.SQRT1_2) * 0.5);
return { top: margin, right: margin, bottom: margin, left: margin };
}
if (shape === 'squircle') {
const r = Math.min(lw, lh) * 0.11;
return { top: r, right: r * 0.6, bottom: r, left: r * 0.6 };
}
return { top: 16, right: 6, bottom: 10, left: 6 };
}
function createWearableBridge(services, wasmGlue) {
const state = {
canvas: null,
ctx: null,
gl: null,
glProgram: null,
glVao: null,
glTexture: null,
glTexW: 0,
glTexH: 0,
imgData: null,
imgW: 0,
imgH: 0,
rgbaBuf: null,
rgbaPtr: 0,
rgbaLen: 0,
rgbaView: null,
u8View: null,
wasmApi: null,
wasmMemory: null,
running: false,
ambient: false,
rafArmed: false,
rafIsTimeout: false,
lastTickTs: 0,
rafId: 0,
timerId: 0,
logicalW: Math.round(DEFAULT_PHYS_W / DEFAULT_DPR),
logicalH: Math.round(DEFAULT_PHYS_H / DEFAULT_DPR),
dpr: DEFAULT_DPR,
shape: WEARABLE_SHAPE
};
function installOffscreenFontFactory() {
const g = typeof globalThis !== 'undefined' ? globalThis : null;
if (!g) return;
g.__EUV_HOST_MODE = 'wearable';
if (typeof g.__euvCreateOffscreenCanvas !== 'function') {
g.__euvCreateOffscreenCanvas = function (width, height) {
const w = Math.max(1, Math.round(width || 128));
const h = Math.max(1, Math.round(height || 128));
if (typeof OffscreenCanvas !== 'undefined') {
try {
return new OffscreenCanvas(w, h);
} catch (_e) {}
}
if (typeof document !== 'undefined' && typeof document.createElement === 'function') {
const c = document.createElement('canvas');
c.width = w;
c.height = h;
return c;
}
return null;
};
}
}
function executeHostCommand(cmd) {
if (!cmd) return;
const s = services || {};
switch (cmd.kind) {
case 'vibrateShort':
if (s.vibrator && typeof s.vibrator.vibrate === 'function') s.vibrator.vibrate({ mode: 'short' });
break;
case 'setStorageSync':
if (s.storage && typeof s.storage.set === 'function') s.storage.set({ key: cmd.key, value: cmd.value });
break;
case 'navigateTo':
if (s.router && typeof s.router.push === 'function') s.router.push({ uri: cmd.url || '' });
break;
case 'navigateBack':
if (s.router && typeof s.router.back === 'function') s.router.back();
break;
default:
break;
}
}
function drainCommands() {
if (!state.wasmApi || typeof state.wasmApi.euv_host_drain_commands_json !== 'function') return [];
const raw = state.wasmApi.euv_host_drain_commands_json();
if (!raw || raw === '[]') return [];
try {
const list = JSON.parse(raw);
if (Array.isArray(list)) {
for (let i = 0; i < list.length; i += 1) executeHostCommand(list[i]);
return list;
}
} catch (_e) {}
return [];
}
function getCachedRgbaView(ptr, len) {
const buf = state.wasmMemory.buffer;
if (state.rgbaView && state.rgbaBuf === buf && state.rgbaPtr === ptr && state.rgbaLen === len) {
return state.rgbaView;
}
state.rgbaBuf = buf;
state.rgbaPtr = ptr;
state.rgbaLen = len;
state.rgbaView = new Uint8ClampedArray(buf, ptr, len);
state.u8View = new Uint8Array(buf, ptr, len);
return state.rgbaView;
}
function initWebGl2(canvas) {
if (!canvas || typeof canvas.getContext !== 'function') return false;
let gl = null;
try {
gl = canvas.getContext('webgl2', {
alpha: false,
antialias: false,
depth: false,
stencil: false,
preserveDrawingBuffer: false
});
} catch (_e) {
gl = null;
}
if (!gl || typeof gl.drawArraysInstanced !== 'function' || typeof gl.texStorage2D !== 'function') {
return false;
}
const vsSrc = '#version 300 es\nconst vec2 P[6]=vec2[6](vec2(-1.0,-1.0),vec2(1.0,-1.0),vec2(-1.0,1.0),vec2(1.0,-1.0),vec2(1.0,1.0),vec2(-1.0,1.0));\nout vec2 v_uv;\nvoid main(){vec2 p=P[gl_VertexID];v_uv=vec2(p.x*0.5+0.5,0.5-p.y*0.5);gl_Position=vec4(p,0.0,1.0);}';
const fsSrc = '#version 300 es\nprecision mediump float;\nin vec2 v_uv;\nuniform sampler2D u_tex;\nout vec4 o_col;\nvoid main(){o_col=texture(u_tex,v_uv);}';
const vs = gl.createShader(gl.VERTEX_SHADER);
const fs = gl.createShader(gl.FRAGMENT_SHADER);
gl.shaderSource(vs, vsSrc);
gl.compileShader(vs);
gl.shaderSource(fs, fsSrc);
gl.compileShader(fs);
const prog = gl.createProgram();
gl.attachShader(prog, vs);
gl.attachShader(prog, fs);
gl.linkProgram(prog);
gl.deleteShader(vs);
gl.deleteShader(fs);
if (!gl.getProgramParameter(prog, gl.LINK_STATUS)) {
gl.deleteProgram(prog);
return false;
}
state.gl = gl;
state.glProgram = prog;
state.glVao = gl.createVertexArray();
state.glTexture = null;
state.glTexW = 0;
state.glTexH = 0;
return true;
}
function blitFrameWebGl2(pw, ph, dx, dy, dw, dh) {
const gl = state.gl;
if (!gl || !state.glProgram || !state.u8View) return false;
if (!state.glTexture || state.glTexW !== pw || state.glTexH !== ph) {
if (state.glTexture) gl.deleteTexture(state.glTexture);
state.glTexture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, state.glTexture);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.texStorage2D(gl.TEXTURE_2D, 1, gl.RGBA8, pw, ph);
gl.pixelStorei(gl.UNPACK_ALIGNMENT, 4);
gl.pixelStorei(gl.UNPACK_ROW_LENGTH, 0);
gl.pixelStorei(gl.UNPACK_SKIP_PIXELS, 0);
gl.pixelStorei(gl.UNPACK_SKIP_ROWS, 0);
gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, pw, ph, gl.RGBA, gl.UNSIGNED_BYTE, state.u8View);
state.glTexW = pw;
state.glTexH = ph;
} else {
gl.bindTexture(gl.TEXTURE_2D, state.glTexture);
gl.pixelStorei(gl.UNPACK_ALIGNMENT, 4);
if (dx === 0 && dy === 0 && dw === pw && dh === ph) {
gl.pixelStorei(gl.UNPACK_ROW_LENGTH, 0);
gl.pixelStorei(gl.UNPACK_SKIP_PIXELS, 0);
gl.pixelStorei(gl.UNPACK_SKIP_ROWS, 0);
gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, pw, ph, gl.RGBA, gl.UNSIGNED_BYTE, state.u8View);
} else {
gl.pixelStorei(gl.UNPACK_ROW_LENGTH, pw);
gl.pixelStorei(gl.UNPACK_SKIP_PIXELS, dx);
gl.pixelStorei(gl.UNPACK_SKIP_ROWS, dy);
gl.texSubImage2D(gl.TEXTURE_2D, 0, dx, dy, dw, dh, gl.RGBA, gl.UNSIGNED_BYTE, state.u8View);
gl.pixelStorei(gl.UNPACK_ROW_LENGTH, 0);
gl.pixelStorei(gl.UNPACK_SKIP_PIXELS, 0);
gl.pixelStorei(gl.UNPACK_SKIP_ROWS, 0);
}
}
gl.viewport(0, 0, pw, ph);
gl.useProgram(state.glProgram);
gl.bindVertexArray(state.glVao);
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, state.glTexture);
gl.drawArraysInstanced(gl.TRIANGLES, 0, 6, 1);
return true;
}
function ensureImageData(pw, ph) {
if (state.imgData && state.imgW === pw && state.imgH === ph) return state.imgData;
if (state.ctx && typeof state.ctx.createImageData === 'function') {
state.imgData = state.ctx.createImageData(pw, ph);
} else if (typeof ImageData !== 'undefined') {
state.imgData = new ImageData(pw, ph);
} else {
state.imgData = { width: pw, height: ph, data: new Uint8ClampedArray(pw * ph * 4) };
}
state.imgW = pw;
state.imgH = ph;
return state.imgData;
}
function blitFrame(forceFull) {
if (!state.wasmApi || !state.wasmMemory || !state.canvas || (!state.gl && !state.ctx)) return false;
const ptr = state.wasmApi.euv_host_framebuffer_ptr();
const len = state.wasmApi.euv_host_framebuffer_len();
const pw = state.wasmApi.euv_host_framebuffer_width();
const ph = state.wasmApi.euv_host_framebuffer_height();
if (!ptr || !len || !pw || !ph) return false;
if (state.canvas.width !== pw) state.canvas.width = pw;
if (state.canvas.height !== ph) state.canvas.height = ph;
const dx = forceFull ? 0 : state.wasmApi.euv_host_dirty_x();
const dy = forceFull ? 0 : state.wasmApi.euv_host_dirty_y();
const dw = forceFull ? pw : state.wasmApi.euv_host_dirty_w();
const dh = forceFull ? ph : state.wasmApi.euv_host_dirty_h();
if (!dw || !dh) return false;
const rgba = getCachedRgbaView(ptr, len);
if (state.gl) {
return blitFrameWebGl2(pw, ph, dx, dy, dw, dh);
}
const imgData = ensureImageData(pw, ph);
if (dx === 0 && dy === 0 && dw === pw && dh === ph) {
imgData.data.set(rgba);
state.ctx.putImageData(imgData, 0, 0);
} else {
const dst = imgData.data;
const stride = pw * 4;
const rowBytes = dw * 4;
for (let row = 0; row < dh; row += 1) {
const off = (dy + row) * stride + dx * 4;
dst.set(rgba.subarray(off, off + rowBytes), off);
}
state.ctx.putImageData(imgData, 0, 0, dx, dy, dw, dh);
}
return true;
}
function hostNeedsFrame() {
if (!state.wasmApi) return false;
if (typeof state.wasmApi.euv_host_needs_frame === 'function') {
return Boolean(state.wasmApi.euv_host_needs_frame());
}
return false;
}
function stepNow(dtSecs, forceRender) {
if (!state.wasmApi) return false;
const rendered = state.wasmApi.euv_host_step(dtSecs, Boolean(forceRender));
drainCommands();
if (rendered) return blitFrame(Boolean(forceRender));
return false;
}
function scheduleInteractiveFrame(cb) {
if (typeof requestAnimationFrame === 'function') {
state.rafIsTimeout = false;
state.rafId = requestAnimationFrame(cb);
} else {
state.rafIsTimeout = true;
state.rafId = setTimeout(() => cb(Date.now()), 16);
}
}
function frameTick(ts) {
state.rafArmed = false;
state.rafId = 0;
if (!state.running || state.ambient) return;
const now = typeof ts === 'number' && ts > 0 ? ts : Date.now();
const dt = state.lastTickTs > 0 ? Math.min(0.05, Math.max(0.002, (now - state.lastTickTs) / 1000)) : (1 / 60);
state.lastTickTs = now;
const rendered = stepNow(dt, false);
if (state.running && !state.ambient && (rendered || hostNeedsFrame())) {
state.rafArmed = true;
scheduleInteractiveFrame(frameTick);
} else {
state.lastTickTs = 0;
}
}
function wakeLoop() {
if (!state.running || state.ambient || !state.canvas || state.rafArmed) return;
state.rafArmed = true;
state.lastTickTs = 0;
scheduleInteractiveFrame(frameTick);
}
function startLoop() {
if (!state.canvas) return;
state.running = true;
if (state.ambient) {
if (!state.timerId) {
state.timerId = setInterval(() => {
if (!state.running || !state.ambient) return;
stepNow(1.0, true);
}, 1000);
}
return;
}
wakeLoop();
}
function stopLoop() {
state.running = false;
state.rafArmed = false;
state.lastTickTs = 0;
if (state.rafId) {
if (state.rafIsTimeout) clearTimeout(state.rafId);
else if (typeof cancelAnimationFrame === 'function') cancelAnimationFrame(state.rafId);
state.rafId = 0;
}
if (state.timerId) {
clearInterval(state.timerId);
state.timerId = 0;
}
}
async function mount(canvas, profile) {
state.canvas = canvas;
state.gl = null;
state.ctx = initWebGl2(canvas)
? null
: (canvas && typeof canvas.getContext === 'function' ? canvas.getContext('2d') : null);
if (profile) {
state.dpr = Math.min(16.0, Math.max(0.25, Number(profile.dpr || DEFAULT_DPR)));
state.logicalW = Math.max(120, Math.round(Number(profile.width || DEFAULT_PHYS_W) / state.dpr));
state.logicalH = Math.max(120, Math.round(Number(profile.height || DEFAULT_PHYS_H) / state.dpr));
if (profile.shape) state.shape = profile.shape;
}
const safe = computeSafeArea(state.shape, state.logicalW, state.logicalH);
installOffscreenFontFactory();
const glue = wasmGlue || (typeof globalThis !== 'undefined' && globalThis.__euvWasmBindgen) || null;
if (!glue || typeof glue.__euvInitHost !== 'function') return false;
const wasmSource = (typeof globalThis !== 'undefined' && globalThis.__EUV_WASM_SOURCE) || DEFAULT_WASM_PATH;
const initialized = await glue.__euvInitHost(wasmSource);
state.wasmApi = initialized.api;
state.wasmMemory = initialized.memory;
state.wasmApi.euv_host_init(3, WEARABLE_VENDOR, state.logicalW, state.logicalH, state.dpr, safe.top, safe.bottom);
state.wasmApi.euv_host_safe_area(safe.top, safe.right, safe.bottom, safe.left);
state.wasmApi.euv_host_theme(true);
state.wasmApi.euv_host_step(1 / 60, true);
blitFrame(true);
drainCommands();
startLoop();
return true;
}
function dispatchTouch(phase, event) {
if (!state.wasmApi || typeof state.wasmApi.euv_host_touch !== 'function') return;
const touches = (event && (event.changedTouches || event.touches)) || [];
const scaleX = state.logicalW / Math.max(1, state.canvas ? state.canvas.width : DEFAULT_PHYS_W);
const scaleY = state.logicalH / Math.max(1, state.canvas ? state.canvas.height : DEFAULT_PHYS_H);
for (let i = 0; i < touches.length; i += 1) {
const t = touches[i];
const rx = Number(typeof t.clientX === 'number' ? t.clientX : (t.x || 0));
const ry = Number(typeof t.clientY === 'number' ? t.clientY : (t.y || 0));
const lx = rx > state.logicalW ? rx * scaleX : rx;
const ly = ry > state.logicalH ? ry * scaleY : ry;
state.wasmApi.euv_host_touch(phase, Number(t.identifier || 0), lx, ly);
}
stepNow(1 / 60, false);
wakeLoop();
}
function dispatchCrown(delta, mode) {
if (!state.wasmApi || typeof state.wasmApi.euv_host_crown !== 'function') return;
state.wasmApi.euv_host_crown(Number(delta || 0), Number(mode || 0));
const s = services || {};
if (delta !== 0 && s.vibrator && typeof s.vibrator.vibrate === 'function') {
s.vibrator.vibrate({ mode: 'short' });
}
stepNow(1 / 60, false);
wakeLoop();
}
function setAmbient(isAmbient) {
state.ambient = Boolean(isAmbient);
if (state.wasmApi && typeof state.wasmApi.euv_host_ambient === 'function') {
state.wasmApi.euv_host_ambient(state.ambient);
stepNow(1.0, true);
}
if (state.running) {
stopLoop();
startLoop();
}
}
function dispatchGesture(tag) {
if (!state.wasmApi || typeof state.wasmApi.euv_host_hardware_gesture !== 'function') return;
state.wasmApi.euv_host_hardware_gesture(Number(tag));
stepNow(1 / 60, true);
wakeLoop();
}
function dispatchLifecycle(tag) {
if (tag === 3 || tag === 4) stopLoop();
else if (tag === 2 && state.canvas && state.wasmApi) startLoop();
if (state.wasmApi && typeof state.wasmApi.euv_host_lifecycle === 'function') {
state.wasmApi.euv_host_lifecycle(tag, '');
if (tag === 2) {
stepNow(1 / 60, true);
wakeLoop();
}
}
}
function navigate(route) {
if (!state.wasmApi || typeof state.wasmApi.euv_host_navigate !== 'function') return 0;
const hash = state.wasmApi.euv_host_navigate(String(route || '/'));
blitFrame(true);
wakeLoop();
return hash;
}
function getStats() {
if (!state.wasmApi || typeof state.wasmApi.euv_host_stats_json !== 'function') return null;
try {
return JSON.parse(state.wasmApi.euv_host_stats_json());
} catch (_e) {
return null;
}
}
function destroy() {
stopLoop();
if (state.wasmApi && typeof state.wasmApi.euv_host_destroy === 'function') {
state.wasmApi.euv_host_destroy();
}
state.canvas = null;
state.ctx = null;
state.gl = null;
state.glProgram = null;
state.glVao = null;
state.glTexture = null;
state.glTexW = 0;
state.glTexH = 0;
state.imgData = null;
state.rgbaBuf = null;
state.rgbaView = null;
state.u8View = null;
}
return {
WEARABLE_VENDOR,
WEARABLE_SHAPE,
mount,
stepNow,
drainCommands,
dispatchTouch,
dispatchCrown,
setAmbient,
dispatchGesture,
dispatchLifecycle,
navigate,
getStats,
destroy
};
}