WebGL Prototyping Harness: Immersive Preview, Perf Metrics & A11y Export
Executive Summary
Sherlock's Verdict : This is a detective's toolkit for immersive prototyping—scanning scenes for fluidity, interactivity, and inclusivity. Built on raw WebGL for precision (with Three.js abstraction for sanity), it simulates WebXR environments, budgets frames like a miser, and exports a11y annotations as forensic reports. Deployable as a single-page app (SPA), it loads GLTF/JSON prototypes, previews in browser XR, tracks 11.1ms/8.3ms frame budgets (90/120Hz), and spits out JSON/CSV a11y audits.
Key Wins :
Preview : Real-time WebXR sessions (VR/AR emulation).
Perf : Live frame waterfalls, budget violators highlighted.
Export : A11y tree with WCAG scores, ARIA mappings, contrast ratios.
Tech Stack :
Component Tech Rendering WebGL 2.0 + Three.js (scenes, XR) Immersive WebXR Device API (polyfill for desktop) Perf performance.now(), RAF loop, WebGL ProfilerA11y axe-core + custom DOM/XR annotations UI React + Tailwind (control panel) Export JSON/CSV via FileSaver.js Build Vite (dev server with HMR)
Demo Flow : Drag GLTF → Enter XR Preview → Toggle Metrics Overlay → Export Report.
Architecture Overview
code Copy code
┌─────────────────────┐ ┌──────────────────┐ ┌─────────────────┐
│ Control Panel │───▶│ WebGL Canvas │◀───│ Performance │
│ (React UI: Load, │ │ (Three.js + XR) │ │ Monitor │
│ Metrics, Export) │ │ - Immersive │ │ - Frame Budget │
└─────────────────────┘ │ Interactions │ │ - Waterfall │
│ - A11y Overlays │ └─────────────────┘
└──────────────────┘
│
▼
┌─────────────────┐
│ A11y Auditor │ ──▶ JSON/CSV Export
│ (axe-core + XR) │
└─────────────────┘
Core Loop : requestAnimationFrame → Update (interactions) → Render (WebGL) → Measure → Audit.
Modular : Plugins for custom interactions/metrics.
Responsive : Desktop (mouse/keyboard sim), Mobile (touch/gaze), XR (controllers).
Feature Deep Dive
1. Immersive Interaction Preview
Load Prototypes : Drag-n-drop GLTF/GLB/USDZ. Parse with Three.js GLTFLoader.
XR Session : Button triggers navigator.xr.requestSession('immersive-vr'|'immersive-ar').
Fallback: Magic Window (perspective camera + device orientation).
Interactions :
Type Implementation Gaze/Pointer Raycasting from controller/camera Gestures Handpose.js (MediaPipe) or XR hand tracking Controllers XRInputSource events (select, squeeze) Physics Cannon.js/Ammo.js for collisions
Preview Modes : Inline canvas, fullscreen, split-view (3D + DOM overlays).
Code Snippet (XR Setup) :
javascript Copy code
import * as THREE from 'three';
import { XRControllerModelFactory } from 'three/examples/jsm/webxr/XRControllerModelFactory.js';
class ImmersivePreview {
constructor(canvas) {
this.renderer = new THREE.WebGLRenderer({ canvas, xr: true });
this.scene = new THREE.Scene();
// ... load GLTF into scene
this.renderer.xr.enabled = true;
document.body.appendChild(THREE.XRButton.createButton(this.renderer));
}
onXRSessionStart(session) {
// Inject controllers, hand tracking
const controller1 = this.renderer.xr.getController(0);
controller1.addEventListener('selectstart', onSelectStart);
this.scene.add(controller1);
}
}
2. Frame Budget Measurement
Budgets : Configurable (90Hz: 11.1ms total; alloc: 4ms update, 6ms render, 1ms GPU).
Metrics :
Metric Source Alert Threshold Frame Time performance.now() deltas>16.7ms (60Hz) GPU Time WEBGL_draw_buffers extension>Budget FPS Smoothed avg <Target Hz Draw Calls gl.getParameter(gl.DRAW_CALLS)>500/frame Memory performance.memory>80% used
UI : Overlay HUD (toggleable): Graph (Chart.js), waterfall timeline, color-coded violators (red for overruns).
Profiling : Sample 100 frames → Histogram + Flame Chart export.
Code Snippet (RAF Loop) :
javascript Copy code
class FrameMonitor {
frameBudget = { total: 11.1, update: 4, render: 6 }; // ms @90Hz
metrics = { fps: 0, frameTimes: [] };
animate = (time) => {
const frameStart = performance.now();
this.updateScene(time); // Interactions
const updateEnd = performance.now();
this.render(); // WebGL draw
const renderEnd = performance.now();
const frameTime = performance.now() - frameStart;
this.metrics.frameTimes.push(frameTime);
this.checkBudget(frameTime, updateEnd - frameStart, renderEnd - updateEnd);
requestAnimationFrame(this.animate);
};
checkBudget(frameTime, updateTime, renderTime) {
if (frameTime > this.frameBudget.total) {
console.warn('Budget overrun!', { frameTime, breakdown: { updateTime, renderTime } });
// UI flash red
}
}
}
3. Accessibility Annotations & Export
Auditing :
Scene Elements : Traverse Three.js hierarchy → Annotate meshes with userData.a11y (role, label, focusable).
DOM Overlays : axe-core on HUD/UI.
Immersive A11y : WCAG 2.2 for XR (spatial audio cues, high-contrast modes, voice-over sim).
Metrics: Contrast (html2canvas), ARIA compliance, keyboard nav in sim mode.
Annotations : JSON tree e.g.:
json Copy code
{
"nodeId": "mesh-123",
"role": "button",
"label": "Interact Here",
"issues": ["low-contrast", "no-focus-indicator"],
"wcagScore": 0.85,
"screenReaderText": "Press to activate portal"
}
Export :
Format Content JSON Full annotation tree CSV Flat issues list HTML Report w/ screenshots (html2canvas) GLTF Embedded a11y metadata
Code Snippet (A11y Auditor) :
javascript Copy code
import axe from 'axe-core';
class A11yExporter {
auditScene(scene) {
const annotations = [];
scene.traverse((obj) => {
if (obj.userData.a11y) {
annotations.push({
...obj.userData.a11y,
violations: axe.run(obj, { runOnly: ['color', 'aria'] }) // Partial axe
});
}
});
return annotations;
}
export(format = 'json') {
const report = this.auditScene(scene);
const blob = new Blob([JSON.stringify(report, null, 2)], { type: 'application/json' });
saveAs(blob, `a11y-report-${Date.now()}.json`);
}
}
Implementation Roadmap
Bootstrap (1 day) : Vite + React + Three.js boilerplate.
Core Rendering (2 days) : GLTF loader, XR integration.
Interactions (2 days) : Controllers, gestures.
Perf Monitor (1 day) : RAF loop, HUD.
A11y Layer (2 days) : Auditor, exporters.
Polish (1 day) : Themes, mobile, error handling.
Total : ~1 week solo.
Usage & Deployment
Run : npm create vite@latest harness --template react-ts && npm i three @types/three axe-core chart.js
Dev Server : vite --port 3000 (HTTPS for XR).
Prod : vite build → Static host (Netlify/Vercel). PWA manifest for fullscreen.
Extensibility : Plugin API: registerInteraction(type, handler), registerMetric(name, fn).
Edge Cases Handled : No XR? Emulate. Low perf? LODs auto-apply. A11y fail? Warnings inline.
This harness turns prototypes into evidence—proving they're immersive, performant, and accessible. Need code repo or tweaks, guv'nor? Pipes up monocle.