[reasoning] The user wants a lava lamp built as a single index.html file with no external requests. Let me plan this carefully. First, let me check the workspace to see what's there. Let me look at the workspace directory first. Requirements: 1. Single index.html file, no external requests 2. Glass lamp on a desk 3. Wax blobs rise as they warm, sink as they cool, merge and split when they touch 4. Switch that turns the lamp off and on 5. Hold 60 fps 6. Fit a phone screen Let me design this thoughtfully. Design: A lava lamp on a desk. The lamp has a glass vessel (the classic lava lamp shape — a tapered glass bottle), with a metal base and cap. On the desk there's a switch (maybe a cord with an inline switch, or a toggle on the base). The glass shows liquid with wax blobs. Physics: Metaballs for rendering, with a particle-based simulation for blobs. Each blob has temperature. Heating occurs near the bottom (heat source from the bulb), cooling near the top. Warm blobs are less dense → rise. Cool blobs → sink. Merging: when blobs touch, they merge (combine mass, momentum, temperature). Splitting: when a blob gets large or has high temperature variance / shear, it can split. For performance: Render metaballs using a 2D canvas with an offscreen low-res field buffer and threshold, or use WebGL. WebGL would be the most performant: a fragment shader computing the metaball field from N blobs (uniform array), then thresholding it to draw wax with shading (fake 3D lighting from the field gradient). That's very cheap — for e.g. 24 blobs at full screen resolution, the fragment shader loops over 24 blobs per pixel. On a phone at DPR 3, that could be heavy: e.g., 1170x2532 = 3M pixels × 24 blobs = 71M distance evaluations per frame... That might be OK on modern phones but risky for 60fps on low-end. Better: render the lamp to a lower-res offscreen buffer (e.g., the lamp region at ~ 1x CSS resolution or even scaled), since wax blobs are soft. Or do the field computation in a low-res grid and upload as a texture, then a shader samples it with bilinear filtering for smooth thresholding. Hmm, but bilinear interpolation of a field at low res can give artifacts at the threshold... Actually, with a smooth field (sum of gaussians), bilinear interpolation at e.g. 2x downsampling is fine, though the field near the threshold is smooth so it's OK. However, I could also do the WebGL approach with a loop but bounded to lamp region only: the lamp occupies maybe 30% of the screen width and 60% of the height → ~18% of pixels. 18% of 3M = 540k pixels × 20 blobs = 10.8M evaluations. That's trivial even for phones. So draw the lamp's interior region with the metaball shader, and render the rest with 2D canvas or static DOM/SVG/CSS. Options: A) Whole scene on a single 2D canvas, with the metaball field computed on CPU in a low-res grid (e.g., 96×240 cells) each frame and drawn via ImageData putImageData scaled up with smoothing. CPU: 96×240 = 23k cells × 20 blobs = 460k evaluations per frame — trivial. But upscaling thresholded binary shapes via canvas drawImage with smoothing gives blurry edges. To get crisp edges: compute the field at low res, then in an ImageData at higher res using bilinear interpolation? That costs more CPU: e.g., 300×750 = 225k pixels — bilinear interpolation per pixel = 225k × ~10 ops — about 2-3 ms in JS. Hmm, that's OK but risky on phones. Alternative: field values mapped to alpha (soft edges) and scaled up with smoothing → blurry edge but can be made to look okay with a threshold applied... no. B) WebGL: one canvas for the glass interior with a fragment shader. Smooth, crisp at any resolution, with nice shading (normal from field gradient → specular highlights, fresnel-ish rim, subsurface glow). It's the best visual result. Fallback if WebGL isn't available: Canvas2D approach. I think having a fallback is good for robustness (e.g., headless test environments without GPU, WebGL could be disabled). Hmm. That doubles the rendering code. But robustness matters: "It should hold 60 fps" — WebGL is the safest for perf. But if WebGL context creation fails (some environments), the lamp would be blank. A Canvas2D fallback with the same field would be wise. Let me think about how much extra code: a 2D fallback would compute field on a grid, then threshold + shade. It's maybe 60-80 lines. I think it's worth it. Actually, let me think about whether to unify: compute the field on CPU once per frame at a moderate resolution, upload as texture (R8 or float?), and then both WebGL and 2D could use it... Simpler: WebGL primary with direct per-pixel computation of the field in the shader (accurate, crisp), with a 2D fallback that computes the field on CPU grid. The field function is shared conceptually. Hmm, wait. Let me think about what gives the best result with least risk. Let me think about the WebGL shader approach in more detail. Field: f(p) = Σ_i w_i * g(|p - c_i| / r_i) where g is a smooth falloff kernel, e.g., (1 - d²/r²)³ for d < r (Wyvill-like) — compact support makes it cheap (can skip with a branch) and gives controllable merge behavior. Threshold at f = T (e.g., 0.5... or 1.0). The surface is f(p) = T. Shading: normal n = normalize(-∇f, k) for some k giving pseudo-height. The "height" h = f (or a function of f). With f being the field, near the boundary the field rises quickly; we could use height = sqrt(f - T) or something to give a rounded profile. Actually, a common approach: height h = (f - T) / (f_max - T) ... then normal from gradient of h. To get a nice rounded look, use a profile function like h = 1 - (1 - clamp((f-T)/s, 0, 1))^2 or a smoothstep. Then lighting: lambert with a light direction, specular highlight, and a darker rim (fresnel-like) to give a 3D blob look. Plus the wax color with gradient (warmer = brighter/more emissive at the bottom of the lamp since the bulb lights it from below). Splitting/merging via metaballs: Two blobs near each other naturally visually merge (the metaball necks). For the physics, I need explicit "merge and split when they touch". So the simulation should have explicit merge events (two blobs combine into one particle) and split events (one blob splits into two). With metaballs, merging in the visual occurs when the fields overlap. For the sim: when two blobs overlap enough (distance < some fraction of the sum of radii, and the field bridge between them is above the threshold), they merge into one blob with conserved area (r² additive in 2D), momentum, and heat (weighted by area). Splitting: when a blob is large and stretched, or has a temperature gradient across it (one side hot, one side cold), it splits into two. To make it look natural: the blob elongates (we could represent as two sub-particles that are close), then separate. An approach that gives natural-looking splits and merges: represent each wax blob as a *cluster* of 1-2 metaball "particles"? Hmm, alternatively: model each blob as a soft body consisting of multiple particles connected by springs (like a "blob" with N sub-particles). Merging = connecting spring bonds between two blobs' particles; splitting = breaking bonds. That's a full soft-body approach—more complex, and perf heavier but still feasible with ~40-60 particles. But it's a risk for weird behaviors. Simpler approach which looks good: each blob = one metaball particle with radius r (area A = πr²) and temperature T. Rendering kernel radius R = k·r where k ≈ 1.6 or so, so that the visible blob radius (where the single blob field crosses the threshold) is r. Let me define field: f(p) = Σ (A_i / A_ref) * K(|p - c_i| / R_i), where K(u) = (1 - u²)³ for u<1. For a single blob with weight w: threshold T: w(1-u²)³ = T → u = sqrt(1 - (T/w)^(1/3)). For the visible radius to be r: R = r / sqrt(1 - (T/w)^(1/3)). If I choose T = 1 and w = (r/r0)²·w0... For area-conserving merges, w should scale with area: w_i = (r_i/r0)². For a base blob with r=r0, w = 1: (1-u²)³ = T. Let me pick T = 0.25 → T^(1/3) = 0.63 → u² = 0.37 → u = 0.608. So R = r/0.608 = 1.645 r. OK. So merging visual: when two blobs approach, their fields sum; the bridge forms when the sum at the midpoint exceeds T. For two equal blobs of weight 1 separated by distance d: at the midpoint each contributes (1 - (d/2R)²)³. The bridge forms when 2(1 - (d/(2R))²)³ = 0.25 → (1 - (d/(2R))²)³ = 0.125 → 1 - (d/(2R))² = 0.5 → d/(2R) = 0.707 → d = 1.414R = 2.33 r. So when the center distance is < 2.33 r (i.e., the blobs' visible edges are separated by 0.33r gap), they visually bridge. That's a nice natural "touch" criterion: blobs "touch" visually when d < ~2.2 r (for equal sizes) — for unequal sizes it's different, but we can just use the criterion d < α(r_i + r_j) with α ≈ 1.05-1.1 (so that there's a real overlap of the visible circles — "when they touch"). Since the metaball bridging happens before the visible circles overlap (at 1.16 r each for equal blobs), a merge at d < 1.1(r_i + r_j) would be after the visual bridging started; the visual would then snap from "two blobs with a neck" to "one blob" — a single metaball of area 2A has radius √2 r = 1.414r, which covers both former blobs' centers, but the shape changes: the merged blob would be a circle of radius 1.414r at the center, which is shorter in the long axis than the two touching blobs (extent 2r + 1.1·2r = 4.2r total length vs. 2.83r for the merged). That's a visible "snap" — a pop. To avoid the pop: animate the merge: after merging, the new blob could be represented with shape memory... Hmm. How do real lava lamps look? Wax blobs merge smoothly, with a neck forming and widening, then relaxing into a larger round blob. And splitting: a large blob stretches, a neck forms, and it pinches off into two. To make this look right with simple particles: keep the two particles as separate until they are nearly coincident, i.e., after they "touch", they are attracted to each other and remain two metaballs with overlapping fields; the visual shape is the union of two overlapping spheres — which, with the metaball field, looks like a peanut that gradually rounds out as the centers approach. When the centers are nearly coincident, replace with a single particle of area 2A (visually nearly identical: at d → 0 two coincident particles of weight 1 each produce field 2·K(u) vs. a single particle of weight 2 with R' = ... hmm, not identical: the merged single particle has weight 2 and R' = 1.645·√2·r = 2.33r; field = 2(1 - d²/(2.33r)²)³ = 2(1 - d²/(5.41r²))³. Two coincident particles: 2(1 - d²/(2.706 r²))³. The single: falls to T=0.25 at d²/5.41r² = 0.37 → d = 1.414r ✓. The two: 2(1-x)³ = 0.25 → (1-x)³ = 0.125 → x = 0.5 → d² = 1.353r² → d = 1.163r. Hmm! So two coincident particles of weight 1 would look like a blob of radius 1.163r, not 1.414r, since the sum of weights is 2 but the kernel radius is smaller. So the merged blob would jump in size from 1.163r to 1.414r. Unless I make the kernel radius scale differently with weight. Let me reconsider: to make the field of coincident particles equal to the field of the merged one, I need the kernel to be additive... which is not possible for a compact kernel like this (fields don't add linearly in shape). Alternative: use a different formulation: field f(p) = Σ w_i K(|p-c_i|/R_i), where w_i = (r_i/R_i)^something... Let me think: what if the kernel radius is the same for all (R_i = R const, or depends only weakly on size) and weight ∝ area: w_i = A_i/A0. Then for coincident particles, the sum of weights = total weight, and the field is exactly identical to a single particle with that total weight (same R). So merges are perfectly seamless when R is constant across blobs. But then the visible radius r_i = R·sqrt(1 - (T/w_i)^(1/3)): for w=1, T=0.25: r = 0.608R. For w=2: (0.125)^(1/3) = 0.5 → r = 0.707R. For w=4: (0.0625)^(1/3)=0.397 → r = 0.774R. For w = 0.5: (0.5)^(1/3) = 0.794 → r = 0.454R. So the radius varies weakly with weight: doubling the area increases the radius by only 16%. That's a too-weak size dependence: all blobs would look nearly the same size. Not good — I want real size variety. Fix: make the kernel radius depend on size, but handle the merge transition smoothly by interpolation. E.g., on merge: new blob with area A = A1 + A2, placed at the area-weighted centroid. Before the merge, the visual is two overlapping particles. After: one particle. The visual pop is the change of the shape. To hide it: merge only when the particles are very close (d small relative to r), and gradually... no wait. Alternatively, we can define the single-blob field in a way that it's consistent with the "many coincident particles" limit: i.e., think of a blob of area A as consisting of A/A0 "unit" particles all at the same position, each with kernel radius R(A) that depends on the blob's area... no. Alternative approach: think of it as each blob having weight w_i and kernel radius R_i = c·r_i with weight w_i = (r_i/r0)²·w0, i.e., what I had. When two blobs merge, to be seamless, do the following animation: the merged blob is initially represented by the two particles still (as a "compound blob"), which continue to attract each other via a spring until coincident... and the pop at the moment of switching to a single particle remains, but it's smaller if done when the particles are nearly coincident: at d=0 the two-particle visual has radius 1.163 r vs. single 1.414 r — a 21% radius pop. That's visible, though in a lava lamp the blobs are constantly deforming, a pop in size would look bad-ish. Unless we make the transition continuous: blend the field over time. E.g., the merged blob keeps a "ghost" pair: particle A at c1 and particle B at c2, each of weight w/2 and radius R' (the merged radius), and they move towards the centroid under a spring while weights... Hmm, here's a cleaner idea: after the merge decision, *both* particles switch to the new kernel radius R' (bigger) and weight w/2 each. At that moment the field changes: before: two blobs of radius r (R=1.645r), weights 1 each, at distance d ≈ 1.1·2r; after: two particles with weight 1 and R' = 2.33r, the same positions. Visible shape: before, each visible radius 1r, with a neck; after, each has visible radius: w=1, R'=2.33r → 0.608·2.33r = 1.417r each, overlapping heavily. So it's also a pop: an instant expansion from 1r to 1.417r. Not continuous either. OK here's another thought: make the field formulation such that a particle's "visible shape" is consistent under merging *by construction*, by using a formulation where the field is a sum over particles of *area-like* contributions with a kernel whose radius scales with the particle's size, but where the merged particle is rendered not as a single kernel but as a smooth blend. Hmm. Alternative: Accept a per-blob "shape" model: each blob is rendered as a *pair* of metaballs (lobes) — an ellipse-like shape formed by 2 particles, whose separation is a shape parameter that relaxes. A blob with separation s between the two lobes; s = 0 means round. Merging two blobs = creating a blob with 2 lobes located at the positions of the two original blobs... Hmm, wait. Actually, let me think about "blob = cluster of n unit metaballs" in a more principled way, i.e., the soft-body approach, but with an *implicit* (field-based) representation rather than springs: Each blob is a set of particles that are bound together. The particle positions within a blob evolve under: (1) cohesion forces (attraction to the blob's other particles at a preferred distance depending on the total area), (2) buoyancy per particle (based on each particle's own temperature), (3) drag. The temperature is exchanged between particles in the same blob (conduction), and with the environment (heating at the bottom, cooling at the top). Merging: when particles of different blobs come within contact distance, the blobs merge (union-find). Splitting: when particles of the same blob are farther apart than a threshold (i.e., the blob is stretched beyond its maximum extent) — the bond breaks. With enough particles per blob (e.g., 4–8), a big blob is elongated, and it can split when the hot part rises and the cool part sinks (differential buoyancy). That's the "real" physics approach and gives natural-looking deformation, merging, and splitting. But it's more complex to tune: needs to be stable, look good, and not jitter. Performance: with ~60-100 particles and O(n²) pair interactions = 10k pair checks per frame — trivial for JS. The rendering: the shader loops over N particles (N ≤ ~64): fine for WebGL if the lamp area is limited; in the 2D fallback, a grid of 23k cells × 64 = 1.5M kernel evals/frame — fine too (each with a few multiplications), maybe 3-5ms in JS. Hmm, on a phone, 1.5M iterations of simple float math per frame is ~3-6 ms. Acceptable but could optimize by bounding-box splatting (only iterate cells within each particle's radius): each particle covers (2R)² cells; R ~ 20-30 cells at 100×250 grid → 2000 cells × 64 = 128k. But the complexity of tuning the soft-body sim to look good is a concern. I can't view the result visually here... Actually, can I? I have tools: read, write, edit, glob, grep. No bash or browser tool! So I cannot run the code at all — no headless browser screenshot. That's a major constraint: I must write the code very carefully, reason through the physics and rendering numerically, and make sure there are no bugs, since I can't test. Hmm. That makes me want to choose a simpler, more predictable approach, with careful analytical reasoning. Given I can't run anything, the approach should be: - Simple and robust code (no fancy fragile stuff). - Use widely-supported APIs. - Think carefully about each piece, especially the math of the shader and the sim. Let me think about which rendering approach is the least risky given no testing: WebGL fragment shader is something I can write correctly with care. A Canvas2D fallback adds a second path I also can't test, but it's simple enough. I think I should include the fallback because the stakes of WebGL being unavailable are high (blank lamp), but each extra path is untested code... I'll write it carefully. Hmm, let me think about whether the fallback is worth it. If WebGL fails in the evaluation environment (e.g., a headless Chrome with software GL — usually SwiftShader works; Playwright's Chromium supports WebGL through SwiftShader by default, though in newer headless versions, WebGL may need `--enable-unsafe-swiftshader`... Indeed! Chrome 137+ deprecated automatic SwiftShader fallback for WebGL: "Starting in Chrome 137, WebGL will no longer fall back to SwiftShader automatically" — I recall that this was planned: WebGL context creation would fail unless `--enable-unsafe-swiftshader` is passed, on platforms where there's no GPU. On macOS, there's always a GPU (or ANGLE Metal), so fine. On Linux headless without GPU, it may fail. An evaluation harness probably runs on macOS (the environment is darwin) or Linux. With a 2D canvas fallback, the lamp would still work in any case. So yes, a fallback is worthwhile. And for "hold 60 fps" checks in headless software rendering, a 2D canvas low-res field would also be fast where WebGL with SwiftShader would be slow (SwiftShader running a fragment shader with a 24-iteration loop at high-res is slow!). Hmm, that's a real concern: if the evaluation runs in headless Chrome with SwiftShader (software GL), a heavy fragment shader may be slow → low FPS. So performance must be robust even under software rendering: so keep the shader light and render at bounded resolution. Idea: make the pipeline robust in both: compute the field on the CPU at a low-res grid (e.g., ~80×200 to 120×300) and upload as a texture; the WebGL shader then does per-pixel sampling + shading at full res (cheap shader: 1 texture fetch + shading math). With SwiftShader, a simple shader at, e.g., 600×1300 pixels is okay-ish (SwiftShader does maybe 100-300 Mpix/s for simple shaders on multi-core; shading math with pow, normalize etc. maybe 50 Mpix/s...). On a phone GPU it's trivial. Alternatively render the whole lamp in 2D canvas only, without WebGL at all: compute the field in a low-res Float32Array grid, then produce the final pixels in an ImageData with bilinear interpolation of the field at the target resolution and per-pixel shading in JS. Cost: lamp region at CSS resolution: e.g., 300×700 = 210k pixels × (bilinear + shading ~40 flops) ≈ 8M flops/frame → ~2-4 ms on desktop, maybe 6-10 ms on a mid phone. Risky for 60 fps on low-end phones but could be managed with dynamic resolution (reduce the internal resolution if frame time is high). But bilinear interpolation of the field from a grid gives slightly faceted edges (the threshold contour of a bilinear-interpolated field is piecewise hyperbolic — smooth enough if the grid is fine relative to the blob curvature). The shading normal from the gradient of the bilinear field would be discontinuous across cell boundaries → visible faceting in the specular highlights. To avoid, compute the gradient analytically per pixel from the blobs (expensive), or use a smoother interpolation (bicubic), or compute the gradient at grid resolution and interpolate that too (gradient field bilinear → continuous normals). That's 3 channels to interpolate: f, gx, gy. Doable: compute the analytic gradient at grid nodes during the splat (the kernel derivative), then per pixel: bilinear interpolate f, gx, gy. The cost per pixel: 3 bilinear interpolations = 12 mul/add... fine. Hmm. So which one? Let me think about what will look best and be robust: Option W (WebGL): CPU computes nothing but particle positions; shader computes the field analytically per pixel within the lamp region. Crisp, smooth, analytic normals → beautiful shading. Cost on real GPUs: negligible. Cost on SwiftShader: lamp region pixels × N blobs loop. If I limit the drawing buffer resolution (e.g., max 2x DPR and cap total pixels), it's OK on most machines. And I could add an adaptive quality: measure frame times, and if consistently slow, reduce the resolution scale (lower the DPR). That's a simple robust mechanism that helps "hold 60 fps" on any device. I like it: adaptive resolution scaling based on the measured frame time. For the 2D fallback (if WebGL unavailable): CPU field grid at low res, with thresholding + simple shading in a small ImageData, drawn scaled with smoothing. Since it's a fallback, moderate quality is acceptable: field grid at e.g. 120×300 (36k cells), splat with bounding boxes, shading per cell (normal from grid gradient), alpha from smoothstep around the threshold (antialiasing at grid scale), then drawImage scaled to the lamp size with imageSmoothingEnabled → blurry upscaled blobs (3-4x upscale) but with soft-looking blobs... Lava lamp blobs are soft and glowing anyway; a 4x bilinear upscale of a smooth shaded image looks blurry at the edges but acceptable. Could increase the grid res for the fallback: 200×500 = 100k cells; the splat cost: each blob covers (2R)² cells... with R ≈ 0.2×lamp width = 40 cells → 6400 cells per blob × 20 blobs = 128k kernel evals. Fine. Then shading 100k cells. It's OK: ~2ms on desktop. Hmm, OK. But wait. Maybe I'm overcomplicating. Let me think about what really matters to the user: "Build a lava lamp as a single index.html file with no external requests. Show a glass lamp on a desk. Wax blobs rise as they warm, sink as they cool, and merge and split when they touch. Add a switch that turns the lamp off and on. It should hold 60 fps and fit a phone screen." Key acceptance criteria: 1. Single index.html, no external requests (no CDN fonts, images, etc.). 2. Glass lamp on a desk — visually recognizable: a desk surface, a lamp with a glass body, metal base and cap, maybe a cord, and a switch. 3. Wax blobs: rise as they warm, sink as they cool (temperature-driven buoyancy). Merge and split when they touch. 4. A switch that turns the lamp off and on — interactive; off state: lamp dark, wax cools and sinks, the light is off; on: light glows, heating resumes. 5. 60 fps — performance. 6. Fits a phone screen — responsive layout, works in portrait on small screens (e.g., 360×640), no scrolling, touch-friendly switch. Since I can't run it, I need to be extra careful with correctness. Let me think about using the simplest robust tech that produces a great look: Rendering plan: - One full-screen `` for the scene? Or layered: a 2D canvas for the static background (desk, wall, lamp body), and a WebGL canvas for the wax/liquid clipped to the glass shape, with CSS/DOM for the switch? Layers give a crisp static background that doesn't need re-rendering. But the lamp casts light on the desk/wall that changes with the on/off state and maybe subtly with the wax — a dynamic glow. That can be done with a 2D canvas redrawn each frame (cheap) or CSS opacity transitions on a glow layer. Hmm, think about which is simpler and more robust: A single WebGL canvas for everything (background + lamp + wax) vs. layered. Layered approach details: - Layer 0: static background canvas (2D) drawn once on resize: wall gradient, desk surface, lamp shadow. - Layer 1: glow (CSS radial gradients, opacity animated by JS for on/off) — the light cast on the wall/desk. - Layer 2: the lamp: glass interior with WebGL canvas (liquid + wax), clipped by the glass shape. The glass shape: a classic lava lamp — a tapered bottle: wider at the bottom, narrowing towards the top. For clipping a canvas to a custom shape: CSS `clip-path: polygon(...)` or use a border-radius trick. `clip-path: polygon()` is widely supported (with -webkit- prefix in older Safari < 14, but modern is fine). Alternatively draw the glass silhouette in the shader itself (SDF of the trapezoid) — more elegant, no clip-path needed: the shader computes the glass shape and draws liquid inside, glass reflections at the edges, etc. That gives full control: antialiased edges, highlights, etc. - Layer 3: foreground overlay canvas (2D, static): the metal base, cap, glass reflections/highlights drawn over the wax (specular streak on the glass), and the switch. The static overlay with highlights drawn once on resize. So: 3 canvases: back (static), GL (dynamic), front (static). Plus a DOM switch (button) or a canvas-drawn switch with hit testing. A DOM ` ``` `100%` height with `position: fixed; inset: 0` for the stage: use `width: 100vw; height: 100vh; height: 100dvh`? `position: fixed; inset: 0` is the most robust for mobile browsers (follows the visual viewport in most cases). I'll use the stage's clientWidth/clientHeight for the layout. **The switch SVG** (viewBox 0 0 120 76), sized by CSS width/height: ```html ``` The halves with rounded corners: use `stroke-linejoin: round` with a stroke of the same color to round the corners: stroke-width 3. State styling: ```css #switch .half { transition: transform .16s ease, fill .16s ease; } #switch[aria-checked="true"] .half.off { fill: #6b6e7b; transform: translateY(-2.5px); } /* raised, lit */ #switch[aria-checked="true"] .half.on { fill: #2c2d35; transform: translateY(1.5px); } /* pressed */ #switch[aria-checked="false"] .half.off { fill: #2c2d35; transform: translateY(1.5px); } #switch[aria-checked="false"] .half.on { fill: #6b6e7b; transform: translateY(-2.5px); } #switch .led { fill: #3a2a22; transition: fill .2s, filter .2s; } #switch[aria-checked="true"] .led { fill: #ff9a45; filter: drop-shadow(0 0 4px #ff7a1a); } ``` The marks move with their halves: put the marks inside the same groups as the halves. The focus ring: `#switch:focus-visible { outline: 2px solid #ffd9a8; outline-offset: 4px; border-radius: 12px; }`. The switch's hit area: the button is sw × sh px: at least 64×44 ✓. **Layout code**: ```js function layout() { const W = stage.clientWidth, H = stage.clientHeight; // lamp scale let S = Math.min(H * 0.74, W * 1.6); // lamp height in px; W*1.6: ensures lamp width (0.3S) + switch fits S = Math.max(S, 180); const by = H - Math.max(S * 0.14, 58) - 14; // base bottom y const ty = by - S; const cx = W / 2; ... } ``` For narrow phones: W = 360, H = 640: S = min(474, 576) = 474 ✓; W = 320, H = 568: S = min(420, 512) = 420 ✓. The glass rect: glassH = 0.592·S; glass bottom y = by - 0.27·S; x: cx ± 0.2·glassH; y: from (by - 0.27·S - 0.02·glassH) to (+1.04·glassH). Wait: I need to double check the mapping between the lamp geometry (S units) and the glass interior (H units): the glass interior bottom at lamp-y = 0.27, top at 0.862: H = 0.592·S ✓. The canvas rect: y ∈ [-0.02, 1.02] in H → in screen px: top = (by - 0.27·S) - 1.02·Hpx... (y up → screen y down: screenY = glassBottomY - y·Hpx): for y = 1.02: screenY = glassBottomY - 1.02·Hpx; for y = -0.02: screenY = glassBottomY + 0.02·Hpx ✓. Height = 1.04·Hpx ✓. x: cx ± 0.2·Hpx. The GL canvas CSS: left = cx - 0.2·Hpx, top = glassBottomY - 1.02·Hpx, width = 0.4·Hpx, height = 1.04·Hpx. To align the canvas pixels with the device pixel grid (crisp edges), round the CSS position/size to integer device pixels: left/top/width/height rounded to multiples of 1/dpr: fine: compute in device px: integers, then divide by dpr for CSS. **The scene drawing function** — let me write it concretely with all the coordinates: ```js function drawScene() { const c = sceneCtx, W = vw, H = vh; // CSS px; ctx scaled by dpr2 c.setTransform(dpr2, 0, 0, dpr2, 0, 0); // wall let g = c.createLinearGradient(0, 0, 0, horizon); g.addColorStop(0, '#090814'); g.addColorStop(1, '#17132c'); c.fillStyle = g; c.fillRect(0, 0, W, horizon + 1); // glow on wall if (light > 0.003) { const gx = cx, gy = ty + 0.56 * S, r = 0.95 * S; g = c.createRadialGradient(gx, gy, 0, gx, gy, r); g.addColorStop(0, rgba(255, 110, 150, 0.34*light)); g.addColorStop(0.28, rgba(190, 80, 230, 0.22*light)); g.addColorStop(0.6, rgba(110, 60, 210, 0.09*light)); g.addColorStop(1, 'rgba(110,60,210,0)'); c.fillStyle = g; c.fillRect(0, 0, W, horizon + 1); // clipped to the wall } // desk g = c.createLinearGradient(0, horizon, 0, H); g.addColorStop(0, '#1c110d'); g.addColorStop(0.35, '#2a1812'); g.addColorStop(1, '#3b2319'); c.fillStyle = g; c.fillRect(0, horizon, W, H - horizon); // wood grain: deterministic pseudo-random lines ... // desk edge highlight c.fillStyle = 'rgba(255,220,190,0.06)'; c.fillRect(0, horizon, W, 2); // light pool on the desk if (light > 0.003) { ellipse gradient at (cx, by + 0.01*S) rx 0.62*S, ry 0.16*S: rgba(255,110,160,0.30*light) → 0 } // lamp contact shadow ellipse (cx, by) rx 0.19*S ry 0.035*S rgba(0,0,0,0.55) → 0 // cord // vignette } ``` For the desk light pool: a radial gradient in a transformed (scaled) context: c.save(); c.translate(cx, cy); c.scale(1, ry/rx); radial gradient radius rx; fillRect(-rx, -rx, 2rx, 2rx); c.restore(). The desk surface: where's the base relative to the horizon: by = horizon + 0.055·S. The light pool center at (cx, by): an ellipse spanning ±0.6·S horizontally, ±0.15·S vertically: the upper half is clipped by the horizon (the wall): clip to the desk region ✓. **Wood grain**: a handful of long thin slightly curved lines: for i in 0..14: y = horizon + (H - horizon)·(i + rand)/15; draw a horizontal line with a slight sinusoidal wobble; stroke rgba(0,0,0,0.12) or rgba(255,200,150,0.03). Use a seeded PRNG so it's stable across redraws ✓ (important: the scene is redrawn during transitions: the grain must not flicker: use a fixed seed). **The front canvas**: ```js function drawFront() { // base // cap // glass streaks } ``` Base path (in CSS px): let me define helper functions: X(u) = cx + u·S; Y(v) = by - v·S (v up from the base bottom). Base outline: bottom ellipse: center (cx, by - 0.012·S), rx = 0.150·S, ry = 0.024·S (the front arc from angle 0 to π (the lower half in screen coords)). Let me define the base body as a polygon: start at the left-bottom (X(-0.150), Y(0.012)), go up the left side to (X(-0.092), Y(0.228)), then the collar: (X(-0.104), Y(0.238)) → (X(-0.104), Y(0.266)) → top ellipse arc to the right: center (cx, Y(0.266)), rx = 0.104·S, ry = 0.016·S: lower half arc from angle π to 0 (in screen coords: from the left (π) through the bottom (π/2) to the right (0))... then down the right side: (X(0.104), Y(0.238)) → (X(0.092), Y(0.228)) → (X(0.150), Y(0.012)), then the bottom arc: center (cx, Y(0.012)), rx 0.150·S, ry 0.024·S: from angle 0 through π/2 (bottom) to π. In canvas, `c.ellipse(cx, cy, rx, ry, 0, 0, Math.PI)` draws the lower half (clockwise from angle 0 (right) to π (left) passing through π/2 (down in screen coords)) ✓. So: the top arc: from the left to the right through the bottom: `c.ellipse(cx, Y(0.266), 0.104*S, 0.016*S, 0, Math.PI, 0, true)` (anticlockwise from π to 0 through π/2) ✓. The bottom arc: from the right to the left through the bottom: `c.ellipse(cx, Y(0.012), 0.150*S, 0.024*S, 0, 0, Math.PI)` ✓. The glass sits in the collar: the glass's bottom at lamp-y 0.27: slightly above the collar top (0.266) ✓. The glass's bottom edge: straight (the GL canvas), hidden behind...: the collar's top arc (lower half ellipse) is drawn in the front canvas over the glass: the glass's straight bottom edge at Y(0.27) is above the collar's top arc's endpoints Y(0.266): the ellipse's lowest point is at Y(0.266) - 0.016·S (screen y larger = lower): so the collar covers from Y(0.266) down to Y(0.266 - 0.016) at the center: the collar's top face (the ellipse) is drawn as a filled ellipse (the full ellipse: the top face of the collar: a ring where the glass enters): draw the full ellipse at (cx, Y(0.266)) rx 0.104·S, ry 0.016·S in a mid-metal tone (the top face), then the glass emerges from its center: the glass's bottom edge is a straight line at Y(0.27): hmm: the glass bottom should look like it emerges from the elliptical opening: the glass's straight bottom edge at Y(0.27) is above the ellipse's top (Y(0.266 + 0.016) = Y(0.282)): so the glass (GL canvas) bottom edge at Y(0.27) would be *behind* the ellipse's upper half (which spans Y(0.266) to Y(0.282))? The ellipse's upper half is the back rim of the collar: it should be *behind* the glass (the glass is in front of the back rim), and the lower half (the front rim) in front of the glass. Since the glass is drawn in a separate canvas between the scene and the front: the front canvas draws only the front rim (the lower half-ellipse band) over the glass ✓, and the back rim (upper half) should be drawn in the scene canvas (behind the glass) ✓. So: the scene canvas draws the collar's top-face ellipse (full) [behind the glass], and the front canvas draws the base body including the front arc (lower half) of the collar ✓. So the base body path (front canvas): as above: left side up to the collar top-left (X(-0.104), Y(0.266)), then the lower-half arc to the right (X(0.104), Y(0.266)), down the right side..., the bottom arc. ✓. And the scene canvas: the collar's top face: a full ellipse at Y(0.266) with a dark inner ellipse (the opening shadow) — mostly covered by the glass (the glass's bottom half-width 0.1066·S ≈ the collar's rx 0.104·S: the glass covers nearly the whole ellipse; only small slivers at the sides are visible: fine: draw it in the scene for correctness. Cap: frustum from Y(0.856) to Y(0.985): half-width 0.066 at the bottom → 0.050 at the top; the bottom arc (lower half ellipse: center (cx, Y(0.856)), rx 0.066·S, ry 0.010·S); the top: a rounded dome: an elliptical arc: center (cx, Y(0.975)), rx 0.050·S, ry 0.022·S upper half. Path: start (X(-0.066), Y(0.856)) → line to (X(-0.050), Y(0.975)) → upper arc to (X(0.050), Y(0.975)) [ellipse from π to 2π clockwise (through 3π/2 = up in screen coords)]: `c.ellipse(cx, Y(0.975), 0.050*S, 0.022*S, 0, Math.PI, 2*Math.PI)` ✓ → line to (X(0.066), Y(0.856)) → bottom arc back to the left: `c.ellipse(cx, Y(0.856), 0.066*S, 0.010*S, 0, 0, Math.PI, true)` (anticlockwise from 0 to π through π/2 (down)) ✓. The cap covers the glass's top: the glass top at Y(0.862): the cap's bottom arc spans Y(0.856) → Y(0.846) at the center: covers the glass top ✓ (the glass's straight top edge at Y(0.862) is above the arc's endpoints Y(0.856): hidden behind the cap body ✓). Metal gradient: horizontal linear gradient from X(-0.15) to X(0.15): for the base; for the cap from X(-0.066) to X(0.066). **Glass streaks** (front canvas): - The left streak: from (cx - 0.62·wb, glassBottom - 0.03·Hpx) to (cx - 0.62·wt, glassTop + 0.02·Hpx): where wb = 0.18·Hpx, wt = 0.10·Hpx. lineWidth = 0.035·Hpx (round caps), strokeStyle: rgba(255,255,255,0.20); a second thinner line inside: lineWidth 0.012·Hpx, alpha 0.25, offset slightly. - The right streak: at +0.72: lineWidth 0.018·Hpx, alpha 0.10. - A subtle overall vertical sheen gradient on the left third: skip. - The glass outline: stroke the trapezoid path: rgba(255,255,255,0.10), lineWidth 1. And when the lamp is off, the streaks should be dimmer: multiply the alpha by (0.35 + 0.65·light) ✓ (the front canvas is redrawn with L). **The bulb glow under the glass**: the base's collar catches light: add in the front canvas: a warm radial glow at the glass bottom center (cx, Y(0.27)), radius 0.12·S: rgba(255,170,120,0.5·light) clipped to the base body? The collar is in front... the glow on the base's upper part: a vertical gradient overlay on the base: from the top (Y(0.266)): rgba(255,140,150,0.30·light) → transparent at Y(0.14) ✓ clip to the base path. OK now the **performance governor** and **DPR**: dprG (for the GL canvas) = min(devicePixelRatio, 3); dpr2 (2D canvases) = min(devicePixelRatio, 2). Let me also think about **iOS Safari specifics**: - `position: fixed; inset: 0` ✓. - Canvas 2D with large sizes ✓. - WebGL: `precision highp float` in fragment shaders is supported on modern iOS ✓ (check via getShaderPrecisionFormat). - The `alpha: true, premultipliedAlpha: true` context ✓. - 100vh issues: avoided by using clientHeight of the fixed stage. - `touch-action: manipulation` on the stage to avoid double-tap zoom delays ✓; ``? Avoid disabling zoom for accessibility; but for a full-screen toy, accidental pinch-zoom is annoying: I'll leave the default (no user-scalable=no) but the fixed layout handles it. - Safe areas (notch): the lamp is centered: OK. **No external requests**: no fonts, no images; inline SVG ✓. Let me now also think about **what the user sees at first load**: lamp on, blobs active, the glow; the switch on the desk in front-right. Potential improvement: a subtle "tap" hint? Not needed. Now let me write out the physics step code in detail with careful attention to signs and units: ```js const N = 56; const px = new Float64Array(N), py = new Float64Array(N), vx = new Float64Array(N), vy = new Float64Array(N); const temp = new Float64Array(N), expo = new Float64Array(N), cond = new Float64Array(N); const fx = new Float64Array(N), fy = new Float64Array(N); const bond = new Uint8Array(N * N); const comp = new Int16Array(N), csize = new Int16Array(N); const ccx = new Float64Array(N), ccy = new Float64Array(N); const phase = new Float64Array(N); const stack = new Int16Array(N); const D0 = 0.036, DBOND = 0.047, DCUT = 0.0666, DBOND2 = DBOND*DBOND, DCUT2 = DCUT*DCUT; const KATT = 10, KREP = 500, FMAX = 6, KC = 1.2, KB = 1.6, TN = 0.52, CD = 2.2, KAPPA = 0.15; const WALL = 0.012, FLOOR = 0.014, CEIL = 0.968; const GL_B = 0.18, GL_A = 0.10; function hw(y) { return GL_B + (GL_A - GL_B) * (y < 0 ? 0 : y > 1 ? 1 : y); } ``` step(h, t): ```js function step(h, t) { // clusters findClusters(); // pair forces + bonds + conduction for (let i = 0; i < N; i++) { fx[i] = 0; fy[i] = 0; cond[i] = 0; } for (let i = 0; i < N; i++) { const xi = px[i], yi = py[i], Ti = temp[i]; const si = csize[comp[i]]; const sizef = si > 12 ? 12 / si : 1; for (let j = i + 1; j < N; j++) { const dx = px[j] - xi, dy = py[j] - yi; const d2 = dx*dx + dy*dy; if (d2 >= DCUT2) { if (bond[i*N+j]) bond[i*N+j] = 0; continue; } const d = Math.sqrt(d2) + 1e-9; const ij = i*N + j; let b = bond[ij]; if (!b && d < DBOND) { b = bond[ij] = 1; } const dT = Ti - temp[j]; let f = 0; if (d < D0) f = -Math.min(KREP * (D0 - d), FMAX); else if (b) { const q = dT / 0.45; const s = (q > 1 ? 0.08 : 1 - q*q) * sizef; // hmm q<0? dT can be negative: use abs if (d > D0 * (1 + 0.85 * s)) { bond[ij] = 0; } else f = KATT * s * (d - D0); } if (f !== 0) { const ux = dx / d, uy = dy / d; fx[i] += f*ux; fy[i] += f*uy; fx[j] -= f*ux; fy[j] -= f*uy; } if (b) { cond[i] -= dT; cond[j] += dT; } } } ... } ``` Wait: there's an issue with the hard core between non-bonded particles that are within D0: e.g., two particles from different clusters overlapping: repulsion ✓ (always). OK. And the bond's symmetric storage: bond[i*N+j] only (i b: bond[b*N+a]. Let me write a helper `isBonded(a,b)`. Or store symmetric: set both bond[ij] and bond[ji] when updating: 2 writes: fine: simpler BFS. I'll store symmetric. Conduction: cond[i] = Σ_j (T_j - T_i) over bonded j ✓ (as written: cond[i] -= dT = T_j - T_i ✓; cond[j] += dT = T_i - T_j ✓). Forces continued: ```js const heatOn = heat; // 0..1 for (let i = 0; i < N; i++) { const c = comp[i]; // surface tension (pull to cluster centre) if (csize[c] > 1) { fx[i] += KC * (ccx[c] - px[i]); fy[i] += KC * (ccy[c] - py[i]); } // buoyancy let a = KB * (temp[i] - TN); // gentle wander fx[i] += 0.05 * Math.sin(0.9 * t + phase[i]); a += 0.05 * Math.cos(0.7 * t + phase[i] * 1.7); // heat const y = py[i]; const up = y > 0.72 ? smooth((y - 0.72) / 0.26) : 0; const rate = C0 + CTOP * up; // cooling rate to liquid const tliq = 0.10 + heatOn * ((0.42 - 0.30 * up) - 0.10); let dT = rate * (tliq - temp[i]); const hy = y < 0.5 ? H0 * heatOn * expo[i] * Math.exp(-(y*y) / 0.04) * (0.8 + 0.2 * Math.sin(9 * px[i] + 0.35 * t)) : 0; dT += hy * (1 - temp[i]); dT += KAPPA * cond[i]; temp[i] += dT * h; clamp 0..1 // integrate vx[i] += fx[i] * h; vy[i] += (fy[i] + a) * h; const damp = Math.exp(-CD * h); vx[i] *= damp; vy[i] *= damp; px[i] += vx[i] * h; py[i] += vy[i] * h; // walls ... } } ``` The wander: the phase per particle: a_x = 0.05·sin(0.9t + φ): each particle oscillates with a period of 7 s: the displacement amplitude: a/ω² = 0.05/0.81 = 0.06 (without drag; with drag: smaller): hmm, that's not tiny: 0.06·H = 22 px on the phone: a particle could wander ±0.06: but bonded particles are held by bonds; the cluster as a whole: the random forces average out (N particles with different phases: the net force ~0.05·sqrt(N)/... ) → clusters jiggle a bit ✓. With the drag: v ~ a/c for slow forcing (ω ≪ c): v = 0.05/2.2 = 0.023 H/s; displacement amplitude v/ω = 0.025: OK small ✓. For the pool: the particles jiggle slightly against the hard cores: no visible effect (the metaball outline wobbles subtly ✓ organic). The heating modulation: (0.8 + 0.2·sin(9x + 0.35t)): varies ±20% along x: a wavelength of 0.7: fine. `expo`: computed once per frame (not per substep) to save time ✓. smooth(x) = x²(3 - 2x) clamped. **Wall constraints**: ```js const lim = hw(py[i]) - WALL; if (px[i] > lim) { px[i] = lim; if (vx[i] > 0) vx[i] = 0; } else if (px[i] < -lim) { px[i] = -lim; if (vx[i] < 0) vx[i] = 0; } if (py[i] < FLOOR) { py[i] = FLOOR; if (vy[i] < 0) vy[i] = 0; } else if (py[i] > CEIL) { py[i] = CEIL; if (vy[i] > 0) vy[i] = 0; } ``` **Exposure**: ```js function exposure() { const R2 = R*R; for (let i = 0; i < N; i++) { const x = px[i], y = py[i] + 0.04; let f = 0; for (let j = 0; j < N; j++) { const dx = px[j] - x, dy = py[j] - y; const u2 = (dx*dx + dy*dy) / R2; if (u2 < 1) { const a = 1 - u2; f += a*a*a; } } const e = 1 - f / 0.5; expo[i] = e < 0 ? 0 : e > 1 ? 1 : e; } } ``` Hmm: for a particle at the pool's bottom row near a wall: the field above includes the particles above ✓ shielded. For the top row: e = 1. For a single particle: e = 1 ✓. But wait: a single particle at the bottom with other single particles around at the same height (side by side, e.g., after the pool depleted): the field 0.04 above: side neighbors at distance sqrt(0.036² + 0.04²) = 0.0538 > R = 0.052: 0 → e = 1 ✓. A 2-particle vertical pair (one above the other): the bottom one: the field above: the top particle at distance 0.004: K ≈ 0.98 → e = 0 ✓; the top one: e = 1. OK. Now the **initial positions**: jittered hex lattice from the bottom: rows at y = FLOOR + 0.018 + r·0.0312; x positions: for row r: offset (r odd ? 0.5 : 0)·0.036; x from -lim to lim step 0.036. Fill until N particles are placed. T = 0.42 initially. Then the warm-up. Hmm, thinking about it more: at init with heat = 1 (lamp on): the top row heats and lifts: blobs rising: after 12 s of sim: blobs at various heights ✓. Let me reconsider the time to pre-run: 12 s sim = 1440 steps at 1/120. Per step cost: pair loop 1540 + BFS 3136 (I can do the BFS every step: 3136 ops) + exposure every 2 steps: ~1500: total ~6k simple ops per step → 1440 steps = 9M ops: ~10-20 ms desktop; ~50 ms phone ✓. **Field encode loop** (per frame): ```js function buildField(t) { F.fill(0); GX.fill(0); GY.fill(0); TS.fill(0); WS.fill(0); for (let i = 0; i < N; i++) { const cx = (px[i] + XH) * SXC - 0.5, cy = (YTOP - py[i]) * SYC - 0.5; // cell coords; YTOP = 1.02 ... } // encode for (let j = 0, o = 0; j < GH; j++) { const wy = ...; for (let i = 0; i < GW; i++, o++) { ... } } } ``` The wobble noise per cell: computing 2 sines per cell per frame: 39k × 2 sin = 78k sin calls: ~1 ms on a phone?? Math.sin is ~10-20 ns → 1.5 ms on a slow phone: too much. Optimize: precompute the noise as separable sums: n(i,j,t) = sin(a·i + b·j + ωt)·sin(c·i - d·j - ω₂t): product of two sines; use the identity: sin A·sin B = 0.5·(cos(A - B) - cos(A + B)): still 2 trig per cell. Alternative: precompute 1D arrays: sinA[i] = sin(a·i + ωt) (GW values), sinB[i] = sin(c·i - ω₂t), and per row: sinC[j] = sin(b·j), sinD[j] = sin(d·j): n = (sinA[i]·cosC[j] + cosA[i]·sinC[j])·(sinB[i]·cosD[j] - cosB[i]·sinD[j]): 4 mults per cell using precomputed 1D arrays (4·GW + 4·GH trig calls per frame) ✓ fast. Simpler: a wobble that is a sum of separable terms: n = s1[i]·c1[j] + s2[i]·c2[j] (each a product of 1D functions): with 1D arrays precomputed per frame: n(i,j) = A[i]·B[j] + C[i]·D[j]: 2 mults + 1 add per cell ✓. A[i] = sin(0.16·i + 1.1t), B[j] = sin(0.11·j + 0.5), C[i] = sin(0.12·i - 0.8t + 1.7), D[j] = sin(0.17·j + 2.3): the pattern: a sum of two plane-wave products: good enough as a wobble. Apply: TH_eff = TH·(1 + 0.1·n): d = (F - TH_eff)/gm. **The encode**: ```js const DMAX = 14; for each cell: const f = F[o]; if (f < 0.004) { data[o4] = 0; data[o4+1] = 128; data[o4+2] = 128; data[o4+3] = 128; continue; } const gx = GX[o], gy = -GY[o]; // y up const gm = Math.sqrt(gx*gx + gy*gy); let d = (f - th) / (gm > 1e-4 ? gm : 1e-4); let k = 0.2 / (RC * ... ) hmm: conf = gm / gref; if (conf > 1) conf = 1; const inv = conf / (gm > 1e-6 ? gm : 1e-6); → dirx = gx*inv, diry = gy*inv T = TS[o] / WS[o] ``` gref = 0.2/Rc (per cell): with Rc = 0.052·(GH/1.04) = 0.052·307.7 = 16 cells → gref = 0.0125. When f < 0.004: d = -DMAX → R8 = 0 ✓. Performance: the encode loop has a sqrt per cell with f ≥ 0.004 (most cells in the lamp): 39k sqrt: fine. **Texture upload & draw**: ```js gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, GW, GH, 0, gl.RGBA, gl.UNSIGNED_BYTE, data); gl.drawArrays(gl.TRIANGLES, 0, 3); ``` Using texImage2D each frame reallocates? In WebGL, texImage2D with the same dimensions may be optimized; texSubImage2D is the recommended per-frame update: use texSubImage2D when the size is unchanged (after the initial texImage2D) ✓. **GL context loss**: handle `webglcontextlost` (preventDefault) and `webglcontextrestored` (re-init the program/texture) ✓. Let me write the WebGL init: ```js function initGL(canvas) { const opts = { alpha: true, premultipliedAlpha: true, antialias: false, depth: false, stencil: false, powerPreference: 'high-performance', preserveDrawingBuffer: false }; let gl = canvas.getContext('webgl', opts) || canvas.getContext('experimental-webgl', opts); if (!gl) return null; const vs = `attribute vec2 aPos; varying vec2 vUv; void main(){ vUv = aPos*0.5+0.5; gl_Position = vec4(aPos,0.,1.); }`; const fs = `...`; function compile(type, src) { const s = gl.createShader(type); gl.shaderSource(s, src); gl.compileShader(s); if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) { console.warn(gl.getShaderInfoLog(s)); return null; } return s; } ... } ``` The fragment shader precision: ```glsl #ifdef GL_FRAGMENT_PRECISION_HIGH precision highp float; #else precision mediump float; #endif ``` ✓ (this is a standard pattern). The full-screen triangle: positions (-1,-1), (3,-1), (-1,3) ✓ (vUv extrapolates beyond 0..1 at the edges but only used within the viewport). **Uniform setup per frame**: uRes = (canvas.width, canvas.height); uCell = canvas.width / GW; uLight; uTime (unused? could animate a subtle shimmer: skip; no uTime needed... maybe a subtle liquid shimmer: skip). Let me write the fragment shader fully: ```glsl #ifdef GL_FRAGMENT_PRECISION_HIGH precision highp float; #else precision mediump float; #endif uniform sampler2D uField; uniform vec2 uRes; uniform float uCell; // device px per field cell uniform float uDome; // dome radius in cells uniform float uLight; varying vec2 vUv; const vec3 WAX_COLD = vec3(0.70, 0.07, 0.25); const vec3 WAX_MID = vec3(1.00, 0.30, 0.33); const vec3 WAX_HOT = vec3(1.00, 0.76, 0.28); const vec3 LIQ_TOP = vec3(0.16, 0.10, 0.46); const vec3 LIQ_BOT = vec3(0.50, 0.22, 0.92); float smax(float a, float b, float k) { float h = clamp(0.5 + 0.5 * (a - b) / k, 0.0, 1.0); return mix(b, a, h) + k * h * (1.0 - h); } void main() { vec2 p = vec2((vUv.x - 0.5) * 0.4, vUv.y * 1.04 - 0.02); float yc = clamp(p.y, 0.0, 1.0); float hw = mix(0.18, 0.10, yc); float sd = smax(abs(p.x) - hw, max(-p.y, p.y - 1.0), 0.03); float pxu = uRes.y / 1.04; // device px per glass height float glassA = clamp(-sd * pxu + 0.5, 0.0, 1.0); if (glassA < 0.004) { gl_FragColor = vec4(0.0); return; } vec4 t = texture2D(uField, vec2(vUv.x, 1.0 - vUv.y)); float d = (t.r - 0.5) * 28.0; // cells vec2 g = t.gb * 2.0 - 1.0; // inward direction (y up) float T = t.a; // --- wax float waxA = clamp(d * uCell + 0.5, 0.0, 1.0); float dc = clamp(d, 0.0, uDome * 0.95); float slope = dc / sqrt(uDome * uDome - dc * dc); vec3 n = normalize(vec3(-g * slope, 1.0)); float difB = clamp(dot(n, normalize(vec3(0.12, -1.0, 0.5))), 0.0, 1.0); float difR = clamp(dot(n, normalize(vec3(-0.45, 0.55, 0.7))), 0.0, 1.0); float spec = pow(clamp(dot(n, normalize(vec3(-0.24, 0.30, 0.92))), 0.0, 1.0), 30.0); float bulb = mix(1.0, 0.45, yc); vec3 wc = mix(WAX_COLD, WAX_MID, smoothstep(0.15, 0.55, T)); wc = mix(wc, WAX_HOT, smoothstep(0.55, 0.92, T)); float rim = smoothstep(0.0, 2.5, d); vec3 wax = wc * (0.42 + 0.95 * difB * bulb + 0.25 * difR) * mix(0.6, 1.0, rim) + vec3(1.0, 0.96, 0.9) * spec * 0.2; // --- liquid vec3 liq = mix(LIQ_TOP, LIQ_BOT, pow(1.0 - yc, 1.6)); liq += vec3(1.0, 0.45, 0.55) * 0.45 * exp(-yc * 7.0); liq *= 1.0 - 0.3 * smoothstep(-4.0, 0.0, d); liq += wc * 0.10 * smoothstep(-10.0, 0.0, d); // --- unlit vec3 waxOff = vec3(0.085, 0.06, 0.12) * (0.55 + 0.9 * difR) * mix(0.7, 1.0, rim); vec3 liqOff = mix(vec3(0.035, 0.035, 0.075), vec3(0.06, 0.05, 0.12), 1.0 - yc); liqOff *= 1.0 - 0.35 * smoothstep(-4.0, 0.0, d); vec3 col = mix(mix(liqOff, liq, uLight), mix(waxOff, wax, uLight), waxA); // --- glass edge float ins = -sd; col *= mix(0.45, 1.0, smoothstep(0.0, 0.02, ins)); col += vec3(0.75, 0.8, 1.0) * 0.07 * (1.0 - smoothstep(0.0, 0.006, abs(ins - 0.012))); gl_FragColor = vec4(col * glassA, glassA); } ``` In the smax: the trapezoid SDF: smax(|x| - hw, max(-y, y - 1), k): the inner max(-y, y-1) has sharp corners at the bottom/top (between the floor and the wall): then smax with the wall rounds the corners between the wall and the floor ✓. The top corners are hidden under the cap. Note: the smax "k" of 0.03 makes the bottom corners rounded with a radius ≈ 0.03: at the bottom corners, the wax (pool) will be clipped by the rounding: fine. Potential issue: the `d` near the glass edges: the field's d is computed on the grid, independent of the glass ✓. The temperature `t.a` for the wax at the glass edge: fine. **The 2D fallback shading in JS**: mirror the above; let me write it compactly: ```js function shade2D() { const img = img2d.data; let o = 0, o4 = 0; for (let j = 0; j < GH; j++) { const py = YTOP - (j + 0.5) * CELLY; // y up const yc = clamp01(py); const hw = 0.18 - 0.08 * yc; const v = max(-py, py - 1); for (let i = 0; i < GW; i++, o++, o4 += 4) { const pxx = (i + 0.5) * CELLX - XH; const sd = smax(Math.abs(pxx) - hw, v, 0.03); const ga = clamp(-sd * pxu + 0.5, 0, 1); if (ga <= 0) { img[o4+3] = 0; continue; } ... decode d, gx, gy, T from data ... compute rgb (same formulas) img[o4] = r*255; ...; img[o4+3] = ga*255; } } } ``` I'll write helper functions for mix/smoothstep in JS. It's a fallback: keep it straightforward. For the per-cell constants (normalize(vec3)) precompute. OK wait, for the fallback, the image is GW×GH = 123×320 px, displayed at e.g. 148×384 CSS px (phone) or 200×520 (desktop): the upscale is ~1.2-1.6x: slightly soft: fine. **Light-dependent scene redraw**: when `light` changes. Now let me think about **layout details for the switch and the cord** more concretely, with the lamp geometry: ```js const sw = clamp(S * 0.125, 62, 92); // switch width const sh = sw * 0.633; // viewBox 120x76 const sx = Math.min(cx + S * 0.2, W - sw/2 - 10); const sy = Math.min(by + Math.max(S * 0.105, sh * 0.5 + 22), H - sh/2 - 8); ``` For the phone (W=390, H=844): S = 624; by = 844 - max(87, 58) - 14 = 743; cx = 195; sw = 78; sh = 49.4; sx = min(195 + 125, 390 - 39 - 10 = 341) = 320; sy = min(743 + max(65.5, 46.7) = 808.5, 844 - 24.7 - 8 = 811.3) = 808.5. So the switch at (320, 808): near the bottom-right: its right edge at 359 (31 px from the edge) ✓; the bottom edge at 833 (11 px from the bottom) ✓. Hmm: the lamp base bottom is at 743 and the screen bottom at 844: the desk area below the lamp: 101 px. The switch at y = 808: OK. Is the lamp too low/large? The top margin: ty = 743 - 624 = 119 px: the lamp spans 119 → 743. The desk horizon at 743 - 0.055·624 = 709. So the desk occupies 709 → 844 = 135 px (16%) ✓; the wall above: 709 px with the lamp from 119: the top margin 119 px (14%): balanced ✓. For desktop (1280×720): S = min(533, 2048) = 533; by = 720 - max(74.6, 58) - 14 = 631.4; ty = 98; horizon = 602; the desk: 118 px; sw = 66.6; sh = 42; sx = min(640 + 106.6, ...) = 746.6; sy = min(631.4 + max(56, 43) = 687.4, 720 - 21 - 8 = 691) = 687.4 ✓. In landscape, there's lots of horizontal space: the switch could be placed further right: sx = cx + 0.2·S: OK as is. The cord: from the base's right-bottom: start point P0 = (cx + 0.13·S, by - 0.012·S) [behind the base's right edge]; → to the switch's left edge P3 = (sx - sw·0.5 + 2, sy + sh·0.08) [the cord enters the switch at its vertical middle: the SVG's cord rect is at y=33..42 of 76 → the center at 37.5/76 = 0.49 → sy - sh·0.01]. Control points: P1 = (P0.x + 0.16·S, P0.y + 0.02·S), P2 = (P3.x - 0.14·S, P3.y + 0.01·S). For the phone: P0 = (276, 735.5); P3 = (283, 808): the cord goes almost straight down from P0 to P3: P1 = (376, 748): the curve bulges right to x ≈ 330 then comes back to 283: an S-curve: OK. Hmm: the switch is at x=320 (the right side), the base's right edge at 195 + 93.6 = 288.6: the switch's left edge at 281: so the switch is partially below the base's right part: visually: the switch is in front of (below) the lamp's right side ✓ fine. Maybe better to position the switch more to the right for clarity: sx = min(cx + 0.26·S, W - sw/2 - 10): phone: min(195 + 162 = 357, 341) = 341 → the switch at the far right edge (341 ± 39 → 302..380): too close to the edge (10 px): OK but cramped. Keep 0.2·S. The cord from the switch's right edge → to the bottom-right corner off-screen: P4 = (sx + sw/2 - 2, sy), Q: bezier to (W + 20, sy + 0.05·S) with control points (P4.x + 0.1·S, P4.y), (W - 0.05·S, sy + 0.06·S). If the switch's right edge is close to the screen's right edge (phone: 359 vs. 390): the cord exits quickly: OK. **Scene: the cord shadow**: draw the cord path offset by (0, 3) with a wider dark stroke: rgba(0,0,0,0.35), lineWidth = lw + 3. Let me think about the **wall glow** more: with the lamp on, the wall behind is lit in a purple-pink halo. The lamp's glass itself is bright (the GL canvas). The base and cap: metallic. Also a **floor reflection of the glass** on the desk? The desk is wood (not glossy): only a diffuse light pool ✓. **The base's shadow on the wall**: no. Let me think about the overall composition on desktop landscape: a tall lamp centered on a wide dark wall: lots of empty wall: the vignette and the glow make it moody ✓. The desk spans the full width ✓. **Color of the desk**: dark walnut; the desk's back edge highlight. Now let me write the final code. I'll write it carefully, section by section. Let me also decide the names. ```html Lava Lamp ``` The fallback: if JS is disabled: nothing: add a `