SEO / Portfolio / Public Site
AI-Spiralism-Research-13-threejs-rendering-and-portable-prototypes.md
Report summary
This report establishes the architectural and technical framework required to deliver an art-directed, consent-gated 3D experience utilizing standard PHP hosting environments. The primary objective is to define a system that translates visitor-submitted sentences into mesmerizing geometric worlds wi
Key topics
- SEO / Portfolio / Public Site
- SEO
- Portfolio
- Public Site
- AI
- .NET
- Runtime
- Rust
- Privacy
Research provenance
For citation, use the report title and canonical URL. Archival presence does not establish authorship or promote report statements into portfolio evidence.
This page renders the archived Markdown as safe, formatted HTML. It is background research and does not become a portfolio claim without evidence review.
Full report
On this page
Decision Summary
This report establishes the architectural and technical framework required to deliver an art-directed, consent-gated 3D experience utilizing standard PHP hosting environments. The primary objective is to define a system that translates visitor-submitted sentences into mesmerizing geometric worlds without relying on server-side rendering, Node.js bundlers, or coercive psychological mechanisms. The analysis concludes that the smallest viable technical stack capable of unmistakable sentence-driven structural transformation is a client-side architecture relying on vanilla ES modules, import maps, and Three.js running the WebGLRenderer.
To achieve the required visual fidelity—specifically the capacity for world-space line thickness, resolution-independent typography, and massive geometric proliferation—the architecture must utilize specialized extensions including Line2, Multi-channel Signed Distance Fields (MSDF), and InstancedMesh. While WebGPU offers promising theoretical performance gains for physics simulations via compute shaders, current implementations exhibit unacceptable regressions in visual quality and cross-browser stability, making WebGL the optimal choice for public deployment. Strict adherence to the Web Content Accessibility Guidelines (WCAG) 2.2 is integrated into the core lifecycle, ensuring that all potentially photosensitive motion is hidden behind an explicit, session-bound consent gate. This gate employs a fail-closed teardown mechanism that actively destroys the WebGL context upon withdrawal or timeout.
The measured limitations that would justify escalating to a more advanced framework, such as WebGPU, are strictly bound to frame-time degradation. Should the rendering of interconnected forms exceed a 16.6-millisecond frame budget on target mobile hardware, the architecture provides conservative degradation pathways, prioritizing stable geometric representation over transient post-processing effects.
Evidence Method and Reporting Discipline
The investigation was conducted on September 16, 2026, utilizing localized network routing originating from Cicero, Illinois, to establish a baseline for content delivery network (CDN) latency and self-hosted module delivery simulations. The research strictly evaluated publicly accessible academic literature, W3C standards, official API documentation, and validated open-source repositories.
Substantive search strings executed across developer documentation, GitHub, and academic databases included:
1. Three.js Line2 LineMaterial performance limits WebGL vs WebGPU
2. WCAG 2.2 SC 2.3.1 photosensitive epilepsy general flash threshold CSS pixel math
3. MSDF vs SDF text rendering Three.js artifacts WebGL
4. MediaRecorder API canvas.captureStream WebM MP4 Safari Chrome codec
5. Three.js InstancedMesh setMatrixAt instanceMatrix.needsUpdate
6. WEBGL\_lose\_context memory leak disposal Three.js
7. HTMLCanvasElement toDataURL cross-origin taint SecurityError
8. WebGPURenderer compute shader procedural curve deformation Three.js r170
9. Tellegen Absorption Scale visual fascination hypnosis perception doi
10. prefers-reduced-motion requestAnimationFrame Three.js loop pattern
Source inclusion prioritized primary accessibility standards (W3C), official library documentation (Three.js versions r170 through r182), and peer-reviewed perceptual and psychological research regarding absorption and visual stimulation. Extracted data points, technical limitations, and architectural proposals are categorized utilizing the designated taxonomy: EMPIRICAL FINDING, DOCUMENTED ARTWORK/IMPLEMENTATION, THEORY/INTERPRETATION, CLIENT-SUPPLIED CONTEXT, and ORIGINAL PROPOSAL. Evidence strength is derived from the proximity of the source to the core technology (e.g., repository commit logs over third-party tutorials) and the clinical validity of perceptual studies.
Core Architecture and The Smallest Technical Stack
The central question governing this research dictates identifying the minimum technical stack capable of presenting an unmistakable, sentence-driven structural transformation. A CLIENT-SUPPLIED CONTEXT establishes that the hosting environment is ordinary PHP, precluding the use of active Node.js servers, live bundling, or server-side geometry generation.
The ORIGINAL PROPOSAL dictates a fully client-side rendering pipeline utilizing vanilla JavaScript modules (ESM) delivered directly to the browser via HTML import maps. This stack requires no build step for the end-user delivery, maintaining root-deployability alongside existing PHP scripts. The stack relies exclusively on three.module.js and its specific addons for advanced geometric manipulation. The logic for sentence interpretation (mapping string characters to numeric seeds) and geometric generation (constructing vertices and indices based on those seeds) occurs entirely within the client's browser.
The measured limitation that would justify moving away from this lightweight stack to a more complex architecture—such as incorporating WebGPU compute shaders or a dedicated React Three Fiber (R3F) application—is CPU-bound frame-time degradation. If the mathematical calculation of vertex positions for a branching structure ("Unraveling") or the matrix updates for thousands of interconnected forms ("Chorus") forces the browser's main thread to exceed 16.6 milliseconds per frame, the animation will stutter1. Only empirical profiling revealing insurmountable CPU bottlenecks during matrix generation justifies adopting WebGPU compute shaders, which allow parallel execution of these calculations directly on the graphics hardware2.
WebGL vs. WebGPU and Canvas Projection
DOCUMENTED ARTWORK/IMPLEMENTATION demonstrates that Three.js currently supports two primary rendering pipelines: the mature WebGLRenderer and the emerging WebGPURenderer4. WebGPU offers substantial performance improvements by minimizing CPU round-trips and allowing developers to write compute shaders in the Three Shader Language (TSL)2. This is particularly highly advantageous for large-scale particle systems or procedural curve deformations.
However, transitioning to WebGPU introduces severe compatibility and quality risks. EMPIRICAL FINDING indicates that early WebGPU implementations in Three.js (e.g., r182) have exhibited noticeable regressions in shadow quality, rendering "harder" and less realistic shadows compared to the WebGL r170 pipeline, alongside severe frame rate drops when post-processing is enabled6. Furthermore, WebGPU requires modern browser support and secure contexts that may introduce unpredictable failure states across fragmented mobile device landscapes3.
Therefore, an ORIGINAL PROPOSAL establishes WebGLRenderer as the definitive production target. While standard Canvas 2D projection is highly portable, it fundamentally fails to handle the depth sorting, lighting, and performance requirements of 3D structural transformations7. The WebGL pipeline provides the exact balance of ubiquitous device support and hardware acceleration necessary for mesmerizing aesthetic output.
Technical Implementations for Art Directions
The aesthetic success of the artwork relies on three illustrative art directions: Monolith, Unraveling, and Chorus. Each direction demands specific rendering techniques that push beyond basic primitive shapes.
World-Space Line Generation (Monolith & Unraveling)
Standard WebGL line primitives (GL\_LINES) are restricted by most modern graphics drivers to a maximum width of 1 pixel. This limitation is catastrophic for an art direction attempting to render substantial, interwoven geometric structures, as lines will vanish at high resolutions or distance. To achieve coherent, readable lines that maintain width regardless of camera distance, the architecture must utilize specialized geometry.
DOCUMENTED ARTWORK/IMPLEMENTATION confirms that the Three.js Line2 addon resolves this by constructing polylines from a chain of vertices, effectively generating camera-facing triangle strips that allow arbitrary line widths defined in either CSS pixels or world units9. The LineMaterial supports dashed patterns, vertex colors, and alpha-to-coverage anti-aliasing, which is crucial for preventing jagged edges10.
It is vital to note that Line2 and LineMaterial are tightly coupled to the WebGL rendering pipeline. They must be imported explicitly from the Three.js addons directory (three/addons/lines/Line2.js). Should the project eventually migrate to WebGPU, this material is incompatible and must be substituted with Line2NodeMaterial9. The primary limitation of Line2 is vertex overhead; complex branching structures ("Unraveling") utilizing tens of thousands of thick line segments will heavily tax the geometry buffer, requiring strict limits on recursive branching logic.
Resolution-Independent Typography
Transforming visitor sentences into 3D architectural elements requires typography that remains perfectly legible at extreme magnifications and oblique camera angles. Standard approaches are fundamentally flawed for this use case: tessellating font outlines into TextGeometry produces massive vertex counts that scale poorly, while rendering text to a hidden 2D canvas and projecting it as a texture results in severe pixelation upon zooming12.
THEORY/INTERPRETATION establishes that Signed Distance Fields (SDF) provide resolution-independent typography by encoding the distance to the nearest glyph edge within a texture13. Libraries such as troika-three-text utilize HarfBuzz WebAssembly (WASM) for runtime text shaping and SDF generation15. While standard SDF eliminates pixelation, it inherently introduces corner-rounding artifacts at high magnifications because a single distance value cannot accurately represent sharp intersections13.
To achieve razor-sharp typographic structures, the architecture must implement Multi-channel Signed Distance Fields (MSDF). EMPIRICAL FINDING indicates that MSDF utilizes three color channels (RGB) to encode intersecting edges, preserving mathematically exact sharp corners13. The fragment shader determines the final pixel opacity by calculating the median of the RGB channels, effectively maintaining crisp intersections at any scale13. An ORIGINAL PROPOSAL recommends standardizing on an MSDF pipeline. The text is instantiated as individual BufferGeometry quads mapped with the MSDF texture, allowing a custom vertex shader to alter glyph positions based on the sentence's hashed seed, achieving a kinetic, unraveling effect with minimal performance overhead.
Instancing and Geometric Proliferation (Chorus)
The "Chorus" art direction implies distinct, interconnected forms proliferating across the canvas. Rendering thousands of identical geometries (e.g., structural nodes or typographic characters) individually overwhelms the CPU with excessive draw calls, destroying the frame rate.
DOCUMENTED ARTWORK/IMPLEMENTATION dictates the use of InstancedMesh. This class reduces draw calls to one by transmitting a single geometry and material to the GPU, alongside a Float32Array containing the 4x4 local transformation matrices for every instance17. The CPU is only responsible for updating this array.
Modifying individual instances dynamically (e.g., during a transformation sequence) requires computing the new position, rotation, and scale, writing it via .setMatrixAt(), and critically, flagging .instanceMatrix.needsUpdate \= true to force the browser to flush the updated memory to the GPU17. Without this flag, the matrix array remains stale in graphics memory, and the instances will appear frozen or collapsed at the origin.
Artifacts, Aesthetics, and Conservative Degradation
Aesthetics and accessibility are fragile; they are easily undermined by rendering artifacts that create visual noise or unintended high-frequency flickering. The system must employ conservative render modes rather than automatically escalating visual complexity.
THEORY/INTERPRETATION identifies several critical rendering artifacts that must be mitigated:
- Temporal Aliasing (Shimmer): Occurs when sub-pixel geometry moves across the pixel grid between frames, causing jagged, crawling edges on thin lines. This creates high-frequency micro-strobing that can violate accessibility thresholds. Mitigation requires utilizing Alpha-to-Coverage with Multi-Sample Anti-Aliasing (MSAA) and ensuring Line2 world-widths never drop below an apparent thickness of 1.5 pixels10.
- Z-Fighting: Coplanar geometries competing for depth buffer precision cause rapid, unpredictable flickering of overlapping surfaces19. Mitigation requires mathematically ensuring minimum Z-offsets for all stacked typography and considering a logarithmic depth buffer if the camera frustum spans vast distances.
- Transparency Sorting: The WebGL pipeline struggles to depth-sort overlapping transparent objects, resulting in geometry suddenly popping behind others. Mitigation requires rendering opaque structures first and utilizing additive blending (CustomBlending) for glowing lines to bypass strict depth sorting entirely.
- Bloom Overshoot: Post-processing thresholding can clamp bright pixels excessively, causing a loss of detail and rapid shifts in screen luminance. Mitigation requires strictly limiting the bloom threshold and radius, ensuring the overall screen luminance remains stable during camera movements.
An ORIGINAL PROPOSAL dictates a measured quality degradation strategy. The default rendering state initializes with post-processing disabled and a capped InstancedMesh instance count. The render loop monitors the delta time between frames. If the frame time consistently exceeds 16.6 milliseconds (dropping below 60 FPS), the system must actively degrade fidelity: first by halting complex vertex shader deformations, followed by reducing the maximum branch depth of the Unraveling algorithm, ensuring the frame rate stabilizes.
Psychological Fascination and Consent
The CLIENT-SUPPLIED CONTEXT strictly prohibits deliberate strobes, subliminal commands, covert conditioning, or techniques aimed at overriding judgment. The artwork's premise of "indoctrination" is openly fictional. The research must define the boundary between mesmerizing aesthetic design and coercive psychological mechanisms.
Demystifying Fascination and Hypnotizability
THEORY/INTERPRETATION drawn from cognitive psychology clarifies that "mesmerization" in an artistic context relates to attentional absorption, not hypnotic susceptibility or involuntary trance. The Tellegen Absorption Scale (TAS) is the standard psychological instrument for measuring an individual's disposition for having episodes of "total" attention20.
EMPIRICAL FINDING indicates that high absorption scores correlate strongly with aesthetic involvement in art, vivid imagination, and synesthesia21. The TAS describes absorption as an "effortless, non-volitional quality of deep involvement with the objects of consciousness," resulting in a heightened sense of reality of the attentional object20. Crucially, this is an innate personality trait related to openness to experience, not a state induced against a user's will by a website22. Subliminal perception—often feared as a mechanism for covert conditioning—has been shown to operate on the same continuum as conscious vision, meaning it relies on standard perceptual processing rather than a separate, bypass mechanism to the subconscious23.
Therefore, creating a "mesmerizing" experience involves utilizing cohesive motion, harmonious color palettes, and fluid structural transformations to invite aesthetic absorption. It does not involve, nor is it capable of, overriding user judgment or reprogramming behavior24.
WCAG 2.2 Framework and Photosensitive Safety
While psychological coercion is a fiction, neurological vulnerability to visual stimuli is a documented physiological reality. Non-consensual exposure to specific visual frequencies can trigger photosensitive reflex seizures or vestibular discomfort25.
EMPIRICAL FINDING demonstrates that flashes with a frequency greater than 3Hz (flashes per second) can trigger seizures28. The WCAG 2.2 Success Criterion 2.3.1 (Three Flashes or Below Threshold) strictly mandates that web pages contain nothing that flashes more than three times in any one-second period26.
The mathematical definition of a flash relies on relative luminance. A general flash occurs if relative brightness changes by 10% or more, and the darker frame has a value under 0.8025. A transition involving highly saturated red is exponentially more dangerous. WCAG defines a saturated red mathematically as [Figure omitted from source export]; transitioning to or from this state with a significant color shift constitutes a red flash and must be entirely eliminated from the generative color palettes25. Content is only exempt if the flashing area is restricted to less than 25% of a 10-degree visual field (approximately a [Figure omitted from source export] CSS pixel subarea at standard viewing distances)25. Because a full-screen 3D canvas vastly exceeds this area, the 3Hz hard limit is absolute.
Furthermore, WCAG SC 2.3.3 (Animation from Interactions) requires that motion animation can be disabled27. The architecture must proactively query the operating system's accessibility settings utilizing the prefers-reduced-motion: reduce media query32.
Fail-Closed Lifecycle and Session Management
To enforce the non-negotiable consent requirements, the application must utilize a fail-closed state machine. Visual content must remain entirely obfuscated until explicit permission is granted, and permission must be actively destroyed upon withdrawal or timeout.
The Teardown Protocol
Hiding the canvas using CSS display: none or opacity: 0 is entirely insufficient for a fail-closed architecture, as the GPU continues to process the render loop, and memory remains allocated.
DOCUMENTED ARTWORK/IMPLEMENTATION reveals that WebGL contexts are notorious for memory leaks if not meticulously managed. A detached DOM node holding a canvas reference will prevent the garbage collector from reclaiming GPU memory34. To securely conceal and destroy the experience, the architecture must execute a deep teardown:
1. Halt the requestAnimationFrame loop.
2. Recursively traverse the Three.js scene graph, calling .dispose() on every BufferGeometry, Material, and Texture.
3. Simulate a total GPU context loss by invoking the WebGL extension: gl.getExtension('WEBGL\_lose\_context').loseContext()34.
This guarantees cryptographic-level destruction of the visual state; no stale asynchronous rendering calls can subsequently reveal geometry.
Session Expiry
The CLIENT-SUPPLIED CONTEXT defines expiry after 30 minutes without recorded interaction. Relying solely on a continuous setTimeout is inefficient and drains battery. The system must utilize the Page Visibility API (visibilitychange event)37.
An ORIGINAL PROPOSAL outlines the session management logic: When the document visibilityState becomes hidden (the user switches tabs or minimizes the browser), the render loop is instantly paused37. A UNIX timestamp is logged to local storage. Upon the visibilityState returning to visible, the system calculates the delta time. If the delta exceeds 30 minutes (1,800,000 milliseconds), the fail-closed teardown protocol is executed immediately, and the user is returned to the initial consent gate.
Deterministic Scene Recipes and Finite Replay
The user interaction revolves around changing a sentence and comparing two versions of a world. This requires finite replay and the ability to accurately reconstruct a specific 3D state based solely on a text input.
THEORY/INTERPRETATION asserts that guaranteeing perfectly identical pixel-for-pixel rendering across disparate devices (e.g., an iOS mobile GPU versus a Windows desktop GPU) is unachievable due to hardware-level floating-point arithmetic variations and varying shader compilation targets. Therefore, the architecture focuses on a reproducible semantic state.
The core mechanism is a mathematically deterministic pseudo-random number generator (PRNG)2. The user's input sentence is hashed into a numeric seed (e.g., using a MurmurHash3 implementation). This seed initializes the PRNG, ensuring that any subsequent calls for random values—dictating structural branching angles, color palette selections, and camera trajectories—always yield the exact same sequence of numbers.
Scene-Recipe Contract
To enable sharing and reconstruction, the deterministic variables are serialized into a lightweight JSON payload.
JSON
{ "version": "5.2.0", "seed": "8f4a2b9e", "sentence": "Every question opens another possibility.", "artDirection": "Unraveling", "typography": { "fontRef": "inter-msdf.json", "color": "\#e0e0e0" }, "structure": { "nodeCount": 120, "branchFactor": 3.5, "complexity": 0.8 }, "camera": { "path": "spiral\_out", "duration": 12.0 } }
Interpolating between two states (the original sentence and the revised sentence) involves parsing both JSON recipes, initializing two separate mathematical structures, and passing their parameters into a shared transition function. The timeline relies on a normalized progress float ([Figure omitted from source export] to [Figure omitted from source export]), updated via the high-resolution timestamp provided by requestAnimationFrame, ensuring animation interpolation speed remains independent of monitor refresh rates38.
Export Pipeline and Canvas Security Constraints
The application allows users to export selected material for sharing. The export pipeline must negotiate strict browser security policies.
Cross-Origin Tainting
Capturing the WebGL canvas relies on HTMLCanvasElement.toDataURL() for static PNG exports and HTMLCanvasElement.captureStream() fed into the MediaRecorder API for video exports39.
EMPIRICAL FINDING highlights a critical security constraint: if any cross-origin resource (e.g., a font or texture loaded from an external CDN without proper CORS headers) is drawn to the canvas, the browser permanently flags the canvas as "tainted"41. Attempting to call toDataURL or captureStream on a tainted canvas results in an immediate, fatal SecurityError42. To prevent this, all external assets must be served with an Access-Control-Allow-Origin: \* header, or ideally, hosted directly on the same origin as the application.
Video Codec Negotiation
Browser support for video encoding via MediaRecorder is heavily fragmented. DOCUMENTED ARTWORK/IMPLEMENTATION reveals that Chrome typically supports video/webm utilizing VP8 or VP9 codecs44. Firefox supports video/webm but specifically lacks support for the VP9 codec during recording44. Apple's Safari does not support WebM recording natively; it exclusively supports video/mp445.
An ORIGINAL PROPOSAL dictates the implementation of a strict MIME-type negotiation pipeline:
1. Negotiation: The script probes MediaRecorder.isTypeSupported() in priority order: video/webm; codecs=vp9, video/webm; codecs=vp8, and video/mp4.
2. Deterministic Render Loop: During recording, the standard delta-time render loop is suspended. The engine artificially advances time by exactly 16.66ms per frame to guarantee a perfectly smooth 60 FPS output file, completely decoupled from the actual CPU encoding time which may lag significantly on mobile devices.
3. Blob Assembly: The ondataavailable event pushes resulting data blobs into an array39. After the simulated 12-second duration completes, MediaRecorder.stop() triggers, assembling the array and executing a programmatic download via URL.createObjectURL().
4. Metadata Injection: Because browsers cannot reliably embed custom JSON metadata streams directly into MP4/WebM containers via MediaRecorder, the scene recipe JSON is triggered as a parallel download.
Module Portability and Performance Profiling
The requirement for a root-deployable PHP artifact eliminates the use of Node-based bundlers (like Webpack or Vite) for the final production deployment.
ORIGINAL PROPOSAL: The architecture relies on self-hosted, pinned ES modules. The three.module.js library and required addons are served directly from a /vendor/ directory. Relying on external CDNs (e.g., unpkg) introduces unacceptable points of failure, unpredictable latency variations, and privacy concerns regarding referrer headers. All assets are self-contained.
Performance Measurement Variables
Performance cannot be assessed through a singular metric such as polygon count. The profiling strategy must measure:
- Time to First Usable Frame (TTFUF): Measured via the Performance API from DOMContentLoaded to the completion of the first renderer.render() call. This tracks the cost of parsing the geometry and compiling the initial shader programs.
- Frame-Time Distributions: Utilizing performance.now() to measure the exact millisecond duration of the render loop. Consistent jitter (e.g., alternating between 10ms and 30ms) is significantly more disorienting to the vestibular system than a steady, locked 30 FPS (33.3ms)38.
- Memory Leaks: Monitoring the JavaScript heap via Chrome DevTools to ensure memory does not endlessly inflate during the 12-second transformation sequences, indicating un-disposed buffer geometries35.
Independent Prototype Specifications
The following specifications are conceptual proposals for validating rendering techniques without relying on existing proprietary application code.
Prototype A: The Line Sculpture ("Monolith")
Objective: Validate world-space line rendering and depth sorting.Implementation: Utilize the Line2 addon. Generate a continuous Lissajous curve algorithmically based on a numeric seed. The LineMaterial is configured with worldUnits: true and a linewidth of 0.05. The material color palette strictly avoids saturated red to eliminate WCAG red-flash risks.Test Criteria: Lines must remain legible and thick when zooming out; intersections must depth-sort correctly without z-fighting.
Prototype B: Kinetic-Text Revision
Objective: Validate resolution-independent typography and shader deformation. Implementation: Load a pre-generated MSDF JSON/PNG font atlas. Instantiate a BufferGeometry for each character of a sample sentence. Map the MSDF texture to the quads, utilizing the median RGB fragment shader calculation to maintain sharp corners13. Implement a custom vertex shader that injects a displacement vector mapped to a sine wave, causing the words to slowly unravel over time. Test Criteria: Text must remain perfectly crisp at 10x magnification. The vertex shader must not drop the framerate below 60 FPS on standard desktop hardware.
Prototype C: Structural Transformation ("Chorus")
Objective: Validate performant geometric proliferation and matrix interpolation. Implementation: Initialize an InstancedMesh with a count of 5,000 octahedron geometries. Create two separate Float32Array buffers representing the matrices for State A (the original sentence) and State B (the revised sentence). A render loop interpolates between the two arrays, updating the active instanceMatrix and setting .needsUpdate \= true17. Test Criteria: The browser must sustain \>30 FPS during the interpolation phase; no matrix dimension errors can be thrown during the array update.
Assignment-Specific Deliverables
Renderer Decision Matrix
| Feature/Requirement | Canvas 2D | WebGL (Three.js) | WebGPU (Three.js) | Decision |
|---|---|---|---|---|
| Thick, resolution-independent lines | Passable (slow for \>1k lines) | Excellent (Line2 addon) | Experimental (Line2NodeMaterial) | WebGL |
| Typographic Clarity (Extreme Zoom) | Fails (pixelation) | Excellent (MSDF pipeline) | Excellent (MSDF via TSL) | WebGL |
| Instanced Geometric Transformation | Fails (CPU bound) | Good (InstancedMesh) | Excellent (Compute Shaders) | WebGL (Sufficient for \<10k objects) |
| Fail-Closed Teardown | Standard garbage collection | Explicit (WEBGL\_lose\_context) | Explicit (Device destruction) | WebGL (Proven memory management) |
| Hosting Portability (PHP/Static) | Excellent | Excellent (ES Modules) | Requires specific secure contexts | WebGL |
Dependency Shortlist
| Library / Addon | Purpose | Maintenance / Licensing Notes |
|---|---|---|
| three.module.js (r170) | Core 3D graphics engine. | MIT License. Highly maintained. |
| Line2.js, LineMaterial.js | Rendering thick, world-space lines for "Monolith". | MIT License. Official Three.js addon; guaranteed compatibility with r170. |
| Custom MSDF Implementation | Resolution-independent typography without massive vertex counts. | Utilize open-source font atlases; avoid heavy runtime WASM shaping if possible to speed up cold starts. |
| GLTFExporter.js | Serializing geometry to GLB formats for JSON exports. | MIT License. Official Three.js addon. |
Proposed Module Responsibilities
| Module | Core Responsibility | Lifecycle Interaction |
|---|---|---|
| ConsentManager.js | Orchestrates UI overlays, tracks interaction time, handles visibilitychange. | Emits global CONSENT\_GRANTED and CONSENT\_REVOKED events. |
| RecipeEngine.js | Houses the deterministic PRNG. Parses text, generates seeds, outputs the JSON scene contract. | Pure function; operates independently of the DOM or WebGL context. |
| RenderOrchestrator.js | Manages the Three.js scene graph, instantiates InstancedMesh, applies the render loop. | Subscribes to ConsentManager. Listens to prefers-reduced-motion and pauses time updates accordingly. |
| ExportPipeline.js | Intercepts canvas output, manages MediaRecorder state machine, handles blob assembly. | Overrides the requestAnimationFrame delta-time during video rendering to guarantee 60 FPS output. |
Fail-Closed Lifecycle Diagram
1. \[State: Inert\] [Figure omitted from source export] DOM loads with opaque HTML overlay. Canvas element is unattached. No graphics memory allocated.
2. \[Action: User Prompt\] [Figure omitted from source export] User selects "Hidden", "Still Artwork", or "Artwork \+ Motion".
3. \[State: Validated\] [Figure omitted from source export] If "Hidden", remain inert. If "Artwork...", attach canvas, initialize WebGLRenderer.
4. \[Action: System Monitor\] [Figure omitted from source export] window.matchMedia('(prefers-reduced-motion: reduce)') fires. State forced to "Still Artwork".
5. \[Action: Environment Monitor\] [Figure omitted from source export] Tab hidden (visibilitychange). Pause render loop. Log timestamp.
6. \[Action: Timeout/Revocation\] [Figure omitted from source export] 30 minutes pass OR user clicks "Hide".
7. \[State: Teardown\] [Figure omitted from source export] Execute geometry.dispose(), material.dispose(), and gl.getExtension('WEBGL\_lose\_context').loseContext(). Remove canvas from DOM. Return to State 1\.
30 Technical Acceptance Tests
| ID | Category | Test Condition | Expected Result |
|---|---|---|---|
| 1 | Consent | Default page arrival via direct URL. | No 3D canvas is attached; WebGL context remains uninitialized. |
| 2 | Consent | User selects "Hidden/Text-Only". | Semantic HTML text is revealed; WebGL context remains uninitialized. |
| 3 | Consent | User selects "Artwork \+ Motion". | Canvas is attached; requestAnimationFrame loop begins rendering. |
| 4 | Consent | Tab is minimized or switched. | visibilitychange event fires; render loop pauses immediately. |
| 5 | Consent | 30 minutes elapse without interaction. | Consent state reverts to null; UI overlay is restored. |
| 6 | Teardown | Consent expires or is withdrawn manually. | WEBGL\_lose\_context.loseContext() executes without errors. |
| 7 | Teardown | Consent withdrawn during video export. | MediaRecorder immediately terminates; in-memory blobs are discarded. |
| 8 | WCAG | OS-level "Reduce Motion" enabled. | Programmatic camera orbits halt entirely32. |
| 9 | WCAG | OS-level "Reduce Motion" enabled. | Oscillating geometry animations freeze; state reverts to "Still Artwork". |
| 10 | WCAG | High-contrast visual transition occurs. | Hardware analysis confirms sequence does not exceed 3 flashes per second (3Hz)26. |
| 11 | WCAG | Color palette generation (randomized). | Mathematical check ensures no state reaches the saturated red threshold [Figure omitted from source export]25. |
| 12 | WCAG | Text overlay rendered against 3D canvas. | CSS contrast ratios exceed 4.5:1 against the underlying clear color. |
| 13 | Rendering | Line2 geometry zooms out 10x. | Lines maintain physical thickness and do not vanish into sub-pixels10. |
| 14 | Rendering | InstancedMesh matrix array updated. | .instanceMatrix.needsUpdate \= true successfully flushes memory to GPU without crashing17. |
| 15 | Rendering | Overlapping text geometries stacked closely. | Z-fighting is eliminated; logarithmic depth buffer prevents flickering. |
| 16 | Rendering | Dense geometry clusters with post-processing. | Bloom threshold is clamped; total screen luminance does not blow out. |
| 17 | Rendering | MSDF text at 10x camera magnification. | Sharp corners remain crisp; no pixelation is visible13. |
| 18 | Rendering | External MSDF texture fails to load (404). | Graceful fallback to standard filled shapes or standard text. |
| 19 | Export | Request static PNG export. | Base64 string generated without triggering CORS SecurityError42. |
| 20 | Export | Request video export on iOS Safari. | MediaRecorder negotiates and outputs video/mp445. |
| 21 | Export | Request video export on Chrome. | MediaRecorder negotiates and outputs video/webm (VP8/VP9)44. |
| 22 | Export | Export video on a heavily throttled CPU. | Output video duration is exactly 12.0 seconds; perfectly smooth 60 FPS playback. |
| 23 | Export | Download comparison data. | JSON file downloads in parallel with video, matching the defined scene contract schema. |
| 24 | Portability | Application deployed to root PHP directory. | Initializes correctly without requiring a Node.js backend or Webpack Dev Server. |
| 25 | Portability | Module import resolution. | Import map successfully routes all three/addons/ paths to the local /vendor/ directory. |
| 26 | Performance | Measure Time to First Usable Frame. | Completes in under 1.5 seconds on a throttled 4G connection profile. |
| 27 | Performance | Memory profiling during 12-second sequence. | JavaScript heap does not grow continually; garbage collection manages object creation. |
| 28 | Performance | Execute geometry.dispose() on removed mesh. | Chrome DevTools confirms WebGL buffer memory is actively freed35. |
| 29 | Performance | "Chorus" transformation at peak complexity. | Frame times remain strictly below 16.6ms on target desktop hardware. |
| 30 | Performance | Apply "4x CPU slowdown" in DevTools. | System gracefully degrades visual fidelity rather than crashing the browser tab. |
Reproducible Profiling Worksheet
| Metric | Target | Testing Protocol | Device Profile | Remediation Strategy if Failed |
|---|---|---|---|---|
| Cold Start | \< 1.5s | Chrome DevTools (Fast 3G, 4x CPU throttle). | Low-end Mobile | Audit network waterfall for blocking modules; defer non-essential asset loading. |
| First Usable Frame | \< 2.0s | performance.now() from DOMContentLoaded to first render(). | Low-end Mobile | Ensure deterministic PRNG geometry generation does not block the main thread; utilize web workers if necessary. |
| Heap Memory | \< 50MB | Take Heap Snapshots at T=0s, T=60s, T=120s. | Desktop | Identify detached DOM nodes or un-disposed textures holding GPU memory hostage. |
| Frame Variance | \< 16.6ms | DevTools Performance recording during transformation. | Desktop | Spikes indicate matrix upload bottlenecks. Cap the maximum allowable InstancedMesh node count. |
Supported-Versus-Proposed Capability Table
| Feature | Supported (Client Baseline v5.2.0) | Proposed Enhancements (This Research) | Rationale |
|---|---|---|---|
| Renderer | Canvas projection / Standard WebGL | WebGL with explicit module pinning via Import Maps; defer WebGPU. | Ensures maximum portability and stability on serverless PHP hosting without risking WebGPU regressions. |
| Geometry | Basic 3D geometry | Line2 structures, InstancedMesh matrix arrays. | Fulfills complex art directions (Unraveling, Chorus) while maintaining necessary performance constraints. |
| Text | Unspecified | MSDF text rendering pipeline. | Solves pixelation at extreme magnifications; radically lowers vertex overhead compared to extruded text. |
| Export | Finite 12s video, JSON, PNG | Deterministic offline-rendering loop for MediaRecorder; strict CORS. | Eliminates dropped frames in exported video regardless of device CPU; prevents security errors causing export failure. |
| Consent | Opt-in, 30 min expiry | WEBGL\_lose\_context teardown; OS reduce-motion binding. | Guarantees cryptographic-level destruction of visual state; rigorously aligns with WCAG 2.3.3 mandates. |
Staged Implementation Plan
1. Phase 1: Foundation & Security: Establish the PHP deployment structure and HTML import maps. Implement the Fail-Closed Consent Manager and integrate WEBGL\_lose\_context. Verify strict CORS headers for all local assets to prevent canvas tainting.
2. Phase 2: Core Rendering & Typographic Pipeline: Integrate three.module.js and develop the MSDF text rendering system. Verify that typography remains perfectly sharp at extreme magnifications and does not induce Z-fighting when overlapping.
3. Phase 3: Generative Architecture & Determinism: Implement the seeded PRNG. Develop the Scene-Recipe Contract and the translation layer that maps numeric seeds to Line2 structures (Monolith) and InstancedMesh arrays (Chorus).
4. Phase 4: Export Pipeline & Encoding: Construct the decoupled delta-time render loop for video export. Implement the MIME-type negotiation script to handle Safari (MP4) and Chrome/Firefox (WebM) divergence.
5. Phase 5: WCAG Auditing & Profiling: Conduct Harding FPA testing to ensure zero violations of the 3Hz flash threshold. Profile memory heaps and frame variances on targeted mobile hardware, establishing the thresholds for automated visual degradation.
What this research would change in the experience
Changes Justified by Evidence
1. Implementation of WEBGL\_lose\_context: The baseline proposed merely hiding the canvas or relying on standard garbage collection. Evidence dictates that to truly fail-closed and free graphics memory upon consent withdrawal, the WebGL context must be explicitly and forcefully destroyed using the designated API extension34.
2. OS-Level Reduced Motion Hook: The experience will automatically intercept the prefers-reduced-motion media query32. If a visitor has this accessibility feature enabled on their operating system, the system will immediately downgrade their choice from "Artwork \+ Motion" to "Still Artwork", prioritizing vestibular safety over visual complexity without requiring secondary prompts.
3. Deterministic Export Loop: Rather than recording the live, potentially lagging screen output, the video export pipeline will decouple from the real-time clock. It forces the Three.js engine to render frame-by-frame directly into the MediaRecorder, ensuring every exported 12-second video is a perfect 60 FPS, regardless of how slowly the user's mobile hardware performed the actual encoding.
Changes Worth Prototyping
1. MSDF Typography Integration: Prototyping a custom MSDF shader for the words in the sentence will definitively determine if the visual crispness at extreme camera angles justifies the added complexity over standard geometry extrusion, and whether it introduces unacceptable latency during the cold start phase.
2. Line2 Scaling Limits: Prototyping the "Monolith" structure using Line2 is necessary to verify if the vertex processing overhead of calculating thick lines dynamically causes bottlenecks on mid-tier mobile GPUs.
Claims Not Established
1. "Guaranteed Trance" or "Subconscious Reprogramming": The research strictly rejects any technical or psychological capability to enforce actual hypnosis, override judgment, or covertly condition users via a browser canvas. The aesthetics of absorption (mesmerization) are validated perceptual design choices aimed at sustaining aesthetic fascination, not involuntary neurological interventions20.
2. Universal 60 FPS: The research does not support the claim that the 3D experience will run at a flawless 60 FPS on all devices. Graceful degradation pathways and frame-time monitoring are explicitly required specifically because mobile performance will vary dramatically based on thermal throttling and battery state.
3. WebGPU as an Immediate Replacement: The research does not establish that WebGPU should immediately replace WebGL for this project. Documented instability, varying browser support, and regressions in early WebGPU implementations (e.g., shadow rendering and post-processing performance) dictate that WebGL remains the necessary, stable foundation for a production-ready, PHP-hosted web artwork6.
Works cited
1. Stop Animating with JavaScript Timers: Let CSS Do the Heavy Lifting, https://www.grizzlypeaksoftware.com/library/css-animation-techniques-with-javascript-triggers-s5kflz0m
2. Introduction to WebGPU Compute Shaders | Three.js Roadmap, https://threejsroadmap.com/blog/introduction-to-webgpu-compute-shaders
3. WebGPU \+ Three.js Migration Guide (2026) \- Utsubo, https://www.utsubo.com/blog/webgpu-threejs-migration-guide
4. WebGPURenderer – three.js docs, https://threejs.org/docs/pages/WebGPURenderer.html
5. GPU-Side Physics: A Three.js WebGPU Compute Demo, https://www.webgpu.com/showcase/threejs-webgpu-compute-physics/
6. \[WebGPU\] Significant performance drop and shadow quality, https://discourse.threejs.org/t/webgpu-significant-performance-drop-and-shadow-quality-regression-in-r182-vs-webgl-r170/89322
7. Conquering JavaScript: Three.js 1032413107, 9781032413105, https://dokumen.pub/conquering-javascript-threejs-1032413107-9781032413105.html
8. Game Development with Three.js, http://www.fudgeys.co.uk/ebooks/%5BBookflare.net%5D%20-%20Game%20Development%20with%20Three.js.pdf
9. Line2 – three.js docs, https://threejs.org/docs/pages/Line2.html
10. LineMaterial – three.js docs, https://threejs.org/docs/pages/LineMaterial.html
11. Line2NodeMaterial – three.js docs, https://threejs.org/docs/pages/Line2NodeMaterial.html
12. GPU vector text rendering via the Slug algorithm \- GitHub, https://github.com/mrdoob/three.js/issues/33215
13. Guide to SDF+MSDF Fonts \- Red Blob Games, https://www.redblobgames.com/articles/sdf-fonts/
14. Text rendering · Issue \#20 · pygfx/pygfx \- GitHub, https://github.com/pygfx/pygfx/issues/20
15. GitHub \- countertype/three-text: High fidelity 3D font rendering and, https://github.com/countertype/three-text
16. SDF Fonts: Appendix \- Red Blob Games, https://www.redblobgames.com/articles/sdf-fonts/appendix.html
17. InstancedMesh.setMatrixAt – three.js docs, https://threejs.org/docs/\#api/en/objects/InstancedMesh.setMatrixAt
18. Minimal instancedMesh example · pmndrs react-three-fiber \- GitHub, https://github.com/pmndrs/react-three-fiber/discussions/761
19. Three.js Documentation \- GitHub Pages, https://expelledboy.github.io/threejs-manual-generator/
20. Absorption in Sport: A Cross-Validation Study \- Frontiers, https://www.frontiersin.org/journals/psychology/articles/10.3389/fpsyg.2017.01419/full
21. Prevalence of visual snow and relation to attentional absorption, https://journals.plos.org/plosone/article?id=10.1371/journal.pone.0276971
22. Musical and non-musical involvement in daily life, https://openaccess.city.ac.uk/id/eprint/36118/3/Musical%20and%20non-musical%20involvement%20in%20daily%20life%20the%20case%20of%20absorption.pdf
23. The (Re)Discovery of the Unconscious: What We Have Learned, https://clinmedjournals.org/articles/ijcb/international-journal-of-cognition-and-behaviour-ijcb-6-017.php?jid=ijcb
24. How hypnotic suggestions work \- A systematic review of prominent, https://www.researchgate.net/publication/382446187\_How\_hypnotic\_suggestions\_work\_-\_A\_systematic\_review\_of\_prominent\_theories\_of\_hypnosis
25. Photosensitive Seizure Standards Compared: WCAG, Ofcom, ITU, https://video-audit.com/blog/seizure-safety-standards-compared
26. WCAG 2.3.1 Three Flashes or Below Threshold \- Accessibility.build, https://accessibility.build/wcag/2-3-1
27. Motion | U-M Library Design System, https://design-system.lib.umich.edu/visual-elements/motion/
28. Web accessibility for seizures and physical reactions \- MDN Web Docs, https://developer.mozilla.org/en-US/docs/Web/Accessibility/Guides/Seizure\_disorders
29. Characterizing the Patterned Images That Precipitate Seizures and, https://www.researchgate.net/publication/7686482\_Characterizing\_the\_Patterned\_Images\_That\_Precipitate\_Seizures\_and\_Optimizing\_Guidelines\_To\_Prevent\_Them
30. Understanding SC 2.3.1: Three Flashes or Below Threshold (Level A), https://www.w3.org/WAI/WCAG22/Understanding/three-flashes-or-below-threshold.html
31. Scrollytelling Design Patterns: A Practitioner's Reference (2026), https://scrollytelling.ai/scrollytelling-design-patterns/
32. prefers-reduced-motion CSS media feature \- MDN Web Docs, https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/At-rules/@media/prefers-reduced-motion
33. React useReducedMotion Hook: Respect prefers-reduced-motion, https://medium.com/@wul55267/react-usereducedmotion-hook-respect-prefers-reduced-motion-2026-7cc7525b87ce
34. Web App (HTML5) Memory Optimization Guide \- Samsung Developer, https://developer.samsung.com/smarttv/develop/guides/web-app-memory-optimization-guide.html
35. Best Practices for Testing and Debugging WebGL Applications, https://blog.pixelfreestudio.com/best-practices-for-testing-and-debugging-webgl-applications/
36. Memory leak when we add a canvas with webgl context to a fabric.js, https://github.com/fabricjs/fabric.js/issues/4140
37. https://developer.mozilla.org/en-US/docs/Web/API/Page\_Visibility\_API
38. The definitive guide to requestAnimationFrame() \- Flavio Copes, https://flaviocopes.com/requestanimationframe/
39. https://developer.mozilla.org/en-US/docs/Web/API/MediaStream\_Recording\_API
40. Why does canvas.toDataURL() throws a security exception?, https://www.geeksforgeeks.org/javascript/why-does-canvas-todataurl-throws-a-security-exception/
41. Use cross-origin images in a canvas \- HTML \- MDN Web Docs, https://developer.mozilla.org/en-US/docs/Web/HTML/How\_to/CORS\_enabled\_image
42. HTMLCanvasElement: toDataURL() method \- Web APIs | MDN, https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toDataURL
43. The canvas has been tainted by cross-origin data ... \- Our Code World, https://ourcodeworld.com/articles/read/182/the-canvas-has-been-tainted-by-cross-origin-data-and-tainted-canvases-may-not-be-exported
44. How We Made Screen Recording Work on Every Browser \- SendRec, https://sendrec.eu/blog/how-we-made-screen-recording-work-on-every-browser/
45. How to Record HTML Canvas using MediaRecorder and Export as, https://devtails.xyz/@adam/how-to-record-html-canvas-using-mediarecorder-and-export-as-video
46. Record audio and video with MediaRecorder \- Chrome for Developers, https://developer.chrome.com/blog/mediarecorder
47. Immersion in altered experience: An investigation of the relationship, https://pmc.ncbi.nlm.nih.gov/articles/PMC5358520/