Interactive Three.js Koi Pond
By @SouranyStudio. Made with Claude Opus 5.5. Watch the original post.
Prompt
Build an ultra-realistic, interactive Japanese koi pond garden as ONE self-contained HTML file named koi-pond.html. No build step, no bundler, no asset folder: every texture, mesh, sound and animation is generated procedurally in the file. The only external loads are three.js r160 UMD from cdnjs (https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.min.js) and dat.gui 0.7.9 from cdnjs. Target 60 fps on a laptop GPU at 1.6x device pixel ratio. Work in rounds. After every implementation round: run it in a browser, take screenshots, measure (fps, frame time, and any metric the round defines), fix what the screenshots show, and only then move on. Commit to git after each round with an imperative subject and a body that explains what changed and why. Do not stop at "it renders": self-verify until the screenshots match the references below. == 0. File layout == One <script> in sections, in this order: parameters & constants; math/noise utilities (hash, value noise, fbm2/fbm3, smoothstep, lerp, clamp, Catmull-Rom interpolation); procedural textures (canvas + DataTexture, height-to-normal); geometry helpers (merge, tube, lathe); renderer/sky/sun/environment; shared material injections; terrain + basin; stones; bridge + pavilion; vegetation; water (sim, shader, passes); koi; post-processing; camera, dive & audio; GUI, quality, main loop. == 1. Renderer, sky, sun == WebGLRenderer, HDR half-float main target with 4x MSAA (2x on Low), ACES tone mapping, exposure 0.9. PCFSoft shadow map 4096 (2048 on Low), updated every other frame through a camera that sees every layer. Preetham analytic sky (after three.js Sky.js) plus an FBM cloud deck lit brighter toward the sun with crude self-shadowing. Sun from time of day (6-19 h, default 10.5) and azimuth (default 55 deg). Environment map re-baked from the sky when the sun moves. Directional sun intensity ~3.3 plus a hemisphere light. Render layers, every mesh on exactly one: ABOVE=1, UNDER=2, BOTH=3, WATER=4, SKY=5, SURFACE=6 (things lying on the water: pads, petals; never mirrored). == 2. Shared material injections (patchMaterial) == One onBeforeCompile helper used by every MeshPhysical/Standard material. It injects: world-position/normal varyings; optional wind sway in a replaced project_vertex (slow sway * per-vertex weight + gusts travelling along the wind + fast leaf flutter); a FLOAT mode where the vertex rides the water surface (same Gerstner sum + ripple texture as the water); underwater lighting computed before the light loop: Beer-Lambert on the refracted sun path, caustics projected along the refracted sun ray (two counter-scrolling Voronoi patterns multiplied, slight chromatic dispersion growing with depth), ambient attenuation with depth (barely dimmed in the first 5 cm), analytic soft koi shadows (see section 6); after the light loop: submerged surfaces lose ~88% of specular; exponential teal absorption fog when the camera is submerged; weather albedo/roughness (snow cover on up-facing surfaces, wet darkening + puddle sheen, autumn tint). Global uniforms shared by every patched material: uTime, uWaterY=0, uSunDir, uSunDirW (refracted), uSunColor, uAbsorb, uScatter, uInscatter, uCamUnder, tCaustics, uWindDir, uWind, uGust, uSnowCover, uWet, uAutumn, uFogDensity, uFogColor, uRain, uIce, uKoiA[20], uKoiB[20]. Options: tri (triplanar rock shading), hedge, leaf (translucency: back-lit leaves glow with the shadowed sun colour), wood (weathering), and a matching depth material for shadow casting that repeats the same vertex deformation. == 3. Terrain, pond, stones, architecture == Pond outline: a closed Catmull-Rom curve sampled to 480 points, with a signed-distance field (sdf) built from it and stored as a 256x256 mask texture; a heightfield ripple sim of N=256 covering a 13.4 m square. Terrain: displaced plane, pond basin depth up to ~1.2 m, pebble floor, mossy banks, granite coping stones around the rim. Boulders: lathe/noise rocks with granite grain, cracks, pits and lichen (triplanar), some breaking the surface. A wooden arched bridge across the pond, a pavilion with a curved tiled roof, stone lanterns, a rock waterfall at one bank, distant mountains, a pier. == 4. Vegetation and pond life == Instanced leaf cards with wind and translucency. Trees: weeping cherry (shidare-zakura, pink, sheds petals), cherry blossom, a red Japanese maple, pines and broadleaf background trees, a bamboo grove (Phyllostachys: segmented culms, nodes, drooping leaves), hedges and mounds. Beds: iris clumps, sacred lotus (hasu: cupped petals, seed pod, raised leaves), water lilies with floating pads (FLOAT), spider lily, hydrangea, ferns, moss. Falling sakura petals that land and float on the surface. Pond life: a frog on a lily pad that leaps on click (parabolic hop, splash, croak), a yellow-bellied slider turtle sunning on a rock (procedural shell, wet sheen), dragonflies (shiokara-tombo, aki-akane) that hover and dart, underwater weed and stems, air bubbles on big movements. == 5. Water == Heightfield ripple simulation (256^2, damped wave equation) driven by clicks, drops, fish wakes, the frog and rain; plus 4 Gerstner waves with lengths [2.9, 1.6, 0.85, 0.42] m, amplitudes [0.016, 0.011, 0.007, 0.004] * (0.3 + wind*1.4), directions from the wind direction + offsets [0, 0.45, -0.5, 0.95] rad; a detail normal texture and gust 'cat's paws'. Two passes each frame: a planar reflection with a mirrored camera and a clip plane (half res, mipmapped; koi excluded above water), and a refraction pass of the far side at FULL resolution with 2x MSAA and a depth texture. Surface shader above water: Schlick Fresnel F0=0.02; reflection blurred by local ripple roughness and smeared vertically; refraction displaced by ONE continuous offset = view-space normal * 0.04 * a depth factor averaged over a small ring of 8 depth taps (so it never tears at a koi's outline), with samples that land in front of the surface falling back to the undistorted view; Beer-Lambert along the water path with absorb (0.35, 0.08, 0.04)/clarity and scatter 0.035/clarity, clarity default 1.6 (crystal), in-scatter colour from the sky; shoreline foam where the column is under 5 cm; GGX sun glint (roughness 0.05, soft-shouldered); rain rings; winter ice sheets creeping from the banks with cracks and snow dust. Below water: fine ripples softened, Snell's window via refract() with total internal reflection past 48.6 deg, the above-water render seen through the window, absorption along the path. The camera can dive: crossing the surface swaps layers, adds a low-pass to the audio and an underwater post pass (god rays, particulate, DOF). == 6. Koi (the centrepiece) == One instanced body mesh, one instanced fin mesh, one instanced eye mesh, 20 instances. Body from analytic profile tables (top, bottom, width vs s = 0 nose..1 tail) with Catmull-Rom interpolation: deep rounded back, broad shoulders (width peak 0.10 at s=0.37), blunt head, operculum ridge, eye bulge, protrusible mouth that opens into an O and extends 22 mm, two pairs of barbels, gill covers that breathe. Fins: long dorsal, forked caudal with rounded lobes, anal, large fan-shaped pectorals (length 0.2, width 0.08) and smaller pelvics, all with a ray/membrane texture, folding back when fast and sculling when slow; butterfly (long-fin) variants scale the paired fins ~1.9x and the tail 2x with a billowing veil. Swimming in the vertex shader: lateral spine wave lat(s) = amp*(0.05+0.95 s^2)*sin(5.7 s - phase) + bend*(s-0.3)^2, with normals corrected by the slope. Instance matrix = position, Euler(roll, heading, pitch, 'YZX'), uniform scale = size. Skin: per-fish pattern atlas 256x128 (R = hi/red field, G = sumi/black field, B = tone, A = belly), low-frequency FBM sampled on the body cylinder; a 512^2 overlapping-cycloid scale normal map (RG normal, B per-scale id, A exposed-rim mask), 4.5x3 repeats; crisp pattern edges scalloped scale by scale (kiwa) at the back of a red patch and a soft blurred sashi edge at the front; sumi granular per scale; pearly white with faint blue-tinted scale pockets; reticulated scale edges for Asagi/Chagoi/Kujaku/Goshiki; lateral line; nostrils, lips, gill slit, pink mouth interior; clearcoat 0.6-1.0, sheen, iridescence 0.25 (0.55-0.6 on metallic varieties); wrap/subsurface warm light past the terminator. Gin Rin: ~35% of scales are tilted mirrors that flash as the fish turns (and still sparkle underwater). Doitsu: scaleless leather skin with rows of large mirror scales beside the dorsal ridge and along the lateral line. Hajiro: white fin tips. Palettes live in an 8xN float texture (base, hi, sumi, belly, fin, fin base, info, flags) so the roster can grow. Roster (variety, size class; S ~0.21-0.29 m, M ~0.38-0.50 m, L jumbo ~0.62-0.74 m): Kohaku L; Sanke M; Yamabuki Ogon L; Showa L (utsuri sumi wraps the flanks + menware head stripe, hajiro); Orenji Ogon M gin rin; Karasugoi M (black, hajiro); Tancho M (single red crown); Bekko S; Sanke S; Asagi M (blue net, red belly and cheeks); Platinum M butterfly; Chagoi L (bronze, negative retic); Shiro Utsuri M; Hi Utsuri S; Kujaku M butterfly (metallic, matsuba net); Doitsu Kohaku M; Goshiki S; Benigoi S (solid red); Ochiba Shigure M; Kohaku S gin rin. Kohaku/Sanke/Doitsu use step patterns: 2-4 separate red patches with clean white windows between. Each fish gets a small hue/saturation/lightness jitter so no two match. Girth = 0.96-1.05 + (size-0.46)*0.5. Juveniles keep to the shallows and beat faster (freq * sqrt(0.46/size)); jumbo koi swim deeper. Behaviour: boids (separation, alignment, cohesion), rate-limited turning with angular acceleration and a C-bend into turns, burst-and-glide (a few tail beats then a coast; hover episodes with flared pectorals), soft boundary via the sdf gradient, pier/rock/turtle avoidance, depth preference bounded by the floor, occasional surfacing that leaves drops, wakes near the surface, slow mouth gulps, eye saccades, curious inspection of a submerged camera. The whole fish always stays below the lowest wave trough (depth cap) so the surface never slices it. Hard overlap resolution with three spheres per spine. Koi do NOT cast into the shadow map; instead every underwater fragment computes an analytic soft shadow per fish by walking up the refracted sun ray to the fish's depth and testing a swimming-spine silhouette (penumbra 0.012 + 0.05*h, strength 0.8*exp(-0.2 h), never self-shadowing, also dims 35% of the skylight). == 7. Interactions == Click the water: ripple ring + splash particles + splash sound. Click the frog: it leaps. E / 'Feed the koi': a first-person hand reaches in from the lower right (SkinnedMesh: forearm, palm, five fingers with three bones each, skin textures with knuckle creases, nails, veins; a sleeve), rubs pellets from between thumb and fingers (up to 70 floating pellets that drift, get nudged and are eaten with a gulp and a splash), fish react with a distance-based delay, jostle, snap at the surface, expel gill bubbles; the hand's reach/withdraw use smootherstep easing and a critically damped follow spring in camera space. G / 'Stroke a koi': the camera leans over the bank, a calm medium-sized koi (0.36-0.66 m) glides in, lies alongside with its back just under the surface, lays its dorsal fin flat; the hand approaches from the shoulder, strokes nose-to-tail three times (2.4 s each), the fish rolls into the hand, then the hand withdraws; the user can drag to stroke. Hand collision: sample spheres along the hand are resolved every frame against every koi (in the fish's local frame), the terrain height, rocks (raycast) and lily pads (pushed aside), up to 4 iterations with a 1 mm margin and a filtered lift (fast rise, slow settle). Verify: 0.0 mm penetration, hand peak acceleration under ~8 m/s^2. == 8. Camera == Modes: Cinematic (default), Manual (drag to look, WASD, Q/Space down/up, Shift faster, wheel sets speed), Follow koi (K cycles fish, classic top-down). Cinematic is a directed film tour with letterbox bars, serif captions and dips to black, in this order and duration: The garden from above (13 s, aerial), The koi pond (11 s), Koi (11 s, follows the highest fish), Sacred lotus (10 s), Bamboo grove (12 s), Weeping cherry (10 s), Cherry blossom (11 s), Pond frog (10 s), Yellow-bellied slider (9 s, follow), Beneath the surface (13 s, underwater), back to the pond view (11 s), then loop. Options: hold shot (P), freeze time (O), path speed, stay above water, change season each loop. Physical lens: DOF with GPU autofocus on what is under the crosshair, aperture default f/8 (whole garden sharp), max bokeh size, lens sharpening 0.35; no stair-stepped DOF. == 9. Weather / seasons (T cycles; GUI dropdown) == Presets, each cross-faded over a few seconds: Sunny: tod 10.5, cloud 0.55, turbidity 2, fog 0.004 (0.5, 0.58, 0.68), wind 0.35, exposure 0.9, grade (1.035, 1, 0.955). Rain: tod 13, cloud 1, turb 6, overcast 0.85, sun x0.1, hemi x2.1, fog 0.02 (0.2, 0.225, 0.25), rain 1, wet 1, wind 0.55, exposure 1.15; falling rain streaks, rings on the water, wet dark surfaces with puddle sheen, muffled sky. Autumn: tod 15.7, cloud 0.42, turb 4.5, fog 0.013 (0.62, 0.52, 0.4), autumn 1 (deciduous foliage turns red/orange and thins), wind 0.45, grade (1.07, 1, 0.9). Winter: tod 11.5, cloud 0.95, overcast 0.7, sun x0.3, hemi x1.9, fog 0.024 (0.56, 0.6, 0.66), snow falling, snow cover 1 on up-facing surfaces, ice sheets from the banks, autumn 0.75 (bare trees), koi sluggish, wind 0.2. == 10. Post-processing == Main HDR -> SSAO (half res, 12-sample normal-oriented hemisphere, blurred) -> bloom (prefilter, threshold 0.9, 5-level mip chain, strength 0.3) -> god rays + DOF when submerged -> composite: exposure, ACES, per-weather colour grade, vignette 0.32, film grain 0.01, lens effects, letterbox. Quality High/Low with automatic drop: first scale resolution smoothly 1.0 -> 0.6 when frame time stays over 22 ms, then switch to Low; recover when fast. == 11. Audio (Web Audio, all procedural; starts on the first click/key) == Master chain: sources -> dry + convolver reverb -> underwater low-pass (420 Hz when submerged, 18 kHz above) -> master gain (volume 0.7). Loops from generated brown/pink/white noise: water lapping (rises with wind and feeding excitement), leaf rustle (wind * gust), waterfall (distance-attenuated), rain, underwater rumble. Events: plip (pellet lands), gulp, splash (scaled by size), frog croak (sawtooth through two bandpasses with AM), frog landing thud, feed-start rattle, dragonfly wing buzz, turtle plop, occasional bird calls, drips, and a shishi-odoshi bamboo knock every 12-30 s. M mutes/unmutes; a Sound switch in the panel mirrors it. == 12. UI == Frosted-glass design system (backdrop blur 20 px + saturate, hairline borders, a soft sheen, one warm accent #f0894c). Bottom-right toolbar dock of icon buttons: camera mode, hold shot, freeze time, clean view, weather, sound, then Stroke a koi and a warm primary Feed the koi; labels collapse on narrow screens, a centred icon dock on phones. Top-right dat.gui restyled as a glass sheet (thin sliders with knobs, pill toggles, glass dropdowns, folder chevrons, a sticky Close bar, never covering the toolbar) with folders: Environment (weather, time, azimuth, wind, wind direction), Water (clarity, wave height, caustics), Koi (fish count 0-20, feed), Rendering (quality, auto-drop, exposure, bloom, bloom threshold, SSAO, god rays, grain, vignette, sharpening), Lens (DOF, f-stop, max bokeh), Camera (film tour, letterbox, change season each loop, mode, follow, path speed, stay above, hold, freeze, clean view, volume, sound), Close-ups. Top-left: an fps/ms HUD and a Guide card listing every shortcut with key chips; I or its x hides it, a small ? brings it back. Shortcuts: C camera mode, P hold, O freeze, V clean view (Esc exits), E feed, G stroke, K follow, T weather, M mute, H panel, I guide. Mute and guide state persist in localStorage. A loader with a progress bar while the world builds. A toast for transient messages. == 13. Verification targets (do these before calling it done) == - Screenshots: aerial, pond level, koi close-up top-down, underwater, each weather; every koi variety lined up in sunlight. - Native-resolution crops of a koi's outline through the water: no doubled/ghost outline, no stair-steps. - Hand: 0.0 mm penetration into koi/rocks/terrain during feed and stroke; peak on-screen acceleration under ~8 m/s^2; no NaN in any fish state. - Performance on a 2x display: High 50-90 fps, Low 100+ fps. - Every shader compiles with no console errors; the full script parses.