<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Will Engineering Notes]]></title><description><![CDATA[Will Engineering Notes]]></description><link>https://czmilo.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Fri, 04 Dec 2026 23:06:22 GMT</lastBuildDate><atom:link href="https://czmilo.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[How to Build a Replayable Protocol Lesson with React and SVG]]></title><description><![CDATA[Protocol Explorer is a browser based workspace for learning network protocols through synchronized scenes, step explanations, and packet inspection. The…]]></description><link>https://czmilo.hashnode.dev/how-to-build-a-replayable-protocol-lesson-with-react-and-svg</link><guid isPermaLink="true">https://czmilo.hashnode.dev/how-to-build-a-replayable-protocol-lesson-with-react-and-svg</guid><dc:creator><![CDATA[Will Zhang]]></dc:creator><pubDate>Sat, 28 Nov 2026 12:18:50 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6b004c32823e7883755c4a33/740d0130-0ea1-4c02-8c5d-a41d05475d7a.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><a href="https://protocolexplorer.org/">Protocol Explorer</a> is a browser based workspace for learning network protocols through synchronized scenes, step explanations, and packet inspection. The key architectural idea is simple: store the lesson as structured facts and derive the scene from the selected step. This keeps the visual state reproducible and the explanation connected to the packet event being shown.## 1. Model the lesson before drawing the scene</p>
<p>Start with stable lesson data: protocol identity, ordered steps, explanatory copy, and events such as a packet moving between endpoints. Keep that information separate from component markup. In Protocol Explorer, course facts are stored in JSON and playback behavior is implemented as pure functions under <code>lib/learning/</code>.</p>
<p>This boundary lets the same lesson power the scene, the step list, deep links, and progress. A URL can point to a protocol and step without encoding a screenshot or animation frame. The UI can rebuild the state from the course id and step index.</p>
<h2>2. Derive playback state from time</h2>
<p>Instead of changing many SVG attributes independently, calculate the current playback position from the lesson and elapsed time. The function returns the active packet/event index and related state. React renders the devices and path from that result.</p>
<p>This approach supports pause, restart, previous/next step, and reduced motion while keeping the lesson semantics independent of rendering. If the page is hidden, the animation clock can pause. If a user prefers less motion, step navigation remains available.</p>
<h2>3. Use SVG for a consistent device vocabulary</h2>
<p>Protocol Explorer draws isometric devices as original SVG components: laptops, routers, switches, servers, cameras, and a network cloud. The same device vocabulary is shared with the exam topology. This reduces visual drift between learning and assessment and keeps the scene responsive to layout changes.</p>
<p>The scene is a teaching model. It shows endpoints and forwarding paths from course facts; it does not run a general protocol stack or simulate arbitrary user traffic. Being explicit about that scope helps set the right expectation.</p>
<h2>4. Make packet examples inspectable</h2>
<p>The inspector exposes field names, offsets, numeric values, hex, and ASCII. The dataset includes 557 illustrative packet snapshots across the current courses. Unknown or encrypted values are represented as null and shown as <code>??</code>.</p>
<p>This small detail prevents a common failure in educational visuals: silently filling gaps with plausible-looking data. If the example cannot reveal a byte, the interface should say so. Textual explanations remain available because an image should not be the only carrier of meaning.</p>
<h2>5. Preserve compatibility as the interface evolves</h2>
<p>There are 39 courses and 231 stable step positions. Keeping step positions stable helps preserve existing progress and direct links as the layout changes. A content update therefore needs to consider more than the current render: it also needs to respect course ids, step indices, progress state, and other consumers such as exams.</p>
<h2>What AI helped with</h2>
<p>In this project, Opus 5.5 and Gemini 4 Neon took about 40 minutes to an hour to produce strong 3D output. GLM 5.4 Max took around four hours, also with a good result. The current Protocol Explorer version was built with GLM 5.4 Max. These timings reflect one task and workflow, not a general model benchmark.</p>
<p>AI helped create the visual world, but the architecture made it a product. The reusable pattern is: facts first, deterministic playback second, rendering third, and textual explanation alongside the scene. That ordering makes a technical lesson easier to inspect, test, and maintain.</p>
<h2>A small state model</h2>
<p>One way to think about a lesson is as a sequence of event groups. Each group may contain a packet event, a stream of packets, or a non-packet state change. The current step selects the event group, while playback progress selects the active event within it. A simplified state shape could look like this:</p>
<pre><code class="language-ts">type LessonState = {
  lessonId: string;
  stepIndex: number;
  elapsedMs: number;
  packetIndex: number;
  visibleNodes: string[];
};
</code></pre>
<p>This is illustrative rather than a copy of the project’s internal types. The useful property is that the state can be derived from lesson facts and a small set of inputs. The renderer does not need to infer meaning from the position of an SVG element. It receives the lesson state and chooses which devices, labels, and paths to display.</p>
<p>For larger lessons, it also helps to distinguish event identity from display index. An index is convenient for the current ordered list, but a stable event id is more durable if the content is reordered. Protocol Explorer preserves stable course and step positions because progress and links may refer to them. Any change in the ordering should be reviewed as a compatibility change, not just an editorial tweak.</p>
<h2>Avoiding coupling between controls</h2>
<p>A learner can be playing step four while inspecting a packet that appeared in step two. If one state variable controls both playback and inspector selection, clicking an old packet may unexpectedly move the lesson backward. Treating these as separate concerns gives the user more freedom:</p>
<pre><code class="language-text">playback: current lesson + step + elapsed time
inspection: selected packet fixture
</code></pre>
<p>The playback selection controls the current scene. The inspection selection controls the detail panel. They can still be synchronized when the user advances to a new step, but the interaction should be intentional. This small distinction helps the interface feel like an exploratory workspace instead of a linear animation.</p>
<h2>Data quality is part of rendering quality</h2>
<p>An SVG can be pixel perfect and still teach the wrong thing if its event points to the wrong packet or its explanation describes a different hop. The quality bar therefore includes the course facts, packet fixture, and copy. In a multi-language workspace, translated descriptions need to preserve the technical relationship even when the sentence structure changes.</p>
<p>Unknown values should be modeled explicitly. In the packet captures, unavailable bytes are null. The inspector renders those positions as <code>??</code>. If an author instead writes a placeholder string into the data, downstream code can accidentally treat it as a real byte value. A typed distinction between known and unknown values makes the renderer safer and the limitation easier to explain.</p>
<p>There is a similar issue with packet examples and real captures. An example fixture may be designed to illuminate one field and omit detail that does not matter to the lesson. Labeling it as an illustrative example prevents readers from assuming it represents every possible packet or an actual exchange on their network. The goal is to teach a protocol concept, not to masquerade as a diagnostic tool.</p>
<h2>A review checklist for a new lesson</h2>
<p>When adding a course, I would review it in this order:</p>
<ol>
<li>Is the lesson id stable and present in the course registry?</li>
<li>Does each step have an explanation and a stable position?</li>
<li>Do all referenced endpoints and packets exist?</li>
<li>Can the learner tell what is unknown or intentionally simplified?</li>
<li>Does playback reproduce the expected event order?</li>
<li>Can the step be reached by direct link and keyboard controls?</li>
<li>Does the explanation remain understandable when read without the scene?</li>
</ol>
<p>This is not a substitute for domain review. It is a way to catch structural gaps before a technical reviewer spends time checking the protocol details. Separating those review layers saves time because the domain reviewer is not debugging a missing node reference at the same time as checking an explanation.</p>
<h2>When to use this architecture</h2>
<p>The data-driven approach is most useful when visual states are tied to durable content: tutorials, onboarding, simulations, or interactive documentation. For a short marketing animation, a graphics timeline may be simpler. For a learning product with localization, progress, deep links, and an exam topology sharing the same devices, structured facts reduce duplicated assumptions.</p>
<p>You do not need a 3D scene to use the pattern. A table, timeline, or network diagram can all be renderers of the same state model. The important question is whether a learner can inspect the item that supports the explanation and revisit the exact point where they became confused.</p>
<p>Protocol Explorer uses isometric SVG because it provides a clear spatial map of the network while remaining editable as interface code. The broader lesson is to put the domain model first and treat the visual output as one readable projection of it.</p>
<h2>Data flow in one lesson</h2>
<p>The lesson starts with an id and a step index. The route layer resolves those values from the page state or URL. The workspace loads the lesson facts and computes the selected step. The playback function maps elapsed time to the current event. Event data identifies the relevant packet and endpoints. Finally, React renders the SVG devices, path, explanation, and packet list.</p>
<p>The packet inspector follows a separate user selection. When the learner selects a packet, the inspector finds its fixture and displays the fields and bytes. That distinction between “what is currently playing” and “what I am currently inspecting” gives the user room to explore without interrupting the lesson. If you implement this pattern, keep those pieces of state separate unless the product explicitly intends inspection to drive playback.</p>
<h2>Updating a course safely</h2>
<p>Course content is a product contract. An update may affect current learners, saved progress, exams, translations, and links from outside the app. Stable course ids and step indices help preserve that contract. When adding or changing a step, review the content in the context of old progress and any consumers that refer to the same facts.</p>
<p>The project keeps course copy and learning facts in data files rather than bundling every explanation into a drawing component. This makes translation and review more straightforward. It also means a data update needs validation: an event should refer to valid devices, packets should exist in the capture set, and every displayed step should have its explanatory text. A schema or content audit can catch structural mistakes before they become confusing screens.</p>
<h2>A few practical trade-offs</h2>
<p>SVG works well for this kind of original, crisp device illustration because parts can scale with the interface and remain sharp. It also makes it possible to build a consistent visual vocabulary with reusable components. However, SVG is not a substitute for responsive design. A wide desktop learning scene still needs a considered mobile behavior; in this project, the canvas can be scrolled horizontally on phones rather than compressing every detail until it is unreadable.</p>
<p>Another trade-off is motion. Animation can clarify order, but continuous movement can distract or make the interface uncomfortable. Playback controls, keyboard shortcuts, page visibility handling, and reduced-motion support are part of the core design. If the lesson only works while animation is running, it is too fragile.</p>
<p>The same reasoning applies to color. A path should not be identified only by hue. Labels and textual descriptions help users who cannot distinguish the palette and help anyone reading a screenshot later. The generated cover art is an editorial illustration; the article itself still explains the idea in words so the asset is never the only source of meaning.</p>
<h2>When this pattern is useful</h2>
<p>This architecture is a good fit when the lesson has stable steps, inspectable entities, and more than one representation of the same facts. It may be too much for a single disposable animation. But if a product needs localization, deep links, learner progress, assessment reuse, or deterministic replay, separating facts from rendering reduces the number of places that can disagree.</p>
<p>The pattern is domain independent. A chemistry lesson might model reaction stages; a distributed systems tutorial might model messages and node state; a compiler lesson might model transformations over a syntax tree. The key is to choose the domain events first, then make the visualization an inspectable projection of those events.</p>
<p>That is what <a href="https://protocolexplorer.org/">Protocol Explorer</a> is trying to do for protocols: keep the route visible, keep the bytes inspectable, and keep the explanation close to both.</p>
<hr />
]]></content:encoded></item><item><title><![CDATA[PoseWear shows why AI image history needs more than a saved picture]]></title><description><![CDATA[Read PoseWear’s IndexedDB history and export code, three visual examples, five saved model outputs, and a proposed experiment manifest.]]></description><link>https://czmilo.hashnode.dev/posewear-shows-why-ai-image-history-needs-more-than-a-saved-picture</link><guid isPermaLink="true">https://czmilo.hashnode.dev/posewear-shows-why-ai-image-history-needs-more-than-a-saved-picture</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[indexeddb]]></category><category><![CDATA[AI]]></category><category><![CDATA[Open Source]]></category><dc:creator><![CDATA[Will Zhang]]></dc:creator><pubDate>Tue, 24 Nov 2026 07:22:34 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6b004c32823e7883755c4a33/2acd2677-d959-43c0-ae26-8b4f3f1751be.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><strong>PoseWear is worth studying because its browser history makes AI image generation useful after the generate button has finished. Its source also shows exactly where a convenient creative history stops short of a reproducible experiment log.</strong> If you are building an image application, this is a practical design problem: preserve enough context for a person to understand a result, while making clear which inputs and execution details were not archived.</p>
<p>This article reviews the open-source <a href="https://github.com/atuizz/posewear/tree/0c97ab4b7e68e6212a5839d8320957f90627e629">atuizz/posewear project at commit 0c97ab4</a>. It uses three existing showcase groups and a separate archive of five real model outputs. No new paid inference was run for this article. The hosted <a href="https://posewear.net/">Posewear application</a> recommended at the end is a separate implementation; its server-side account and task storage should not be described using the upstream browser schema.</p>
<p>Disclosure: this article introduces and promotes the hosted Posewear application. The text was prepared with AI assistance, with technical claims checked against the linked source and existing image records.</p>
<h2>Follow the result into the database</h2>
<p>The upstream project is a static frontend built with Python and browser JavaScript. Generation still happens through remote APIs. The workbench prepares a person reference, garment references and pose references, composes a numbered explanation, and sends the request through a provider-specific adapter. OpenAI-style edits, Gemini content parts and Seedream JSON requests are separate protocol paths.</p>
<p>After a successful call, <code>run()</code> creates a record and passes it to <code>save()</code>. A shortened outline of the record, preserving the source's field names, is:</p>
<pre><code class="language-javascript">const recordShape = {
  t: "numeric timestamp-based key",
  prov: "provider identifier",
  model: "selected model",
  prompt: "actual sent prompt",
  orig: "original prompt when transformed, otherwise null",
  neutral: "whether neutral wording was enabled for this request",
  mode: "tryon or gen",
  label: "pose description",
  before: "first portrait Blob, or null",
  after: "generated image Blob"
};
</code></pre>
<p>This is a schema explanation, not executable replacement code. The <a href="https://github.com/atuizz/posewear/blob/0c97ab4b7e68e6212a5839d8320957f90627e629/src/studio.js">actual implementation</a> opens IndexedDB database <code>lk-studio</code>, version <code>1</code>, and creates store <code>h</code> with key path <code>t</code>. It uses transactions to write records. The generation save path trims older keys when the count exceeds 200, and the compact workbench history displays the newest 30 records with a route to the full history.</p>
<p>The important choice is to store image Blobs rather than only temporary display URLs. The UI creates object URLs when rendering stored images and revokes them during cleanup. A <code>blob:</code> URL is a display handle for the current browser context; treating that string as a portable image archive would lose the actual content.</p>
<p>There is a second useful detail: the saved <code>prompt</code> is the text actually sent after any neutral wording transformation, while <code>orig</code> can retain the earlier version. That gives a later reviewer a more precise explanation than a screenshot of the prompt box taken before submission.</p>
<h2>Inspect the export before promising replay</h2>
<p>The <a href="https://github.com/atuizz/posewear/blob/0c97ab4b7e68e6212a5839d8320957f90627e629/src/history.js">history module</a> has two different download paths. One packages selected generated images. The fuller export also adds <code>metadata.json</code>, containing export time, record count, and a list of records with provider, model, prompt, original prompt, neutral flag, label, time and file name.</p>
<p>That is already useful for reviewing a creative session. Someone can open the ZIP, see the result, and read the text associated with it. However, the exported metadata does not include the full collection of garment and pose input files. The in-browser record preserves the first portrait as <code>before</code>, but that alone does not reconstruct every reference passed into generation.</p>
<p>The history action labelled as regeneration also deserves a source-level reading. Its implementation restores the mode and the saved portrait into the workbench. It does not reconstruct a complete archived request containing all garment and pose attachments. A developer building an exact replay feature would need a broader record and an explicit restoration path.</p>
<p>Persistence has an operational boundary too. The generation <code>save()</code> catches storage errors without surfacing them there. A successful model response therefore does not, by itself, prove a durable local history write. The 200-record trimming policy controls record count; it does not establish that every browser has sufficient storage for those images. Exporting important results remains a deliberate step.</p>
<h2>Let three concrete examples tell you what to record</h2>
<h3>Standing fashion photography needs separate clothing checks</h3>
<p><img src="https://cdn.hashnode.com/uploads/covers/6b004c32823e7883755c4a33/c213013b-b5b0-420a-84c7-caeaec9dfb0d.webp" alt="Standing pose, beige coat outfit, portrait and the existing ImageGen showcase result" /></p>
<p>In <code>sc-001</code>, the pose sketch places both hands behind the head. The outfit reference contains a beige long coat, black turtleneck, pleated skirt, tights and tall boots; the portrait shows a long-haired adult. The completed showcase image keeps the raised elbows, coat layers and shoulder bag visible.</p>
<p>A useful review note would record those properties separately. “Good image” is too vague to explain the decision later. A more helpful note says that the coat length, pleats, boots and bag remain readable, then names anything that changed. Keep the source references beside the output so another person can check the same observation.</p>
<h3>A reclining pose needs camera geometry and omissions</h3>
<p><img src="https://cdn.hashnode.com/uploads/covers/6b004c32823e7883755c4a33/1951e86d-0fb0-4ac3-9a8f-24e7f297c732.webp" alt="Low-angle reclining pose, grey hoodie outfit, portrait and the existing ImageGen showcase result" /></p>
<p>Group <code>sc-003</code> uses a reclining figure with one knee raised, a grey hoodie, jeans, black shoes and a bag. In the result, a shoe sole occupies the foreground and the raised knee produces clear depth. The clothing reference also includes a cap, but the output omits it.</p>
<p>This result needs at least two independent notes: the camera relationship is readable, and accessory fidelity is incomplete. Recording only the model name and prompt makes the omission harder to investigate later. A photograph of the finished image cannot tell you whether a cap was present in the original reference.</p>
<h3>An anime transformation needs a stated style target</h3>
<p><img src="https://cdn.hashnode.com/uploads/covers/6b004c32823e7883755c4a33/9631b8b2-5d05-48f3-bd6f-bda098a25198.webp" alt="Side-sitting pose, pale blue outfit, portrait and the existing ImageGen anime showcase result" /></p>
<p>The third group combines a side-sitting sketch with one raised arm, a pale blue top and cardigan, white trousers, sandals, a bag and a short-haired portrait. Its completed image is an anime-style drawing on a pastel background. The blue-and-white palette, short hairstyle and overall pose remain legible.</p>
<p>For this case, the log should state that illustration was the intended target. Photographic texture is not the right acceptance criterion for every result. Pose, garment colours and recognisable hairstyle can be reviewed while acknowledging that no quantitative identity score was measured.</p>
<p>These three finished showcase images were recorded as built-in ImageGen illustrations on 24 November 2026. They are separate from the five-model archive below. They do not show five providers each passing the same three-case test.</p>
<h2>A model comparison becomes more useful when its gaps are visible</h2>
<p><img src="https://cdn.hashnode.com/uploads/covers/6b004c32823e7883755c4a33/e43d9818-0fb3-40d5-b76f-a73004fcb725.webp" alt="Five archived model outputs for the same standing person, outfit and pose references" /></p>
<p>The separate application archive contains one real output per configured model for the standing case. Each call used the same three references and prompt: one fictional adult, soft studio light, a neutral seamless backdrop, full-body composition and a requested 2:3 layout. The archive used person–outfit–pose ordering. The current hosted application's first three roles are pose–outfit–person, so the older prompt must be read with its original attachment order.</p>
<table>
<thead>
<tr>
<th>Configured model label</th>
<th>Delivered dimensions</th>
<th>Observation in this saved sample</th>
</tr>
</thead>
<tbody><tr>
<td>GPT Image 2.6</td>
<td>832 × 1248</td>
<td>Tighter framing makes the coat and boots prominent.</td>
</tr>
<tr>
<td>Seedream 5.5</td>
<td>836 × 1254</td>
<td>Broad coat panels and relatively even studio lighting are easy to inspect.</td>
</tr>
<tr>
<td>Kling Image 4.0</td>
<td>1664 × 2496</td>
<td>The delivered raster is larger than the others in this set.</td>
</tr>
<tr>
<td>MiniMax H3</td>
<td>832 × 1248</td>
<td>A stronger floor shadow extends to the right, with deeper contrast.</td>
</tr>
<tr>
<td>MAI Image 2.7</td>
<td>912 × 1152</td>
<td>There is more room around the subject; the delivered aspect ratio differs from 2:3.</td>
</tr>
</tbody></table>
<p>All five communicate the broad raised-arm pose and beige-over-black styling. That is a concrete observation supported by these images. The archive does not establish a universal quality winner, a repeatable success rate or average generation cost.</p>
<p>Resolution is another recorded condition, not a score. The current application adapter requests different output settings for some endpoints, including a 2k setting for Kling and omitted explicit ratio and resolution fields for the Microsoft model. This archive reflects integration choices as well as model behaviour. The comparison board preserves aspect ratios within equal display boxes; it does not stretch each result into identical geometry.</p>
<h2>Design a manifest that explains what can actually be repeated</h2>
<p>For a future experiment log, I would extend the existing history with a versioned manifest. This is a proposed design, not a feature claimed to exist upstream:</p>
<pre><code class="language-json">{
  "schemaVersion": 1,
  "referenceOrder": ["person", "outfit", "pose"],
  "references": [
    { "role": "person", "file": "person.jpg", "sha256": "…" },
    { "role": "outfit", "file": "outfit.jpg", "sha256": "…" },
    { "role": "pose", "file": "pose.jpg", "sha256": "…" }
  ],
  "actualPrompt": "…",
  "adapterVersion": "…",
  "referencesAccepted": "unknown",
  "output": { "file": "result.webp", "width": 832, "height": 1248 }
}
</code></pre>
<p>The prepared input bytes matter because portraits and library images follow resizing and conversion paths. Hashing only the original upload would not identify the exact bytes sent after preparation. Adapter version matters because a selected model label does not capture every request field or compatibility fallback. If the application cannot verify that references were accepted, the record should preserve that uncertainty rather than manufacture a positive boolean.</p>
<p>Secrets belong outside a shareable experiment bundle. The upstream API configuration export separately asks whether to include the key. That is different from exporting history metadata, and a publisher should inspect the actual bundle before sharing it. Local storage also describes where application state lives; it does not mean remote inference or optional proxy forwarding happens entirely on the device.</p>
<p>The broader lesson is to make the purpose of each artifact explicit: a creative history helps a person revisit results, while an experiment archive must preserve the inputs and execution conditions needed to explain a comparison. PoseWear already provides a compact, readable foundation for the first purpose and a useful starting point for designing the second.</p>
<p>I recommend exploring the open-source project for its practical combination of reference selection, provider adapters, browser history and export. For a quick way to experience the person–outfit–pose idea, try <a href="https://posewear.net/">Posewear</a>, following the role labels shown in that application's current interface. For the bring-your-own-key browser workbench, read the upstream repository and its deployment guidance. Thanks to <strong>atuizz</strong>, the contributors and the original reference-library creators for making the project available and its engineering decisions inspectable.</p>
]]></content:encoded></item><item><title><![CDATA[Defensive Edge Engineering for 3D Web Apps: Zero-Dependency PNG/JPEG/WebP & GLB Binary Parsers + Procedural PMREM Lighting in Three.js]]></title><description><![CDATA[TL;DR: When you run an Image-to-3D SaaS on Cloudflare Workers, you cannot import sharp on the edge to validate uploads, you cannot run Three.js on the…]]></description><link>https://czmilo.hashnode.dev/defensive-edge-engineering-for-3d-web-apps-zero-dependency-png-jpeg-webp-glb-binary-parsers-procedural-pmrem-lighting-in-three-js</link><guid isPermaLink="true">https://czmilo.hashnode.dev/defensive-edge-engineering-for-3d-web-apps-zero-dependency-png-jpeg-webp-glb-binary-parsers-procedural-pmrem-lighting-in-three-js</guid><dc:creator><![CDATA[Will Zhang]]></dc:creator><pubDate>Sat, 21 Nov 2026 01:51:24 GMT</pubDate><content:encoded><![CDATA[<p><strong>TL;DR:</strong> When you run an Image-to-3D SaaS on Cloudflare Workers, you cannot import <code>sharp</code> on the edge to validate uploads, you cannot run Three.js on the server to verify generated <code>.glb</code> files before charging credits, and you shouldn't force browsers to download 8 MB HDRI files just to light a 3D preview. In <strong><a href="https://idolmax.net/">Idol Max</a></strong>, we solved all three constraints with <strong>~220 lines of zero-dependency TypeScript binary parsers (<code>DataView</code>)</strong> on the edge and <strong>100% procedural PMREM lighting rigs</strong> in Three.js.</p>
<p>This technical deep dive walks through the exact byte-level checks, glTF 2.0 container verification logic, and procedural WebGL environment baking used in production today—plus how you can test the viewer directly on any local GLB.</p>
<hr />
<h2>Problem 1: Validating User Uploads on V8 Isolates Without <code>sharp</code></h2>
<p>In an Image-to-3D app, every upload triggers real paid GPU inference ($0.10 to $0.35 per call depending on model and PBR/rig options). Trusting client-supplied <code>file.type</code> or filename extensions opens two classic edge failures:</p>
<ol>
<li><strong>Garbage requests burning API quota:</strong> Corrupt files or renamed HTML/PDF blobs sent upstream.</li>
<li><strong>Decompression bombs:</strong> A tiny 40 KB PNG whose IHDR declares <code>32000 × 32000</code> pixels, blowing up decoder memory downstream.</li>
</ol>
<p>Inside <code>lib/ai3d/image.ts</code>, we enforce three invariants—<strong>size ≤ 6 MB</strong>, <strong>supported format (PNG / JPEG / WebP)</strong>, and <strong>64 px ≤ width, height ≤ 4,096 px</strong>—purely by reading binary headers via <code>DataView</code>:</p>
<h3>PNG (IHDR Chunk)</h3>
<p>Verify the 8-byte signature <code>89 50 4E 47 0D 0A 1A 0A</code>. In every valid PNG, the IHDR chunk immediately follows, placing big-endian <code>uint32</code> width at byte offset <code>16</code> and height at byte offset <code>20</code>:</p>
<pre><code class="language-ts">if (
  bytes[0] === 0x89 &amp;&amp; bytes[1] === 0x50 &amp;&amp; bytes[2] === 0x4e &amp;&amp; bytes[3] === 0x47 &amp;&amp;
  bytes[4] === 0x0d &amp;&amp; bytes[5] === 0x0a &amp;&amp; bytes[6] === 0x1a &amp;&amp; bytes[7] === 0x0a
) {
  return { mime: 'image/png', width: view.getUint32(16), height: view.getUint32(20) };
}
</code></pre>
<h3>JPEG (Walking Marker Segments to SOF)</h3>
<p>Verify <code>FF D8 FF</code>, then step through variable-length segments starting at offset <code>2</code>. Skip standalone markers (<code>0xD8</code>, <code>0x01</code>, restart markers <code>0xD0..0xD7</code>), skip Huffman/DAC/arithmetic markers (<code>0xC4</code>, <code>0xC8</code>, <code>0xCC</code>), and stop at the first Start-Of-Frame marker (<code>0xC0..0xCF</code>). Height sits at <code>offset + 5</code> (uint16 big-endian) and width at <code>offset + 7</code>.</p>
<h3>WebP (<code>RIFF....WEBP</code> Across Three Bitstream Variants)</h3>
<p>Verify <code>RIFF</code> at bytes <code>0..3</code> and <code>WEBP</code> at bytes <code>8..11</code>, then read the 4-byte chunk ID at <code>12..15</code>:</p>
<ul>
<li><strong><code>VP8X</code> (extended):</strong> 24-bit little-endian <code>(width - 1)</code> at bytes <code>24..26</code> and <code>(height - 1)</code> at bytes <code>27..29</code>.</li>
<li><strong><code>VP8 </code> (lossy):</strong> Verify keyframe start code <code>9D 01 2A</code> at bytes <code>23..25</code>, then read 14-bit masked little-endian <code>uint16</code> width (<code>26</code>) and height (<code>28</code>).</li>
<li><strong><code>VP8L</code> (lossless):</strong> Verify signature byte <code>0x2F</code> at offset <code>20</code>, then unpack two 14-bit values (+1 each) from the <code>uint32</code> at offset <code>21</code>.</li>
</ul>
<p>Zero WASM modules, zero native bindings, sub-millisecond execution time inside a Cloudflare Worker isolate—and once validated, the bytes convert directly to a chunked base64 <code>data:</code> URI (32 KB chunks to stay clear of call-stack limits) and stream to fal.ai with <code>X-Fal-Store-IO: 0</code> so no source image ever touches disk.</p>
<hr />
<h2>Problem 2: Verifying AI-Generated GLB Files Before Settling User Credits</h2>
<p>AI inference APIs occasionally succeed at HTTP <code>200</code> while delivering a truncated download, an empty scene graph, or a malformed binary container. If your backend settles credits immediately upon seeing <code>status: "COMPLETED"</code>, users get billed for unusable files.</p>
<p>Running Three.js <code>GLTFLoader</code> inside a Worker is bloated and unnecessary just to validate container integrity. Instead, <code>lib/ai3d/glb.ts</code> implements <code>inspectGlb(buffer: ArrayBuffer)</code> directly against the <strong>glTF 2.0 binary specification</strong> in ~70 lines:</p>
<ol>
<li><strong>Minimum header size &amp; magic bytes:</strong> Reject buffers smaller than 28 bytes. Verify little-endian <code>uint32</code> at byte <code>0</code> equals <code>0x46546c67</code> (<code>"glTF"</code>), and version at byte <code>4</code> equals <code>2</code>.</li>
<li><strong>Truncation check:</strong> Read declared total byte length at byte <code>8</code>. If <code>declared &gt; buffer.byteLength</code>, throw <code>'GLB file is truncated'</code>.</li>
<li><strong>JSON chunk extraction:</strong> Read chunk 0 length at byte <code>12</code> and type at byte <code>16</code>. Verify type equals <code>0x4e4f534a</code> (<code>"JSON"</code>) and <code>20 + jsonLength &lt;= buffer.byteLength</code>. Decode via <code>TextDecoder</code> and <code>JSON.parse</code>, checking <code>json.asset?.version === '2.0'</code>.</li>
<li><strong>Geometry &amp; animation accounting:</strong> Iterate <code>json.meshes[].primitives[]</code>, filtering triangle primitives (<code>mode === undefined || mode === 4</code>), summing <code>POSITION</code> accessor counts for <code>vertexCount</code> and <code>Math.floor(indexCount / 3)</code> for <code>triangleCount</code>. Extract <code>json.skins?.length</code> and <code>json.animations?.length</code>.</li>
<li><strong>Non-empty gate:</strong> If <code>vertexCount === 0</code>, throw <code>'GLB contains no geometry'</code>.</li>
</ol>
<p>Why this matters in production:</p>
<ul>
<li><strong>Fair billing:</strong> Credits reserved at submission (<code>credit_reservations</code>, 90-minute hold) are only settled <em>after</em> <code>inspectGlb</code> passes. Truncated or empty meshes trigger an automatic full refund.</li>
<li><strong>Rich metadata at rest:</strong> Exact <code>vertexCount</code>, <code>triangleCount</code>, <code>skinCount</code>, and <code>animationCount</code> are stored right on the D1 <code>models</code> row so the Studio and My Models views know the asset's footprint before the browser even starts downloading the <code>.glb</code>.</li>
</ul>
<hr />
<h2>Problem 3: High-Craft PBR Lighting in Three.js With Zero External HDRI Files</h2>
<p>Switching from the edge to the browser: PBR materials (especially when users enable <code>enable_pbr</code> on Idol Max or Idol Max Turbo to generate roughness and metalness maps) look dead under bare directional lights alone. They need <strong>Image-Based Lighting (IBL)</strong> via <code>scene.environment</code>.</p>
<p>The naive solution is bundling 4 separate <code>.hdr</code> or <code>.exr</code> environment maps—easily adding 6–15 MB of network transfer and delaying first paint.</p>
<p>Instead, <code>components/viewer/scene-presets.ts</code> builds all four studio lighting rigs (<code>Studio</code>, <code>Soft</code>, <code>Dramatic</code>, <code>Outdoor</code>) <strong>100% procedurally on the GPU</strong> using <code>THREE.PMREMGenerator</code>:</p>
<ul>
<li><strong>Indoor rigs (<code>Studio</code>, <code>Soft</code>, <code>Dramatic</code>):</strong> Bake Three.js's built-in <code>RoomEnvironment()</code> through <code>pmrem.fromScene(source, rig.envBlur)</code> with tuned <code>envBlur</code> (<code>0.04</code> for crisp studio reflections, <code>0.10</code> for soft diffused reflections) and <code>envIntensity</code> (<code>0.9</code>, <code>1.3</code>, and <code>0.1</code> respectively for dramatic chiaroscuro).</li>
<li><strong>Outdoor rig (<code>Outdoor</code>):</strong> Constructs an in-memory procedural sky sphere (<code>SphereGeometry(50, 48, 24)</code>, <code>BackSide</code>) with per-vertex color interpolation from deep sky blue (<code>#5b9bff</code>) to horizon mist (<code>#e8f0fb</code>) and warm ground bounce (<code>#8a7f6d</code>), plus an HDR-intensity sun sphere (<code>color.setRGB(16, 13, 9)</code> at <code>[28, 36, 20]</code>). Baking this lightweight scene into a PMREM cubemap gives realistic outdoor specular highlights on metallic PBR materials with <strong>0 KB of HDR network payload</strong>—and disposes the temporary geometry, materials, and <code>PMREMGenerator</code> immediately after baking so GPU memory stays clean.</li>
</ul>
<p>Each rig pairs its procedural PMREM with a calibrated 4-light hierarchy (<code>HemisphereLight</code>, shadow-casting <code>key</code> <code>DirectionalLight</code> with per-preset <code>shadowRadius</code>, <code>fill</code>, and <code>rim</code> lights) rendered through <code>ACESFilmicToneMapping</code> and <code>PCFShadowMap</code>.</p>
<h3>Keeping WebGL Battery-Friendly: On-Demand Rendering</h3>
<p>To avoid spinning laptop fans on idle pages, <code>ModelViewerEngine</code> never runs an unbounded <code>requestAnimationFrame</code> loop. It draws frames strictly when:</p>
<ul>
<li><code>OrbitControls</code> fires <code>change</code> or damping (<code>dampingFactor = 0.08</code>) is still settling,</li>
<li>Auto-rotate or a skeletal <code>AnimationMixer</code> clip (<code>walk</code>, <code>run</code>, <code>jump</code>, <code>idle</code>) is actively playing, or</li>
<li>A deterministic export frame (<code>renderExportFrame</code>) is requested for PNG, Web Worker GIF, or WebCodecs MP4/WebM output.</li>
</ul>
<hr />
<h2>Verify It Yourself on Any Local GLB</h2>
<p>Every piece of the browser engine described above—Meshopt and locally vendored Draco decoding, procedural PMREM lighting rigs, Clay/Wireframe inspection, bounding-box auto-framing, and geometry statistics—is exposed publicly without login at our <strong><a href="https://idolmax.net/glb-viewer">free online GLB Viewer</a></strong>. Drop any <code>.glb</code> file onto the canvas (it stays strictly local in memory) and toggle between <code>Studio</code>, <code>Soft</code>, <code>Dramatic</code>, and <code>Outdoor</code> lighting to see procedural PMREM reflections on PBR materials in real time.</p>
<p>And if you want to see the full edge-to-browser pipeline—from binary-verified image upload and fal.ai queue generation through glTF validation and interactive studio export—you can try <strong><a href="https://idolmax.net/">Idol Max</a></strong> directly.</p>
]]></content:encoded></item></channel></rss>