diff --git a/.claude/agents/midnight-ops.md b/.claude/agents/midnight-ops.md index 3070873a..53afbee3 100644 --- a/.claude/agents/midnight-ops.md +++ b/.claude/agents/midnight-ops.md @@ -11,25 +11,25 @@ You are the specialist for **Midnight Ops**, a game on Arjun's site (ascoding11. ## What it is -Midnight Ops (**preview, admin page only**; Back Room folder; the folder keeps the working title `ironveil`, and the display name lives in ONE constant, `IV.GAME_NAME` in `js/core.js`, which fills the page title, the logo, the content note and the "turn your phone" card, so the name can change without touching anything else), a single-player first-person Second World War campaign (an over-the-shoulder view stays in Settings as "View") (three.js r187 from the site's own build, `/lib/three/r187/three.min.js` plus `three-addons.min.js` for GLTFLoader and SkeletonUtils, see `lib/three/README.md`; plus `../autores.js`, `../keybinds.js`, `/e63334287a3deaa3/lang.js` with its own `es.js`, `stats.js`; Web Audio; no Firebase, nothing online). +Midnight Ops (**preview, admin page only**; folder `ironveil`, display name `MO.GAME_NAME` in `js/core.js`) is a single-player first-person Second World War shooter, rebuilt from scratch so that every model, texture and sound is made in code when the page opens (no asset files). A campaign of missions, one file each in `js/maps/` (Night Drop: spike three flak guns in a Norman hamlet; The Radio Mast: silence a transmitter and topple a mast in a fenced compound before the artillery clock runs out). The README entry lists every file and what it does. -The README entry has 8 more detailed sub-points under it; read them before touching those areas. ## Where it lives -- Folder: `e63334287a3deaa3/ironveil/`: `CREDITS-env.md`, `CREDITS-weapons.md`, `CREDITS.md`, `assets/`, `chars-test.html`, `chars.js`, `env/`, `env-test.html`, `es.js`, `index.html`, `js/`, `preview.jpg`, `tools/` +- Folder: `e63334287a3deaa3/ironveil/`: `index.html`, `es.js`, `js/` (the whole game: `core`, `geo`, `tex`, `render`, `sky`, `ground`, `phys`, `props`, `level`, `fx`, `audio`, `input`, `player`, `gunmodel`, `weapon`, `enemy`, `hud`, `missions`, `mission`, `main`, and `maps/` with one file per mission), `preview.jpg`. `env/core.js`, `env/post.js`, `env/texgen.js`, `env/scans/`, `CREDITS-env.md` and `assets/lib/meshopt_decoder.js` are kept only because Ironwing loads them: don't delete or change them for this game. - Docs: the bullet for `e63334287a3deaa3/ironveil/` in `README.md` (and the indented points under it). This is the source of truth for how the game works and stores data; read it in full before changing anything, and update it when you change behaviour, storage or file layout. ## What it uses (detected from the code) -- three.js (global r128 build from cdnjs, not ES modules) +- three.js r187 as a plain global (`/lib/three/r187/three.min.js`, with the r128 compatibility layer: colour management off, lights times pi; the game does its own HDR tone mapping and writes sRGB itself) - `../autores.js` loaded straight after three.min.js (automatic resolution) -- Firebase (shared `rumblekarts` project) -- `../stats.js` for play time / Leaderboards -- `../keybinds.js` rebindable controls (keep its `keybinds:` storage key) ## Must stay true +- Everything stays generated in code: no model, image or sound files. New art goes through `MO.Builder` (`js/geo.js`) and a material preset or texture family in `js/tex.js`; new sounds are recipes in `js/audio.js`. +- The techniques follow those documented for the game Saltline, but none of its code may be copied in: it has no licence. +- Test long sequences with `window.__mo.step(n)` (runs n frames without drawing); the headless browser draws under one frame a second. + - Keep every storage path, room prefix, localStorage key, stats/leaderboard id and saved-data format working exactly as it is, so players' saved progress, settings, ratings and invite links carry over. Old names mentioned above (folder, keys, ids) are kept on purpose: never "tidy" them. - Don't change Firebase security rules or the Firebase config, and don't create a new Firebase project. If a change needs storage the rules don't allow, stop and say so instead. - Keep the keyboard-and-mouse version unchanged on computers, and keep the touch controls working: shown only on touch screens, nothing overlapping in portrait or with the phone sideways. diff --git a/.claude/skills/war-game-series/SKILL.md b/.claude/skills/war-game-series/SKILL.md index ac0341e7..a9020421 100644 --- a/.claude/skills/war-game-series/SKILL.md +++ b/.claude/skills/war-game-series/SKILL.md @@ -5,6 +5,11 @@ description: Build or extend a game in Arjun's realistic war-game series (Midnig # War-game series +> **Midnight Ops was rebuilt from scratch.** It no longer uses model files, the `IVEnv` environment kit, the Blender +> tools in `ironveil/tools/` or the old `IV.*` modules described below: everything is generated in code on a +> `window.MO` namespace (see its README entry for the files). Where this skill names an old Midnight Ops file or +> pipeline, treat it as history; Ironwing still uses `ironveil/env/core.js`, `post.js` and `texgen.js`. + Midnight Ops (`e63334287a3deaa3/ironveil/`) is the reference game for the series. Every new entry (a tank game, a dogfight game, a naval game, more Midnight Ops missions) should feel like part of the same family: the same render stack and look, the same quality tiers, the same way of separating gameplay from art, and the same rules on diff --git a/README.md b/README.md index 6fae3f53..d7679c0e 100644 --- a/README.md +++ b/README.md @@ -27,7 +27,7 @@ Personal site hosted with GitHub Pages at **https://ascoding11.github.io**, the - `e63334287a3deaa3/chromaflage/`: Chromaflage (Back Room), paint-yourself hide and seek for up to 8 players (Three.js, Firebase Realtime Database rooms under `rooms/cf-…`, same project and rules as Rumble Karts; Quick match uses `rooms/cf-pub-1` to `cf-pub-4`; invite links go through the home page as `#cf-`). Hiders paint their own bodies in a paint studio (brush, an eyedropper that reads the true colour of whatever surface you click, fill, undo, glossiness) and pose to hide (crouch under tables, lie under beds, flatten, or stick to a wall with G or the Stick button and slide up, down and along it at any height, upright or sideways, until they jump to let go); seekers tag them with a blaster that fires a shot every 0.18 s (`FIRE_GAP`) for as long as the mouse button or the touch Tag button is held, with no reload pause: a miss costs one of 10 ink (`INK_MAX`), a hit costs nothing, and ink trickles back all the time at one shot every 2.5 s (`INK_REGEN`), so a seeker can keep firing at a hider who jumps about but blind spraying soon runs the tank dry and then gets a shot every 2.5 s. Fire rate and ink live only on the seeker's computer, which also decides hits (a ray against the hiders as it draws them) and sends a tag claim (`tg`) for the host to check, so changing them needs no change to the room data. Modes: Classic and Infection. Like Showdown, everything travels through each player's own node at `rooms/cf-/players/`, because the shared rules expect `n, c, x, z, h, ts` there and refuse other paths (such as `events`) for new prefixes: position and pose (`y, po, fl, p`, and `wl`: 0, or 1 to 4 for the way the wall a hider is stuck to faces, with `y` its height), body (`s` shape, `sz` size, `rf` glossiness), paint (`pv` version and `pd`, the 256 × 256 body texture as a WebP data URL, or JPEG where the browser can't make WebP; about 1 KB for a plain colour and 10–20 KB for a detailed pattern, re-sent at most every 1.2 s and only when it changed, so late joiners read it straight from the node), the last shot (`sh`), squeak (`ta`) and tag claim (`tg`). The host (newest host number `he`, else whoever has been in the room longest) publishes the round as JSON in its own `rs` and checks tag claims loosely; if it leaves, the next player carries on from the last round it saw. Anything read from another player's node is untrusted (any player can make itself host with a high `he`): `sanitizeRS` rebuilds a received round state field by field (known phases, numbers clamped, player ids checked and lists capped, settings through `cleanSet`), `remoteTarget` keeps positions inside the map and angles finite, and scores are shown as numbers, so keep new round-state fields going through `sanitizeRS` and escape anything put in `innerHTML`. A tab in the background gets no animation frames, so a 1 s timer keeps its node's `ts` fresh and, for the host, keeps the round ticking. Bodies are modelled about 1.7 units tall and drawn at `BODY` (0.64) times their size setting, so Normal is about 1.08 m. The Doll is a soft, rounded figure (a big round head on a short neck, a plump body, thick arms and legs with rounded ends, two small eyes), each part turned on a lathe (`latheGeo`, `dollParts`) with the texture spread evenly up the profile and normals taken from the profile so there are no shading seams; the Block is a slim slab. Each body shape has a 256 × 256 texture atlas where every texel knows its 3D spot on the body, so brushes paint by distance in 3D (`atlasOf`, `Paint`). Keep each part's region of the atlas (the `rect` passed to `latheGeo`) when reshaping a body, or saved and synced paint jobs land on the wrong parts; the Doll was reshaped inside the same regions, so paint saved before that lands on roughly the same places. Maps are axis-aligned boxes plus round props, built by `buildManor` (Hollyhock Manor: 48 × 38 m, a party night in a country house, with an 8 m grand hall whose staircase climbs to a gallery, ten rooms under 4.2 m ceilings), `buildMuseum` (Marlowe Museum: 58 × 50 m, a 7 m lobby, a top-lit grand gallery with free-standing walls, six galleries, a gift shop, a café and the storeroom) `buildRyokan` (Kirinoya Inn: 50 × 40 m, a Japanese inn round a glass-roofed garden courtyard, with four tatami guest rooms, a banquet hall, a tea room, a futon store, the hot-spring bath, the kitchen and a games lounge), and six everyday places: `buildSchool` (Birchwood High: 44 × 32 m, a locker-lined corridor, two classrooms, a science lab, a library, an art room, the staff room, toilets and the PE store), `buildOffice` (Larkspur & Co: 48 × 34 m, a reception, an open-plan floor of desk pods, a meeting room, the manager's office, a kitchenette, a server room, a store, a lounge and toilets), `buildMarket` (Greenleaf Market: 50 × 36 m, a 4.2 m supermarket floor of aisles, produce tables, chillers, freezer islands, a bakery, a deli and six checkouts, a café, the bakery kitchen, a stockroom with pallet racking and a forklift, the staff room, an office, toilets and a cold room), `buildHotel` (Hotel Bellamy: 48 × 36 m, a marble lobby with columns, a piano and a reception desk, a bar with a pool table, a restaurant, and off a carpeted corridor five guest rooms, each with a bathroom whose bath you can climb into, plus housekeeping and the laundry), `buildLeisure` (Riverside Leisure Centre: 50 × 38 m, a 7 m sports hall with bleachers, hoops and a climbing wall, a gym, a dance studio, the reception and café, two changing rooms with lockers and showers, first aid, the equipment store, an office and the plant room) and `buildFlats` (Maple Court: 46 × 31 m, four flats off a landing, each with a living room and kitchen, a bedroom, a children's room with bunk beds, a study, a hall and a bathroom, plus the residents' laundry and the bike and bin store; the north flats are the south ones mirrored by `flat()`). The everyday maps share painters, `everydayMats` and the `everyday` furniture (desks, office and school chairs, lockers, gondola shelving, counters, divans and bunk beds, bathroom pieces, gym kit, bleachers, trolleys, pallets). Walls, floors and ceilings come from `kit`: `wallX`/`wallZ` build a wall as two half-thick slabs, one per room, each reaching 1 cm past the centre line so the two overlap and leave no seam to slip into, each from a side spec (`w` wallpaper, `lo` and `lh` lower panelling, `h` height, `base`, `rail`, `crown`, `casing`), with door openings and their casings; `win`, `pic`, `flat` and `sconce` hang windows (an evening view), framed pictures, signs and wall lights, and `ag` places furniture with its back to a wall. Wall slabs are marked `wall`, and trims, pictures and curtains are not solid, so a hider can still stick to the wall behind them. The `Builder` helpers are `box`, `at` for turned furniture, `prop` for round things from the shared `geo()` cache (baked with the boxes into one mesh per material, so a map is about one draw call per material), `ceil` for ceilings drawn from below only so the menu's view from above looks into the rooms, `spot` for places bots hide under tables, beds and the inn's futon cupboard, and `lamp` for point lights, of which only six spread-out ones are used, three on the Fast setting; the furniture helpers are in `furn` (tables, round tables with cloths, chairs, benches, sofas, beds, a grand piano, a fireplace, plants and palms, lamps and chandeliers, washing lines, curtains you can walk into, vending machines, plinths and mannequins, which make good decoys). The bots only walk the floor: the manor's gallery and the inn's raised entrance step are for players. Each map gives `spawns`, a `seek` start and an `attract` spot for the menu's doll. Boxes marked `soft` (cloth and leaves) block the view and the seeker bot's line of sight but not the blaster's pellets. The boxes are also the colliders, the bots' navigation grid, line of sight and the surfaces the eyedropper and bots sample; they are filed in a 2 m grid (`buildGrid`, `solidsIn`, `rayMap`) so rays and collisions stay quick. Every pattern is drawn on a canvas by the `P` painters (damask and striped wallpapers, wood panelling, marble, tatami, shoji and fusuma, rugs, portraits, landscapes and modern paintings, and so on), from a fixed seed so all players get the same map. Every room must keep a ceiling. To add a map, write a `build…` function and add it to `MAPS`, then check it the way the existing ones were checked: every spawn, the seeker start and every bot `spot` free and reachable from the seeker start, a ceiling and a floor everywhere, no ray escaping the shell, and no solid furniture cut into a wall. Bodies collide as their pose's footprint circles against the boxes (`moveEnt`): each move is cut into steps shorter than the body's radius and anything it runs into pushes it back out the face it came in through (`pushOut`), so nothing can be crossed in one frame; a box whose top is within a step of the feet (`stepOf`: 0.45 m standing, half the body's height crouching or lying) is climbed only when there is room to stand on it, otherwise it is solid (a chair seat over its legs, a bed frame under its quilt); a box whose bottom is within 1 cm of the top of the head doesn't block, so a body that just fits under a table fits; low furniture is solid down to the floor unless the gap under it is at least as tall as the smallest lying body (`minGap`, the Petite Block, about 0.15 m: `Builder.finish` adds an invisible collider under anything lower); a body that finds itself inside something (after growing, say) moves to the nearest free spot that isn't across a wall (`freeSpot`, `wallBetween`), and a move never ends on the far side of a wall. The practice seeker bot "sees" by rendering a small view of you with and without you and comparing the colours (`perceive`, delta E), so better paint really does keep you hidden; it sweeps its gaze up and down so it can spot hiders high on walls, and furniture blocks its view. Practice hider bots sometimes hang on walls or tuck under furniture. Online rooms follow a daily map rotation: `dayMaps` shuffles all the maps with the day number as the seed (days start at midnight US Eastern standard time, `DAY_SHIFT`) and keeps the first three, and the map is `dayMaps(now)[floor(now / 15 min) % 3]` (`rotMap`), worked out from the shared server clock (`Net.now`). The host publishes it as `rs.map` in the lobby and when it starts a round, so a round in progress finishes on its map and the next round or the lobby moves on; the lobby shows the map now and "Next map in m:ss" with the next map's name (`rotText`), and the menu names today's three. The host of a private room can still pick a single map instead of "Daily rotation" (the `map` round setting, -1 for the rotation); Practice has a picker of every map; Quick match and invite links are unchanged. Nothing is stored online between rounds; your name, body, last paint job and settings are saved in the browser under `chroma-…`. Parties can launch it (its row in `GAMES` in `party.js`). On touch screens the page adds `touch` to `body`, and the `body.touch` rules at the end of the stylesheet place the HUD, the lobby card and the paint studio for phones held upright or sideways (keep them clear of the stick and buttons when adding HUD pieces). The lobby card and the paint studio scroll an inner box (`.lb-body`, `.st-body`) instead of the card itself, because Chrome can leave a blank patch in the 3D view under a scrolling box with a solid background. Effects (`splat`, `pellet`, `confetti`, `puff`, all under `fxRoot`) are drawn only on each player's own computer and are hidden from the practice bot's eyes (`perceive` hides `fxRoot`), so they can be restyled without changing what can be hidden against: a pellet is a short streak with a pale tail and a small flash at the blaster, the mark it leaves is one of five splat shapes made once by `splatGeo` (a wobbly blob with lobes and stray drops, in the same pink and about the same size as a plain round mark) that pops open and throws off a few drops, and a find adds a gold ring and a sparkle to the confetti. The Fast setting gets fewer drops and less confetti (`fxHigh`). On the HUD the crosshair kicks on each shot, the FOUND banner, the "Found …" text and the Still hidden number pop when they change (`hudPop`), the clock turns pink and beats in the last ten seconds of hide or seek time, and the results card rises into place; all of these are skipped when the device asks for reduced motion. Lighting, shadows, map colours and patterns, the paint palette and how paint is sampled were deliberately left alone, because in this game any change to how a surface is lit changes how well a paint job matches it. **Turkey Week** (`../events.js`, November 15 to 26, 2026): seekers wear a pilgrim hat as part of their gear; hiders never do, because a hat would give them away: one shared hat geometry and material from `events.js` (`tkHat`), one extra draw call each. The game reads the one Turkey Week switch on the Back Room page (see `events.js` below) once, when it loads (off means no hats are made); it has no button of its own. **Seeker kit** (hidden: captains only for now; `KIT_PUBLIC = false` and `kitOn()` in `index.html`, and `?seekerkit=1` turns it on for testing, on localhost or in an automated browser only): seven hats (a detective deerstalker, a safari hat, a painter's beret, a museum guard cap, a hard hat, an exterminator cap and goggles), four tools that take the blaster's place in the hand (a magnifying glass, a paint scraper, a spray bottle and a feather duster), plus, from 19 Nov, twelve more hats (8 to 19: team cap, football helmet, sweatband, referee cap, pirate hat with an eye patch, fedora, top hat, robot antenna, champion headband, hockey helmet, bowler hat, mascot ears) and eight more tools (5 to 12: foam finger, pirate hook, walking cane, whistle, tennis racket, hockey stick, spyglass, robot claw), each still one merged mesh, a paint splash when the wearer catches someone (a ring of see-through droplets that flies outward and is gone within 0.6 s, and a small SPLAT! above the caught hider's head) and a caught animation for the hider they catch (it hops and pops along its own up direction, spinning only when it was upright), all drawn by `kit.js`, which the page fetches only when this player may open the Seeker kit (a button under the body choices on the menu opens a screen with a model of you as a seeker) or someone in the room wears a kit; for everyone else it never loads and every hook (`if(CK)`) does nothing. Seekers only: hats and tools are added inside the seeker gear (`Avatar.gear` and `Avatar.gun`), which the page shows only while a body is a seeker, and the two effects start only once the host has marked a hider found, are drawn under `fxRoot` for at most 1.2 s and leave no marks, so nothing changes how a hider looks or how easy a hider is to see while hiding. Shooting is still the camera's ray, so a tool changes neither reach nor tagging (the pellet still starts at the hand), hats stay low and above the visor, and your own hat and tool are hidden while the camera is pulled in close to them. A kit is four item numbers, the `no` of Chromaflage's items in `cosmetics.js` ([hat, tool, splash, caught], 0 for none; `kit.js` keeps its lists in the same order, so never reorder them), saved as `chroma-kit` and sent in the player's own node as `kt` (`'3.1.1.0'`, only when something is worn; older pages ignore it, and `kit.js` checks every number and draws the plain gear for one it does not know). Each hat and tool is one mesh (its pieces merged with vertex colours, one geometry per item, one shared material); a dressed seeker's blaster becomes one merged mesh too and a hat replaces the Turkey Week hat, so a dressed seeker is never more draw calls than a plain one. It has Spanish: its words are in `chromaflage/es.js` (lang.js; map names and the signs inside the maps stay in English), with a Language switch in Settings and the pause menu. - `e63334287a3deaa3/backrooms-1v1/`: Backrooms 1v1–4v4 (Back Room; the folder keeps its original `backrooms-1v1` name), a third-person build-fight shooter in Level 0 of the Backrooms (Three.js). Practice is you against the Entity, a bot that runs only in your browser. Online rooms hold up to 8 players split into Red and Blue (1v1 to 4v4, uneven teams like 4v3 are allowed and never filled with bots) in the Firebase Realtime Database under `rooms/br-…` (same project and rules as Rumble Karts; invite links go through the home page as `#br-`). Quick match waits in `rooms/br-queue/players` and pairs two people into a `br-q…` room for a 1v1. Each player writes only their own node `players/`: `n`, `c`, `x`, `z`, `h` and `ts` always (the shared rules expect that shape), plus height, pitch, health, shield, weapon, a dead flag, the match `m` and round `rd` the position belongs to, the team picked in the lobby `t`, kills this match `k`, join time `j`, `mv`, the newest map version the page can build (3), and `ev`, set to 1 by a page that can edit builds; about 20 times a second during a round (15 in rooms of 5 or more) while something changed, and twice a second otherwise or while nothing has. The host is the live player who has been in the room longest (the next in line takes over when they leave; a newcomer only starts judging who the host is once the room's players and round have loaded, so a slow phone joining mid-match can't take over and reset it) and is the only one who changes `round`: `{id, ends, seed, ns, ph, pt, to, rn, sr, sb, ro, dd, rw, mw, fm, rz, mv, ed}`, where `id` is the match, `ph` the phase (`lobby`, `cd` countdown, `fight`, `over`, `end`), `pt` when the phase ends, `to` the rounds to win (3, 5 or 10, host's choice), `rn` the round, `sr`/`sb` the team scores, `ro` the roster (`uid:r;uid:b`), `dd` who is out this round, `rw`/`mw` the round and match winners, `fm` a forfeit, `rz` the host's "Randomize teams" draw (each player then moves themself), `mv` the map version for this match (see below) and `ed` whether builds can be edited in it (see Editing builds). The host writes with transactions guarded on `id`, `ph` and `rn`, and keeps `ends` at the time of writing because the rules cap how far ahead it can be. Shots, builds and deaths go through `events/` (deleted after 5 s): the shooter's rays pass through teammates and the shot lists only the enemies it hit; the victim applies damage only from someone on the other team of the same match, and reports its own death naming the last shooter, which gives the kill credit. A round ends when one team has nobody left: dead, or silent for 10 s (a closed tab removes its node at once). A team with nobody left in the room (disconnected, or silent for 20 s) forfeits the match. A host whose own tab has just frozen waits a moment for the queued updates before judging anyone. Players who join mid-match wait in the lobby or watch until the next one, and dead players watch a living teammate (click, or tap Next on a touch screen, for the next one). **Find tags:** once a round's fight has run for 1 minute 30 seconds (`FIND_AT`), every 15 seconds (`FIND_EVERY`) a name tag shows over every living player for 2 seconds (`FIND_SHOW`), through walls, with how far away they are, so players who can't find each other can; it pops in white, holds in the team colour and blinks out (a plain fade with reduced motion), with a soft ping. A tag for someone off the screen is pinned to the nearest edge with an arrow showing which way to turn. Nothing is sent for this: the clock (`findClock`) is the round's own, online the server-clock time since the fight began (the round node's `pt`, which is when the countdown ended and is left alone for the whole fight phase), so every browser flashes at the same moments, and in practice the seconds fought this round (the tag is the Entity's). Between flashes nothing changes: teammates' tags show all the time, as before, and an enemy's only while in sight. From ten seconds before the first flash a small chip (`#find`, under the score; on a phone, under the health bars sideways and in the top right corner upright) counts down to the next one, and the first flash of a match adds one line to the feed. The tags are the same HTML labels as the ordinary name tags (a fixed size on screen, so readable far away and not huge up close), so they add no draw calls. An older copy of the page in the room just never shows them. **Maps:** every round is a new, randomly generated Level 0, in practice and online, on a grid of 4 m cells with walls on the cell edges and posts on the corners (`layoutV3`, map version 3). Every map is built the same way, so they all feel like the same place: a 3 × 3 room round each spawn, then rooms of 2 × 2 to 2 × 4 cells dropped at random until about two fifths of the floor is rooms, and everything else one-cell-wide (4 m) corridor. Every wall is full height: no low partitions, stray wall slabs, open halls or pillar fields (the most a room gets is one column in the middle, about one room in three). The rooms and corridor cells are joined into a tree and then given a few loops (a second or third way into some rooms, the odd extra link between corridors, most dead ends opened onto something), with three rules: never two openings side by side in one room wall, never four corridor cells open as a square (corridors stay one cell wide), and never a short piece of wall left standing on its own. Where a room opens onto something else the opening is a doorway, with a 0.8 m jamb of wall (`JAMB`) each side wherever the wall carries on past it. Any straight line of more than six cells (`V3_RUN`, 24 m) gets a wall across it near the middle, and the corridor jogs round it. The lighting is the same everywhere: about one ceiling panel in twelve is dead (the floor under it a little darker), up to three flicker on their own, and most maps have one or two banks (a room or a stretch of corridor) that flicker together and dim the walls, floor and ceiling around them; there are no tinted wallpapers, damp carpets or special rooms. Then each spawn is cleared to an open, lit 3 × 3 area, anything that can't be reached on foot is opened up, and the layout is checked for fairness (`fairV2`: both teams' spawns about as far from the middle on foot, the two halves within about a third of each other's cover, no huge detour between the teams); one that fails is redrawn (about one in four), and if sixteen in a row fail (in practice never), the closest is made point-symmetric, which is fair by construction but can leave a few open patches along the middle. Checked on 600 generated maps of every size and roster: no low partitions or free-standing wall pieces, no 3 × 3 block of cells without a wall inside it outside the spawn areas, no straight run longer than six cells, every cell reachable, the same seed always gives the same map; the longest sightline on a map is 23–53 m (v2: 42–69 m). A v3 map has more walls, so its collision boxes are joined up along each wall line (`solidsV3`: walls and jambs that touch end to end become one box, and posts in the middle of a straight run are left out), which leaves fewer boxes than a v2 map (about 210 against 310) and less work per frame for movement and shots. Size depends on the number of players and a little chance: 11–13 cells across for a 1v1 (and practice), 12–14 for 3–4 players, 14–15 for 5–6, 15–16 for 7–8. Red spawns along the west edge and Blue along the east. Online, the layout of round `rn` comes from the match's `seed` and `rn` (`roundSeed`), and its size from that and the roster size, so every player builds the same rooms without anything new being sent; a short blackout covers the change between rounds. **Older copies of the page** (still open in someone's tab after an update) only know earlier layouts, which are kept unchanged in the page and checked to build exactly the same walls, pillars and lights for the same seed: the original maze (`layoutV1`: one per match from `seed`, 12, 14 or 16 cells by room size (`ns`), Red's and Blue's spawn areas cleared), and the previous random layout (`layoutV2`, map version 2: the floor split into areas furnished in different ways (twisty corridors, small rooms, open halls with stray wall slabs, pillar fields, office cubicles behind 1.25 m grey partitions you can see and jump over, solid blocks of wall), joined by doorways or with no wall at all, each lit its own way, sometimes with a different wallpaper or a special room). Each player's node says which maps their page can build (`mv`), and the host writes into a new match the newest version every player in the room has: `mv: 3`, `mv: 2`, or no `mv`, in which case everyone, new pages included, plays the original maze for that match, so a mixed room always agrees on the walls (an older page that joins in the middle of a newer match only watches, and may see the wrong walls until the next match). A host on a v2 page writes `mv: 2` at most, and one on a v1 page never writes `mv`, so the same applies. The collision rules below hold for every layout: automated walks and jumps into walls, doorway jambs, partitions, big pillars and wall blocks, spawns for every roster shape and shots at every kind of solid, run on hundreds of generated layouts, found nothing passing through or stuck inside a wall; and scripted runs and jumps at built walls, floors and ramps from every side, at 60, 30 and 20 frames a second and thrown at up to 20 m/s, with random building and with the Entity's own code, found nothing inside or through a build. Builds can't be placed inside a solid block of wall. **Editing builds:** aim at a wall, floor or ramp your team built (in practice, one you built; never the other team's or the Entity's) from within 6 m (`EDIT_RANGE`) and press Edit (G, or the Edit touch button): the piece turns into a grid of tiles, 3 × 3 on a wall and 2 × 2 on a floor or a ramp (a ramp's are its low and high halves, left and right). **Edit on release** (a setting, on by default, in the menu under Look sensitivity and on the pause screen, saved as `br1v1-editOnRelease`; a `br1v1-editRelease` saved by the first version is still read; the Edit key itself is rebindable in Change keys like any other): hold Edit and the tile under the crosshair is picked at once, every tile the crosshair then sweeps across is picked too (no need to hold Shoot / place, though it does the same), and letting go of Edit confirms (`editHold`, `editKeyUp`, `paintTile`). The first tile of a sweep decides whether it opens or closes tiles. A quick tap of Edit (under 0.25 s, `EDIT_TAP`) that did no more than pick that first tile leaves the grid open with that tile still picked (so two taps make a one-tile window), the setting-off way: Shoot / place opens or closes the tile under the crosshair (hold and sweep for several) and Edit again confirms. A longer hold that changes nothing cancels. Either way Reload resets the piece to whole (the touch button reads Reset) and Aim cancels; on a touch screen the buttons read Tile, Done, Reset and Cancel while editing, and a finger put down on the grid picks the tiles it touches instead of turning the view (`editFingerDown`, `screenRay`), so you hold Edit with one thumb, drag the other over the tiles and let go. While you edit, the line of help names the shape so far (Door, Window, Arch, Half wall, Narrow ramp…, `edName`) and what to press next; until your first confirmed edit it spells the whole thing out (`br1v1-editHelp`). The tile under the crosshair is worked out on the grid's own plane, and a point up to a third of a tile off the edge counts as the edge tile (`edTileAt`, `EDIT_EDGE`), so the bottom row of a wall you stand against is easy to pick; when the line of sight finds none of your builds, eight lines just around it are tried (`EDIT_FAN`), so an edge or a seam up close still opens. Your own body is hidden while the grid is up, so it doesn't cover the tiles. That gives a window, a door, a half wall, an arch, a floor with a corner cut, a half-width ramp and so on. At least one tile has to stay. Nothing changes until you confirm, and then the new shape is there at once (it used to land 0.4 s later, `EDIT_T`, now gone); you can't shoot while the grid is up, and a Shoot / place still held from picking tiles doesn't fire until it's let go (`editLatch`). The build message is the same as before. A piece's shape is `ed`, one bit per tile cut out (tile (u,v) is bit `v*n+u`; 0 is the whole piece). The tiles left are joined into as few rectangles as it takes (`edRects`), and each rectangle is one ordinary solid box, or for a ramp one ordinary ramp sheet with a smaller footprint (`pieceShape`), so there is no second collision system: movement, `pushOut` / `rampOut` and shots run the same code as for a whole piece, you walk through a door and shoot through a window because no box is there, and what is left blocks from every side (tiles that come back on a body move it out, as a new build does). The picture is one mesh made of the same rectangles (`pieceGeo`), so an edited piece is still one draw call; the grid you see while editing is three, in place of the piece, and only on your screen. Checked with the game's own movement and shots against the tiles themselves: every one of the 511 wall shapes both ways round (shots straight and slanted through every tile from both sides, walks at it along its length, thrown and jumping bodies), all 15 floor shapes and all 15 ramp shapes in all four directions, at 60, 30 and 20 frames a second, and whole pieces compared number for number with the page before editing. Online an edit travels as the build message for that spot again with `ed` added, the host answers anyone who comes into a round late (`bq`) with every piece standing, its health, shape and team (`bs`), and only the team that built a piece may reshape it (a message from anyone else is ignored). A page from before editing ignores a build for a spot that is taken, so it would keep the whole piece; to keep a mixed room agreeing on the shapes, every page says in its player node whether it can edit (`ev`), and the host turns editing on for a match (`ed: 1` in the round node, written like `mv`) only if every page in the room can: otherwise the Edit key says a player needs to refresh. The Entity does not edit; when a build stops it, it shoots the part it walked into (`bump`), whatever the shape, and it sees and shoots through openings only. Keys and mouse buttons can be changed in the Controls panel (`keybinds.js`, saved as `keybinds:backrooms-1v1`; the Change keys button under Controls in the menu, and Controls on the pause screen): move, jump, shoot / place, aim (Shift and right click), the three guns, reload, the three build pieces (two keys each), Edit (G), the arrow keys that look around when the mouse can't be locked, and pause (P; Esc is fixed). Clicking to watch the next teammate stays on the left mouse button, and the mouse wheel still switches guns. On touch screens it has a move stick, drag-to-look, Fire/Place, Jump, Aim, Reload, Edit and pause buttons, with the weapon and build slots as buttons along the top; while you watch, those give way to a Next button, and the lobby, pause and results screens are plain buttons that fit a phone either way up. Each browser is trusted for its own health and hits, so it isn't cheat-proof. A test hook (`window.__br`) exists only when `navigator.webdriver` is set (its `findShift` moves the find-tag clock forward so a test need not wait a minute and a half). **How it's drawn** (the picture only: nothing here is sent to other players or changes collision, damage or movement): the scene is lit by a soft overall light plus a warm light from one side and a weak cool one from the other, so walls facing different ways, and the two sides of a character, come out in different shades. The carpet is darker than the walls, and its texture repeats once per cell with a pool of light baked into the middle, so the floor is brightest under each ceiling panel and darkest along the walls. Walls, posts, pillars and doorway jambs have a dark skirting board, which is part of the same geometry (`joinGeos`, `skirtW`), so each kind is still one instanced mesh and the collision boxes are unchanged; working ceiling panels have a soft glow round them (one more instanced mesh). A character's suit is a few meshes, each made of several boxes joined together (`parts`), and each of the three guns is one shared mesh coloured per corner (`GUN_GEO`; `GUN_TIP` is how far each muzzle is from the hands), so the detail costs no extra draw calls; every character has a round shadow on the ground under it, which shrinks during a jump and lies along a ramp. The detail stays inside the outline the plain characters had, so nobody is drawn bigger than before: the suit's body, legs and head are the same boxes, each gun is squeezed along its barrel to the length of the plain one it replaced (`gunFit`: rifle 0.78 m, shotgun 0.86 m, sniper 1.18 m), and the shadow is 1 m across, about the width of the figure (a wider one made characters read as larger). Keep to that if you add more detail. A shot shows a muzzle flash at the end of the shooter's barrel and kicks the gun back; tracers are thin glowing beams sized to stay about two pixels wide near and far, and are drawn from the end of the barrel, though the shot itself still starts at `muzzleOf` as before; where a shot lands there is a flash and three sparks. The tracers, flashes and sparks come from small pools made once (`pool`; the sparks are one instanced mesh), so shooting creates no new objects. With the browser's reduced-motion setting on, the muzzle flash, gun kick and sparks are left out. **Turkey Week** (`../events.js`, November 15 to 26, 2026): every suit wears a pilgrim hat: one shared hat geometry and material from `events.js` (`tkHat`), one extra draw call each. The game reads the one Turkey Week switch on the Back Room page (see `events.js` below) once, when it loads (off means no hats are made); it has no button of its own. **Locker** (hidden: captains only for now): `locker.js` holds 36 outfits (18 sports kits, 4 robots, 4 pirates with eye patches, 6 costume-party suits, astronaut, wizard, firefighter and knight), 19 gun skins (7 of them animated: Gold, Chrome, Neon Pulse, Frostbite, Lava, Galaxy, Rainbow Flow and Circuit Board shine, pulse, flow or twinkle on one shared clock), 6 build skins, 8 elimination effects and 8 round-win celebrations, all drawn in code; the same items, by number, are Backrooms' block in `../cosmetics.js` (`backrooms-1v1`, prefix `br`). `BR_PUBLIC = false` near the top of the page is the one switch that opens it to everyone; until then `lockerOn()` asks `../captains.js` (`BackRoomCaptains.may(false, 'locker', 'br1v1-locker')`, so `?locker=1` works on localhost or in an automated browser), and a Locker button and screen appear in the menu only for those players. `locker.js` is fetched only for them, or when someone in the room wears something; for everyone else it is never loaded, `LK` stays null and the page draws, sends and saves exactly what it did before. While the shop is off everything is free to wear and what is worn is saved as `br1v1-kit`. Online it travels in the player's own node as one optional field, `lk` (a letter per slot and the item's number, e.g. `o12g3c2`: o outfit, g gun skin, b build skin, e elimination, c celebration), checked strictly; an unknown number draws the default for that slot, and a page from before the Locker ignores the field and draws the plain suit. Looks only and fair in ranked play: every outfit is built on the plain suit's own boxes (legs, body, head, sleeves, gloves) with a pack the size of the air tank on its back, so none is drawn smaller; the main colour is the team colour online (an outfit's own colours only in practice). The test hook's `__lk.fair()` draws each outfit flat from four sides against the plain suit in both team colours: outline 100–120% (hats add height), brightness never lower, colour distance from the walls and carpet never more than 0.02 lower, no more of it close to the wall or carpet colours, at least 40% of it in team colours (the rest is bold white, black, gold, silver and bright accents, never wall yellow, carpet brown or the other team's colour). Locker items use their own shared material (`lockerMat`), which adds a little of each item's own colour as light, because the dim yellow room light turns bright colours muddy; the plain suit and plain guns keep the game's own materials. Gun skins recolour the same three guns (`GUN_SRC`, cut into stripes or patches, through the same `gunFit`, so length and shape are unchanged; the sniper's lens stays). Build skins only change the picture on a piece (opaque, the same frame and brace; each measured at least as far from the walls, carpet and team colours as plywood), and a piece takes its builder's skin (a late joiner's `bs` copy of the round draws plywood). Elimination effects play where the player falls (centred on the body), for everyone, when the player who got them wears one, and are over in 1.5 s (the falling body takes 2.2 s). Celebrations play only while the round is over and the wearer's team won it, and stop as soon as they move or shoot; they move only the picture. An outfit is fewer draw calls than the plain suit (6–7 against 12) with geometry cached per outfit and team colour; skins and effects add none except two instanced meshes while an effect plays. During Turkey Week an outfit with its own hat hides the pilgrim hat. **Spanish** (lang.js): its words are in `backrooms-1v1/es.js`, text it puts together (banners, lobby, help line, results) goes through `TX()`, HUD parts that change during play are `data-noi18n`, and only team and room keys go over the network, never words. - `e63334287a3deaa3/drop-zone/`: Driftfall (Back Room; the folder is `drop-zone`), a third-person battle royale for up to 30 players on Gullrock Isle (Three.js; Firebase Realtime Database rooms under `rooms/dz-…`, same project and rules as Rumble Karts; invite links go through the home page as `#dz-`; Quick match uses the public rooms `dz-pub-1` to `dz-pub-4`, the fullest one still boarding first; online matches are people only, at least 2). It runs on the site's own three.js r187 (`/lib/three/r187/three.min.js` with its r128 layer, see `lib/three/README.md`; `../autores.js` still loads right after it) instead of r128 from cdnjs, and looks and plays as before: every edit the page and `locker-extra.js` make to a built-in shader goes through `shRep` / `shEd` (near the renderer), which names the place in the console if r187 hasn't got the text it searches for, and the few r187 differences that showed are handled where they arise (comments there say r187). Everyone rides the Drifter (a big blue cargo plane, see The Drifter below) across the island, jumps when they like on a line that changes every match, jumps when they like (Space, or Jump on a phone; anyone still aboard drops automatically as it leaves the island), falls, opens a steerable glider (Space again, or automatically about 44 m up) and lands anywhere, on roofs and hillsides too. Then it's loot, build and fight until one is left. **Island:** 240 × 240 m, with real terrain since map version 5 (hills, a ridge, cliffs, a reservoir and a shore: see Land) (it was 320 m until map version 2: the seven places were moved closer together as whole blocks on the 4 m grid, the buildings themselves are unchanged), about 40 s' run across and 57 s corner to corner at 6 m/s, built by `buildWorld()` from a few tools; each place is built inside `grp(dx, dz, dy, …)` with its shift from the old layout and the height of its pad in `OFS`, so the place code still reads in the old coordinates: `house()` (walls with doors and windows, a floor per 4 m level and a flat roof, both sitting between the walls rather than under them, zigzag ramp stairs from `zigzag()` that need a free cell at each end, a parapet, and a trim band round the outside between levels; how each is drawn is in Buildings below), `wallRun`, `slab`, `staticRamp`, props (`crate`, `bale`, `car`, `fence`, `pine`, `oak`, `rock`, `bush`). Seven places: Haybale Farm (barn with a loft and roof stairs, farmhouse, silo), Signal Point (a 20 m lattice tower with zigzag ramps), Pinecone Plaza (a two-level mall round an atrium, shops along the north side, car park), Spillway Dam (a 12 m dam wall with stair towers at both ends, a pump house), Moonbeam Motel (two wings of rooms, a balcony reached by a ramp, an empty pool), Starfall Crater (a ring of boulders round a fallen star, two sheds) and Timber Camp (log cabins and a sawmill shed), plus sheds along the tracks. Every floor and roof is at a multiple of 4 m on the same 4 m grid as builds (each place's pad is too). All static geometry is merged into 16 chunk meshes with vertex colours (one material; on the plain look no textures except the builds', the ground's and the buildings' own (see Buildings), which are mipmapped and anisotropic, and no shadow maps), the ground is one mesh over the height grid, chests, floor loot, each build kind, tracers and particles are one instanced mesh each, so a view with 30 players in the match measured 16–55 draw calls; each player is one mesh (the merged body, plus the glider when it's out), and everyone's legs are one instanced mesh and the held items one instanced mesh per kind (`legIM`, `gunIM`, filled by `syncLimbs()` just before each render from the models' leg and item `Object3D`s, which only carry the pose), so 30 players close together cost about 36 draw calls instead of about 120 (legs and items are hidden past 70 m). Solid boxes sit in a spatial hash of 8 m cells (`hash`, `rhash` for ramps), which movement, `groundAt` and the ray walk (`raycast`, cell by cell) use instead of the whole list. **Look:** characters are built from `ROUND_BOX` (a box with rounded edges and smooth shading, added with `bagRBox`), still one merged body per player with instanced legs; hitboxes were unchanged by that (they shrank with the characters later, see Character size). The Graphics setting (`driftfall:gfx`, Pretty or Fast) and `fxWatch()` pick one of three levels, applied by `lookSync()` from `drawScene()`: 0 is the plain look above (always on touch screens and on Fast); 1 adds a surface grain to the one shared material (`MAT.onBeforeCompile` lays a drawn noise texture over every face from three sides using each mesh's own coordinates, compiled in only while `MAT.defines.FINE` is set), real shadows from the sun (one 2048 px map covering 92 m around the camera, moved in whole-texel steps by `followSun()`; everything using `MAT` and the builds cast and receive, flagged by `shadowFlags()`), a sky dome with a soft sun (hidden inside the storm, where the flat purple sky takes over) and a sea that catches the light; 2 adds a light colour grade (`grade`: the finished frame is copied to a texture and redrawn with darker corners; there is no bloom, because in daylight most pale surfaces are already at full brightness). **Look after the move to r187 (November 2026):** *Both looks:* the sky is a dome whose colours come from `skySample()` (haze at the horizon equal to the fog colour, deeper blue overhead, a warm halo round the sun, soft clouds from `detailTex`); the plain look draws it baked once at load into the corners of a dome (`skyLoGeo()`, 160 × 43 corners, no texture, still clouds) in the place of the old low-poly cloud mesh (`cloudMesh`, same draw call), and Pretty works it out per pixel (`skyDome`, drifting clouds), so there is one kind of cloud on each look. The open sea pales toward the haze colour with distance from the island, baked into its corner colours (`waterGeo`). The haze opens up as the camera climbs (`lookSync`, fog numbers only), so the island reads clearly from the drop. Cliff rock is warm layered stone, dirt has broad trodden and dusty patches and grass warm and cool patches (sums in the ground shader, no extra texture reads); the pebbles in the detail texture are fewer and fainter (they read as polka dots on dirt). *Pretty only:* a little more colour and contrast from three's custom tone mapping (`CustomToneMapping`, replaced in `THREE.ShaderChunk.tonemapping_pars_fragment` at load, switched on by `lookSync()`, gentler in dark tones so players in shade stay visible): it is the colour half of the old level-2 grade, which now only darkens the corners; drawings into render targets (icons, the Locker's pictures) never get it, so items look as they did. The sea (`fineSea()`) ripples from a 256 px smooth-noise slope texture read at two sizes and angles (no tiling), reflects the sky by view angle and has a sun glint (powers by squaring, not `pow()`, which is slow in software drawing). Haze starts at 72 m instead of 110; the light is `LIGHT1` (a touch more sun, a touch less fill; the plain look keeps `LIGHT0`); indoors keeps its old brightness with darker upper walls and ceilings. Effects, from their own random numbers (`fxR`, never `Math.random`): a soft glowing line where the storm wall meets the ground (`lStormU` in the ground shader), upright beams over Rare, Epic and Legendary floor weapons and a short column in a player's colour where they are knocked out (`beamIM`, one instanced mesh, a draw call only while one is in view; `drawBeams`, `koColumn`), a few clods kicked out when a piece is built or edited (`buildDust`, the shared bit pool), and a quick flat ring of fine sparks on top of the usual pop when a shot lands on a player (`hitSpark`, called from `hitPop`; shield blue, the player's colour or gold on a headshot). All of these take their random numbers from `fxR`, never `Math.random`. *Cost,* measured side by side: the plain look has the same draw calls, the same programs and textures and the same texture reads per pixel, about 11,000 more triangles (the baked sky dome replaces the cloud mesh); Pretty has one draw call fewer (no cloud mesh) plus one while beams are in view, one more program (the beams), one texture fewer and about 0.3 MB more texture memory. Which look a computer gets is unchanged: Pretty unless Graphics is Fast or the screen is touch-first, so a Chromebook with a trackpad starts on Pretty and drops to the plain look only if its frames stay slow. Nothing played, sent or saved changed. Because it is a shooter the frame rate comes first: it starts at level 1, steps up to 2 only after about 6 s of frames under 12.5 ms, and steps down after 2 s over 18 ms once `autores.js` has lowered the resolution to 0.8 or less; a level it had to leave is not tried again that visit (`fxMax`). Level 1 roughly doubles the draw calls near buildings (the shadow pass draws the chunks around you again). Nothing about the look is sent to other players. **Flicker fixes (map version 2):** no two faces share a plane any more (floors and roofs used to share the walls' outer faces, partitions reached into the floor above, posts shared faces with slabs and railings, and the trim band was a solid slab over each upper floor that also hid the mall's atrium and the stair holes); the camera's near plane follows the view (0.08 m pulled in against a wall, 0.15 m on foot, 0.5 m in the air, 1 m on the Drifter) and the far plane is 800 m, so distant faces a few centimetres apart don't fight; the farm's stripes were 4 m wide to match the ground's 2 m vertex grid (they are 1 m furrows now that the ground is a picture, see Ground). Keep new boxes off each other's faces (stop a box 1–2 cm short, or let it pass through the other) rather than flush with them. **Movement, building and shooting** started as a copy of Backrooms 1v1–4v4 (the same jump, step and `moveEntity`/`pushOut`; the speed, the collision box and the ramp rules have since changed, see Collision, Character size and Pace), the same wall/floor/ramp binds (Q/Z, F/X, C/E) and pieces on the 4 m grid (up to 8 levels above the land under them; see Land for how they meet a slope), the same over-the-shoulder aim from the camera with rays from the muzzle, headshots and damage numbers. Builds cost 10 scrap (you start with 30); the Crowbar (V or 5, or an empty slot) gathers scrap from trees (14 a hit), rocks and walls (6–10), and loot has scrap bundles. **Destruction:** builds and most of the map break. Each weapon has its own structure damage `sd` per bullet (Pistol 24, Heavy Pistol 55, SMG 12, Drum SMG 15, Pump Shotgun 13 and Auto Shotgun 9 a pellet with their close-range falloff, AR 22, Heavy AR 40, Bolt Sniper 150, Scout Sniper 80; the Crowbar 50), scaled by rarity and distance like player damage. Builds have 150 (walls) or 140 health and darken in three stages. On the map, `buildWorld()` makes breakable *pieces* with `brk(health, scrap, fn)` (everything `fn` adds is one piece): each 4 m cell of a house wall per level (with its trim band and, on top, its parapet; 240), each 4 × 4 m cell of a floor or roof (200), partitions (150 a cell), trees (170), rocks (80 + 60 per metre of size), cars (260), the farm truck, crates, bales, fence sections, railings (in up to 4 m lengths), the motel's balcony, posts and sign, the sawmill's posts and roof and the log pile. The ground, the dam's wall, ribs and stair towers, the tower's posts and floors, the silo, the star, stairs and ground-level decorations never break, so the map stays playable. A piece is a range of vertices in the chunk meshes plus its boxes; breaking it squashes the vertices to a point (one small buffer update a frame, `mpFlush`, no extra draw calls) and takes its boxes out of the hash, so players, shots, builds and bots go through; the pieces left standing round a broken wall, floor or railing keep a ragged edge (see Buildings). Damage darkens a piece in three stages the same way. Boxes of pieces in a line (a wall's cells, a floor's row) are merged into one solid per unbroken stretch (`runs()`), so movement and rays check about as many boxes as before. `mpLink()` records which pieces touch and which touch the ground or something unbreakable; when a piece breaks, anything that has lost every path to the ground breaks too (a roof whose walls are gone), and chests and loot on it drop (`mpBreak`). The breaker gets twice the piece's crowbar scrap. Pieces are numbered in build order (1,185 of them), the same in every browser; a new match restores them (`resetMap`). **Loot** is decided by the match seed, so nobody has to send it: about 82% of the 40 chest spots have a chest each match (`spawnLoot`), and each floor spot has a 72% chance of an item (`FLOOR_R` odds); a chest gives a weapon (`CHEST_R` odds, better than the floor's) with its ammo, often a heal and sometimes scrap (`chestLoot`). Weapons (`WEAP`): ten, two in each of five families (`fam`: pistols, SMGs, shotguns, rifles, snipers), each with its own model, colour, sound, damage, fire rate, spread, range and falloff, magazine and reload, and ammo type (light, rifle, shells, heavy); see Weapons below; rarity (Common to Legendary, grey/green/blue/purple/gold) adds 7% damage a step and trims the reload. Heals (`HEALS`): Bandage +25 health (2.5 s), Medkit to full (6 s), Shield Fizz +25 shield (2 s), Shield Jug +50 shield (4.5 s); shield caps at 100 and you walk slowly while using one. Four slots (1–4, the mouse wheel, or tapping the slots); ammo, scrap, heals and weapons are picked up by walking over them when there's room, and G (or the touch Open/Take/Swap button) opens chests and swaps the item in your hand for one on the floor (with nothing in reach it edits the build you are aiming at, see Building and editing). Knocked-out players drop everything. **Storm** (`STORM`, `makeStorm`): the circle (180 m radius, `R0`) covers the island at first, then closes in six phases toward seeded centres, each pulled toward the middle if it would fall at sea (first close 70 s after the Drifter sets off; the last closes to nothing about 4¾ minutes in), and damage outside (health only) grows from 1 to 15 a second. The Drifter's line starts and ends 230 m either side of a point within 37 m of the middle, so it's always over the sea at both ends. The minimap (tap it, or M, for the big map with place names) shows the circle, the next one (dashed), the Drifter's line with a little plane on it, and you. **Rooms and matches:** each player writes only their own node `rooms/dz-/players/`: `n, c, x, z, h, ts` always (as the shared rules expect), plus `y`, `p` (pitch), `hp`, `sh`, `st` (state: `l` lobby, `b` on the Drifter, `f` falling, `g` gliding, `a` on the ground, `d` knocked out, `o` watching), `w` (what's in hand), `m` (the match), `j` (join time), `k` (knockouts), `pl` (placing), `dm` (damage), `oc` (chests they opened this match, dot-separated) and `pk` (loot they took, comma-separated, so a late joiner or a new host sees the right island), and `ev/e0`…`ev/e23`, a ring of their recent events (each with a number `i` that only goes up, the match `m` and a time `t`): `s` shots (muzzle, tracer ends, the new health of builds hit `pd` `[key, hp]` and of map pieces hit `md` `[id, hp]`, hits on players `hs`), `b` builds and edits of them (see Building and editing), `o` chest opened, `u` item taken, `dr` item dropped, `x` knocked out (by whom, placing, the dropped items). Writes are `update()`s of only the fields that changed: about 12 a second while you're moving in a match (10 with 10+ others in the room, 8 with 20+), a heartbeat every second or two otherwise. Every node also carries `mv`, the map version (2 since the island shrank, 3 for the slower pace, 4 for the November 2026 fixes: solid ramps, and later the smaller characters, the pace and the new weapons, 5 for real terrain, 6 for edited builds; a node without it is version 1). The host is the live player on the same map version who has been in the room longest; its node also carries `ms`, the match state (`{id, ph: 'lobby'|'play'|'end', ce: countdown end, sd: seed, t0: when the Drifter sets off, ro: roster, nh: people at the start, wn: winner, we: when the results end, mv: map version}`), and during a match `br: {m: match, b: …}`, the broken map pieces as a base64 bitset with trailing zeros dropped (about 200 characters with everything broken). Players apply the shooter's reported health for builds and pieces, the lowest anyone reports, but never more than one shot of that weapon could take; a late joiner, anyone who missed an event, and the next host take the rest from `br`. The host's node also lists the builds standing (`bd`, see Building and editing), so a late joiner gets them too; there's no list of broken builds, because a broken one is just not in it. **Map versions:** the host only counts people on its own version for the lobby, the countdown and the roster, and only those elect a host; a page that sees someone on a newer version says "This match uses a newer map, reload to join." with a Reload button and sits matches out; the host's lobby says how many people have an older copy. Pages from before map versions existed don't know any of this: they're simply left out of the new pages' matches. Next time the island changes, raise `MAPV`. A match starts when the host presses Start (with 2 or more people) or 60 s after a second person joins the lobby; a lone player can't start one; the Drifter line, the storm and the loot all come from `sd`, and the clock from `t0` (server time), so everyone agrees without sending them. **Bots** are in Practice only (11 of them; online matches are people only, so no bot slots, no bot list in the host's node and no bot hand-over). They're marked BOT in tags, the feed and the results, and this browser runs them: they jump, glide to a chest, loot, fight, heal, run from the storm and now and then wall up when shot; they walk straight at things where the way is clear, round cliffs, boulders and buildings by `landPath` (see Land) and in and out of buildings by the nearest ground-floor door (`setGoal`), stepping to one side when something holds them up, shoot through breakable cover (builds, walls, trees) at someone within 35 m, break through a breakable thing they're stuck against (up to ten tries) or a line of builds they can't get round (see Building and editing), and leave loot they get stuck on alone for 25 s; they don't use stairs, so upstairs loot is for people. They're tuned to be beatable: a reaction of 1–1.6 s, loose aim (0.085–0.135 rad error, more until they've watched you a while), a little over half their weapon's fire rate and rare building; a rifle bot 20 m from someone standing still does about a quarter of the damage it used to. **Hits:** the shooter's browser decides what its shots hit (`resolveShot`) and lists hits in the shot event; the victim's browser applies them only after a sanity check (`acceptHit`: a real weapon, no more than one shot of it can do, from within 16 m of where the shooter really is, within the weapon's range, and not faster than it fires), and reports its own knockout, which credits the shooter; hits on bots go to the host. If the host leaves, the next in line carries on the same match from the last `ms` it saw, with the broken pieces it already has. Someone who joins mid-match waits in the lobby panel or watches (Watch the match), and drops in at the next one; a room holds 30 (`MAX_ROOM`). Other players and bots are drawn with `netsmooth.js`. Results: placing, knockouts, damage and time, with the room's final order when the match ends. Leaderboards hooks (online matches only, which always start with at least two people): `add('matches', 1)`, `add('wins', 1)`, `max('kills', n)` (most knockouts in a match) and `min('place', n)` (best placing; `place` is in stats.js's `LOWER`). Saved in the browser under `driftfall:` keys: `name`, `col` (your colour), `sens`, `room`; keys in `keybinds:drop-zone`. Touch: a move stick, drag-to-look, Fire (Place, Use or Hit as it fits), Jump, Aim, Reload, an Open/Take/Swap button that appears when something's in reach, an Edit button that appears when the crosshair is on a build of yours, and the Crowbar, four slots and the scrap chip as buttons along the top (tap the chip to build: the three pieces appear next to it; tap it again, or a slot, to stop); the map is top right. Practice (offline) is the same match against 11 bots with no database at all, on its own clock that stops while paused. A slow frame is played in steps of at most 1/20 s (up to a quarter of a second), since the Drifter and the storm run on the clock. **Keeping it smooth (November 2026 audit):** every shader is compiled while the page loads (`warmShaders`, with the hidden meshes shown for a moment; the storm wall's used to compile, and freeze a frame, the first time it closed in), and the minimap's island picture is drawn during the menu rather than on a match's first frame (it takes about 30 ms). Sounds have a budget (`voice`: 14 nodes per 1/20 s, then only loud ones, and your own hit, hurt and pick-up sounds always), so a big fight or a building coming down doesn't build hundreds of audio nodes in one frame. The HUD only writes a value to the page when it changes (`hudSet`), name tags reuse their vectors and only move when they move a pixel, banners restart their slide-in without forcing a layout, and the storm (`stormAt`), hitboxes, the camera and movement no longer make new objects every frame. The lobby list is only drawn while the lobby is showing (every update from anyone used to redraw it, four times a second, mid-match), player names go through the name filter once (`cleanName` keeps them), and an update with no new events doesn't sort the event ring, so taking in another player's update costs about a fifth of what it did with 30 in a room. Writes are unchanged (`update()`s of the changed fields, about 50 bytes each, 10–12 a second while moving), so it plays with pages from before the audit. Each browser is trusted for its own health and hits, so it isn't cheat-proof. A test hook (`window.__dz`) exists only when `navigator.webdriver` is set. **Turkey Week** (`../events.js`, November 15 to 26, 2026): every player's cap is a pilgrim hat, built into the same body geometry (`bodyGeo`), so no extra draw calls; the game reads the one Turkey Week switch on the Back Room page (see `events.js` below) once, when it loads, and has no button of its own. **Collision (November 2026 fix):** ramps used to be a walking surface only, so a body could walk into one from the side or from under its high end and jump up through it from below, which is how people came up through stairs, ramp builds and the floors the stairs lead to. A ramp is now also a solid slab 0.36 m thick under its surface (`rampIn`, `rampBlocked`, `rampUnder` next to `moveEntity`): its side and its underside stop a body, its underside is a ceiling for a jump, and like a box it carries a body whose footprint overlaps it at all. So the map's zigzag stairs have to be walked round to the foot of each flight (the free cell at each end is for that), and two ramps built in one cell facing opposite ways no longer make a staircase. A body on the ground follows a ramp up as it moves rather than afterwards. Something built on a body (`pushOut`) moves it out the side its middle is already on, by no more than 1.2 m, never across the piece and never into a ramp; while a body is inside something it can only move back out, and can't rise. A piece built by this browser (you, a Practice bot) isn't placed if someone here would be left inside it (a floor through the head of someone on a ramp used to pop them up through it); a ramp built on someone stands them on it. Pieces arriving from other players are always placed. Loot heights come from `groundAt`, which now counts a ramp's edge, one more reason old and new pages mustn't share a match (see map versions). **Character size (November 2026):** characters were a fifth too big for the world, so everything about them is 0.8 of what it was (`BS`): the model is 1.72 m tall with its cap instead of 2.15 m and about 0.8 m across the shoulders instead of 1.0 m (the group is scaled, so the legs, the held item and the glider shrink with it); the collision box is 0.6 m wide and 1.6 m tall (`R` 0.3, `H` 1.6; was 0.72 and 1.95); the hit areas are a head box 0.45 m wide from 1.2 to 1.67 m up and a body box 0.67 m wide up to 1.2 m (were 0.56 m, 1.5 to 2.08 m, and 0.84 m up to 1.5 m), so everyone is a smaller target by about a third in area; the eye and bot-aim heights (`EYE` 1.3, `AIM_Y` 0.9), the muzzle (`MUZ_Y` 1.1) and the name tag (2 m up) follow. The camera sits 4 m behind instead of 3.5 m and 0.7 m to the side instead of 0.78 m, so a character takes about a third of the screen's height instead of nearly half. Jump height (1.7 m), step height (0.6 m), doors, walls and builds are unchanged, so doors and windows are roomier and a jump clears relatively more than it did. **Pace:** everything that sets how fast a match feels is in one block near the top (`SPEED`, `AIR`, `BUS_V`, then `WEAP`'s `dmg` and `STORM`'s times). In November 2026 it was all slowed by a sixth to a fifth (running 6.6 to 5.4 m/s, weapon damage about a sixth lower, the storm's times 1.2 times longer so the last circle closes 5:41 in rather than 4:44); running then felt sluggish, so the movement speeds came most of the way back while damage and the storm's times stayed: running 5.4 to 6.0 m/s (bots still 0.92 of it; aiming 0.7 and healing 0.45 of it as before), steering while falling 13.5 to 15 m/s and falling 25 to 28 m/s, gliding 9.2 to 10.3 m/s forward and 5.5 to 6.1 m/s down, the Drifter 20 to 22.5 m/s (it crosses the island in about 20 s instead of 23 s). **Weapons (November 2026: ten instead of five):** each family has a quick, light one and a slow, hard-hitting one, so two finds of the same family play differently. Damage a shot (headshot), seconds between shots, magazine, reload: Pistol 20 (35), 0.2, 12, 1.3 s and Heavy Pistol `hc` 42 (74), 0.55, 6, 1.7 s (silver, a fat cylinder, wood grip); SMG 12 (18), 0.075, 28, 2 s and Drum SMG `ds` 15 (23), 0.11, 40, 2.6 s (yellow, a drum under it; slower but tighter, longer range, a bigger magazine); Pump Shotgun 9 pellets of 8, 0.9, 5, 2.1 s and Auto Shotgun `as` 7 pellets of 6, 0.4, 8, 2.6 s (dark red; wider spread, 32 m instead of 40 m); AR 18 (27), 0.12, 30, 1.9 s and Heavy AR `hr` 34 (54), 0.28, 18, 2.2 s (dark teal; the most accurate when aimed, 180 m); Bolt Sniper 82 (164), 1.3, 4, 2.5 s and Scout Sniper `ss` 44 (88), 0.5, 8, 2.8 s (pale slate, a small green scope, less zoom). The old five keep their ids (`pi`, `sm`, `sg`, `ar`, `sr`) and numbers; the Shotgun and Sniper are now called Pump Shotgun and Bolt Sniper. **Names (November 2026, clearer guns):** every name is " " with the type one of Pistol, SMG, Shotgun, AR or Sniper, so it always says what kind of gun it is (the Rifle and Heavy Rifle became AR and Heavy AR; ids, saved data and network messages are unchanged); `name` is shown everywhere (hotbar, pickup prompt, pickup line, kill feed, ammo panel) and `short`, the type alone, only in a hotbar slot too narrow for the whole name (`fitSlotName`, so on a phone a slot reads PISTOL, SMG, SHOTGUN, AR or SNIPER and the ammo panel above the slots gives the whole name of the gun in hand). The two of a family share a colour, light and dark (pistols cream and silver, SMGs orange and yellow, shotguns red and dark red, ARs teal and dark teal, snipers slate and pale slate). Chests and floor loot roll all ten (`W_ODDS`: 12, 10, 11, 9, 11, 9, 15, 11, 7, 5 in the order above), so the loot a seed gives is different from before; the new ids travel in `w` (what's in hand), in shot events and in dropped and taken items, and a page from before them would reject them, which is why the map version went to 4: old pages are kept out of new matches and told to reload. To add a weapon: a row in `WEAP` (with `fam` and `col`), its id in `WIDS` and `W_ODDS`, a model in `GUN_GEO` (with the end of its barrel, which goes into `GUN_TIP`), a rarity-band position in `RTAG`, a sound in `sfxShot`, and optionally `TR_W`, `FLASH`, `KICK`, `PUNCH`, `RECOIL` and `RELOAD_ST`; then raise `MAPV`. Bots pick and use weapons by family. `ICONS` holds a small picture of every weapon, the crowbar, the two heal models and the three build pieces, drawn once at load from the same geometry the game uses (`makeIcons`). **Aiming (November 2026):** holding Aim is different for every weapon, set by four fields in its `WEAP` row: `fov` (the zoom; the normal view is 72), `ad` and `as` (how far behind and to the side the camera sits; the normal view is 4 m and 0.7 m) and `pose` (where the gun is held while aiming, seen over the shoulder: since the models were remade it is only a small lift from the normal hold, because the arms stay in the pose the body is drawn in while a weapon is held). Pistol fov 58, Heavy Pistol 50, SMG 62, Drum SMG 56, Pump Shotgun 60, Auto Shotgun 66: these six stay over the shoulder at 3 to 3.4 m; the two ARs go to the eye (`ad` 0, your own character hidden), AR fov 46 and Heavy AR 34. **Reticles (November 2026, clearer guns):** one style per family, the same from the hip and aimed (aiming only pulls it in, because the spread is smaller and the view zoomed), drawn by `RET` into `#cross` (an inline SVG, one CSS pixel per unit, put on a whole pixel in the middle of the view, 2 px white lines over a 1 px dark edge on each side so they stay sharp and read on bright sky and in dark rooms): Pistol a dot in a thin ring; SMG a small ring with four short ticks outside it; Shotgun a wide ring broken into four arcs; AR the classic four lines and a dot (the dot turns red when aimed, like a red-dot sight); Sniper from the hip a ring with cross hairs through it; the crowbar, heals and building a dot. Rings and gaps are the real spread of the shot in pixels at the current zoom (`RET.size`: `hip` or `ads`, more while moving, from `curSpread`, the same numbers the shot uses), plus a short kick of a few pixels after each of your own shots (`retKick`, `RET_KICK`) that eases back in about a tenth of a second. The snipers aim through a real scope (`#scope`: a round lens in a black surround with a rim and a darker edge to the glass, `SCOPE` sets its size and colours; Bolt Sniper fov 16, Scout Sniper fov 30 with a wider, green-rimmed lens), both with the same plain reticle (`SNIPER_RET`): thin cross hairs 1.5 px wide at any size with an open middle and a red centre point, two small marks on each arm and thick posts from the edge, with a faint pale edge so they show in a dark room. (Before, every weapon had its own sight picture in `SIGHT` and `#sight`; both are gone.) Look sensitivity already scales with the zoom. Nothing about aiming is sent to other players, so they don't see your gun raised. **Weapon models and feel (November 2026 remake):** all ten were rebuilt to the standard of Shell Crackers' guns; only looks, motion and sound changed, so damage, fire rates, magazines, spread, ranges and everything sent to other players are as they were and the map version is still 4. Each is still one merged mesh with its colours in the corners (one draw call for everyone holding that weapon and one for all of them on the ground, as before), now 300 to 770 triangles instead of 110 to 240 (Pistol 304, Heavy Pistol 508, SMG 504, Drum SMG 536, Pump Shotgun 612, Auto Shotgun 552, AR 556, Heavy AR 536, Bolt Sniper 772, Scout Sniper 676). In the clearer-guns pass (November 2026) each was pushed towards its stereotype so the family shows at a glance: the Pistol lost its under-barrel lamp (a plain slide on a frame); the Pump Shotgun's barrel is thicker; the Auto Shotgun lost its carry handle (it read as a rifle) and got shorter and chunkier: a fat barrel with a big square brake, a low rail, a fat box magazine and a solid stock; the AR has the classic black carry handle with the rear sight on it, a tall front sight post, a round ringed handguard and a black stock; the Heavy AR has a top rail with a small boxy red-dot sight, a long square handguard with a front grip, a big curved magazine and a shorter, thicker barrel with a brake (no bipod or wood any more, which made it look like a sniper); the Bolt Sniper's bipod legs now hang down and forward instead of lying folded. The Heavy Pistol stays a revolver (its reload works the cylinder) and the SMG, Drum SMG and Scout Sniper keep their shapes. `GUN_GEO` builds them from a few kinds of part: `bx` a box (optionally tilted), `ob` a bar with its long edges cut off and shaded smooth (so a body reads as rounded plastic), `cyl`, `pin` and `peg` a cylinder along the barrel, across it or upright, and `ex` a side outline pushed out sideways with bevelled edges (the stocks); `grip` and `guard` add the grip and the trigger guard every weapon shares. In a weapon's own coordinates -z is forward and the right hand (a 0.146 cube) is centred on (0, 0, 0.12): the grip goes down through the hand, the body sits on top of it, and a stock runs back over the forearm and stops at the chest (z 0.4), so with any outfit the weapon is in the hand and nothing passes through the arm or the body (before, the hand was inside the body of the gun and the stock ran through the forearm). `HOLD` is where a weapon is held: a little outside and above the middle of the hand and turned 4° outward, so its top shows over your shoulder from behind; it also tips up and down with the aim (yours, bots' and other players', from the pitch already sent). From directly behind your own character you still only see the back half of it past your shoulder (the colour, the scope, the drum, the carry handle of the AR), because the arms hold every weapon in the pose the body is drawn in; the whole outline shows on other players, on the ground, in the hotbar and when you aim over the shoulder. `GUN_TIP[id]` is the end of the barrel: the flash, the tracer and the spent case are drawn from the weapon as it is held (`gunTip`, `gunPoint`), while the shot itself still starts at `muzzleOf` and what is sent is unchanged; looking down the rifles' sights the flash and the tracer start just under the sight, and a scope shows no flash. `animModel` adds the motion, all of it turning about the hand: `KICK[id]` (how far a shot shoves the weapon back, how far the muzzle jumps and how fast it settles; the crowbar has its own swing, `SWING`, see Body and animation), the pump of the Pump Shotgun and the bolt of the Bolt Sniper worked between shots (0.2 to 1.1 s after the shot, two sounds and the case hopping out, `gunAct`; other players' too, from their shot events), a reload motion for each kind (`RELOAD_ST`: magazine out, magazine in, rack; the Pump Shotgun a shell at a time; the Heavy Pistol's cylinder; the Bolt Sniper's bolt) with a sound at each stage, and a swing up from below when an item is taken out (`userData.sw`). Reloads show for you and for bots only, since a reload is not sent. `FLASH[id]` is the size of the muzzle flash and the length of its tongue (shotguns wide and short, rifles and snipers long, SMGs a flicker; the big ones add a dimmer glow), `TR_TL` how long each family's tracer is, `shell` the spent case (a bit from the shared pool, only within 30 m; shotgun shells are red, the Heavy Pistol keeps its cases), and `PUNCH[id]` widens your view by up to 1.7° for a moment with each of your own shots (zoom only, so the aim point does not move; `updateCamera` eases it back). With reduced motion there is no kick, action, swing, case or view punch. Sounds are still made on the spot: `sfxShot` has ten shots that differ in pitch, length and tail (`burst` can now start late and sweep its filter), and `sfxPump`, `sfxBolt`, `sfxReload` (out, in, rack, shell, open, shut), `sfxSwitch` and `sfxDry` (the click of an empty weapon with nothing left to load) are new. Floor loot is the same model, turning about its own middle (`GUN_MID`) and nearly level so the outline reads, over a glow in the rarity colour with a clearer ring; past 75 m a weapon is only its glow. The rarity band on a held weapon is a cut-edged sleeve to match the bodies (`RTAG`, drawn by `rarIM` as before). **Hotbar (November 2026):** every slot shows a picture of what is in it, taken from `ICONS` (so it is the item's real model: the ten weapons, the crowbar, a first-aid box for Bandage and Medkit, a bottle for the two shields, and the three build pieces), with the rounds loaded or the count in the top right corner, the name underneath (a weapon's whole name, or just its type where the slot is too narrow) and the rarity as a bar along the bottom (`slotIcon`, `slotLabel`). Scrap has its own chip in the hotbar (`#matsBox`: a stack of planks and the count in big figures, which jumps when it changes and turns red below the cost of a piece) instead of a small line in the health panel, and each build piece shows its cost (10) next to the same little plank, greyed and red when you can't afford it. The three build pieces are only in the hotbar while you are building (`#slots.building`): the new Build key (B, `build` in the key settings, `toggleBuild`) or a tap on the scrap chip goes in with the piece you last used and comes back out, and Q/Z, F/X and C/E still go straight to a piece as before; a slot key, the crowbar or Aim leaves build mode and the pieces go away again. **Land (November 2026, map version 5):** the island is no longer flat. `designLand()` fills a grid of heights (`TH`, one every 2 m, reaching 16 m past the 240 m square for the sea bed) and `terrainH(x, z)` reads it with the very triangles the ground is drawn with, so what you see is what you stand on. Everything asks that one function: the drawn ground (`landGeo`), walking, falling, gliding and landing (`walkH`, `groundAt`, `moveEntity`), shots, sight lines and the camera (`rayTerrain` inside `raycast`), where loot, chests, props, trees and bots stand, builds, the storm's centres, the bots' paths and both maps. The grid is made from whole-number hashes, + − × ÷ and square roots only and rounded to 1/32 m, so every browser has the same land to the last bit and loot lies at the same height for everyone. Sea level is 0. Shape (`designH`): rolling noise for the low ground; smooth mounds measured from points pushed about by noise, the highest winning where they meet (Signal Point's hill at 16 m, a ridge from it east to the top of the dam at 20 m, the plateau that holds the reservoir, the farm's tableland at 8 m, a knoll on the west shore, a hillock south of the plaza, the timber shelf at 8 m); creased, ridged noise on the high ground; the crater is a real bowl whose rim is lower at four gaps; a wandering coast with round corners and beaches, and cliffs where the high north and east meet the sea. Each place stands on a level pad (`PADS`, `LVL`: farm 8 m, Signal Point 16, plaza 4, dam yard 8, motel 4, crater floor 4, timber camp 8; the five sheds on the multiple of 4 m nearest the land under them, `SHED_Y`) that blends back into the land over 6 to 12 m, and `grp()` raises everything the place adds by its level (`OFY`), so buildings, doors, stairs and ramps are exactly as they were. Single props (`onLand`: trees, rocks, bales, crates, fence sections, the crater's boulders) stand on the land under them, sunk a little. What moved: the farm's field is smaller and lies on the slope below the yard; the dam's paved yard is shorter (the valley closes in at both ends of the wall); the reservoir is real water 9 m above the yard and narrower than its old painted rectangle; one shed moved 12 m south; trees stand in clumps; two crater boulders that sat across a shed's doors are gone; a chest against a wall keeps its loot inside the room. **Slopes:** the steepest ground a body can walk up is 45° (`SLOPE_MAX`: 1 m up per metre along). Steeper land is a cliff: it stops a body like a wall, and a body that lands on one slides down it at 7.5 m/s (`SLIDE_V`) and can't jump until it is off (`e.slide`). Gentler ground is followed up as you move and stuck to on the way down, so nobody hops downhill. Where the sea is deeper than 1 m a body stays 1 m under the surface (`WADE`), and wading waist-deep is slower (0.72 of running). The camera is pushed in by the land as by a wall and is never under it. **Surface** (`landMaterial`; it replaces the 2048 px picture of the whole island, which was a blur up close): the shader decides what each pixel of ground is from its height, its slope and a small control map drawn once at load (`paintControl`: 1024 px, 512 on Fast and on phones; red is dirt, green is paving, blue is how much darker): grass with broad paler and darker patches, sand below about 1.4 m that is wet at the waterline with a line of foam, bare rock on faces steeper than about 40°, dirt for the tracks, yards, clearings and the ploughed field, paving with its joints drawn on the 4 m grid. Fine detail comes from one tiling texture made in code (`landDetail`: 512 px, 256 on Fast; blades, grain and pebbles, rock strata and concrete in its four channels), read once every 5 m and, for broad variation, at a 47 m scale, so it is sharp at your feet and the tiling never shows from the air; where two materials meet the grain decides which wins, so a track's edge is a crisp ragged line of pebbles and tufts rather than a fade. Every corner of the ground carries a baked shade: darker in hollows and where a hill or cliff stands between it and the sun. Pretty reads the 47 m scale from the texture, adds a finer layer of detail, strata mapped from both sides on cliffs and wind in the grass (six reads a pixel, as many as the old Pretty ground, one of them filtered at a slant); Fast reads two textures a pixel (the old ground read one) and takes its broad variation from a value stored at each corner of the ground. Water (`waterGeo`): the sea and the reservoir are sheets whose colour and clearness are set at each corner from the depth under them (clear turquoise shallows, solid blue further out). Scatter (`scatterLand`): grass tufts where the ground is grass (4,400 on Pretty, 1,600 on Fast, 1,200 on phones; they shrink away between 40 and 65 m) and small stones (420, or 150), two instanced meshes, neither solid. **Cost,** at the same five views before and after: draw calls are up by one to four (Pretty 18–32 before, 20–35 after; Fast 8–22 before, 9–24 after: the ground is still one mesh, the sea and the reservoir replace the sea and its shallow ring, tufts and stones add two); triangles went from 55–84 thousand to 84–114 thousand on Pretty and from 51–80 thousand to 64–94 thousand on Fast (the ground's own 37 thousand are unchanged; the rest is tufts, stones and a few more trees); the ground's textures went from about 21 MB of graphics memory to 7 MB on a computer and from 5.3 MB to 1.8 MB on Fast and phones. Frame times could only be measured in software drawing, where they were too noisy to rank (between the same and half as long again in both looks), so try it on a real school laptop before trusting it. Nothing new runs every frame except height lookups (one grid read and a few multiplies each) and the wind's clock; a 150 m ray over the land costs about 8 millionths of a second (6 before). **Builds on slopes:** the grid stays level, at multiples of 4 m, so builds still line up with buildings and each other. A wall must show at least 1.5 m above the highest land along it, and where its foot is above the land a skirt of darker planks fills the gap down to the ground (`skirtOf`, `skirtIM`: part of the same solid, one more draw call while any exist); a floor may not be more than 0.3 m under the land at the highest point of its cell; a ramp's top must stand 0.5 m clear of the land, its foot may run into the hillside and you walk onto it where it comes out; nothing may be more than 8 levels above the land under it (`landOk`). `playerBuildSpec()` and the bots take the lowest level that passes (`landFit`), so a piece is never placed underground; on a place's pad the levels are what they always were. The rule that a piece isn't built where it would trap someone is unchanged and counts the skirt. Every browser has the same land, so everyone agrees which pieces are allowed and nothing new is sent. **Bots on the land:** `buildNav()` cuts the island into 4 m cells and closes the ones that are cliff, inside a building, or filled by a boulder, the dam's wall or the foot of a stair; when the straight line to a goal crosses a closed cell (`landClear`), `landPath()` finds a way round (A*, run only when a bot picks a goal) and hands back a few corners to walk through. Deep water costs three times as much as land and high ground a little less than low; of two places to wander to, a bot usually takes the higher. Held up by a trunk or a corner, a bot steps to one side, then the other, before giving up. In stepped bots-only matches (tests only: `__dz.step`, `STUCK_LOG`) no bot gave up on a goal. **Maps:** `buildMapBg` draws the minimap and the big map from the land itself: sea by depth, sand, grass that pales with height, rock on steep faces, tracks and paving from the control map, lit from the north-west so slopes read, and a darker line every 4 m of height. To change the land: edit `designH` or `PADS` (keep every pad a multiple of 4 m), check that no cliff cuts a place off, then raise `MAPV`. **Buildings (November 2026, still map version 5):** every building, the props round them and the light they stand in were remade, without changing what is solid. `house()` makes exactly the boxes it always did, in the same order, so the 1,185 breakable pieces keep their numbers, sizes and neighbours, and stairs, doors, loot spots and the bots' paths are where they were (checked with a fingerprint of every box, piece, ramp, loot spot and nav cell before and after; a page from before the change and a new one play in the same room and break the same pieces). What changed is what is drawn. Each building has a style (`KS`: barn, farmhouse, hut, mall, pump, motel, office, mine, cabin, shed; pass `st` to `house()`): an outer and an inner wall surface, trim, a plinth, corners (boards, log ends, steel angles or concrete pilasters), window and door frames with sills, the door (a sliding barn pair, a leaf folded back against the wall, a steel leaf with a hazard band, or none), shutters, flower boxes, a canopy or porch roof over doors, the roof edge (eaves on rafter ends, a stepped cornice, or a fascia with a neon tube), a capped parapet, the roof, floors, a floor laid on the ground indoors, ceilings and skirting. `kitWall()` adds all of that to a wall cell inside the cell's own `brk()`, so it breaks with the cell and nothing is left hanging; a building can add its own extras per wall cell (`x`), roof cell (`rx`) and floor cell (`fx`): the barn's hatch, hoist, beams and vents, the mall's name, skylights, coolers and strip lights, the hut's cooler and dish, the pump house's risers, the office's and motel's signs, the cabins' chimney breasts. The drawing tools: `kb()` (a detail box: drawn only, never solid, only the faces asked for), `wk()` (the same in a wall's own terms: along it, up, out from its face), `deco()` (any other shape, turned any way), `sign()` (raised block letters from a small dot font, `FONT`, drawn cell by cell so each letter breaks with its piece of wall), `lampPost()` and `bays()`; `FK` makes `sbox()` draw its box with a different surface on each face, and `NOVIS` makes it count toward its piece's size without being drawn (the kit draws it instead). Detail drawn while `DECO` is set, and everything from `kb()`, doesn't count toward a piece's size, because that size decides which pieces touch and hold each other up. To add detail: draw it with these inside the piece's `brk()` and never call `solid()`; keep anything that isn't solid thin, low (under about 0.4 m), flat against a wall or above head height, so nobody can hide inside something shots pass through. Anything that changes a solid box, a doorway, a stair or the number or order of pieces needs `MAPV` raised. **Surfaces** (`KIT_TEX`, `TX`): one array texture with eighteen layers, each a 2 m tile drawn in code at load (upright boards, clapboard, brick, stucco, corrugated sheet, cast concrete, shingles, logs, floor tiles, roofing felt, glass, riveted panels, straw, stone blocks, hazard stripes, and since the audit natural rock with cracks and lichen for `rock()`, bark for trunks and leaf clumps for canopies and bushes, `TX.RK`, `TX.BK`, `TX.LV`), laid on in metres from each face's own position, so a plank or a brick is the same size on every wall (128 pixels a metre; 64 on phones). A layer is a pale pattern tinted by the wall's paint (its vertex colour), except where its alpha is 0, where it keeps its own colour (mortar, nail heads, stripes). The island's chunks carry one more attribute, `dzA`: the layer, the height above the foot of the thing (the shader darkens and dirties the bottom metre or so of every wall, post and trunk) and how far indoors a face is (indoor faces are dimmer, more so on Fast, which has no shadows to do it). Each building has its own slight colour cast (`TINT`). It needs WebGL 2; without it the island keeps plain paint. One texture read a pixel on both looks, and no new passes. **Stairs, railings, props:** the map's stairs are drawn as sixteen steps over a soffit (what is walked on is still the smooth ramp); railings are panels with a cap rail and a post; cars and the farm's tractor are rounded toy vehicles with wheels, lights and bumpers inside the same solid boxes; crates are banded planks and bales are straw; the motel has loungers, a tiled pool with lane lines and a ladder and its name in raised letters with neon round it; the plaza's planters have a timber seat round the rim and its cars stand in painted bays under lamp posts (drawn only: a pole is 12 cm thick); the silo is ribbed and hooped with a ladder; the tower has white bands, cross braces above the first floor and a mast with drums, panels and a beacon; the dam is cast concrete with sluice gates, its name and lamps along the walkway; the sawmill stands on stone pads under a tin roof on rafters, with plank stacks and stumps; shards stand out of the fallen star. **Broken edges:** a wall, floor, roof or railing piece that breaks no longer leaves a clean hole: the pieces still standing round it keep a few jagged stubs of it where it joined them, and a wall that stood on the ground leaves rubble along its foot (`shardsFor`, one instanced mesh, `shardIM`, up to 1,200 stubs, a draw call only while something is broken). Stubs are drawn only; a stub goes when the piece it hangs on goes (`shardsOff`); which stubs exist depends only on what is broken, so everyone sees the same and a late joiner gets them from the broken list. **Light:** the sun is where it was (a roof, the two sunlit sides and the two shaded sides of a building are different tones); the fill light's ground colour is pale stone instead of grass green and a little stronger (0.58, ambient 0.11), so walls in shade keep their own colour instead of going olive. Shadows (Pretty) are unchanged and sit under the new eaves, canopies, sills and the balcony; the darker foot round every building on the ground was already there. **Cost,** at five views, before and after: draw calls are unchanged (16–25 on Pretty, 16–24 on Fast, not counting the shadow pass, which draws the chunks near you again); triangles went from 96–111 thousand to 121–150 thousand on Pretty and from 79–94 thousand to 99–125 thousand on Fast (Fast, as set when the page loads, and phones leave out the kit's smallest pieces, `KLITE`); the chunks' vertices went from 109 thousand to 224 thousand (about 4 MB to 11 MB of graphics memory with the new attribute); the surfaces add one texture of 5.2 MB (1.3 MB on phones). Frame times could not be measured here (software drawing), so try it on a real school laptop and a phone. Not done: a simpler version of far buildings (the island is 240 m across and already 16 meshes), filmic tone mapping and sRGB output (they would change every colour in the game, guns and characters included), ambient occlusion and bloom passes, glass in windows (windows stay open holes because shots pass through them), pitched roofs (roofs are walked on), benches and big roof clutter such as tanks (they would need new solid boxes, which needs a new map version). **Building and editing (November 2026, map version 6):** building was a copy of Backrooms 1v1–4v4's from the start (the same placing from your own cell and the way you face, the same 0.09 s build clock, so holding Place while you move or turn puts up about ten pieces a second, the same ghost and sounds), and it now has Backrooms' editing too, on Driftfall's own pieces, so there is still one build system. Also carried over: a new piece pops in from 0.82 of its size in about a ninth of a second (`piecesTick`; not with reduced motion); the ghost shows what you will get, a wall's skirt included (it used to show only the 4 m box, which floats above a slope); every piece knows who built it (`owner`: a player's id, a Practice bot's, `me` in Practice). Kept from Driftfall: 10 scrap a piece (an edit is free), the land rules and skirts, the rule that a piece isn't built where it would trap someone, the 4 m grid, health and the three shades, build mode and the hotbar. **Editing:** aim at a wall, floor or ramp you built from within 6 m (`EDIT_RANGE`) and press Edit (H, `edit` in the key settings, because G is Open / Take here and T is the chat; G does it too when nothing is in reach to open or take; on a touch screen an Edit button appears while the crosshair is on a build of yours): the piece turns into a grid of tiles, 3 × 3 on a wall and 2 × 2 on a floor or a ramp (a ramp's are its low and high halves, left and right). It works as in Backrooms (one copy of the code, see there): **Edit on release** is a setting, on by default, in the menu next to the faces switch and on the pause screen (`driftfall:editOnRelease`): hold Edit (or G when it is doing the editing), the tiles the crosshair sweeps across are picked, and letting go confirms; a quick tap leaves the grid open, and then (or with the setting off) Fire opens or closes the tile under the crosshair and Edit again confirms. Reload resets the piece to whole and Aim cancels; the touch buttons read Tile, Done, Reset and Cancel meanwhile, and a finger put down on the grid picks the tiles it touches, so on a phone you hold Edit, drag the other thumb over the tiles and let go. The line of help names the shape and spells everything out until your first confirmed edit (`driftfall:editHelp`); targeting is as generous as Backrooms' (`edTileAt`, `EDIT_FAN`), and your own body is hidden while the grid is up. At least one tile has to stay. Nothing changes until you confirm, and then the new shape is there at once (it used to land 0.4 s later); you can't shoot while the grid is up, and a Fire still held from picking tiles doesn't fire until it's let go. Driftfall has no teams, so your side is you: the only builds you can edit are the ones you placed, never another player's or a bot's. Picking a slot, the crowbar or a build piece, opening the big map, being knocked out or going more than 10 m away closes the grid and changes nothing. **Shapes:** a piece's shape is `ed`, one bit per tile cut out (tile (u,v) is bit `v*n+u`; 0 is the whole piece), with Backrooms' own `ED_N`, `edRects` and `pieceShape`: the tiles left are joined into as few rectangles as it takes, and each rectangle is one ordinary box in the spatial hash, or for a ramp one ordinary ramp sheet with a smaller footprint, so there is no second collision system: you walk through a door and shoot through a window because no box is there. For that, every ramp (the map's stairs too) is now a sheet with a footprint `ax0`…`az1` and a range `t0`…`t1` up its slope (`addRamp` gives the map's the whole cell), and `rampH`, `rampUnder`, `rayRamp` and the ceiling test in `moveEntity` read those instead of assuming the cell; a whole piece is the one box or sheet it always was. A wall's skirt is not part of the grid: under an edited wall it is a box of its own, the full width, from the land up to the wall's foot, so a door cut where the land is lower has a sill (walked over if it is under 0.6 m, jumped onto if it is more). The trap rule covers edits: tiles are not put back onto someone in this browser who can't simply be nudged clear (`wouldTrap`; you are told someone is in the way), and a door put back with you standing in it moves you out. **Drawing:** whole pieces stay in the three instanced meshes; an edited piece's rectangles are unit boxes in one more instanced mesh shared by every edited piece of every kind (`partIM`, `partsOf`; each box's window of the plank texture is a per-instance attribute, `uvw`, so the planks run on across a cut), which makes thirty edited pieces one draw call, not thirty (measured: 36 calls with thirty whole pieces in view, 34 with the same thirty edited, the three kinds' own meshes then being empty); the grid you see while editing is three more, in place of the piece, and only on your screen. **Online:** an edit travels as the build event for that spot again with `ed` and `n` added (`n` counts the piece's edits, so an older shape never replaces a newer one), and is taken only from the player who built the piece. The host's node also carries `bd: {m, s}`, the builds standing, nine characters a piece (kind and direction, x, z, level, `ed`, `n`, and the builder as a place in the roster; `buildList`), written again at most every two seconds: a late joiner gets every piece in its shape from it, and a page that missed a build or an edit catches up (`applyBuilds`). A page never removes a piece because of the list (a build the host itself missed stays missing for the host), and doesn't put back one it saw break in the last 8 s. A page from before this would keep the whole piece where a door was cut, and the two would disagree about what is solid, so the map version went to 6: older pages are kept out of new matches and told to reload, the usual way. **Bots** don't edit. They see and shoot through openings only (their sight line and their shots are the game's rays), walk through a door that is in their way, and break the part of a build that holds them, looking at head and shin height as well as chest height (`botBreak`), since an edited piece can hold a body by its top or its bottom alone. A bot that slides to and fro along a line of builds for two seconds without getting nearer its goal now breaks through it (stepping aside never came to a stop, so it never counted as stuck; that was so before editing too). **Checked** with the game's own movement and shots against the tiles themselves: on flat ground every one of the 511 wall shapes both ways round (275,940 shots straight and slanted through every tile from both sides, 14,308 walks, 840,000 moves of thrown and jumping bodies at 60, 30 and 20 frames a second), all 15 floor shapes and all 15 ramp shapes in all four directions; on slopes 14 walls with skirts of 0.5 to 3.7 m in 20 shapes each (shots at every tile and at the skirt, 1.7 million moves, doors walked through where the land allows and stopped by the sill where it doesn't), and 8 floors and 8 ramps in every shape; whole pieces compared number for number with the page before (37 pieces on flat and sloping ground, 444,000 moves and 11,100 rays, all identical). Weak or not done: the first wall on rising ground can still show as little as 1.5 m above it (the land rule from map version 5 was left alone); you still start with 30 scrap, three pieces, so a build fight needs the crowbar first; on a phone the build pieces are still behind the scrap chip; a body that another player's build lands on can still be left inside it (as before: only this browser's own builds and edits are refused). **Spanish (November 2026):** the whole game has Spanish through `../lang.js` (switch in the menu's settings and the pause menu), with Driftfall's words in `drop-zone/es.js`; the menus, lobby, results, Creative tools, Face and Locker are translated by lang.js, while the HUD, banner and kill feed are `data-noi18n` and put their words through `T()` (an exact lookup in es.js's list, cheap enough for every frame), and player names, room codes and place names are never translated, nothing translated is sent, and a weapon's rarity is written out per weapon in es.js because Spanish adjectives agree with the noun (`'Rare Pump Shotgun'`), with an extra shorter word (`'Shotgun (tight)'`) for the narrowest phone slots. -- `e63334287a3deaa3/ironveil/`: Midnight Ops (**preview, admin page only**; Back Room folder; the folder keeps the working title `ironveil`, and the display name lives in ONE constant, `IV.GAME_NAME` in `js/core.js`, which fills the page title, the logo, the content note and the "turn your phone" card, so the name can change without touching anything else), a single-player first-person Second World War campaign (an over-the-shoulder view stays in Settings as "View") (three.js r187 from the site's own build, `/lib/three/r187/three.min.js` plus `three-addons.min.js` for GLTFLoader and SkeletonUtils, see `lib/three/README.md`; plus `../autores.js`, `../keybinds.js`, `/e63334287a3deaa3/lang.js` with its own `es.js`, `stats.js`; Web Audio; no Firebase, nothing online). v1 has **Boot Camp** (a five-minute training course) and **Mission 1, Night Drop**; missions 2 to 8 are listed on the map table as "Coming soon" with their one-line briefings (`IV.menus.COMING` in `js/menus.js`). **Content note and blood:** the first time the game opens (until accepted) a screen before the title says it contains war violence and blood, with an "I understand, continue" button and a Back link (`localStorage` `ironveil:terms` = `1`). Settings has a **Blood effects** switch (on once accepted): off turns every blood effect (hit puffs, spray, the small fading decals, which are capped at `TUNING.blood.decals`, the screen-edge flecks) into dust. No dismemberment, gore close-ups or executions, no hate symbols: the enemy wears field grey with a plain invented white chevron on the helmet. **Files:** `index.html` (page, styles, HUD and menu markup), `js/core.js` (namespace, the one `TUNING` object with every feel number and its units, maths, seeded noise, settings and save), `world.js` (renderer, quality presets Low/Medium/High, sky, moon and fog, the heightfield, colliders in an 8 m spatial hash, ray casts, how lit a point is for stealth), `kit.js` (merged static geometry with world-space UVs, hedgerows, walls, fences, trees, buildings with real door and window openings, props, instanced grass and crops), `env/` (the environment kit, `window.IVEnv`, made separately: ground, grass, trees, hedges, walls, props, atmosphere and decals, all generated in code (its `env/post.js` is Ironwing's now; Midnight Ops draws through `js/render.js`); loaded with plain script tags before the game's own files; `?noenv` shows the old code-made stand-ins), `art.js` (the art factory: every hedge, wall, fence, tree, building, prop, pole, crop field, grass, the stream, the atmosphere and the bullet-impact hook go through `IV.art.*`; when `window.IVEnv` (the environment art module in `ironveil/env/`) is loaded it draws them and `kit.js` only makes the colliders, so layout, collision, nav and cover never change with the look), `nav.js` (0.5 m walk grid, A*, string pulling, cover points), `player.js`, `camera.js` (over-the-shoulder camera with collision, shoulder swap, the scope, aim assist), `weapons.js` (every bullet is a projectile with drag, gravity and wind; the scope's drop marks are computed from the same simulation), `ai.js`, `ally.js`, `fx.js`, `audio.js` (all synthesised), `hud.js`, `menus.js`, `touch.js`, `main.js` (fixed 60 Hz step with interpolation, app state, test hooks), `missions/bootcamp.js`, `missions/nightdrop.js`, and `js/chars-standin.js` (see Characters). **Saving:** `localStorage` `ironveil:save` = `{v: 1, diff, missions: {id: {done, medal, best, last}}, settings: {...}, cp: {mission, diff, idx, data}, tut}`; `cp` is the last checkpoint (its `data` holds the mission's flags, which soldiers are dead, objectives, ammunition, the clock and stats), so Continue on the title resumes there; finishing a mission clears it. Key bindings are `keybinds:ironveil`, the language is the Back Room's `lang:v1`. Bump `v` and migrate in `load()` if the shape changes. **Missions are data plus a few functions**, registered with `IV.missions.register({id, num, title, line, briefing: [...], preview: [{text, opt}], world: {size, day, height(x,z), surface(x,z), groundColor(x,z,y,n,c), waterLevel?, fog, fogColor}, build(M), setup(M, cpIndex, data), step?(M, dt), frame?(M, dt), sketch(g, w, h, sk), medals: [{text, ok(stats, M)}] x3})`. `build` makes the static world once (kept while you replay); `setup` places the player, squadmate and soldiers for a checkpoint and starts the script. The script uses `M.obj(id, text, {optional, marker})`, `M.done(id)`, `M.when(cond, fn)`, `M.after(sec, fn)`, `M.interact({x, z, r, text, hold, done})`, `M.say(text)` / `M.hq(text)` (radio subtitles, text only), `M.checkpoint(n)`, `M.fail(reason)` and `M.complete()`; the medal lines (the mission's own plus a skill rating of 700 or better) give gold (every line), silver (all but one) or bronze. To add a mission: copy `missions/nightdrop.js`, give it the next `num` and a new `id`, add its ` - - - - - - - - - - diff --git a/e63334287a3deaa3/ironveil/chars.js b/e63334287a3deaa3/ironveil/chars.js deleted file mode 100644 index 1e68b4f7..00000000 --- a/e63334287a3deaa3/ironveil/chars.js +++ /dev/null @@ -1,1425 +0,0 @@ -/* - * Ironveil characters (window.IVChars) for three.js r187 (the site's global build in /lib/three/r187/). - * - * Load after three.min.js and three-addons.min.js (GLTFLoader, SkeletonUtils) and env/core.js (IVEnv.patch). It loads - * the meshopt decoder from assets/lib/ if the page has not. - * IVChars.load(onProgress) -> Promise fetches hero, ally, enemies, clips and weapons (about 9 MB) - * IVChars.spawn(kind) -> actor 'hero','ally','rifleman','officer','sniper','gunner' - * IVChars.weapon(kind[, {lod:true}]) -> Object3D 'rifleScoped','smg','pistol','enemyRifle','enemySmg','mg','knife','binoculars','grenade','stickGrenade' (lod: reduced rifle/SMG for others) - * IVChars.tris(kind), IVChars.info, IVChars.clips (names), IVChars.camera (set it for LOD + far-actor throttling) - * Actor (1 unit = 1 m, feet at the origin, facing +Z): - * actor.root, play(name,{fade,loop,speed,once}), setUpper(name|null), setAim(pitch,yaw), attach(obj,socket), detach(obj), - * bone(name), height, setVisible(b), update(dt), dispose(), plus: actor.clipLength(name), actor.isPlaying(name), - * actor.onFinished = fn(name) for one-shot clips, actor.leftHandIK (0..1 override, default automatic). - * If any file fails, a code-made skinned human with procedural animation is used instead (info.fallback = true). - * - * First person: the gun and hands the player sees are js/vm.js and js/hands.js (not this file). - * actor.setFirstPerson(true|false) the player's body for looking down: no head, neck or arms, eyes/hair and the - * held weapon hidden, a full shadow kept (an invisible copy casts it); call after attach(). - * - * Integration notes for the game: - * - Skeleton (all kinds share it): root, pelvis, spine_01..03, neck_01, Head, clavicle_l/r, upperarm_l/r, lowerarm_l/r, - * hand_l/r, finger bones, thigh_l/r, calf_l/r, foot_l/r, ball_l/r, plus weapon_r (a prop bone under hand_r that - * attach(obj,'handR') uses, so reload/bolt clips can move the gun independently of the hand). - * - Clips are in place (no root motion). vault: move the root ~1.3 m forward over its 1.1 s. takedown/takedownVictim: - * place the victim 0.42 m in front of the attacker, same facing, start both together (2.6 s). - * Deaths, hit, throw, reload, fire* etc. play once and hold their last frame (see ONESHOT); actor.onFinished(name). - * - Extra clips beyond the brief: holdRifle, holdPistol, aimPistol, firePistol, fire, fireCrouch, fireCover, aimCover, - * sprintRifle, stackUp, wallLean, breachKick, signalMoveUp, stagger, deathRun, limp. IVChars.clips lists them all. - * - A long gun or pistol in handR automatically layers holdRifle/holdPistol on the upper body unless setUpper() is used - * or the full-body clip already carries the weapon. The left hand is pulled onto weapon.userData.gripL by IK in the - * aim/hold/fire clips (actor.leftHandIK = 0..1 forces it). - * - Set IVChars.camera = yourCamera for the LOD switch (IVChars.lodDistances = [mid, far] metres, default [12, 30]; - * every kind has a ~5k mid and a ~1.8k far mesh; set lower distances on low quality) and for updating far - * actors (beyond IVChars.throttleDistance, default 45 m) every other frame. - * A full weapon model held by anyone but the hero switches to its reduced model beyond IVChars.weaponLodDistance (6 m). - * - Weapons: barrel along +Z, up +Y, origin at the right-hand grip; userData.muzzle (Object3D, use its world position), - * userData.gripR / gripL (hand frames). Drop a gun on death with actor.detach(gun) and add it to the scene. - * Assets and their licences: CREDITS.md. Pipeline notes: README section "Ironveil characters". - */ -(function () { - 'use strict'; - if (!window.THREE) { console.warn('IVChars: three.js missing'); return; } - var T = THREE; - var SCRIPT = document.currentScript && document.currentScript.src; - var BASE = SCRIPT ? SCRIPT.replace(/[^\/]*$/, '') : ''; - var ASSETS = BASE + 'assets/'; - var VERSION = '12'; // bump whenever any file in assets/ changes, so browsers fetch the new copies - - // ---------- kinds and files - var FILES = { - hero: 'hero.glb', ally: 'ally.glb', enemy: 'enemy.glb', anims: 'anims.glb', weapons: 'weapons.glb' - }; - // which meshes of which file make each kind (enemy.glb holds all four enemy outfits + their LODs on one body) - var KINDS = { - hero: { file: 'hero', meshes: ['Hero', 'HeroHair', 'HeroEyes'], lod: ['HeroLOD1', 'HeroLOD2'] }, - ally: { file: 'ally', meshes: ['Ally', 'AllyHair', 'AllyEyes'], lod: ['AllyLOD1', 'AllyLOD2'] }, - rifleman: { file: 'enemy', meshes: ['Rifleman', 'EnemyHair', 'EnemyEyes'], lod: ['RiflemanLOD1', 'RiflemanLOD2'] }, - officer: { file: 'enemy', meshes: ['Officer', 'EnemyHair', 'EnemyEyes'], lod: ['OfficerLOD1', 'OfficerLOD2'] }, - sniper: { file: 'enemy', meshes: ['Sniper', 'EnemyHair', 'EnemyEyes'], lod: ['SniperLOD1', 'SniperLOD2'] }, - gunner: { file: 'enemy', meshes: ['Gunner', 'EnemyHair', 'EnemyEyes'], lod: ['GunnerLOD1', 'GunnerLOD2'] } - }; - var WEAPONS = ['rifleScoped', 'smg', 'pistol', 'enemyRifle', 'enemySmg', 'mg', 'knife', 'binoculars', 'grenade', 'stickGrenade', 'rifleScopedLod', 'smgLod']; - var LONG = { rifleScoped: 1, smg: 1, enemyRifle: 1, enemySmg: 1, mg: 1 }; - - // clip aliases: API names that are served by another clip (documented in README) - var ALIAS = { - takedownVictim: 'takedownVictim', crouchAimWalk: 'crouchWalk' - }; - // clips where the left hand belongs on the weapon's fore-end (left-hand IK on when a long gun is in handR) - var TWO_HAND = { aimIdle: 1, aimWalk: 1, crouchAim: 1, holdRifle: 1, sprintRifle: 1, fire: 1, fireCrouch: 1, fireCover: 1, - proneAim: 1, proneIdle: 1, stackUp: 1, boltCycle: 0, aimPistol: 1, firePistol: 1, holdPistol: 0, wallLean: 1, limp: 1, aimCover: 1 }; - // clips that play once and hold their last frame unless {loop:true} is passed - var ONESHOT = { deathLeft: 1, deathRight: 1, deathCover: 1, reload: 1, boltCycle: 1, throw: 1, melee: 1, takedown: 1, takedownVictim: 1, vault: 1, hit: 1, deathFront: 1, deathBack: 1, - deathRun: 1, salute: 1, fire: 1, firePistol: 1, fireCrouch: 1, fireCover: 1, breachKick: 1, signalMoveUp: 1, stagger: 1 }; - - var IV = window.IVChars = { - info: { loaded: false, fallback: false, files: {}, bytes: 0, errors: [], version: VERSION }, - clips: [], camera: null, lodDistance: 22, lodDistances: [12, 30], throttleDistance: 45, weaponLodDistance: 6 - }; - var META = {}, gltf = {}, CLIPS = {}, UPPER = {}, LOWER = {}, TEMPLATES = {}, WTEMPLATES = {}, TRIS = {}, upperSet = null; - - // ---------- script loading (the meshopt decoder; GLTFLoader and SkeletonUtils come with three-addons.min.js) - function addScript(src) { - return new Promise(function (res, rej) { - var s = document.createElement('script'); s.src = src; s.onload = res; s.onerror = function () { rej(new Error('script ' + src)); }; - document.head.appendChild(s); - }); - } - function needLibs() { - if (!T.GLTFLoader || !T.SkeletonUtils) return Promise.reject(new Error('chars.js needs /lib/three/r187/three-addons.min.js')); - return (window.MeshoptDecoder ? Promise.resolve() : addScript(ASSETS + 'lib/meshopt_decoder.js')).then(function () { return window.MeshoptDecoder && MeshoptDecoder.ready; }); - } - - function loadGLB(name, prog) { - return new Promise(function (res, rej) { - var l = new T.GLTFLoader(); - if (window.MeshoptDecoder) l.setMeshoptDecoder(window.MeshoptDecoder); - l.load(ASSETS + FILES[name] + '?v=' + VERSION, function (g) { res(g); }, function (e) { prog(name, e.loaded, e.total || 0); }, function (e) { rej(e); }); - }); - } - - // ---------- material tweaks - function prepMaterial(m) { - if (!m) return; - if (/Eye/.test(m.name)) { m.roughness = 0.08; m.metalness = 0; m.envMapIntensity = 1.4; return; } // wet eye: sharp catchlight - if (/Hair/.test(m.name)) { - m.alphaTest = 0.5; m.transparent = false; m.depthWrite = true; m.side = T.DoubleSide; - m.roughness = 0.55; m.metalness = 0; - } else if (!m.metalnessMap) { - m.metalness = 0; - } - if (m.normalMap) m.normalScale.set(1, 1); - if (m.map) m.map.anisotropy = 4; - if (window.IVEnv && IVEnv.rimPatch) IVEnv.rimPatch(m); // edge light so a soldier reads against the dark (env/rooms.js) - } - - // ---------- clips - function prepClips(anims) { - var bones = {}; - anims.forEach(function (c) { - c.tracks = c.tracks.filter(function (t) { - var bn = t.name.split('.')[0], prop = t.name.split('.')[1]; - bones[bn] = 1; - if (prop === 'scale') return false; - if (prop === 'position' && bn !== 'pelvis') return false; - return true; - }); - }); - // upper body = spine_01 and everything below it in the hierarchy (bone names from the shared skeleton) - upperSet = {}; - ['spine_01', 'spine_02', 'spine_03', 'neck_01', 'Head', 'weapon_r'].forEach(function (b) { upperSet[b] = 1; }); - Object.keys(bones).forEach(function (b) { - if (/(clavicle|upperarm|lowerarm|hand|thumb|index|middle|ring|pinky)_/.test(b)) upperSet[b] = 1; - }); - anims.forEach(function (c) { - CLIPS[c.name] = c; - UPPER[c.name] = new T.AnimationClip(c.name + '#U', c.duration, c.tracks.filter(function (t) { return upperSet[t.name.split('.')[0]]; })); - LOWER[c.name] = new T.AnimationClip(c.name + '#L', c.duration, c.tracks.filter(function (t) { return !upperSet[t.name.split('.')[0]]; })); - }); - IV.clips = Object.keys(CLIPS); - } - function clipName(n) { - if (CLIPS[n]) return n; - if (ALIAS[n] && CLIPS[ALIAS[n]]) return ALIAS[n]; - return null; - } - - // ---------- templates - function triCount(o) { - var n = 0; - o.traverse(function (m) { if (m.isMesh) { var g = m.geometry; n += (g.index ? g.index.count : g.attributes.position.count) / 3; } }); - return Math.round(n); - } - function buildTemplate(kind) { - var def = KINDS[kind], g = gltf[def.file]; - if (!g) return null; - var keep = {}; - def.meshes.concat(def.lod || []).forEach(function (n) { keep[n] = 1; }); - var src = g.scene; - // clone the whole file once per kind, then drop meshes of the other kinds - var root = T.SkeletonUtils.clone(src); - var drop = []; - root.traverse(function (o) { - if (o.isMesh) { - var nm = meshName(o); - if (!keep[nm]) drop.push(o); - } - }); - drop.forEach(function (o) { o.parent.remove(o); }); - var tris = 0, lodTris = [0, 0, 0]; - root.traverse(function (o) { - if (!o.isMesh) return; - prepMaterial(o.material); - o.castShadow = true; o.receiveShadow = false; - var g2 = o.geometry; - // skinned bounds: generous sphere around the body so animated limbs (prone, deaths) never pop out - g2.boundingSphere = new T.Sphere(new T.Vector3(0, 0.9, 0), 1.45); - var nm = meshName(o); - o.userData.lod = (def.lod || []).indexOf(nm) + 1; // 0 full, 1 mid (~5k), 2 far (~1.8k) - var c = (g2.index ? g2.index.count : g2.attributes.position.count) / 3; - if (o.userData.lod) lodTris[o.userData.lod] += c; else tris += c; - }); - TRIS[kind] = { tris: Math.round(tris), lod: Math.round(lodTris[1]), lod2: Math.round(lodTris[2]) }; - return root; - } - function meshName(o) { - // GLTFLoader names a single-primitive mesh after its node; multi-primitive meshes become groups - var n = o.name || ''; - if (o.parent && o.parent.isGroup && o.parent.name && !o.parent.isBone) n = o.parent.name; - return n.replace(/_\d+$/, ''); - } - - function prepWeapons(g) { - g.scene.updateMatrixWorld(true); - WEAPONS.forEach(function (k) { - var o = g.scene.getObjectByName(k); - if (!o) return; - o.traverse(function (m) { if (m.isMesh) { prepMaterial(m.material); m.castShadow = true; } }); - WTEMPLATES[k] = o; - TRIS[k] = { tris: triCount(o) }; - }); - } - - // ---------- load - IV.load = function (onProgress) { - if (IV._loading) return IV._loading; - var seen = {}, totals = { hero: 2.9e6, ally: 2.9e6, enemy: 3.2e6, anims: 1.2e6, weapons: 8e6 }; - function prog(name, loaded, total) { - seen[name] = loaded; if (total) totals[name] = total; - var a = 0, b = 0; - for (var k in totals) { a += Math.min(seen[k] || 0, totals[k]); b += totals[k]; } - if (onProgress) try { onProgress(Math.min(0.99, a / b)); } catch (e) {} - } - IV._loading = needLibs().then(function () { - var names = IV.forceFallback ? [] : Object.keys(FILES); - return Promise.all(names.map(function (n) { - return loadGLB(n, prog).then(function (g) { gltf[n] = g; IV.info.files[n] = 'ok'; }, function (e) { - IV.info.files[n] = 'failed'; IV.info.errors.push(n + ': ' + (e && e.message || e)); - }); - })); - }).then(function () { - if (gltf.anims) prepClips(gltf.anims.animations); - return Promise.all([ - fetch(ASSETS + 'anims.json?v=' + VERSION).then(function (r) { return r.json(); }).then(function (j) { META = j; }, function () { META = {}; }) - ]); - }).then(function () { - if (gltf.weapons) prepWeapons(gltf.weapons); - Object.keys(KINDS).forEach(function (k) { - var t = buildTemplate(k); - if (t) TEMPLATES[k] = t; - }); - if (!gltf.anims || !TEMPLATES.hero) IV.info.fallback = true; - IV.info.loaded = true; - for (var k in seen) IV.info.bytes += seen[k]; - if (onProgress) try { onProgress(1); } catch (e) {} - return IV; - }).catch(function (e) { - IV.info.errors.push(String(e && e.message || e)); IV.info.fallback = true; IV.info.loaded = true; - if (onProgress) try { onProgress(1); } catch (e2) {} - return IV; - }); - return IV._loading; - }; - - IV.tris = function (kind) { - if (TRIS[kind]) return TRIS[kind].tris; - return kind in KINDS || WEAPONS.indexOf(kind) >= 0 ? (FB.tris || 0) : 0; - }; - IV.lodTris = function (kind, level) { return TRIS[kind] ? (level === 2 ? TRIS[kind].lod2 : TRIS[kind].lod) || 0 : 0; }; // mid (1, default) or far (2) - - // ---------- weapons - IV.weapon = function (kind, opts) { - var src = opts && opts.lod && WTEMPLATES[kind + 'Lod'] ? kind + 'Lod' : kind; // reduced model (other characters, distance) - var t = WTEMPLATES[src], o; - if (t) { - o = t.clone(true); - o.position.set(0, 0, 0); o.quaternion.identity(); o.scale.set(1, 1, 1); - o.userData.kind = kind; - o.userData.muzzle = o.getObjectByName(src + '_muzzle') || o; - var gr = o.getObjectByName(src + '_gripR'), gl = o.getObjectByName(src + '_gripL'); - o.userData.grip = { r: gr || null, l: gl || null }; - o.userData.gripR = gr; o.userData.gripL = gl; - } else { - o = FB.weapon(kind); - } - o.userData.long = !!LONG[kind]; - return o; - }; - - // ---------- math helpers - var _v1 = new T.Vector3(), _v2 = new T.Vector3(), _v3 = new T.Vector3(), _v4 = new T.Vector3(), _v5 = new T.Vector3(); - var _q1 = new T.Quaternion(), _q2 = new T.Quaternion(), _q3 = new T.Quaternion(), _m1 = new T.Matrix4(); - function worldPos(o, v) { return v.setFromMatrixPosition(o.matrixWorld); } - function worldQuat(o, q) { o.matrixWorld.decompose(_v5, q, _v4); return q; } - // rotate bone by a world-space rotation q (pre-multiplied), keeping children attached - function rotWorld(bone, q) { - var p = bone.parent; - worldQuat(p, _q2); - // local' = inv(P) * q * P * local - _q3.copy(_q2).invert().multiply(q).multiply(_q2); - bone.quaternion.premultiply(_q3); - bone.updateMatrixWorld(true); - } - function setWorldQuat(bone, q) { - worldQuat(bone.parent, _q2); - bone.quaternion.copy(_q2.invert().multiply(q)); - bone.updateMatrixWorld(true); - } - function angleBetween(a, b) { return Math.acos(Math.max(-1, Math.min(1, a.dot(b) / (a.length() * b.length() || 1)))); } - // two-bone IK (keeps the clip's current bend plane), then matches the end rotation - function twoBone(a, b, c, tPos, tQuat, w) { - if (w <= 0) return; - var qa = a.quaternion.clone(), qb = b.quaternion.clone(), qc = c.quaternion.clone(); - var A = worldPos(a, new T.Vector3()), B = worldPos(b, new T.Vector3()), C = worldPos(c, new T.Vector3()); - var lab = B.distanceTo(A), lcb = C.distanceTo(B); - var lat = Math.max(0.01, Math.min(tPos.distanceTo(A), lab + lcb - 0.001)); - var ac = _v1.copy(C).sub(A), ab = _v2.copy(B).sub(A), ba = new T.Vector3().copy(A).sub(B), bc = new T.Vector3().copy(C).sub(B), at = _v3.copy(tPos).sub(A); - var ac_ab_0 = angleBetween(ac, ab), ba_bc_0 = angleBetween(ba, bc), ac_at_0 = angleBetween(ac, at); - var ac_ab_1 = Math.acos(Math.max(-1, Math.min(1, (lcb * lcb - lab * lab - lat * lat) / (-2 * lab * lat)))); - var ba_bc_1 = Math.acos(Math.max(-1, Math.min(1, (lat * lat - lab * lab - lcb * lcb) / (-2 * lab * lcb)))); - var axis0 = new T.Vector3().crossVectors(ac, ab); - if (axis0.lengthSq() < 1e-8) axis0.set(0, 1, 0); - axis0.normalize(); - var axis1 = new T.Vector3().crossVectors(ac, at); - if (axis1.lengthSq() < 1e-10) axis1.copy(axis0); else axis1.normalize(); - rotWorld(a, _q1.setFromAxisAngle(axis0, ac_ab_1 - ac_ab_0)); - rotWorld(b, _q1.setFromAxisAngle(axis0, ba_bc_1 - ba_bc_0)); - rotWorld(a, _q1.setFromAxisAngle(axis1, ac_at_0)); - if (tQuat) setWorldQuat(c, tQuat); - if (w < 1) { - a.quaternion.copy(qa.slerp(a.quaternion, w)); b.quaternion.copy(qb.slerp(b.quaternion, w)); - c.quaternion.copy(qc.slerp(c.quaternion, w)); a.updateMatrixWorld(true); - } - } - - // sockets for attach(): bone and, for back/hip, a carry pose in the bind-pose character frame - var SOCKET = { handR: 'weapon_r', handL: 'hand_l', back: 'spine_03', sling: 'spine_03', hip: 'pelvis', head: 'Head' }; - function carryMatrix(socket, obj) { - var m = new T.Matrix4(), q = new T.Quaternion(), p = new T.Vector3(); - var long = obj.userData.long; - if (socket === 'back') { - // slung across the back, muzzle up over the left shoulder - var z = new T.Vector3(0.42, 0.9, 0).normalize(), y = new T.Vector3(0, 0, -1), x = new T.Vector3().crossVectors(y, z); - m.makeBasis(x, y, z); p.set(-0.05, 1.28, -0.2); - if (!long) { m.identity(); p.set(0.12, 1.05, -0.17); } - } else if (socket === 'sling') { - // slung muzzle up across the back: butt low behind the right hip, muzzle above the left shoulder blade, the - // sights facing out from the back. Muzzle-down carry put a 1.2 m rifle's barrel beside the left knee (seen when - // looking down in first person) and the scope above the helmet when the torso bent to aim. - var z3 = new T.Vector3(0.36, 0.93, 0).normalize(), y3 = new T.Vector3(0, -0.05, -1).normalize(), x3 = new T.Vector3().crossVectors(y3, z3).normalize(); - y3.crossVectors(z3, x3); - m.makeBasis(x3, y3, z3); p.set(-0.03, 1.02, -0.27); - if (!long) { m.identity(); p.set(0.12, 1.05, -0.17); } - } else if (socket === 'hip') { - // holstered on the right hip, muzzle down - var z2 = new T.Vector3(0, -1, 0.15).normalize(), y2 = new T.Vector3(-1, 0, 0), x2 = new T.Vector3().crossVectors(y2, z2); - m.makeBasis(x2, y2, z2); p.set(-0.2, 0.98, 0.03); - if (long) { p.set(-0.25, 1.0, 0); } - } else { m.identity(); p.set(0, 0, 0); } - m.setPosition(p); - return m; - } - - // ---------- hand grips per weapon - // Curl of each finger (0 straight .. 1 closed) and thumb, per weapon class and hand, applied after the mixer on - // the finger bones whenever a weapon is in the right hand, so the fingers wrap the real-size grips instead of - // closing into the clip's fist through them. Right: round the wrist of the stock or the pistol grip with the - // index finger laid along the trigger guard (on the trigger while firing). Left: cupping the fore-end from - // below with the thumb up the side. Joint split per finger: base, middle, tip. - var GRIPF = { // right/left hand offsets (weapon frame) and curl scales for the third-person bodies - rifle: { r: { index: 0.088, middle: 0.44, ring: 0.475, pinky: 0.51, thumb: 0.132, trigger: 0.334, off: [0.041, 0.04, 0] }, - l: { index: 0.18, middle: 0.34, ring: 0.38, pinky: 0.42, thumb: 0.05, off: [-0.016, -0.016, 0.01] } }, - enemyRifle: { r: { index: 0.091, middle: 0.455, ring: 0.491, pinky: 0.528, thumb: 0.137, trigger: 0.346, off: [0.035, 0.044, 0] }, - l: { index: 0.06, middle: 0.34, ring: 0.38, pinky: 0.42, thumb: 0.05, off: [-0.016, -0.04, 0] } }, - smg: { r: { index: 0.064, middle: 0.333, ring: 0.358, pinky: 0.384, thumb: 0.096, trigger: 0.4, off: [0.04, 0.04, -0.028] }, - l: { index: 0.2, middle: 0.36, ring: 0.4, pinky: 0.44, thumb: 0.06, off: [-0.014, -0.028, 0] } }, - pistol: { r: { index: 0.094, middle: 0.47, ring: 0.508, pinky: 0.545, thumb: 0.282, trigger: 0.338, off: [0.022, 0.014, -0.01] }, - l: { index: 0.36, middle: 0.34, ring: 0.26, pinky: 0.22, thumb: 0.145, off: [0, -0.014, 0] } }, - mg: { r: { index: 0.064, middle: 0.32, ring: 0.346, pinky: 0.371, thumb: 0.096, trigger: 0.243, off: [0.041, 0.04, 0.024] }, - l: { index: 0.18, middle: 0.34, ring: 0.38, pinky: 0.42, thumb: 0.05, off: [0.008, -0.044, -0.036] } } - }; - IV.grips = GRIPF; // per-weapon finger curls (tunable) - var GRIPCLASS = { rifleScoped: 'rifle', rifleScopedLod: 'rifle', enemyRifle: 'enemyRifle', smg: 'smg', smgLod: 'smg', enemySmg: 'smg', pistol: 'pistol', mg: 'mg' }; - var FSEG = { index: [0.9, 1.1, 0.8], middle: [0.9, 1.1, 0.8], ring: [0.9, 1.1, 0.8], pinky: [0.9, 1.1, 0.8], thumb: [0.5, 0.8, 0.9] }; - function fingerFrames(bones, root) { - root.updateMatrixWorld(true); - var out = {}, rq = new T.Quaternion(), p0 = new T.Vector3(), p1 = new T.Vector3(); - ['l', 'r'].forEach(function (s) { - var palm = new T.Vector3(0, -1, 0); // bind pose palms face down - Object.keys(FSEG).forEach(function (f) { - for (var j = 1; j <= 3; j++) { - var b = bones[f + '_0' + j + '_' + s], c = bones[f + '_0' + (j + 1) + (j === 3 ? '_leaf_' : '_') + s]; - if (!b) continue; - b.getWorldPosition(p0); - if (c) c.getWorldPosition(p1); else p1.copy(p0).add(new T.Vector3(s === 'l' ? 1 : -1, 0, 0)); - var dir = p1.clone().sub(p0).normalize(), ax = new T.Vector3().crossVectors(dir, palm); - if (ax.lengthSq() < 1e-6) continue; - b.getWorldQuaternion(rq); - out[b.name] = { bone: b, rest: b.quaternion.clone(), axis: ax.normalize().applyQuaternion(rq.clone().invert()), f: f, j: j - 1, s: s }; - } - }); - }); - return out; - } - // ---------- actor - function Actor(kind) { - var t = TEMPLATES[kind]; - this.kind = kind; - this.fb = !t || IV.info.fallback; - if (this.fb) { FB.init(this, kind); return; } - var root = T.SkeletonUtils.clone(t); - this.root = new T.Group(); this.root.name = 'IV_' + kind; this.root.add(root); - this.model = root; - var bones = {}, meshes = [], lods = []; - root.traverse(function (o) { - if (o.isBone) bones[o.name] = o; - if (o.isMesh) { if (o.userData.lod) lods.push(o); else meshes.push(o); } - }); - this.bones = bones; this.meshes = meshes; this.lods = lods; - lods.forEach(function (m) { m.visible = false; }); - this.lodLevel = 0; - this.mixer = new T.AnimationMixer(root); - this.base = []; this.upper = []; this.cur = null; this.curUpper = null; - this.aimP = 0; this.aimY = 0; this.aimPT = 0; this.aimYT = 0; - this.attached = []; - this.leftHandIK = null; this._lhW = 0; - this._acc = 0; this._frame = 0; - this.height = kind === 'hero' || kind === 'ally' ? 1.79 : (kind === 'officer' ? 1.83 : 1.80); - var self = this; - this.mixer.addEventListener('finished', function (e) { - var n = e.action._ivName; - if (self.driven && n && !/^death|takedownVictim/.test(n)) { - self.base.forEach(function (b) { if (b.full === e.action) { b.target = 0; b.rate = 1 / 0.25; } }); - if (self.cur && self.cur.full === e.action) self.cur = null; - } - if (self.onFinished && n) self.onFinished(n); - }); - // finger rest frames (bind pose) and each joint's curl axis in its own frame, for the per-weapon grips - this._fing = fingerFrames(bones, root); - this._fgW = 0; - // face morphs: 'faceB'/'faceC' pick one of three enemy faces; 'blink' closes the hero's and ally's lids - this._morphMeshes = meshes.filter(function (m) { return m.morphTargetDictionary && m.morphTargetInfluences; }); - this._blinkT = 1 + Math.random() * 3; this._blink = 0; - if (!/^(hero|ally)$/.test(kind)) this.setFace(Actor._faceN = ((Actor._faceN || 0) + 1) % 3); - this.play('idle', { fade: 0 }); - // settle on the idle pose now, so the first frame drawn after spawn is never the bind pose - // (a full update: play() only sets the weights that update() hands to the mixer) - this.update(0); this.root.updateMatrixWorld(true); - } - var AP = Actor.prototype; - // weapon moving parts driven by the clips: the rifle bolt follows the hand through boltCycle (lift, back, - // forward, down) and the pistol slide kicks back on each firePistol shot - function smooth01(a, b, t) { var x = Math.max(0, Math.min(1, (t - a) / (b - a))); return x * x * (3 - 2 * x); } - AP._parts = function (held) { - if (!held) return; - var kind = held.userData.kind, e = this.curUpper && this.curUpper.w > 0.3 ? this.curUpper : (this.cur && this.cur.w > 0.3 ? this.cur : null); - var n = e && (e.name || ''), t = e ? (e.action || e.full).time : 0; - var bolt = held.userData._bolt; - if (bolt === undefined) { bolt = held.userData._bolt = held.getObjectByName(kind + '_bolt') || null; if (bolt) bolt.userData.p0 = bolt.position.clone(); } - if (!bolt) return; - var lift = 0, back = 0; - if (n === 'boltCycle' && (kind === 'rifleScoped' || kind === 'enemyRifle')) { - lift = smooth01(0.18, 0.3, t) * (1 - smooth01(0.62, 0.72, t)); - back = smooth01(0.3, 0.48, t) * (1 - smooth01(0.48, 0.62, t)) * 0.085; - } else if (n === 'firePistol' && kind === 'pistol') { - back = t < 0.03 ? t / 0.03 * 0.028 : Math.max(0, 0.028 * (1 - (t - 0.03) / 0.07)); - } - bolt.position.copy(bolt.userData.p0); bolt.position.z -= back; - bolt.rotation.set(0, 0, -lift * 1.4); - }; - AP._grips = function (dt, held) { - var cls = held && GRIPCLASS[held.userData.kind], T0 = cls && GRIPF[cls]; - // clips where the right hand leaves the grip (working the bolt, reloading, throwing...) keep their own hand - var cn = (this.curUpper && this.curUpper.w > 0.3 && this.curUpper.name) || (this.cur && this.cur.w > 0.3 && this.cur.name) || ''; - var free = /^(boltCycle|reload|throw|melee|signal|salute|breach|takedown|vault|death|hit|stagger)/.test(cn); - this._fgW = this._snap ? (T0 && !free ? 1 : 0) : approach(this._fgW, T0 && !free ? 1 : 0, 5, dt); - if (T0) this._fgT = T0; - var w = this._fgW, G0 = this._fgT; if (w < 0.01 || !G0) return; - // right hand: our gloved hand is thicker than the hand the grip frames were fitted to, so the hand is moved - // off the weapon by a small per-class offset (weapon frame: x weapon-left, y up, z forward) with arm IK, - // while the weapon keeps its place on the sight line - var off = T0 && T0.r.off; - if (off && held.userData._ap && this.bones.weapon_r) { - held.position.copy(held.userData._ap); held.quaternion.copy(held.userData._aq); held.updateMatrixWorld(true); - var W0 = held.matrixWorld.clone(), hq = worldQuat(held, new T.Quaternion()); - var hr = this.bones.hand_r, tp = worldPos(hr, new T.Vector3()).sub(new T.Vector3(off[0], off[1], off[2]).applyQuaternion(hq).multiplyScalar(w)); - twoBone(this.bones.upperarm_r, this.bones.lowerarm_r, hr, tp, worldQuat(hr, new T.Quaternion()), 1); - this.bones.upperarm_r.updateMatrixWorld(true); - var Lm = new T.Matrix4().copy(held.parent.matrixWorld).invert().multiply(W0); - Lm.decompose(held.position, held.quaternion, new T.Vector3()); held.updateMatrixWorld(true); - } - var n = (this.curUpper && this.curUpper.name) || (this.cur && this.cur.name) || ''; - var firing = /^fire/.test(n), q = new T.Quaternion(), tq = new T.Quaternion(); - // the left hand only grips while it is on the fore-end (its IK weight); otherwise its clip pose stays - var wl = Math.min(w, this._lhW || 0); - if (cls === 'pistol') wl = w * Math.max(this._lhW || 0, /Pistol/.test(n) ? 1 : 0); - for (var k in this._fing) { - var e = this._fing[k], g = G0[e.s], ww = e.s === 'r' ? w : wl; - if (!g || ww < 0.01) continue; - var a = e.f === 'index' && e.s === 'r' && firing ? g.trigger : g[e.f]; - var ang = a * FSEG[e.f][e.j] * (e.f === 'thumb' ? 1.1 : 1.45); - tq.copy(e.rest).multiply(q.setFromAxisAngle(e.axis, ang)); - if (ww >= 0.999) e.bone.quaternion.copy(tq); else e.bone.quaternion.slerp(tq, ww); - } - if (this.bones.hand_r) this.bones.hand_r.updateMatrixWorld(true); - if (this.bones.hand_l) this.bones.hand_l.updateMatrixWorld(true); - }; - AP.setMorph = function (name, v) { - if (this.fb) return this; - for (var i = 0; i < this._morphMeshes.length; i++) { - var m = this._morphMeshes[i], k = m.morphTargetDictionary[name]; - if (k != null) m.morphTargetInfluences[k] = v; - } - return this; - }; - // one of three faces (0, 1, 2) on the enemy kinds; ignored where a model has no face morphs - AP.setFace = function (i) { - this.face = ((i | 0) % 3 + 3) % 3; - return this.setMorph('faceB', this.face === 1 ? 1 : 0).setMorph('faceC', this.face === 2 ? 1 : 0); - }; - // blinks every 2-6 s (close 0.07 s, open 0.13 s); dead or far actors do not blink - AP._blinkUpdate = function (dt, far) { - if (!this._morphMeshes.length || far > 15) return; - this._blinkT -= dt; - if (this._blinkT <= 0) { this._blink += dt; var b = this._blink, w = b < 0.07 ? b / 0.07 : (b < 0.11 ? 1 : Math.max(0, 1 - (b - 0.11) / 0.13)); - this.setMorph('blink', w * w * (3 - 2 * w)); - if (b > 0.24) { this._blink = 0; this._blinkT = 2 + Math.random() * 4; this.setMorph('blink', 0); } - } - }; - AP._action = function (clip, tag) { - var a = this.mixer.clipAction(clip); - a._ivName = tag; - return a; - }; - AP.clipLength = function (n) { var c = clipName(n); return c ? CLIPS[c].duration : 0; }; - AP.isPlaying = function (n) { return this.cur && this.cur.name === n; }; - AP.play = function (name, o) { - if (this.fb) return FB.play(this, name, o); - o = o || {}; - var c = clipName(name); - if (!c) { if (!this._warned) { console.warn('IVChars: no clip', name); this._warned = 1; } c = 'idle'; } - var fade = o.fade == null ? 0.2 : o.fade; - var once = o.once || o.loop === false || (ONESHOT[name] && o.loop !== true); - if (this.cur && this.cur.name === name && !once) { - if (o.speed != null) { this.cur.full.timeScale = this.cur.lower.timeScale = o.speed; } - return this; - } - var full = this._action(CLIPS[c], name), lower = this._action(LOWER[c], name); - [full, lower].forEach(function (a) { - a.reset(); a.enabled = true; - a.setLoop(once ? T.LoopOnce : T.LoopRepeat, Infinity); - a.clampWhenFinished = !!once; - a.timeScale = o.speed == null ? 1 : o.speed; - a.setEffectiveWeight(0); a.play(); - }); - lower._ivName = null; - var rate = fade > 0 ? 1 / fade : 1e9; - // fade everything else out at the same rate so the weights always sum to one (no blend toward the bind pose) - for (var i = 0; i < this.base.length; i++) { this.base[i].target = 0; this.base[i].rate = rate; } - var e = { name: name, clip: c, full: full, lower: lower, w: fade > 0 ? 0 : 1, target: 1, rate: fade > 0 ? 1 / fade : 1e9 }; - this.base = this.base.filter(function (b) { return b.full !== full; }); - if (fade <= 0) this.base.forEach(function (b) { b.w = 0; }); - this.base.push(e); this.cur = e; - return this; - }; - AP.setUpper = function (name, o) { - if (this.fb) return FB.setUpper(this, name, o); - o = o || {}; - var fade = o.fade == null ? 0.2 : o.fade; - if (this.curUpper && this.curUpper.name === name) return this; - for (var i = 0; i < this.upper.length; i++) { this.upper[i].target = 0; this.upper[i].rate = fade > 0 ? 1 / fade : 1e9; } - this.curUpper = null; - if (name) { - var c = clipName(name); - if (!c) { console.warn('IVChars: no clip', name); return this; } - var a = this._action(UPPER[c], name), once = o.once || o.loop === false || (ONESHOT[name] && o.loop !== true); - a.reset(); a.enabled = true; a.setLoop(once ? T.LoopOnce : T.LoopRepeat, Infinity); a.clampWhenFinished = !!once; - a.timeScale = o.speed == null ? 1 : o.speed; a.setEffectiveWeight(0); a.play(); - this.upper = this.upper.filter(function (u) { return u.action !== a; }); - var e = { name: name, clip: c, action: a, w: fade > 0 ? 0 : 1, target: 1, rate: fade > 0 ? 1 / fade : 1e9 }; - this.upper.push(e); this.curUpper = e; - } - this._autoUpper = !!o.auto; - return this; - }; - AP.setAim = function (p, y) { - this.aimPT = Math.max(-1.2, Math.min(1.2, p || 0)); - this.aimYT = Math.max(-1.1, Math.min(1.1, y || 0)); - return this; - }; - AP.bone = function (n) { return this.fb ? FB.bone(this, n) : (this.bones[n] || (n === 'handR' ? this.bones.hand_r : null) || null); }; - // ---------- first-person body: the player's own body seen when looking down (legs, torso, shadow) - // setFirstPerson(true) draws the full-detail body without the head, neck and arms (the viewmodel draws the arms), - // hides the eyes, hair and anything held in the hands, and keeps a complete shadow: an invisible copy of each - // hidden part (no colour, no depth) still casts it. Legs and feet keep following the clips and the drive graph. - // head, neck, arms and the upper chest kit (pouches, collar, pack top) are dropped: looking down shows the belt, - // legs and boots; the viewmodel draws the arms - var FP_DROP = /^(Head|neck_01|spine_03|clavicle_|upperarm_|lowerarm_|hand_|index_|middle_|ring_|pinky_|thumb_|weapon_r)/; - function attrComp(a, i, k) { // the value, denormalised (r187's getX does that itself; r128's did not) - var v = k === 0 ? a.getX(i) : k === 1 ? a.getY(i) : k === 2 ? a.getZ(i) : a.getW(i); - if (a.normalized && !T.BufferAttribute.prototype.getComponent) { - var arr = a.array; - if (arr instanceof Uint8Array) v /= 255; else if (arr instanceof Uint16Array) v /= 65535; - else if (arr instanceof Int8Array) v = Math.max(v / 127, -1); else if (arr instanceof Int16Array) v = Math.max(v / 32767, -1); - } - return v; - } - function fpGeometry(mesh) { - var g = mesh.geometry; - if (g.userData.fpGeom) return g.userData.fpGeom; - var si = g.attributes.skinIndex, sw = g.attributes.skinWeight, bones = mesh.skeleton.bones; - var isDrop = bones.map(function (b) { return FP_DROP.test(b ? b.name : '') ? 1 : 0; }); - var n = si.count, drop = new Uint8Array(n); - for (var i = 0; i < n; i++) { - var dw = 0, tot = 0; - for (var k = 0; k < 4; k++) { var w = attrComp(sw, i, k); tot += w; if (isDrop[attrComp(si, i, k) | 0]) dw += w; } - drop[i] = dw > 0.25 * (tot || 1) ? 1 : 0; // any real share of a dropped bone hides the vertex - } - var idx = g.index ? g.index.array : null, out = []; - var tri = idx ? idx.length : n; - // belt kit (pouches, grenade, rope) is in separate islands skinned to the waist: looking down it would float - // where the game masks the waist, so small islands mostly weighted to pelvis / spine_01 / spine_02 go too - var waist = bones.map(function (b) { return /^(pelvis|spine_01|spine_02)$/.test(b ? b.name : '') ? 1 : 0; }); - var pos0 = g.attributes.position, par = new Int32Array(n), wkey = {}; - for (var i0 = 0; i0 < n; i0++) { var kk0 = pos0.getX(i0) + ',' + pos0.getY(i0) + ',' + pos0.getZ(i0); par[i0] = wkey[kk0] != null ? wkey[kk0] : (wkey[kk0] = i0); } - function root(x) { while (par[x] !== x) { par[x] = par[par[x]]; x = par[x]; } return x; } - for (var t0 = 0; t0 < tri; t0 += 3) { - var a0 = root(idx ? idx[t0] : t0), b0 = root(idx ? idx[t0 + 1] : t0 + 1), c0 = root(idx ? idx[t0 + 2] : t0 + 2); - if (a0 !== b0) par[b0] = a0; a0 = root(a0); if (a0 !== c0) par[c0] = a0; - } - var csize = {}, cwaist = {}; - for (var i1 = 0; i1 < n; i1++) { - var r1 = root(i1), dom = 0, best = -1; - for (var k1 = 0; k1 < 4; k1++) { var w1 = attrComp(sw, i1, k1); if (w1 > best) { best = w1; dom = attrComp(si, i1, k1) | 0; } } - csize[r1] = (csize[r1] || 0) + 1; cwaist[r1] = (cwaist[r1] || 0) + waist[dom]; - } - for (var i2 = 0; i2 < n; i2++) { var r2 = root(i2); if (csize[r2] < n * 0.1 && cwaist[r2] > 0.5 * csize[r2]) drop[i2] = 1; } - for (var t = 0; t < tri; t += 3) { - var a = idx ? idx[t] : t, b = idx ? idx[t + 1] : t + 1, c = idx ? idx[t + 2] : t + 2; - if (!drop[a] && !drop[b] && !drop[c]) out.push(a, b, c); - } - var fg = g.clone(); - var kept = out.length; - capCut(fg, idx, tri, out); - fg.setIndex(out); - fg.boundingSphere = g.boundingSphere; fg.groups = []; - if (out.length > kept) { fg.addGroup(0, kept, 0); fg.addGroup(kept, out.length - kept, 1); } // 1: the dark cap - g.userData.fpGeom = fg; - return fg; - } - // Close the openings the cut leaves (looking straight down otherwise shows the inside of the torso ring): edges - // that bordered two triangles before and one after are chained into loops (welded by position, so UV seams do - // not break them) and each loop is fanned to a new centre vertex that copies the attributes of a rim vertex. - function capCut(fg, idx, tri, out) { - for (var an in fg.attributes) { // meshopt-decoded attributes can be interleaved: copy them out (raw values) - var ia = fg.attributes[an]; - if (!ia.isInterleavedBufferAttribute) continue; - var Ctor = ia.data.array.constructor, da = new Ctor(ia.count * ia.itemSize), gets = ['getX', 'getY', 'getZ', 'getW']; - // raw values straight from the interleaved array: r187's getX denormalises, which rounded quantized positions to 0 - var src = ia.data.array, st = ia.data.stride; - for (var vi = 0; vi < ia.count; vi++) for (var ci_ = 0; ci_ < ia.itemSize; ci_++) da[vi * ia.itemSize + ci_] = src[vi * st + ia.offset + ci_]; - fg.setAttribute(an, new T.BufferAttribute(da, ia.itemSize, ia.normalized)); - } - var pos = fg.attributes.position, n0 = pos.count, key = {}, wid = new Int32Array(n0); - for (var i = 0; i < n0; i++) { var kk = pos.getX(i) + ',' + pos.getY(i) + ',' + pos.getZ(i); if (key[kk] == null) key[kk] = i; wid[i] = key[kk]; } - function ek(a, b) { a = wid[a]; b = wid[b]; return a < b ? a + '_' + b : b + '_' + a; } - var full = {}, kept = {}, t, e, a, b, c; - for (t = 0; t < tri; t += 3) { - a = idx ? idx[t] : t; b = idx ? idx[t + 1] : t + 1; c = idx ? idx[t + 2] : t + 2; - [[a, b], [b, c], [c, a]].forEach(function (p) { var k = ek(p[0], p[1]); full[k] = (full[k] || 0) + 1; }); - } - for (t = 0; t < out.length; t += 3) { - a = out[t]; b = out[t + 1]; c = out[t + 2]; - [[a, b], [b, c], [c, a]].forEach(function (p) { var k = ek(p[0], p[1]); (kept[k] = kept[k] || []).push(p); }); - } - var next = {}; // rim edge a->b of a kept triangle: the cap runs b->a - for (e in kept) if (kept[e].length === 1 && full[e] >= 2) { var p = kept[e][0]; next[wid[p[1]]] = p[0]; } - var seen = {}, loops = []; - Object.keys(next).forEach(function (s) { - if (seen[s]) return; - var loop = [], v = +s, guard = 0; - while (v != null && !seen[v] && guard++ < 4000) { seen[v] = 1; loop.push(v); var nv = next[v]; v = nv == null ? null : wid[nv]; } - if (loop.length >= 3 && v === +s) loops.push(loop); - }); - fg.userData.cap = { rim: Object.keys(next).length, loops: loops.length, sizes: loops.map(function (l) { return l.length; }) }; - if (!loops.length) return; - // the cap gets its own copies of the rim vertices (same skinning) with one flat UV and the cap's normal, so it - // reads as plain shadowed cloth instead of the rim's texture smeared to a point - var names = Object.keys(fg.attributes), add = 0; - loops.forEach(function (l) { add += l.length + 1; }); - names.forEach(function (nm) { // grow every attribute - var at = fg.attributes[nm], arr = new at.array.constructor((n0 + add) * at.itemSize); - arr.set(at.array); fg.setAttribute(nm, new T.BufferAttribute(arr, at.itemSize, at.normalized)); - }); - var base = n0; - loops.forEach(function (loop) { - var P = fg.attributes.position, N = fg.attributes.normal, UV = fg.attributes.uv, m = loop.length, ci = base + m, src = loop[0]; - var cx = 0, cy = 0, cz = 0, nx = 0, ny = 0, nz = 0, j, k; - for (j = 0; j <= m; j++) { - var from = j < m ? loop[j] : src, to = base + j; - names.forEach(function (nm) { var at = fg.attributes[nm]; for (k = 0; k < at.itemSize; k++) at.array[to * at.itemSize + k] = at.array[from * at.itemSize + k]; }); - if (UV) UV.setXY(to, UV.getX(src), UV.getY(src)); - } - loop.forEach(function (v) { cx += P.getX(v); cy += P.getY(v); cz += P.getZ(v); }); - cx /= m; cy /= m; cz /= m; - P.setXYZ(ci, cx, cy, cz); - for (j = 0; j < m; j++) { // the loop already runs opposite to the rim: faces A->B->centre - var A = base + j, B = base + (j + 1) % m; - var ax = P.getX(A) - cx, ay = P.getY(A) - cy, az = P.getZ(A) - cz, bx = P.getX(B) - cx, by = P.getY(B) - cy, bz = P.getZ(B) - cz; - nx += ay * bz - az * by; ny += az * bx - ax * bz; nz += ax * by - ay * bx; - out.push(A, B, ci); - } - var l = Math.sqrt(nx * nx + ny * ny + nz * nz) || 1; - if (N) { - // r128's setXYZ stored raw values (scale by hand); r187's normalises itself - var sc = !N.normalized || T.BufferAttribute.prototype.getComponent ? 0 : N.array instanceof Int8Array ? 127 : N.array instanceof Int16Array ? 32767 : 0; - for (j = 0; j <= m; j++) { - if (sc) N.setXYZ(base + j, Math.round(nx / l * sc), Math.round(ny / l * sc), Math.round(nz / l * sc)); - else N.setXYZ(base + j, nx / l, ny / l, nz / l); - } - } - base += m + 1; - }); - } - function shadowOnly(m) { - if (!m.userData.shadowMat) { - var sm = m.material.clone(); sm.colorWrite = false; sm.depthWrite = false; sm.transparent = false; - m.userData.shadowMat = sm; - } - return m.userData.shadowMat; - } - AP.setFirstPerson = function (on) { - on = !!on; - if (this.fb || on === !!this.fpOn) return this; - this.fpOn = on; - var self = this; - this.meshes.forEach(function (m) { - var body = /^(Hero|Ally)$/.test(meshName(m)); // eyes, hair, brows, lashes and anything else: shadow only - if (on) { - if (body && m.isSkinnedMesh) { - if (!m.userData.fpShadow) { - var c = new T.SkinnedMesh(m.geometry, shadowOnly(m)); c.bind(m.skeleton, m.bindMatrix); - c.castShadow = true; c.receiveShadow = false; c.frustumCulled = false; c.name = m.name + '_fpShadow'; - m.parent.add(c); m.userData.fpShadow = c; - } - m.userData.fullGeom = m.geometry; m.geometry = fpGeometry(m); m.castShadow = false; - if (m.geometry.groups.length) { // the cap over the cut reads as the shadowed inside of the collar - if (!m.userData.capMat) { var cm = m.material.clone(); cm.color.multiplyScalar(0.18); cm.normalMap = null; m.userData.capMat = cm; } - m.userData.bodyMat = m.material; m.material = [m.material, m.userData.capMat]; - } - m.userData.fpShadow.visible = true; - } else { - m.userData.fullMat = m.material; m.material = shadowOnly(m); - } - } else { - if (m.userData.fullGeom) { m.geometry = m.userData.fullGeom; m.castShadow = true; if (m.userData.fpShadow) m.userData.fpShadow.visible = false; } - if (m.userData.bodyMat) { m.material = m.userData.bodyMat; m.userData.bodyMat = null; } - if (m.userData.fullMat) { m.material = m.userData.fullMat; m.userData.fullMat = null; } - } - }); - // the weapon in the hands: the viewmodel shows it; keep only its shadow - this.attached.forEach(function (a) { - if (a.socket !== 'handR' && a.socket !== 'handL') return; - a.obj.traverse(function (o) { - if (!o.isMesh) return; - if (on) { o.userData.fullMat = o.material; o.material = shadowOnly(o); } - else if (o.userData.fullMat) { o.material = o.userData.fullMat; o.userData.fullMat = null; } - }); - }); - // full-detail meshes only (no LOD switch on the player's own body) - if (on) { this.lodLevel = 0; this.meshes.forEach(function (m) { m.visible = true; }); this.lods.forEach(function (m) { m.visible = false; }); } - return this; - }; - - AP.setVisible = function (b) { this.root.visible = !!b; return this; }; - AP.attach = function (obj, socket) { - socket = socket || 'handR'; - var bn = SOCKET[socket] || socket, bone = this.bone(bn) || this.bone('hand_r'); - if (!bone) return this; - this.detach(obj); - bone.add(obj); - var grip = socket === 'handL' ? (obj.userData.gripL || obj.userData.gripR) : obj.userData.gripR; - if ((socket === 'handR' || socket === 'handL') && grip) { - // weapon placed so its grip frame coincides with the hand bone - grip.updateMatrix(); - var GM = grip.matrix.clone(); - var inv = GM.invert(); - inv.decompose(obj.position, obj.quaternion, obj.scale); - obj.userData._ap = obj.position.clone(); obj.userData._aq = obj.quaternion.clone(); - } else if (socket === 'back' || socket === 'sling' || socket === 'hip') { - // carry pose defined in the bind-pose character frame, converted into the bone's frame - var rest = this._restWorld(bn); - var m = new T.Matrix4().copy(rest).invert().multiply(carryMatrix(socket, obj)); - m.decompose(obj.position, obj.quaternion, obj.scale); - } else { - obj.position.set(0, 0, 0); obj.quaternion.identity(); - } - this.attached.push({ obj: obj, socket: socket }); - if (socket === 'handR') this.held = obj; - // pose at once with the weapon in its grip (hold layer, fingers and left hand at full weight), so an actor that - // is spawned and armed in the same frame is never drawn in the bind pose or with the weapon floating - if (socket === 'handR' && !this.fb) { this._snap = true; this.update(0); this._snap = false; } - // reduced weapon model for characters other than the player beyond IV.weaponLodDistance (see update) - if (socket === 'handR' && !obj.userData.lodTwin && WTEMPLATES[obj.userData.kind + 'Lod'] && WTEMPLATES[obj.userData.kind]) { - var tw = IV.weapon(obj.userData.kind, { lod: true }); - tw.visible = false; tw.userData.isLodTwin = true; obj.add(tw); obj.userData.lodTwin = tw; obj.userData.lodOn = false; - } - return this; - }; - AP._restWorld = function (bn) { - // bone's bind-pose matrix in the actor frame, from the skeleton's inverse bind matrices - var sk = this.meshes[0].skeleton, i = sk.bones.indexOf(this.bones[bn]); - var m = new T.Matrix4(); - if (i >= 0) m.copy(sk.boneInverses[i]).invert(); - return m; - }; - AP.detach = function (obj) { - if (obj.parent) obj.parent.remove(obj); - this.attached = this.attached.filter(function (a) { return a.obj !== obj; }); - if (this.held === obj) this.held = null; - return this; - }; - AP.update = function (dt) { - if (this.fb) return FB.update(this, dt); - dt = Math.min(dt || 0, 0.1); - // far actors: LOD mesh and update every other frame - var far = 0; - if (IV.camera && this.root.parent) { - worldPos(this.root, _v1); - far = _v1.distanceTo(IV.camera.position); - // three levels with 10 % hysteresis: full -> mid at IV.lodDistances[0], mid -> far at [1] (the hair goes at mid) - var D = IV.lodDistances || [IV.lodDistance * 0.55, IV.lodDistance * 1.4], cur = this.lodLevel || 0, lod = cur; - if (this.lods.length && !this.fpOn) { - if (cur < 2 && far > D[1] * 1.05) lod = 2; else if (cur < 1 && far > D[0] * 1.05) lod = 1; - else if (cur > 1 && far < D[1] * 0.95) lod = far > D[0] * 0.95 ? 1 : 0; else if (cur > 0 && far < D[0] * 0.95) lod = 0; - } - if (lod !== cur) { - this.lodLevel = lod; - this.meshes.forEach(function (m) { m.visible = !lod; }); - this.lods.forEach(function (m) { m.visible = m.userData.lod === lod; }); - } - } - // weapon in hand: full model for the player, the reduced one for others beyond a few metres - var hw = this.held && this.held.userData.lodTwin; - if (hw) { - var wl = this.kind !== 'hero' && IV.camera && far > (IV.weaponLodDistance || 6); - if (wl !== this.held.userData.lodOn) { - this.held.userData.lodOn = wl; hw.visible = wl; - this.held.children.forEach(function (c) { if (c !== hw && c.isMesh) c.visible = !wl; c !== hw && c.traverse && c.traverse(function (m) { if (m.isMesh && m !== c) m.visible = !wl; }); }); - } - } - this._frame++; - this._acc += dt; - if (far > IV.throttleDistance && (this._frame & 1)) return this; - dt = this._acc; this._acc = 0; - // automatic weapon hold when nothing is layered on top - var held = this.held, autoName = null; - if (held && (!this.curUpper || this._autoUpper)) { - var cn = this.cur && this.cur.w > 0.5 ? this.cur.name : ''; - var needs = !/^(aim|crouchAim|prone|death|takedown|vault|sit|salute|throw|melee|hit|stagger|reload|bolt|fire|sprintRifle|stackUp|breach|signal|wallLean|limp|alert)/.test(cn); - var pistol = held.userData.kind === 'pistol'; - if (this.driven && !cn) { - var st = this.ds; - needs = st.stance !== 'prone' && this._stW.prone < 0.5; - this._upperFade = 0.2; - if (needs && st.aiming) autoName = pistol ? 'aimPistol' : 'aimIdle'; - else if (needs && !pistol && this._sprintW > 0.5) autoName = 'sprintRifle'; - } - if (!autoName) autoName = needs ? (held.userData.long ? 'holdRifle' : (pistol ? 'holdPistol' : null)) : null; - if (autoName && !clipName(autoName)) autoName = null; - // the rifle travels furthest between the sprint carry and the shoulder: give that swap the longest fade - var swapF = (this.curUpper && this.curUpper.name === 'sprintRifle') || autoName === 'sprintRifle' ? 0.38 : (this._upperFade || 0.2); - if (autoName && (!this.curUpper || this.curUpper.name !== autoName)) this.setUpper(autoName, { auto: true, fade: this._snap ? 0 : swapF }); - if (!autoName && this._autoUpper && this.curUpper) this.setUpper(null); - } - // weights - var U = 0, i, e; - for (i = 0; i < this.upper.length; i++) { - e = this.upper[i]; - e.w += Math.sign(e.target - e.w) * Math.min(Math.abs(e.target - e.w), e.rate * dt); - U += e.w; - } - U = Math.min(1, U); - for (i = 0; i < this.upper.length; i++) this.upper[i].action.setEffectiveWeight(this.upper[i].w); - this.upper = this.upper.filter(function (u) { if (u.w <= 0 && u.target === 0) { u.action.stop(); return false; } return true; }); - var baseTot = 0; - for (i = 0; i < this.base.length; i++) { - e = this.base[i]; - e.w += Math.sign(e.target - e.w) * Math.min(Math.abs(e.target - e.w), e.rate * dt); - e.full.setEffectiveWeight(e.w * (1 - U)); - e.lower.setEffectiveWeight(e.w * U); - baseTot += e.w; - } - if (this.driven) this._graph(dt, Math.max(0, 1 - baseTot), U); - this.base = this.base.filter(function (b) { if (b.w <= 0 && b.target === 0) { b.full.stop(); b.lower.stop(); return false; } return true; }); - // three.js only writes a bone when the mixed value differs from last frame's, so a bone whose clip value is - // steady (a held aim pose) would keep last frame's post-process edits (lean, IK, aim offset) and accumulate them. - // Marking the previous-frame slot as unknown makes every bound property be written again each update. - var bs = this.mixer._bindings, ai = this.mixer._accuIndex; - if (bs && ai != null) for (i = 0; i < bs.length; i++) { var pm = bs[i]; if (pm.buffer) pm.buffer[(ai + 1) * pm.valueSize] = NaN; } - this.mixer.update(dt); - for (i = 0; i < this.base.length; i++) { e = this.base[i]; e.lower.time = e.full.time; } - if (this.driven) for (var gk in this.gr) { e = this.gr[gk]; e.lower.time = e.full.time; } - this.root.updateMatrixWorld(true); - // aim offset over spine, neck and head - var k = 1 - Math.exp(-dt * 14); - this.aimP += (this.aimPT - this.aimP) * k; this.aimY += (this.aimYT - this.aimY) * k; - if (Math.abs(this.aimP) > 1e-4 || Math.abs(this.aimY) > 1e-4) this._applyAim(); - if (this.driven) this._post(dt, far); else this._flinch(dt); - if (!(this.cur && /^death|takedownVictim/.test(this.cur.name))) this._blinkUpdate(dt, far); else this.setMorph('blink', 1); - this._grips(dt, held); - this._parts(held); - // left hand onto the fore-end - var want = 0; - if (held && held.userData.gripL && held.userData.long !== undefined) { - var on = (this.curUpper && TWO_HAND[this.curUpper.name]) || (!this.curUpper && this.cur && TWO_HAND[this.cur.name]); - want = on ? 1 : 0; - if (this.leftHandIK != null) want = this.leftHandIK; - } - this._lhW = this._snap ? want : approach(this._lhW, want, 5, dt); - if (this._lhW > 0.01 && held) { - held.userData.gripL.updateMatrixWorld(true); - var tp = worldPos(held.userData.gripL, new T.Vector3()), tq = worldQuat(held.userData.gripL, new T.Quaternion()); - // left hand target moved by a per-class offset in the weapon's frame (off the fore-end) - var lcls = GRIPF[GRIPCLASS[held.userData.kind]], loff = lcls && lcls.l.off; - if (loff) tp.add(new T.Vector3(loff[0], loff[1], loff[2]).applyQuaternion(worldQuat(held, new T.Quaternion()))); - this._reachL(tp, this._lhW); - twoBone(this.bones.upperarm_l, this.bones.lowerarm_l, this.bones.hand_l, tp, tq, this._lhW); - } - return this; - }; - // left-arm reach: when the fore-grip is further than the arm can stretch, bring the shoulder forward (clavicle, - // so the hand can close on the grip instead of stopping short of it - AP._reachL = function (tp, w) { - var b = this.bones, cl = b.clavicle_l, ua = b.upperarm_l, la = b.lowerarm_l, h = b.hand_l; - if (!cl || !ua || !la || !h) return; - var S = worldPos(ua, new T.Vector3()), E = worldPos(la, new T.Vector3()), W = worldPos(h, new T.Vector3()); - var reach = (S.distanceTo(E) + E.distanceTo(W)) * 0.995, q = new T.Quaternion(), used = 0; - for (var it = 0; it < 3; it++) { - S = worldPos(ua, S); - var d = S.distanceTo(tp) - reach; - if (d <= 0.001) break; - // clavicle: swing the shoulder joint toward the target, up to about 25 degrees in all - var C = worldPos(cl, new T.Vector3()), a0 = S.clone().sub(C), want = tp.clone().sub(C); - var ang = Math.min(0.6 - used, d / Math.max(a0.length(), 0.05)); - var axis = new T.Vector3().crossVectors(a0, want); - if (ang <= 0 || axis.lengthSq() < 1e-10) break; - used += ang; q.setFromAxisAngle(axis.normalize(), ang * w); rotWorld(cl, q); - } - this.root.updateMatrixWorld(true); - }; - // ---------------- driven locomotion graph (actor.drive) ---------------- - var DIRS = [['F', 0], ['FL', 45], ['L', 90], ['BL', 135], ['B', 180], ['BR', -135], ['R', -90], ['FR', -45]]; - var SPEED = { walk: 1.5, jog: 3.8, sprint: 6.4, crouch: 1.3, prone: 0.6 }; - function ease01(x) { x = Math.max(0, Math.min(1, x)); return x * x * (3 - 2 * x); } - function approach(v, t, rate, dt) { return v + Math.sign(t - v) * Math.min(Math.abs(t - v), rate * dt); } - AP.drive = function (st) { - if (this.fb) { FB.play(this, (st.speed || 0) > 0.3 ? (st.stance === 'crouch' ? 'crouchWalk' : (st.speed > 3 ? 'run' : 'walk')) : 'idle'); return this; } - if (!this.driven) { - this.driven = true; this.gr = {}; this.phase = 0; this._move = 0; this._stW = { stand: 1, crouch: 0, prone: 0 }; - this._sprintW = 0; this._turnW = 0; this._lean = 0; this._pitchLean = 0; this._lastSpeed = 0; this._acc = 0; this._t = 0; - this._dirA = 0; this._tier = 0; this._pelDrop = 0; - for (var i = 0; i < this.base.length; i++) { this.base[i].target = 0; this.base[i].rate = 1 / 0.3; } - this.cur = null; - } - this.ds = st; - if (st.aimPitch != null || st.aimYawOffset != null) this.setAim(st.aimPitch || 0, st.aimYawOffset || 0); - return this; - }; - AP.undrive = function () { this.driven = false; for (var k in this.gr) { this.gr[k].full.stop(); this.gr[k].lower.stop(); } this.gr = {}; return this; }; - var GCLIPS = {}, GLOWER = {}; - AP._gEntry = function (name) { - var e = this.gr[name]; - if (e) return e; - var c = clipName(name); if (!c) return null; - // the graph plays its own copies of the clips: three.js shares one action per clip, so using CLIPS[c] here would - // let play()/stop() on the same clip (the spawn idle, a one-shot) stop or reweight a graph entry mid-blend - if (!GCLIPS[c]) { GCLIPS[c] = CLIPS[c].clone(); GCLIPS[c].name = c + '#g'; GLOWER[c] = LOWER[c].clone(); GLOWER[c].name = c + '#gl'; } - var full = this._action(GCLIPS[c], null), lower = this._action(GLOWER[c], null); - [full, lower].forEach(function (a) { a.enabled = true; a.setLoop(T.LoopRepeat, Infinity); a.setEffectiveWeight(0); a.play(); }); - var m = META[c] || {}; - e = this.gr[name] = { full: full, lower: lower, w: 0, tw: 0, loco: !!m.stride || /turnStep|proneCrawl/.test(name), meta: m, dur: CLIPS[c].duration }; - return e; - }; - AP._graph = function (dt, scale, U) { - var st = this.ds, i, k, e; - var vx = st.vx || 0, vz = st.vz || 0, speed = Math.hypot(vx, vz); - var stance = st.stance || 'stand'; - // stance super-state weights, eased (~0.25 s) - // going down to or up from prone takes longer (about 0.6 s) than stand <-> crouch (0.25 s) - var stRate = stance === 'prone' || this._stW.prone > 0.01 ? 1.6 : 4; - for (k in this._stW) this._stW[k] = approach(this._stW[k], k === stance ? 1 : 0, stRate, dt); - var sw = this._stW, swSum = sw.stand + sw.crouch + sw.prone || 1; - // moving weight follows the speed: the stepping clips are blended with the stance idle at about speed / clip speed - // while the phase keeps the clips' own cadence (below), so a planted foot moves with the ground during starts, - // stops and slow walking instead of skating - var wantMove = speed > 0.08 ? 1 : 0; - // direction flips (over ~100 degrees): keep the old blend direction while the body slows, plant, and swap the - // direction only once nearly still, so opposing directions are never blended at speed - var aNow = Math.atan2(vx, vz) * 180 / Math.PI, dFlip = Math.abs(((aNow - this._dirA + 540) % 360) - 180); - if (speed > 0.08 && dFlip > 100 && this._move > 0.1) this._pivot = true; - if (this._pivot && (speed < 0.3 || this._move <= 0.1)) { this._dirA = aNow; this._pivot = false; } - var vRef = this._vRef || 1.5; - var mvT = wantMove && !this._pivot ? Math.min(1, speed / (0.8 * vRef)) : 0; - // starting from (nearly) still: re-seat the phase at the nearest foot contact (both feet down), so the first - // step starts from double support instead of mid-swing; the pose is idle here, so the jump is not visible - if (this._move < 0.04 && mvT > 0) this.phase = (Math.round(this.phase * 2) / 2) % 1; - this._move = approach(this._move, mvT, 5, dt); - var mv = this._move; - // direction (local: +x left, +z forward) and speed tier - if (speed > 0.05 && !this._pivot) { - var a = Math.atan2(vx, vz) * 180 / Math.PI, da = ((a - this._dirA + 540) % 360) - 180; - this._dirA += da * (1 - Math.exp(-dt / 0.18)); - } - var dirA = ((this._dirA + 540) % 360) - 180; - // walk or jog: the game scales speeds by direction (strafe 85 %, back 70 %), so judge the tier against this - // direction's own walk speed; a narrow walk->jog band (1.45-1.7x walk) keeps one gait at a time, played a - // little faster or slower, instead of mixing two cadences (which skates the planted foot) - var d2 = vx * vx + vz * vz, dirF = d2 > 1e-6 ? (vx * vx * 0.85 + vz * vz * (vz > 0 ? 1 : 0.7)) / d2 : 1; - var wv = SPEED.walk * dirF; - var tierT = Math.max(0, Math.min(1, (speed - wv * 1.45) / (wv * 0.25))); - this._tier = approach(this._tier, tierT, 4, dt); - var fwdish = Math.abs(dirA) < 35; - this._sprintW = approach(this._sprintW, st.sprinting && fwdish && speed > SPEED.jog * 0.9 && stance === 'stand' ? 1 : 0, 4, dt); - var turnWant = speed < 0.15 && Math.abs(st.yawRate || 0) > 0.9 && stance !== 'prone' ? 1 : 0; - this._turnW = approach(this._turnW, turnWant, 5, dt); - // two nearest of the eight directions - var ia = 0, ib = 0, fb = 0; - for (i = 0; i < 8; i++) { - var d0 = DIRS[i][1], d1 = DIRS[(i + 1) % 8][1]; - var span = ((d1 - d0 + 540) % 360) - 180, off = ((dirA - d0 + 540) % 360) - 180; - if (span < 0 ? (off <= 0 && off >= span) : (off >= 0 && off <= span)) { ia = i; ib = (i + 1) % 8; fb = off / span; break; } - } - var tw = {}; - function add(n, w) { if (w > 1e-4) tw[n] = (tw[n] || 0) + w; } - var idleW = 1 - mv; - var sStand = sw.stand / swSum, sCrouch = sw.crouch / swSum, sProne = sw.prone / swSum; - add(this._turnW > 0.01 ? 'turnStep' : 'idle', sStand * idleW * Math.max(this._turnW, 0) ); - add('idle', sStand * idleW * (1 - this._turnW)); - add(this._turnW > 0.01 ? 'crouchTurnStep' : 'crouchIdle', sCrouch * idleW * this._turnW); - add('crouchIdle', sCrouch * idleW * (1 - this._turnW)); - add(st.aiming ? 'proneAim' : 'proneIdle', sProne * idleW); // prone and aiming: elbows down, rifle level - add('proneCrawl', sProne * mv); - var dA = DIRS[ia][0], dB = DIRS[ib][0]; - var walkW = (1 - this._tier) * (1 - this._sprintW), jogW = this._tier * (1 - this._sprintW); - add('walk' + dA, sStand * mv * walkW * (1 - fb)); add('walk' + dB, sStand * mv * walkW * fb); - add('jog' + dA, sStand * mv * jogW * (1 - fb)); add('jog' + dB, sStand * mv * jogW * fb); - add('sprintF', sStand * mv * this._sprintW); - add('crouch' + dA, sCrouch * mv * (1 - fb)); add('crouch' + dB, sCrouch * mv * fb); - // ease every graph weight toward its target, then renormalise so the total is exactly one (no blend toward the bind pose) - for (k in tw) this._gEntry(k); - var tot = 0; - var chg = 0; - for (k in this.gr) { e = this.gr[k]; var w0 = e.w; e.w = approach(e.w, tw[k] || 0, 6, dt); chg += Math.abs(e.w - w0); tot += e.w; } - // how fast the blend is changing (0 in steady locomotion): the planted-foot lock only works while this is high, - // which is when a weight change would otherwise drag a planted foot (sharp stops, direction flips, stance changes) - var lockT = this._pivot ? 1 : Math.max(0, Math.min(1, (chg / Math.max(dt, 1e-3) - 0.8) / 2)); - this._lockK = approach(this._lockK || 0, lockT, lockT > (this._lockK || 0) ? 8 : 4, dt); - var strideW = 0, strideSum = 0, speedSum = 0; - for (k in this.gr) { - e = this.gr[k]; - var w = tot > 0 ? e.w / tot : 0; - e.full.setEffectiveWeight(w * scale * (1 - U)); e.lower.setEffectiveWeight(w * scale * U); - if (e.loco && e.meta.stride) { strideSum += w * e.meta.stride; strideW += w; speedSum += w * (e.meta.speed || 1.5); } - } - if (strideW > 0.05) this._vRef = speedSum / strideW; - // one shared phase. The blended pose moves a planted foot by sum(w * stride) per cycle (idle adds nothing), so the - // phase advances by speed / that; capped at 1.3x the clips' own cadence when the move weight lags behind the speed - var prev = this.phase; - if (strideW > 0.01) { - var natural = speedSum / strideSum; // cycles per second at the clips' own speed - this.phase += Math.min(speed / Math.max(strideSum, 1e-3), natural * 1.6) * dt; - } else if (this._turnW > 0.05) this.phase += dt / 0.9; - if (sProne > 0.5 && speed > 0.05) this.phase += dt * speed / 0.6 * 0.0; // crawl uses its own clock (below) - this.phase %= 1; - for (k in this.gr) { - e = this.gr[k]; - if (e.loco) { e.full.timeScale = 0; e.full.time = this.phase * e.dur; } - if (k === 'proneCrawl') { e.full.timeScale = 0; e.full.time = (this.phase) * e.dur; } - } - // foot contact events from phase windows (left at 0, right at 0.5) - if (this.onFoot && mv > 0.3 && sProne < 0.5) { - var crossed = function (p0, p1, c) { return p0 <= p1 ? (c > p0 && c <= p1) : (c > p0 || c <= p1); }; - var str = Math.min(1, 0.25 + speed / SPEED.sprint); - if (crossed(prev, this.phase, 0.0001)) try { this.onFoot('l', str); } catch (er) {} - if (crossed(prev, this.phase, 0.5)) try { this.onFoot('r', str); } catch (er) {} - } - // remove dead entries - for (k in this.gr) { e = this.gr[k]; if (e.w <= 0 && !tw[k]) { e.full.stop(); e.lower.stop(); delete this.gr[k]; } } - // lean: roll into turns, pitch into acceleration - var accel = (speed - this._lastSpeed) / Math.max(dt, 1e-3); - // stopping: from the moment the body is nearly stopped, the feet that are on the ground stay where they are and - // any that ended up away from the idle stance is brought in by a small lifted settle step (see _stopFeet) - var decel = (this._lastSpeed - speed) / Math.max(dt, 1e-3); - if (!this._stop && this._move > 0.15 && stance !== 'prone' && ((speed < 0.45 && speed <= this._lastSpeed) || (decel > 4 && speed < this._lastSpeed * 0.93))) this._stop = { t: 0, init: false }; - if (this._stop && (stance === 'prone' || (speed > this._lastSpeed + 0.01 && speed > 0.2))) { this._stop = null; this._lock = null; } - this._lastSpeed = speed; - this._lean += (Math.max(-0.14, Math.min(0.14, -(st.yawRate || 0) * speed * 0.035)) - this._lean) * Math.min(1, dt * 6); - this._pitchLean += (Math.max(-0.06, Math.min(0.06, accel * 0.012)) - this._pitchLean) * Math.min(1, dt * 5); - this._t += dt; - }; - // additive hit flinch (no physics): dir = world direction the bullet travels, part = 'head'|'chest'|'arm_l'|'arm_r'|'leg' - AP.flinch = function (dir, part, strength) { - var rq = worldQuat(this.root, new T.Quaternion()).invert(); - var d = (dir ? dir.clone() : new T.Vector3(0, 0, -1)).applyQuaternion(rq); d.y = 0; if (d.lengthSq() < 1e-6) d.set(0, 0, -1); d.normalize(); - this._fl = { t: 0, d: d, part: part || 'chest', k: strength == null ? 1 : strength }; - return this; - }; - AP._flinch = function (dt) { - var f = this._fl; if (!f) return; - f.t += dt; var T1 = 0.45; if (f.t > T1) { this._fl = null; return; } - // fast hit, damped spring back - var x = f.t / T1, a = Math.sin(Math.min(1, f.t / 0.06) * Math.PI / 2) * Math.exp(-x * 4) * f.k; - var rq = worldQuat(this.root, new T.Quaternion()); - var up = new T.Vector3(0, 1, 0).applyQuaternion(rq); - // bend away from the shot: rotate about the axis perpendicular to the shot direction - var axis = new T.Vector3().crossVectors(up, f.d.clone().applyQuaternion(rq)).normalize(); - var q = new T.Quaternion(), b = this.bones; - var map = { head: [['neck_01', 0.25], ['Head', 0.45], ['spine_03', 0.08]], chest: [['spine_02', 0.18], ['spine_03', 0.22], ['Head', 0.1]], - arm_l: [['clavicle_l', 0.35], ['upperarm_l', 0.3], ['spine_03', 0.08]], arm_r: [['clavicle_r', 0.35], ['upperarm_r', 0.3], ['spine_03', 0.08]], - leg: [['pelvis', 0.08], ['spine_01', 0.1], ['thigh_l', 0.1], ['thigh_r', 0.1]] }[f.part] || [['spine_03', 0.2]]; - for (var i = 0; i < map.length; i++) { var bn = b[map[i][0]]; if (!bn) continue; q.setFromAxisAngle(axis, a * map[i][1]); rotWorld(bn, q); } - }; - AP._post = function (dt, far) { - this._flinch(dt); - var b = this.bones, q = new T.Quaternion(); - var rq = worldQuat(this.root, new T.Quaternion()); - var fwd = new T.Vector3(0, 0, 1).applyQuaternion(rq), left = new T.Vector3(1, 0, 0).applyQuaternion(rq); - // lean (spine) and breathing (additive, small) - if (b.spine_01) { - q.setFromAxisAngle(fwd, this._lean * 0.5); rotWorld(b.spine_01, q); - q.setFromAxisAngle(left, this._pitchLean * 0.5); rotWorld(b.spine_01, q); - q.setFromAxisAngle(fwd, this._lean * 0.5); rotWorld(b.spine_02, q); - var br = Math.sin(this._t * 2 * Math.PI / 3.6) * 0.012 * (1 - Math.min(1, this._move)); - q.setFromAxisAngle(left, -br); rotWorld(b.spine_03, q); - } - // foot IK with pelvis drop against actor.groundAt(x, z) (if the game provides it), near the camera only - // foot IK fades out (not off in one frame) as the body goes down to prone - var ikW = Math.max(0, Math.min(1, 1 - this._stW.prone * 1.6)), ikOK = far < (IV.footIKDistance || 25) && ikW > 0.01; - this._ikW = ikW; - if (this.groundAt && ikOK) this._footIK(dt); - if (ikOK && this._stop) this._stopFeet(dt, fwd); - else if (ikOK && IV.footLock !== false && far < (IV.footLockDistance || 12)) this._footLock(dt); // transitions only (see _lockK) - }; - // planted-foot lock: while a foot is in its contact window (from the shared phase) it stays where it landed, - // so direction changes and turns do not skate it; eased in and out at the window edges - var LOCKW = { l: [0.0, 0.30], r: [0.5, 0.80] }; - // analytic two-bone leg IK with an explicit knee pole (the pelvis forward), so the knee can never flip - function legIK(thigh, calf, foot, target, pole, w) { - var fq = worldQuat(foot, new T.Quaternion()); - var A = worldPos(thigh, new T.Vector3()), B = worldPos(calf, new T.Vector3()), C = worldPos(foot, new T.Vector3()); - var l1 = A.distanceTo(B), l2 = B.distanceTo(C); - var tgt = C.clone().lerp(target, w); - var d = tgt.clone().sub(A), dist = Math.min(d.length(), (l1 + l2) * 0.985); d.normalize(); - tgt.copy(A).addScaledVector(d, dist); - var cosA = Math.max(-1, Math.min(1, (l1 * l1 + dist * dist - l2 * l2) / (2 * l1 * dist))), sinA = Math.sqrt(1 - cosA * cosA); - var pv = pole.clone().addScaledVector(d, -pole.dot(d)); if (pv.lengthSq() < 1e-8) return; pv.normalize(); - var K = A.clone().addScaledVector(d, cosA * l1).addScaledVector(pv, sinA * l1); - var q = new T.Quaternion(); - q.setFromUnitVectors(B.clone().sub(A).normalize(), K.clone().sub(A).normalize()); rotWorld(thigh, q); - var C2 = worldPos(foot, new T.Vector3()), K2 = worldPos(calf, new T.Vector3()); - q.setFromUnitVectors(C2.sub(K2).normalize(), tgt.clone().sub(K2).normalize()); rotWorld(calf, q); - setWorldQuat(foot, fq); - } - // planted-foot lock: while a foot is in its contact window (shared phase) it keeps the ground point where it landed, - // so blend direction changes do not skate it; eased in and out at the window edges, reach capped, knee pole fixed - var LOCKW = { l: [0.0, 0.30], r: [0.5, 0.80] }; - AP._footLock = function (dt) { - // While the blend is changing (this._lockK), a foot in stance keeps the ground point where it landed. When it - // lifts off, the offset between the locked and the animated foot is carried into the swing and eased out there, - // so the foot never jumps back while it bears weight. - var b = this.bones, m = this._lockK || 0; - if (!this._lock) this._lock = { l: { L: null, off: new T.Vector3(), w: 0 }, r: { L: null, off: new T.Vector3(), w: 0 } }; - var rq = worldQuat(this.root, new T.Quaternion()), fwd = new T.Vector3(0, 0, 1).applyQuaternion(rq); - var v = this._vRef || 1.5, stance = v < 2 ? 0.58 : (v > 3.5 ? 0.26 : 0.58 - (v - 2) / 1.5 * 0.32); - for (var i = 0; i < 2; i++) { - var s = i ? 'r' : 'l', st = this._lock[s], foot = b['foot_' + s], ball = b['ball_' + s]; - if (!foot || !ball) continue; - var u = (this.phase - (i ? 0.5 : 0) + 1) % 1; - var bp = worldPos(ball, new T.Vector3()), ap = worldPos(foot, new T.Vector3()); - var inStance = u < stance && this._stW.prone < 0.5; - if (inStance) { - if (!st.L) st.L = bp.clone(); - if (m < 0.02 && st.w < 0.02) { st.L.copy(bp); st.off.set(0, 0, 0); st.w = 0; continue; } - st.w = Math.max(st.w, m); - var sh = new T.Vector3(st.L.x - bp.x, 0, st.L.z - bp.z), sl = sh.length(); - // reach cap: past 30 cm the lock point is pulled along with the body instead of letting go in one frame - if (sl > 0.3) { sh.multiplyScalar(0.3 / sl); st.L.x = bp.x + sh.x; st.L.z = bp.z + sh.z; } - st.off.copy(sh); - if (m < 0.02) st.w = approach(st.w, 0, 4, dt); - } else { - st.L = null; - // swing: ease the carried offset out (about 0.2 s) - st.off.multiplyScalar(Math.exp(-dt / 0.07)); - if (st.off.lengthSq() < 1e-6) { st.w = 0; continue; } - } - if (st.w < 0.01 || st.off.lengthSq() < 1e-6) continue; - var tgt = ap.clone().addScaledVector(st.off, inStance ? 1 : 1); - var hip = worldPos(b['thigh_' + s], new T.Vector3()), knee = worldPos(b['calf_' + s], new T.Vector3()); - var axis = ap.clone().sub(hip).normalize(), kd = knee.clone().sub(hip); - // knee pole: the animated bend plus the body's forward, so a nearly straight leg cannot pick a flipped plane - var pole = kd.addScaledVector(axis, -kd.dot(axis)).addScaledVector(fwd, 0.08); - legIK(b['thigh_' + s], b['calf_' + s], foot, tgt, pole.normalize(), Math.min(1, st.w + (inStance ? 0 : 1))); - } - }; - AP._stopFeet = function (dt, fwd) { - var b = this.bones, S = this._stop, ry = worldPos(this.root, new T.Vector3()).y, i, s; - S.t += dt; - if (!S.init) { - S.init = true; S.f = {}; - for (i = 0; i < 2; i++) { - s = i ? 'r' : 'l'; - var p = worldPos(b['foot_' + s], new T.Vector3()); - // on the ground = ankle within 4 cm of standing height - S.f[s] = { L: p.clone(), planted: p.y - ry < 0.13, step: -1, done: false }; - } - } - var wIn = 1; // the pins start where the feet are, so they can take hold at once - // settle steps once the body has (nearly) reached the idle pose: the foot furthest from its idle spot first - var idle = this._move < 0.08; - for (i = 0; i < 2; i++) { - s = i ? 'r' : 'l'; - var f = S.f[s], foot = b['foot_' + s]; if (f.done) continue; - var A = worldPos(foot, new T.Vector3()); - // a foot that was in the air when the stop began follows its clip until it touches down, then stays there - if (!f.planted) { if (A.y - ry < 0.11) { f.planted = true; f.L.copy(A); } else continue; } - var off = Math.hypot(A.x - f.L.x, A.z - f.L.z); - var other = S.f[i ? 'l' : 'r']; - if (idle && f.step < 0 && off > 0.02 && !(other.step >= 0 && !other.done)) f.step = 0; - // a pinned foot the body has moved away from (the leg would be at full stretch) steps now instead of dragging - if (f.step < 0 && !(other.step >= 0 && !other.done)) { - var H0 = worldPos(b['thigh_' + s], new T.Vector3()), legL = H0.distanceTo(worldPos(b['calf_' + s], new T.Vector3())) + worldPos(b['calf_' + s], new T.Vector3()).distanceTo(A); - if (H0.distanceTo(new T.Vector3(f.L.x, A.y, f.L.z)) > legL * 0.95) f.step = 0; - } - var tgt = f.L.clone(); tgt.y = A.y; - if (f.step >= 0) { - f.step += dt; var u = Math.min(1, f.step / 0.28), e = u * u * (3 - 2 * u); - tgt.set(f.L.x + (A.x - f.L.x) * e, A.y + Math.sin(Math.PI * u) * 0.06, f.L.z + (A.z - f.L.z) * e); - if (u >= 1) { f.done = true; continue; } - } else if (idle && off <= 0.02) { f.done = true; continue; } - var hip = worldPos(b['thigh_' + s], new T.Vector3()), knee = worldPos(b['calf_' + s], new T.Vector3()); - var axis = A.clone().sub(hip).normalize(), kd = knee.clone().sub(hip); - var pole = kd.addScaledVector(axis, -kd.dot(axis)).addScaledVector(fwd, 0.08); - legIK(b['thigh_' + s], b['calf_' + s], foot, tgt, pole.normalize(), wIn); - } - }; - AP._footIK = function (dt) { - var b = this.bones, root = this.root, ry = new T.Vector3().setFromMatrixPosition(root.matrixWorld).y; - var sides = ['l', 'r'], off = {}, pos = {}, i; - for (i = 0; i < 2; i++) { - var s = sides[i], f = b['foot_' + s]; if (!f) return; - var p = worldPos(f, new T.Vector3()); - var g = this.groundAt(p.x, p.z); - pos[s] = p; off[s] = (g == null ? ry : g) - ry; - // ease each foot's ground height (a step edge would otherwise lift the foot in one frame); faster upward - // so a toe never sinks into a step - if (!this._gOff) this._gOff = {}; - var go = this._gOff[s] == null ? off[s] : this._gOff[s]; - go += (off[s] - go) * Math.min(1, dt * (off[s] > go ? 22 : 12)); - this._gOff[s] = go; off[s] = go; - } - var drop = Math.min(0, Math.min(off.l, off.r)) * (this._ikW == null ? 1 : this._ikW); - this._pelDrop += (drop - this._pelDrop) * Math.min(1, dt * 12); - var pel = b.pelvis, wp = worldPos(pel, new T.Vector3()); - wp.y += this._pelDrop; - var inv = new T.Matrix4().copy(pel.parent.matrixWorld).invert(); - pel.position.copy(wp.applyMatrix4(inv)); pel.updateMatrixWorld(true); - for (i = 0; i < 2; i++) { - var s2 = sides[i], foot = b['foot_' + s2]; - var cur = worldPos(foot, new T.Vector3()); - var target = cur.clone(); target.y = pos[s2].y + off[s2]; // animated height above local ground - var fq = worldQuat(foot, new T.Quaternion()); - twoBone(b['thigh_' + s2], b['calf_' + s2], foot, target, fq, this._ikW == null ? 1 : this._ikW); - } - }; - var AIM_P = [['spine_01', 0.15], ['spine_02', 0.2], ['spine_03', 0.35], ['neck_01', 0.12], ['Head', 0.18]]; - var AIM_Y = [['spine_01', 0.18], ['spine_02', 0.22], ['spine_03', 0.3], ['neck_01', 0.12], ['Head', 0.18]]; - AP._applyAim = function () { - var rq = worldQuat(this.root, new T.Quaternion()); - var left = new T.Vector3(1, 0, 0).applyQuaternion(rq), up = new T.Vector3(0, 1, 0).applyQuaternion(rq); - var q = new T.Quaternion(); - // prone: the body lies on its elbows, so the aim can only tilt a little (the clip already holds the rifle level); - // a camera looking down must not bend the lying spine and point the gun into the ground - var pr = this._stW ? this._stW.prone : 0, aY = this.aimY * (1 - 0.6 * pr); - var aP = this.aimP * (1 - pr) + Math.max(-0.2, Math.min(0.25, this.aimP)) * 0.5 * pr; - for (var i = 0; i < AIM_Y.length; i++) { - var b = this.bones[AIM_Y[i][0]]; if (!b) continue; - q.setFromAxisAngle(up, aY * AIM_Y[i][1]); rotWorld(b, q); - } - for (i = 0; i < AIM_P.length; i++) { - b = this.bones[AIM_P[i][0]]; if (!b) continue; - // pitch about the character's current left axis (after yaw) - var l2 = left.clone().applyAxisAngle(up, aY * 0.7); - q.setFromAxisAngle(l2, -aP * AIM_P[i][1]); rotWorld(b, q); - } - }; - AP.dispose = function () { - if (this.fb) return FB.dispose(this); - this.mixer.stopAllAction(); this.mixer.uncacheRoot(this.model); - if (this.root.parent) this.root.parent.remove(this.root); - }; - - IV.spawn = function (kind, opts) { - if (!(kind in KINDS)) kind = 'rifleman'; - var a = new Actor(kind); - if (opts && opts.face != null && !a.fb) a.setFace(opts.face); - return a; - }; - - // ===================================================================================== - // Fallback: a code-made skinned human (lofted limbs on the same 22-bone layout) with procedural motion. - // Used only when the GLB files cannot be loaded, so the game never shows nothing. - // ===================================================================================== - var FB = IV._fallback = (function () { - var J = { // bind-pose joint positions (three.js frame: +X left, +Y up, +Z forward) - pelvis: [0, 1.0, 0.007], spine_01: [0, 1.09, 0.031], spine_02: [0, 1.16, 0.039], spine_03: [0, 1.22, 0.037], neck_01: [0, 1.57, 0.12], - Head: [0, 1.68, 0.14], clavicle_l: [0.024, 1.5, 0.124], upperarm_l: [0.188, 1.5, 0.027], lowerarm_l: [0.456, 1.5, 0.022], - hand_l: [0.728, 1.5, 0.027], thigh_l: [0.113, 1.0, -0.005], calf_l: [0.113, 0.54, -0.009], foot_l: [0.113, 0.086, -0.045], ball_l: [0.113, 0.01, 0.083] - }; - ['clavicle', 'upperarm', 'lowerarm', 'hand', 'thigh', 'calf', 'foot', 'ball'].forEach(function (n) { - var p = J[n + '_l']; J[n + '_r'] = [-p[0], p[1], p[2]]; - }); - var PARENT = { pelvis: null, spine_01: 'pelvis', spine_02: 'spine_01', spine_03: 'spine_02', neck_01: 'spine_03', Head: 'neck_01' }; - ['l', 'r'].forEach(function (s) { - PARENT['clavicle_' + s] = 'spine_03'; PARENT['upperarm_' + s] = 'clavicle_' + s; PARENT['lowerarm_' + s] = 'upperarm_' + s; - PARENT['hand_' + s] = 'lowerarm_' + s; PARENT['thigh_' + s] = 'pelvis'; PARENT['calf_' + s] = 'thigh_' + s; PARENT['foot_' + s] = 'calf_' + s; PARENT['ball_' + s] = 'foot_' + s; - }); - PARENT.weapon_r = 'hand_r'; J.weapon_r = J.hand_r; - var NAMES = Object.keys(PARENT); - // limb segments: [bone, from joint, to joint, radius at start, radius at end] - var SEG = [ - ['pelvis', [0, 0.92, 0.0], [0, 1.1, 0.0], 0.16, 0.15], ['spine_02', [0, 1.1, 0.0], [0, 1.3, 0.0], 0.15, 0.17], - ['spine_03', [0, 1.3, 0.0], [0, 1.52, 0.0], 0.18, 0.15], ['neck_01', [0, 1.52, 0.03], [0, 1.66, 0.05], 0.06, 0.055], - ['Head', [0, 1.62, 0.06], [0, 1.82, 0.06], 0.085, 0.07] - ]; - ['l', 'r'].forEach(function (s) { - var m = s === 'l' ? 1 : -1; - SEG.push(['upperarm_' + s, [m * 0.17, 1.47, 0.02], [m * 0.456, 1.5, 0.022], 0.065, 0.048]); - SEG.push(['lowerarm_' + s, [m * 0.456, 1.5, 0.022], [m * 0.728, 1.5, 0.027], 0.045, 0.034]); - SEG.push(['hand_' + s, [m * 0.728, 1.5, 0.027], [m * 0.85, 1.5, 0.03], 0.033, 0.028]); - SEG.push(['thigh_' + s, [m * 0.11, 1.0, 0.0], [m * 0.113, 0.54, -0.009], 0.095, 0.06]); - SEG.push(['calf_' + s, [m * 0.113, 0.54, -0.009], [m * 0.113, 0.1, -0.04], 0.058, 0.04]); - SEG.push(['foot_' + s, [m * 0.113, 0.06, -0.06], [m * 0.113, 0.03, 0.17], 0.045, 0.04]); - }); - var geo = null, matCache = {}; - function buildGeo() { - var pos = [], nrm = [], idx = [], si = [], sw = [], col = []; - var RING = 12, ROWS = 6; - SEG.forEach(function (s) { - var bi = NAMES.indexOf(s[0]), pi = NAMES.indexOf(PARENT[s[0]] || s[0]); - var a = new T.Vector3().fromArray(s[1]), b = new T.Vector3().fromArray(s[2]); - var ax = b.clone().sub(a), len = ax.length(); ax.normalize(); - var u = Math.abs(ax.y) > 0.9 ? new T.Vector3(1, 0, 0) : new T.Vector3(0, 1, 0); - var v1 = new T.Vector3().crossVectors(ax, u).normalize(), v2 = new T.Vector3().crossVectors(ax, v1).normalize(); - var base = pos.length / 3; - for (var r = 0; r <= ROWS; r++) { - var f = r / ROWS, rad = s[3] + (s[4] - s[3]) * f; - rad *= Math.sin(Math.PI * (0.12 + 0.76 * f)) * 0.25 + 0.8; // rounded ends - var c = a.clone().addScaledVector(ax, len * f); - for (var k = 0; k < RING; k++) { - var th = k / RING * Math.PI * 2, n = v1.clone().multiplyScalar(Math.cos(th)).addScaledVector(v2, Math.sin(th)); - var p = c.clone().addScaledVector(n, rad); - pos.push(p.x, p.y, p.z); nrm.push(n.x, n.y, n.z); - // blend into the parent bone over the first third - var wp = Math.max(0, 0.5 - f * 1.6); - si.push(bi, pi, 0, 0); sw.push(1 - wp, wp, 0, 0); - } - } - for (r = 0; r < ROWS; r++) for (k = 0; k < RING; k++) { - var i0 = base + r * RING + k, i1 = base + r * RING + (k + 1) % RING; - idx.push(i0, i1, i0 + RING, i1, i1 + RING, i0 + RING); - } - }); - var g = new T.BufferGeometry(); - g.setAttribute('position', new T.Float32BufferAttribute(pos, 3)); - g.setAttribute('normal', new T.Float32BufferAttribute(nrm, 3)); - g.setAttribute('skinIndex', new T.Uint16BufferAttribute(si, 4)); - g.setAttribute('skinWeight', new T.Float32BufferAttribute(sw, 4)); - g.setIndex(idx); g.computeVertexNormals(); - g.boundingSphere = new T.Sphere(new T.Vector3(0, 0.9, 0), 1.45); - return g; - } - var COL = { hero: 0x67664a, ally: 0x6a6a4c, rifleman: 0x5f6352, officer: 0x56594c, sniper: 0x65684e, gunner: 0x5f6352 }; - var api = { tris: 0 }; - api.init = function (a, kind) { - if (!geo) { geo = buildGeo(); api.tris = geo.index.count / 3; } - var mat = matCache[kind] || (matCache[kind] = new T.MeshStandardMaterial({ color: new T.Color(COL[kind] || 0x666655).convertSRGBToLinear(), roughness: 0.85, skinning: true })); - var bones = {}, list = []; - NAMES.forEach(function (n) { var b = new T.Bone(); b.name = n; bones[n] = b; list.push(b); }); - NAMES.forEach(function (n) { - var p = PARENT[n], b = bones[n], jp = new T.Vector3().fromArray(J[n]); - if (p) { bones[p].add(b); jp.sub(new T.Vector3().fromArray(J[p])); } - b.position.copy(jp); - }); - var mesh = new T.SkinnedMesh(geo, mat); mesh.castShadow = true; - var root = new T.Group(); root.name = 'IV_' + kind + '_fallback'; - root.add(mesh); mesh.add(bones.pelvis); root.updateMatrixWorld(true); - mesh.bind(new T.Skeleton(list)); - a.root = root; a.bones = bones; a.meshes = [mesh]; a.lods = []; a.t = 0; a.state = 'idle'; a.upperName = null; - a.aimP = a.aimY = 0; a.attached = []; a.height = 1.8; a.speed = 1; a.once = false; a.stateT = 0; - a.rest = {}; NAMES.forEach(function (n) { a.rest[n] = bones[n].quaternion.clone(); }); - }; - api.play = function (a, name, o) { o = o || {}; if (a.state !== name) a.stateT = 0; a.state = name; a.speed = o.speed == null ? 1 : o.speed; a.once = !!(o.once || o.loop === false); return a; }; - api.setUpper = function (a, name) { a.upperName = name; return a; }; - api.bone = function (a, n) { return a.bones[n] || null; }; - var q = new T.Quaternion(), e = new T.Euler(); - function rot(a, n, x, y, z) { var b = a.bones[n]; if (!b) return; e.set(x, y, z); b.quaternion.copy(a.rest[n]).multiply(q.setFromEuler(e)); } - api.update = function (a, dt) { - a.t += dt * a.speed; a.stateT += dt; - var s = a.state, t = a.t, k; - var gait = { walk: [1.9, 0.45], run: [2.8, 0.75], sprint: [3.4, 0.95], crouchWalk: [1.6, 0.4], aimWalk: [1.9, 0.4], limp: [1.5, 0.35] }[s]; - for (var n in a.rest) a.bones[n].quaternion.copy(a.rest[n]); - a.bones.pelvis.position.set(0, 1.0, 0.007); - // arms down from the T bind pose - rot(a, 'upperarm_l', 0, 0, -1.25); rot(a, 'upperarm_r', 0, 0, 1.25); - if (gait) { - var ph = t * gait[0] * Math.PI, amp = gait[1]; - rot(a, 'thigh_l', Math.sin(ph) * amp, 0, 0); rot(a, 'thigh_r', -Math.sin(ph) * amp, 0, 0); - rot(a, 'calf_l', Math.max(0, -Math.cos(ph)) * amp * 1.3, 0, 0); rot(a, 'calf_r', Math.max(0, Math.cos(ph)) * amp * 1.3, 0, 0); - rot(a, 'upperarm_l', -Math.sin(ph) * amp * 0.6, 0, -1.25); rot(a, 'upperarm_r', Math.sin(ph) * amp * 0.6, 0, 1.25); - rot(a, 'pelvis', 0, Math.sin(ph) * 0.08, Math.sin(ph) * 0.04); - a.bones.pelvis.position.y = 1.0 - Math.abs(Math.cos(ph)) * 0.03 * amp - (s === 'crouchWalk' ? 0.3 : 0); - } - if (/crouch/.test(s)) { a.bones.pelvis.position.y = 0.7; rot(a, 'thigh_l', -1.2, 0, 0); rot(a, 'thigh_r', -1.0, 0, 0); rot(a, 'calf_l', 1.9, 0, 0); rot(a, 'calf_r', 1.7, 0, 0); } - if (/prone/.test(s)) { a.bones.pelvis.position.y = 0.15; rot(a, 'pelvis', 1.5, 0, 0); } - if (/death/.test(s)) { k = Math.min(1, a.stateT / 0.9); a.bones.pelvis.position.y = 1.0 - k * 0.85; rot(a, 'pelvis', (s === 'deathBack' ? -1 : 1) * 1.45 * k * k, 0, 0); } - if (/aim|fire|hold/.test(s) || (a.upperName && /aim|fire|hold/.test(a.upperName))) { - rot(a, 'upperarm_r', -1.2, 0.3, 0.3); rot(a, 'lowerarm_r', 0, -1.2, 0); rot(a, 'upperarm_l', -1.2, -0.6, -0.2); rot(a, 'lowerarm_l', 0, 0.6, 0); - } - rot(a, 'spine_02', -a.aimP * 0.5, a.aimY * 0.5, 0); - a.root.updateMatrixWorld(true); - return a; - }; - api.dispose = function (a) { if (a.root.parent) a.root.parent.remove(a.root); }; - api.weapon = function (kind) { - var L = { rifleScoped: 1.1, smg: 0.75, pistol: 0.2, enemyRifle: 1.1, enemySmg: 0.6, mg: 1.2, knife: 0.3, binoculars: 0.15, grenade: 0.1 }[kind] || 0.5; - var g = new T.BoxGeometry(0.04, 0.06, L); g.translate(0, 0, L * 0.4); - var m = new T.Mesh(g, new T.MeshStandardMaterial({ color: new T.Color(0x2a2620).convertSRGBToLinear(), roughness: 0.6 })); - var mz = new T.Object3D(); mz.name = kind + '_muzzle'; mz.position.set(0, 0, L * 0.9); m.add(mz); - m.userData.muzzle = mz; m.userData.grip = { r: null, l: null }; m.userData.kind = kind; - return m; - }; - return api; - })(); -})(); diff --git a/e63334287a3deaa3/ironveil/env-test.html b/e63334287a3deaa3/ironveil/env-test.html deleted file mode 100644 index 835d2b6c..00000000 --- a/e63334287a3deaa3/ironveil/env-test.html +++ /dev/null @@ -1,328 +0,0 @@ - - - - - - -Midnight Ops: environment test - - - - -
Making textures…
-
- - -
-
Drag to look, WASD / arrows to fly, Q/E down/up, Shift fast. Touch: drag to look, two fingers to move.
-
- - - - - - - - - - - - - - - - - diff --git a/e63334287a3deaa3/ironveil/env/atmosphere.js b/e63334287a3deaa3/ironveil/env/atmosphere.js deleted file mode 100644 index 51d7a0ff..00000000 --- a/e63334287a3deaa3/ironveil/env/atmosphere.js +++ /dev/null @@ -1,494 +0,0 @@ -/* Midnight Ops environment: atmosphere. Sky dome (gradient, stars, moon, moving cloud, dithered so it does not band), - moon/sun light with shadows, hemisphere fill, exponential fog plus low ground mist that pools in hollows, an - environment map rendered from the sky (reflections in puddles and glass), exposure, wetness and rain. - IVEnv.atmosphere(scene, renderer, preset, opts) -> { sun, hemi, update(dt, camera), set(preset), preset } - Ground mist works by extending three's fog shader chunks (every material with fog: true gets it). The mist settings - ride in the fog object's near/far uniforms: IVEnv uses an object that is both FogExp2 (for the define) and Fog - (so three uploads near = density, far = packed mist base height and amount). */ -(function () { - 'use strict'; - const E = window.IVEnv; - - // sRGB hex helper -> linear THREE.Color - const L = (h) => E.lin(h); - E.PRESETS = { - // Night Drop. One key: the moon, cool and from the same direction as before (stealth reads it), strong enough to - // throw long shadows but not to paint the fields pale; a low, cool fill so shadow is real dark (lifted a little by - // the grade, never crushed); a wide soft glow round the moon in a broken deck. Lamps and windows do the rest. - night_moon: { - skyTop: 0x04060b, skyHor: 0x26303f, ground: 0x07080a, fog: 0x161d27, fogD: 0.0105, mist: 0.5, mistTop: 1.8, - sunDir: [-0.5, 0.74, 0.45], sunCol: 0xa3b8de, sunI: 2.2, sunShadow: true, soft: 2.5, moon: 1, stars: 1, cloud: 0.42, cloudCol: 0x161b24, glow: 0.55, cscale: 0.6, - hemiSky: 0x33435f, hemiGround: 0x1c1712, hemiI: 0.5, env: 0.45, exposure: 1.1, wind: 0.35, wet: 0.22, rain: 0, grade: 'night', rim: 0.55, rimCol: 0x8aa0c8 - }, - night_overcast: { - skyTop: 0x080a0d, skyHor: 0x1b1f25, ground: 0x0b0c0d, fog: 0x171b20, fogD: 0.0135, mist: 0.7, mistTop: 2.2, - sunDir: [-0.3, 0.8, 0.4], sunCol: 0x8a96aa, sunI: 0.16, sunShadow: false, moon: 0.15, stars: 0, cloud: 1.0, cloudCol: 0x1d2128, - hemiSky: 0x6a7488, hemiGround: 0x34322e, hemiI: 1.0, env: 0.6, exposure: 1.1, wind: 0.5, wet: 0.3, rain: 0, grade: 'night' - }, - dawn_mist: { - skyTop: 0x3c4e66, skyHor: 0xb39a86, ground: 0x2a2a28, fog: 0x8c8e8e, fogD: 0.016, mist: 1.0, mistTop: 3.2, - sunDir: [0.85, 0.12, 0.3], sunCol: 0xffc690, sunI: 0.9, sunShadow: true, moon: 0, stars: 0, cloud: 0.55, cloudCol: 0x9a8f88, - hemiSky: 0x8f9cb0, hemiGround: 0x3c3a34, hemiI: 0.5, env: 0.7, exposure: 0.95, wind: 0.2, wet: 0.35, rain: 0, grade: 'dawn' - }, - night_rain: { - skyTop: 0x06080b, skyHor: 0x1a1e24, ground: 0x0b0c0d, fog: 0x161a1f, fogD: 0.016, mist: 0.6, mistTop: 2.0, - // key: a low, cool moon through a ragged gap in the deck (lit side, dark side and a rim on everything; a long - // glint toward it on wet ground); the fill drops so the key reads. Moon shadows on High only (shadowHi). - sunDir: [-0.78, 0.3, 0.5], sunCol: 0x9fb0d0, sunI: 1.45, sunShadow: true, shadowHi: 1, moon: 0.55, gap: 1, stars: 0, cloud: 1.0, cloudCol: 0x1a1d22, - hemiSky: 0x56606f, hemiGround: 0x262422, hemiI: 0.74, env: 0.5, exposure: 1.1, wind: 1.1, wet: 1.0, rain: 1, grade: 'rain' - }, - dusty: { - skyTop: 0x9a9284, skyHor: 0xc8b89c, ground: 0x6a5c48, fog: 0xb8a78a, fogD: 0.012, mist: 0.0, mistTop: 1.0, - sunDir: [0.5, 0.55, 0.3], sunCol: 0xf0d8b0, sunI: 1.6, sunShadow: true, moon: 0, stars: 0, cloud: 0.4, cloudCol: 0xb0a490, - hemiSky: 0xc8b8a0, hemiGround: 0x6a5a44, hemiI: 0.7, env: 0.9, exposure: 0.9, wind: 0.9, wet: 0.0, rain: 0, grade: 'day' - }, - dusk_rain: { - skyTop: 0x1a1f28, skyHor: 0x4a4c50, ground: 0x151617, fog: 0x34383d, fogD: 0.017, mist: 0.6, mistTop: 2.0, - sunDir: [-0.85, 0.22, -0.2], sunCol: 0xb79a88, sunI: 0.75, sunShadow: true, moon: 0, gap: 0.7, stars: 0, cloud: 1.0, cloudCol: 0x2c3036, - hemiSky: 0x7a8494, hemiGround: 0x2e2c2a, hemiI: 0.85, env: 0.8, exposure: 1.0, wind: 1.3, wet: 1.0, rain: 1, grade: 'rain' - }, - // Boot Camp. Overcast, but with a direction: the sun is a bright patch behind thinner cloud low in the south-west - // quarter, so there is a lit side and a shade side, soft shadows under huts, sandbags and people, and big cloud - // shapes with a lit edge toward it; the fill is lower than before so things have weight; haze separates the range, - // the hedge line and the hills. - day_overcast: { - skyTop: 0x5f6f80, skyHor: 0xaeb4b7, ground: 0x4b4a44, fog: 0xa3a9ac, fogD: 0.0042, mist: 0.0, mistTop: 1.0, - sunDir: [0.55, 0.36, -0.77], sunCol: 0xece0c8, sunI: 1.3, sunShadow: true, soft: 4, moon: 0, stars: 0, cloud: 1.0, cloudCol: 0x6a7076, glow: 0.6, cscale: 0.75, - hemiSky: 0xa3b3c6, hemiGround: 0x8a7f68, hemiI: 1.7, env: 0.8, exposure: 1.0, wind: 0.6, wet: 0.0, rain: 0, grade: 'day', rim: 0.08, cloudShadow: 1 - } - }; - - // ------------------------------------------------------------------ environment light as three r128 drew it - // The game's environment maps are small cube renders of the sky with plain mipmaps (cubeRT below; js/fp.js vmEnv). - // three r128 used such a cube for reflections only (a mip picked by roughness); it added no diffuse light from it - // (that came only with a PMREM). r187 turns every cube into a PMREM and adds its diffuse light too, which lit - // interiors about twice as bright (measured: Boot Camp hut, environment-only light 23 -> 45 of 255). The cubes are - // flagged isPMREMTexture so r187 uses them as they are, and this chunk puts r128's lookups back (Midnight Ops only: - // this page's ShaderChunk, after lib/three's r128 compatibility layer). - let envChunkDone = false; - E.r128EnvChunk = function () { - if (envChunkDone) return; envChunkDone = true; - THREE.ShaderChunk.envmap_physical_pars_fragment = `#ifdef USE_ENVMAP - float ivEnvMaxMip() { return log2(float(textureSize(envMap, 0).x)); } - vec3 getIBLIrradiance( const in vec3 normal ) { return vec3( 0.0 ); } - vec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) { - vec3 reflectVec = reflect( - viewDir, normal ); - reflectVec = normalize( mix( reflectVec, normal, roughness * roughness ) ); - reflectVec = inverseTransformDirection( reflectVec, viewMatrix ); - float maxMip = ivEnvMaxMip(), sigma = PI * roughness * roughness / ( 1.0 + roughness ); - vec4 envMapColor = textureLod( envMap, envMapRotation * reflectVec, clamp( maxMip + log2( sigma ), 0.0, maxMip ) ); - return envMapColor.rgb * envMapIntensity; - } - #endif`; - }; - // a cube render target used as an environment map the r128 way (see above) - // r187 reads a PMREM texture's size from texture.mipmaps[0] when it builds the program; a real list of levels there - // would make it allocate the target per level (and CubeCamera cannot draw into that), so it gets an empty list that - // still answers [0] (the chunk above takes the level count from textureSize instead) - E.r128EnvCube = function (rt) { - E.r128EnvChunk(); rt.texture.isPMREMTexture = true; - rt.texture.mipmaps = { length: 0, 0: { width: rt.width, height: rt.width }, slice() { return []; } }; - return rt; - }; - - // ------------------------------------------------------------------ fog + mist chunks (installed once) - let chunksDone = false; - function installFogChunks() { - if (chunksDone) return; chunksDone = true; - const C = THREE.ShaderChunk; - C.fog_pars_vertex = '#ifdef USE_FOG\n varying float fogDepth;\n varying vec3 vFogW;\n#endif'; - C.fog_vertex = `#ifdef USE_FOG - fogDepth = - mvPosition.z; - { vec3 vt = mvPosition.xyz - viewMatrix[3].xyz; vFogW = vec3(dot(viewMatrix[0].xyz, vt), dot(viewMatrix[1].xyz, vt), dot(viewMatrix[2].xyz, vt)); } - #endif`; - C.fog_pars_fragment = `#ifdef USE_FOG - uniform vec3 fogColor; varying float fogDepth; varying vec3 vFogW; - #ifdef FOG_EXP2 - uniform float fogDensity; - #endif - uniform float fogNear; uniform float fogFar; - float ivFogH(vec2 p){ p = fract(p * vec2(0.1031, 0.1030)); p += dot(p, p.yx + 33.33); return fract((p.x + p.y) * p.x); } - float ivFogN(vec2 p){ vec2 i = floor(p), f = fract(p); vec2 u = f * f * (3.0 - 2.0 * f); - return mix(mix(ivFogH(i), ivFogH(i + vec2(1.0, 0.0)), u.x), mix(ivFogH(i + vec2(0.0, 1.0)), ivFogH(i + vec2(1.0, 1.0)), u.x), u.y); } - #endif`; - C.fog_fragment = `#ifdef USE_FOG - #ifdef FOG_EXP2 - bool ivMine = fogNear < 0.5; float fd = ivMine ? fogNear : fogDensity; - float fogFactor = 1.0 - exp( - fd * fd * fogDepth * fogDepth ); - if (ivMine && fract(fogFar) > 0.001) { - // ground mist: density falls off with height above a base; integrated along the view ray - float mAmt = fract(fogFar), mBase = floor(fogFar) / 10.0 - 500.0, Hm = 1.4; - float h1 = max(cameraPosition.y - mBase, 0.0), h2 = max(vFogW.y - mBase, 0.0); - float dist = length(vFogW - cameraPosition), dh = h2 - h1; - float e1 = exp(-h1 / Hm), e2 = exp(-h2 / Hm); - float integ = abs(dh) > 0.05 ? (e1 - e2) * Hm / dh : e1; - float pocket = 0.45 + 0.9 * ivFogN(vFogW.xz * 0.045 + 3.1) * ivFogN(vFogW.xz * 0.11); - float mist = 1.0 - exp(-integ * dist * 0.05 * mAmt * pocket); - fogFactor = 1.0 - (1.0 - fogFactor) * (1.0 - mist * 0.9); - } - #else - float fogFactor = smoothstep( fogNear, fogFar, fogDepth ); - #endif - gl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor ); - #endif`; - } - function makeFog() { - const f = new THREE.FogExp2(0x000000, 0.01); - f.isFog = true; f.near = 0.01; f.far = 0; // near = density, far = mist pack (see above) - return f; - } - function packMist(base, amt) { return Math.floor((base + 500) * 10) + Math.min(0.99, Math.max(0, amt)); } - - // ------------------------------------------------------------------ sky - const SKY_VS = 'varying vec3 vD; void main(){ vD = normalize(position); vec4 p = projectionMatrix * modelViewMatrix * vec4(position,1.0); gl_Position = p.xyww; }'; - // The sky: a gradient that is brighter in the quarter of the sky the key light is in, a wide glow round the sun or - // moon (haze scattering it forward) and a tighter core, stars, the moon's disc, and a cloud deck with relief: the - // deck's density sampled again a step toward the light, so cloud sides facing the light are lit and the far sides - // and thick cores fall dark; thin edges near the light glow. Lightning lights the deck from inside. - const SKY_FS = E.GLSL.noise + ` - uniform vec3 top, hor, gnd, moonDir, moonCol, cloudCol, flashDir; uniform float moonAmt, starAmt, cloud, time, bright, gap, flash, glow, cscale; - varying vec3 vD; - float fbm3(vec2 p){ float s = 0.0, a = 0.5; for (int i = 0; i < 5; i++){ s += a * ivN(p); p = p * 2.03 + 7.1; a *= 0.5; } return s; } - void main(){ - vec3 d = normalize(vD); - float h = d.y; - float md = max(dot(d, moonDir), 0.0); - vec2 hz = normalize(d.xz + 1e-4), lz = normalize(moonDir.xz + 1e-4); - float side = max(dot(hz, lz), 0.0); - vec3 c = mix(hor, top, pow(clamp(h, 0.0, 1.0), 0.5)); - c *= 1.0 + glow * 0.5 * side * side * (1.0 - smoothstep(0.0, 0.7, h)); - c = mix(c, gnd, smoothstep(0.0, -0.08, h)); - if (starAmt > 0.0 && h > 0.0) { - vec2 sp = vec2(atan(d.z, d.x) * 180.0, asin(clamp(h, -1.0, 1.0)) * 180.0); - vec2 ci = floor(sp), cf = fract(sp) - 0.5; - float r = ivH(ci), b = ivH(ci + 17.3); - float star = step(0.985, r) * smoothstep(0.12, 0.0, length(cf - (vec2(b, ivH(ci + 3.1)) - 0.5) * 0.6)); - star *= (0.5 + 0.5 * b) * (0.8 + 0.2 * sin(time * (2.0 + b * 3.0) + r * 40.0)); - c += vec3(0.55, 0.6, 0.75) * star * starAmt * smoothstep(0.0, 0.25, h); - } - if (moonAmt > 0.0) { - float disc = smoothstep(0.99955, 0.99975, md); - float mare = 0.8 + 0.2 * ivN(d.xy * 900.0); - c = mix(c, moonCol * 2.2 * mare, disc * moonAmt); - } - // the glow round the light (and the sun's own small bright core by day) - vec3 halo = moonCol * glow * (pow(md, 5.0) * 0.22 + pow(md, 40.0) * 0.5 + pow(md, 900.0) * 3.0 * (1.0 - moonAmt)); - float cov = 0.0; - if (h > 0.0 && cloud > 0.0) { - vec2 cp = d.xz / (h + 0.1) * cscale + vec2(time * 0.010, time * 0.004); - float n = fbm3(cp); - cov = smoothstep(1.0 - cloud * 0.85 - 0.12, 1.0 - cloud * 0.85 + 0.28, n + cloud * 0.35); - if (gap > 0.0) { float gd = md + (n - 0.5) * 0.16 + (fbm3(cp * 2.3 + 5.0) - 0.5) * 0.05; cov *= 1.0 - gap * 0.9 * smoothstep(0.9, 0.975, gd); } - // relief: thinner a step toward the light = this side faces the light - float n2 = fbm3(cp + lz * 0.16); - float rel = clamp((n - n2) * 5.0, -1.0, 1.0); - float thick = smoothstep(0.45, 0.95, n); - float toward = 0.35 + 0.65 * pow(md, 2.0); - vec3 dark = cloudCol * 0.6, litc = mix(cloudCol, moonCol, 0.25) * (1.0 + 0.45 * toward); - vec3 cc = mix(dark, litc, clamp(0.45 + 0.55 * rel * toward - 0.4 * thick, 0.0, 1.0)); - float edge = cov * (1.0 - cov) * 4.0; - cc += moonCol * glow * (pow(md, 6.0) * 0.6 + pow(md, 30.0) * 1.2) * edge; - if (flash > 0.0) { - float fd = max(dot(d, flashDir), 0.0), dens = cov * smoothstep(0.3, 0.75, n); - vec2 fl = normalize(flashDir.xz + 1e-4) * 0.07; float frel = clamp((n - fbm3(cp + fl)) * 4.0, -1.0, 1.0); - float core = pow(fd, 14.0) * (0.15 + 1.6 * dens * dens) * (1.0 + 0.8 * frel), hl = pow(fd, 4.0) * 0.1 * dens; - cc += vec3(0.5, 0.56, 0.74) * flash * (core + hl) * 0.55; - } - float band = fbm3(cp * 0.33 + vec2(7.0, 1.3)); - cc *= mix(0.72, 1.1, smoothstep(0.32, 0.68, band)); - cov *= smoothstep(0.0, 0.12, h); - c = mix(c, cc, cov); - } - c += halo * (1.0 - 0.7 * cov); - c *= bright; - c += (ivH(gl_FragCoord.xy + fract(time) * 61.0) - 0.5) / 255.0; - gl_FragColor = vec4(c, 1.0); - }`; - function skyMaterial() { - return new THREE.ShaderMaterial({ - uniforms: { - top: { value: new THREE.Color() }, hor: { value: new THREE.Color() }, gnd: { value: new THREE.Color() }, moonDir: { value: new THREE.Vector3(0, 1, 0) }, - moonCol: { value: new THREE.Color(0xdde6ff) }, cloudCol: { value: new THREE.Color() }, moonAmt: { value: 1 }, starAmt: { value: 1 }, cloud: { value: 0.4 }, time: { value: 0 }, bright: { value: 1 }, - gap: { value: 0 }, flash: { value: 0 }, glow: { value: 0.3 }, cscale: { value: 1.3 }, flashDir: { value: new THREE.Vector3(0.3, 0.4, -0.8).normalize() } - }, - vertexShader: SKY_VS, fragmentShader: SKY_FS, side: THREE.BackSide, depthWrite: false, depthTest: true, fog: false, toneMapped: true - }); - } - - // ------------------------------------------------------------------ rain - // Rain: line streaks in a box that wraps round the camera, all motion in the vertex shader. Nearly invisible in - // the dark, they flare inside lamp light (the four nearest point lights are passed in each frame). - function makeRain(n) { - const g = new THREE.BufferGeometry(), p = new Float32Array(n * 6), e = new Float32Array(n * 2), R = E.rng(5); - for (let i = 0; i < n; i++) { const x = R(), y = R(), z = R(); p.set([x, y, z, x, y, z], i * 6); e[i * 2] = 0; e[i * 2 + 1] = 1; } - g.setAttribute('position', new THREE.BufferAttribute(p, 3)); g.setAttribute('aEnd', new THREE.BufferAttribute(e, 1)); - const m = new THREE.ShaderMaterial({ - uniforms: { uTime: E.U.uTime, uWind: E.U.uWind, uAmt: { value: 1 }, uLamp: { value: [0, 1, 2, 3].map(() => new THREE.Vector4()) }, uLampC: { value: [0, 1, 2, 3].map(() => new THREE.Color()) }, uFlash: { value: 0 } }, - vertexShader: `uniform float uTime, uAmt, uFlash; uniform vec3 uWind; uniform vec4 uLamp[4]; uniform vec3 uLampC[4]; attribute float aEnd; varying vec3 vC; varying float vA; - void main(){ - vec3 B = vec3(26.0, 16.0, 26.0); - vec3 vel = vec3(uWind.x * uWind.z * 2.2, -9.5 - position.x * 2.5, uWind.y * uWind.z * 2.2); - vec3 p = position * B + vel * uTime; - p = mod(p - cameraPosition + 0.5 * B, B) - 0.5 * B + cameraPosition; - p -= normalize(vel) * aEnd * 0.3; - vec3 c = vec3(0.32, 0.36, 0.42) * 0.25; float a = 0.07; - for (int i = 0; i < 4; i++) { float d = length(p - uLamp[i].xyz); float gl = uLamp[i].w * smoothstep(9.0, 0.5, d); c += uLampC[i] * gl * 0.9; a += gl * 0.5; } - c += vec3(0.6, 0.65, 0.8) * uFlash; a += uFlash * 0.3; - float dc = length(p - cameraPosition); - vA = a * step(position.y, uAmt) * smoothstep(0.4, 1.5, dc) * smoothstep(13.0, 7.0, dc); - vC = c; - gl_Position = projectionMatrix * viewMatrix * vec4(p, 1.0); - }`, - fragmentShader: 'varying vec3 vC; varying float vA; void main(){ gl_FragColor = vec4(vC * vA, vA); }', - transparent: true, depthWrite: false, blending: THREE.AdditiveBlending, fog: false - }); - const ls = new THREE.LineSegments(g, m); ls.frustumCulled = false; ls.renderOrder = 5; - return ls; - } - - // ------------------------------------------------------------------ the atmosphere object - E.atmosphere = function (scene, renderer, preset, opts) { - opts = opts || {}; - installFogChunks(); - const A = { flashes: opts.flashes !== false, scene, renderer, sun: null, hemi: null, mistBase: opts.mistBase != null ? opts.mistBase : 0, shadowR: opts.shadowRadius || (E.Q.name === 'low' ? 24 : 32) }; - const sun = A.sun = new THREE.DirectionalLight(0xffffff, 1); - const hemi = A.hemi = new THREE.HemisphereLight(0xffffff, 0x000000, 0.3); - scene.add(sun); scene.add(sun.target); scene.add(hemi); - const Q = E.Q; - if (opts.shadows !== false) { - const sz = opts.shadowMapSize || (Q.name === 'high' ? 2048 : Q.name === 'medium' ? 1536 : 1024); - sun.castShadow = true; sun.shadow.mapSize.set(sz, sz); - const s = A.shadowR; Object.assign(sun.shadow.camera, { left: -s, right: s, top: s, bottom: -s, near: 1, far: 260 }); - sun.shadow.bias = -0.0004; sun.shadow.normalBias = 0.035; sun.shadow.radius = 2; - sun.shadow.camera.updateProjectionMatrix(); - } - const sky = A.skyMat = skyMaterial(); - const dome = A.dome = new THREE.Mesh(new THREE.SphereGeometry(800, 48, 24), sky); - dome.frustumCulled = false; dome.renderOrder = -10; scene.add(dome); - const fog = A.fog = makeFog(); scene.fog = fog; - const rain = A.rain = makeRain(Q.name === 'low' ? 1200 : 3000); rain.visible = false; scene.add(rain); - // environment map from a copy of the sky - const envScene = new THREE.Scene(), envDome = new THREE.Mesh(new THREE.SphereGeometry(100, 32, 16), sky.clone()); - envScene.add(envDome); - // A small cube render of the sky with mipmaps (PMREM float targets proved unreliable on software GL). - const cubeRT = E.r128EnvCube(new THREE.WebGLCubeRenderTarget(64, { generateMipmaps: true, minFilter: THREE.LinearMipmapLinearFilter, magFilter: THREE.LinearFilter, type: THREE.UnsignedByteType })); - const cubeCam = new THREE.CubeCamera(0.1, 200, cubeRT); envScene.add(cubeCam); - A.dir = new THREE.Vector3(); - - // one weather state: A.set(name) at once, A.blendTo(name, seconds) eased; sky, sun/moon, fill, fog and mist, - // exposure, wetness, wind, rain and the environment map all follow the same blended values - A.blendTo = function (name, secs) { const to = E.PRESETS[name]; if (!to) return A; A.blend = { from: Object.assign({}, A.P), to, name, t: 0, T: Math.max(0.1, secs || 30), envT: 0 }; return A; }; - const mixP = (a, b, k) => { const o = {}; for (const key in b) { const x = a[key], y = b[key]; if (typeof y === 'number' && typeof x === 'number') { if (/(sky|Hor|ground|fog$|Col|hemi(Sky|Ground)|cloudCol)/.test(key) && y > 2) { o[key] = new THREE.Color(x).lerp(new THREE.Color(y), k).getHex(); } else o[key] = x + (y - x) * k; } else if (Array.isArray(y) && Array.isArray(x)) o[key] = y.map((v, i) => x[i] + (v - x[i]) * k); else o[key] = k < 0.5 ? x : y; } o.rain = k > 0.35 ? b.rain : a.rain; o.grade = k < 0.5 ? a.grade : b.grade; return o; }; - A.stepBlend = function (dt) { const B = A.blend; if (!B) return; B.t += dt; const u = Math.min(1, B.t / B.T), k = u * u * (3 - 2 * u); B.envT -= dt; const refresh = B.envT <= 0 || u >= 1; if (refresh) B.envT = 1; A.apply(mixP(B.from, B.to, k), B.name, !refresh); if (u >= 1) { A.blend = null; A.preset = B.name; A.P = B.to; } }; - A.set = function (name) { A.blend = null; return A.apply(E.PRESETS[name] || E.PRESETS.night_moon, name); }; - A.apply = function (P, name, skipEnv) { - A.preset = name; A.P = P; - A.dir.set(P.sunDir[0], P.sunDir[1], P.sunDir[2]).normalize(); - const u = sky.uniforms; - u.top.value.copy(L(P.skyTop)); u.hor.value.copy(L(P.skyHor)); u.gnd.value.copy(L(P.ground)); u.moonDir.value.copy(A.dir); - u.moonAmt.value = P.moon; u.starAmt.value = P.stars; u.cloud.value = P.cloud; u.glow.value = P.glow != null ? P.glow : 0.3; u.cscale.value = P.cscale || 1.3; u.cloudCol.value.copy(L(P.cloudCol)); u.gap.value = P.gap || 0; - if (!P.moon) u.moonCol.value.copy(L(P.sunCol)); else u.moonCol.value.set(0xdde6ff).convertSRGBToLinear(); - sun.color.copy(L(P.sunCol)); sun.intensity = P.sunI; sun.shadow.radius = (P.soft || 3) * (Q.name === 'high' ? 1.25 : 1); // shadow edge width in map texels (js/render.js widens the kernel) - sun.castShadow = opts.shadows !== false && !!P.sunShadow && (P.shadowHi < 0.5 || !P.shadowHi || Q.name === 'high'); - hemi.color.copy(L(P.hemiSky)); hemi.groundColor.copy(L(P.hemiGround)); hemi.intensity = P.hemiI; - E.U.uRim.value.copy(L(P.rimCol || P.hemiSky)).multiplyScalar(P.rim != null ? P.rim : 0.1); - E.U.uWinC.value.copy(L(P.hemiSky)).multiplyScalar(P.hemiI).add(L(P.sunCol).multiplyScalar(P.sunI * 0.12)); // the light coming in at windows and doors - // a room's own scattered light: by day a little of the window light; at night more, and warm from the lamps in the - // rooms (moonlit windows alone left a hall near black and blue) - if (P.grade === 'night' || P.grade === 'rain') E.U.uRoomAmb.value.copy(E.U.uWinC.value).multiplyScalar(0.2).add(new THREE.Color(0.05, 0.034, 0.018)); else E.U.uRoomAmb.value.copy(E.U.uWinC.value).multiplyScalar(0.12); - fog.color.copy(L(P.fog)); fog.near = (opts.fogD || P.fogD) * (opts.fogMul || 1); // opts.fogD: a map's own haze in place of the preset's fog.far = packMist(A.mistBase + P.mistTop - 1.8, P.mist * 0.99); - scene.background = null; - renderer.toneMappingExposure = P.exposure * (A.brightness || 1) * (E.Q.post ? 1 : P.grade === 'day' ? 1.2 : 1.0); // Low has no grade/lift pass - E.U.uWet.value = P.wet; E.U.uRain.value = P.rain ? 1 : 0; E.U.uDust.value = P.rain ? 0 : P.grade === 'day' ? 0.5 : 0.35; E.U.uNight.value = P.grade === 'night' || P.grade === 'rain' ? 1 : 0; - E.setWind(E.U.uWind.value.x, E.U.uWind.value.y, P.wind); - rain.visible = !!P.rain && Q.name !== 'low' || (!!P.rain && opts.rainOnLow); - // environment map: the sky (no stars, no sun disc glare) scaled by env - if (skipEnv) return A; - const eu = envDome.material.uniforms; for (const k in u) if (eu[k]) eu[k].value = u[k].value && u[k].value.clone ? u[k].value.clone() : u[k].value; - eu.starAmt.value = 0; eu.bright.value = P.env; eu.moonAmt.value = P.moon * 0.6; - const tm = renderer.toneMapping; renderer.toneMapping = THREE.NoToneMapping; - envDome.material.uniforms.bright.value = P.env; - cubeCam.update(renderer, envScene); - renderer.toneMapping = tm; - scene.environment = cubeRT.texture; - return A; - }; - // brightness setting for players (multiplies exposure) - A.setBrightness = function (b) { A.brightness = b; renderer.toneMappingExposure = A.P.exposure * b * (E.Q.post ? 1 : A.P.grade === 'day' ? 1.2 : 1.0); }; - A.setFlashes = function (on) { A.flashes = !!on; if (!on) A.flashAge = 99; }; // reduced-effects setting - A.update = function (dt, camera) { - if (A.blend) A.stepBlend(dt); - sky.uniforms.time.value += dt; - dome.position.copy(camera.position); - // shadow camera follows the camera, snapped to texels so shadows do not swim - if (sun.castShadow) { - const s = A.shadowR, texel = (2 * s) / sun.shadow.mapSize.x; - const fwd = new THREE.Vector3(); camera.getWorldDirection(fwd); fwd.y = 0; if (fwd.lengthSq() > 0) fwd.normalize(); - const fx = Math.round((camera.position.x + fwd.x * s * 0.5) / texel) * texel, fz = Math.round((camera.position.z + fwd.z * s * 0.5) / texel) * texel; - const fy = Math.round(camera.position.y); - sun.target.position.set(fx, fy, fz); sun.position.set(fx + A.dir.x * 120, fy + A.dir.y * 120, fz + A.dir.z * 120); - } else { sun.position.copy(A.dir).multiplyScalar(100); sun.target.position.set(0, 0, 0); } - if (rain.visible) { - const U = rain.material.uniforms, cp = camera.position; let k = 0; - const ls = []; scene.traverse(o => { if (o.isPointLight && o.intensity > 0 && o.visible) ls.push(o); }); - ls.sort((a, b) => a.position.distanceToSquared(cp) - b.position.distanceToSquared(cp)); - for (; k < 4; k++) { const l = ls[k]; if (l) { U.uLamp.value[k].set(l.position.x, l.position.y, l.position.z, Math.min(1.5, l.intensity * 0.5)); U.uLampC.value[k].copy(l.color); } else U.uLamp.value[k].w = 0; } - // lightning: a double flicker every 12-25 s, cool white, on the hemisphere light and the rain - A.flashT = (A.flashT == null ? 8 : A.flashT) - dt; - if (A.flashT < 0) { A.flashT = 12 + Math.random() * 13; A.flashAge = A.flashes ? 0 : 99; - { const az = Math.random() * Math.PI * 2, el = 0.12 + Math.random() * 0.4; sky.uniforms.flashDir.value.set(Math.cos(az) * Math.cos(el), Math.sin(el), Math.sin(az) * Math.cos(el)); } /* each strike somewhere else in the deck */ const dist = 600 + Math.random() * 2400; if (E.onAmbience) E.onAmbience({ kind: 'thunder', delay: dist / 343, dist }); } // thunder arrives after the sound delay - A.flashAge = (A.flashAge == null ? 99 : A.flashAge + dt); - const f = A.flashAge < 0.07 ? 1 : A.flashAge < 0.16 ? 0 : A.flashAge < 0.24 ? 0.55 : Math.max(0, 0.55 - (A.flashAge - 0.24) * 2.5); - hemi.intensity = A.P.hemiI * (1 + f * 1.4); U.uFlash.value = f; sky.uniforms.flash.value = f; - } - }; - A.set(preset || 'night_moon'); - E.atmo = A; - return A; - }; - - E.setWind = function (dx, dz, strength) { - const l = Math.hypot(dx, dz) || 1; E.U.uWind.value.set(dx / l, dz / l, strength == null ? E.U.uWind.value.z : strength); - }; - E.setPushers = function (list) { - const v = E.U.uPush.value; - for (let i = 0; i < 8; i++) { const p = list && list[i]; if (p) v[i].set(p.x, p.z, p.r || 0.8, p.s == null ? 1 : p.s); else v[i].set(0, 0, 0, 0); } - }; - - // ------------------------------------------------------------------ background activity (not gameplay) - // IVEnv.backdrop(scene, spec) -> { group, info() }: far-off life that is cheap and never reads as an enemy. - // spec.searchlights: [[x, z]] sites far away, beams sweeping the sky - // spec.flak: [[x, z]] sites: shell bursts high up and slow tracer streams climbing - // spec.planes: true -> dark aircraft crossing high (an 'ambience' event 'drone' while one is overhead) - // spec.chutes: [[x, z]] a few distant parachutes drifting down during the first minute - // spec.bombing: [[x, z]] flashes beyond the hills ('ambience' 'rumble' after the sound delay) - // spec.fires: [[x, z, scale]] a burning place on the horizon: glow and a lit smoke column - // spec.flares: [[x, z]] areas where flares rise, hang and drift down - // spec.smoke: [[x, y, z, dark]] chimney smoke; spec.birds: [[x, z, r, h]] flocks wheeling; spec.bats: [[x, z]] - // spec.squalls: [[x, z]] rain curtains hanging over far hills; spec.truck: { path: [[x, z]], heightAt, speed } - // spec.pennant: { x, y, z } a plain camp pennant flying from a mast (no emblem) - // spec.sounds: [{ kind, every: [a, b], x, z }] 'ambience' events for the game's audio (dog, bell, rifle, owl) - // opts.reduced (Reduced motion) slows and thins everything and turns off flashes; Low quality halves the counts. - let softTex = null; - function soft() { if (softTex) return softTex; const c = document.createElement('canvas'); c.width = c.height = 64; const g = c.getContext('2d'), gr = g.createRadialGradient(32, 32, 0, 32, 32, 32); gr.addColorStop(0, 'rgba(255,255,255,1)'); gr.addColorStop(0.45, 'rgba(255,255,255,0.45)'); gr.addColorStop(1, 'rgba(255,255,255,0)'); g.fillStyle = gr; g.fillRect(0, 0, 64, 64); softTex = new THREE.CanvasTexture(c); return softTex; } - E.backdrop = function (scene, spec, opts) { - opts = opts || {}; spec = spec || {}; - const red = !!opts.reduced, low = E.Q.name === 'low', k = (low ? 0.5 : 1) * (red ? 0.5 : 1), R = E.rng(4242), group = new THREE.Group(); group.name = 'IVEnv.backdrop'; - const parts = [], emit = opts.emit || (() => {}); - // every soft particle (flak, tracer, smoke, flares, birds, leaves, glows) is one instance of one of two batched - // billboard meshes (additive and normal blend): two draw calls in all, however many there are - const pools = { add: [], norm: [] }; - const sprite = (col, add, op) => { const o = { position: new THREE.Vector3(), scale: new THREE.Vector3(1, 1, 1), material: { opacity: op == null ? 1 : op, color: new THREE.Color(col), rotation: 0 }, visible: true }; pools[add ? 'add' : 'norm'].push(o); return o; }; - const batch = (list, add) => { - if (!list.length) return null; - const n = list.length, g = new THREE.InstancedBufferGeometry(); g.copy(new THREE.PlaneGeometry(1, 1)); g.instanceCount = n; - const P = new THREE.InstancedBufferAttribute(new Float32Array(n * 3), 3), Sc = new THREE.InstancedBufferAttribute(new Float32Array(n * 3), 3), C = new THREE.InstancedBufferAttribute(new Float32Array(n * 4), 4); - P.setUsage(THREE.DynamicDrawUsage); Sc.setUsage(THREE.DynamicDrawUsage); C.setUsage(THREE.DynamicDrawUsage); g.setAttribute('iPos', P); g.setAttribute('iScale', Sc); g.setAttribute('iCol', C); - const m = new THREE.ShaderMaterial({ uniforms: THREE.UniformsUtils.merge([THREE.UniformsLib.fog, { map: { value: soft() } }]), transparent: true, depthWrite: false, fog: !add, blending: add ? THREE.AdditiveBlending : THREE.NormalBlending, - vertexShader: 'attribute vec3 iPos; attribute vec3 iScale; attribute vec4 iCol; varying vec2 vUv; varying vec4 vCol;\n#include \nvoid main(){ vUv = uv; vCol = iCol; vec4 mvPosition = viewMatrix * vec4(iPos, 1.0); float c = cos(iScale.z), s = sin(iScale.z); vec2 q = position.xy * iScale.xy; mvPosition.xy += vec2(c * q.x - s * q.y, s * q.x + c * q.y); gl_Position = projectionMatrix * mvPosition;\n#include \n}', - fragmentShader: 'uniform sampler2D map; varying vec2 vUv; varying vec4 vCol;\n#include \nvoid main(){ float a = texture2D(map, vUv).a * vCol.a; if (a < 0.003) discard; gl_FragColor = vec4(vCol.rgb, a);\n#include \n}' }); - m.customProgramCacheKey = () => 'ivbackdrop' + (add ? 'A' : 'N'); - const mesh = new THREE.Mesh(g, m); mesh.frustumCulled = false; mesh.userData.dynamic = true; mesh.renderOrder = add ? 3 : 2; group.add(mesh); - return () => { for (let i = 0; i < n; i++) { const o = list[i], v = o.visible === false ? 0 : o.material.opacity; P.array[i * 3] = o.position.x; P.array[i * 3 + 1] = o.position.y; P.array[i * 3 + 2] = o.position.z; Sc.array[i * 3] = o.scale.x; Sc.array[i * 3 + 1] = o.scale.y; Sc.array[i * 3 + 2] = o.material.rotation || 0; C.array[i * 4] = o.material.color.r; C.array[i * 4 + 1] = o.material.color.g; C.array[i * 4 + 2] = o.material.color.b; C.array[i * 4 + 3] = v; } P.needsUpdate = Sc.needsUpdate = C.needsUpdate = true; }; - }; - // searchlights: long thin additive cones from the ground; each wanders over the sky and lights a soft pool on the - // cloud base; now and then two or three cone on the same point and hold it - const beams = [], up = new THREE.Vector3(0, 1, 0), dv = new THREE.Vector3(); let cone = { t: 25, hold: 0, x: 0, z: 0 }; - for (const [x, z] of spec.searchlights || []) { - const g = new THREE.CylinderGeometry(4, 0.4, 1, 10, 1, true); g.translate(0, 0.5, 0); - const m = new THREE.MeshBasicMaterial({ color: 0x8090a8, transparent: true, opacity: 0.06, blending: THREE.AdditiveBlending, depthWrite: false, side: THREE.DoubleSide, fog: false }); - const bm = new THREE.Mesh(g, m), y = opts.heightAt ? opts.heightAt(x, z) : 0; bm.position.set(x, y, z); bm.userData.dynamic = true; group.add(bm); - const pool = sprite(0x6a7890, true, 0.12); pool.scale.set(70, 70, 1); - beams.push({ bm, pool, x, y, z, ph: R() * 6.28, sp: 0.05 + R() * 0.05 }); - } - if (beams.length) parts.push((t, dt) => { - cone.t -= dt; if (cone.t < 0) { cone.hold = 9; cone.t = 35 + R() * 30; cone.x = R.range(-300, 300); cone.z = R.range(-300, 300); } - cone.hold = Math.max(0, cone.hold - dt); - for (const b of beams) { - const wx = b.x + Math.sin(t * b.sp + b.ph) * 380, wz = b.z + Math.cos(t * b.sp * 0.8 + b.ph * 2) * 380, k = cone.hold > 0 ? Math.min(1, cone.hold) : 0; - const tx = wx * (1 - k) + cone.x * k, tz = wz * (1 - k) + cone.z * k, ty = 380; - dv.set(tx - b.x, ty - b.y, tz - b.z); const L = dv.length(); dv.normalize(); b.bm.quaternion.setFromUnitVectors(up, dv); b.bm.scale.set(1, L, 1); - b.pool.position.set(tx, ty, tz); - } - }); - // flak: a brief hard flash, then a small dark puff that drifts and thins; tracer as strings of points climbing on an - // arc and burning out - if ((spec.flak || []).length) { - const bursts = []; for (let i = 0; i < Math.round(9 * k); i++) { const f = sprite(0xfff0d0, true, 0), p = sprite(0x2a2826, false, 0); f.scale.set(5, 5, 1); bursts.push({ f, p, t: -R() * 6, life: 99 }); } - const streams = []; for (let i = 0; i < Math.round(5 * k); i++) { const dots = []; for (let q = 0; q < 7; q++) { const d = sprite(0xffa860, true, 0); d.scale.set(1.4, 1.4, 1); dots.push(d); } streams.push({ dots, t: R() * 5, site: spec.flak[i % spec.flak.length], a: R() * 6.28, sp: 75 + R() * 30, tilt: 0.3 + R() * 0.4 }); } - parts.push((t, dt) => { - for (const b of bursts) { b.t -= dt; b.life += dt; if (b.t < 0) { const st = spec.flak[(R() * spec.flak.length) | 0]; const x = st[0] + R.range(-110, 110), y = 170 + R() * 170, z = st[1] + R.range(-110, 110); b.f.position.set(x, y, z); b.p.position.set(x, y, z); b.t = (red ? 4 : 1.4) + R() * 4; b.life = 0; b.dx = R.range(-2, 2); } - b.f.material.opacity = red ? 0 : (b.life < 0.07 ? 1 : 0); b.p.material.opacity = b.life < 0.07 ? 0 : Math.max(0, 0.55 * (1 - b.life / 5)); b.p.scale.setScalar(4 + b.life * 3); b.p.position.x += b.dx * dt; b.p.position.y += 0.6 * dt; } - for (const q of streams) { q.t += dt; if (q.t > 5.5) { q.t = 0; q.a = R() * 6.28; } for (let n = 0; n < q.dots.length; n++) { const tt = q.t - n * 0.09; const d = q.dots[n]; if (tt < 0 || tt > 4.2) { d.material.opacity = 0; continue; } const h = tt * q.sp - 4 * tt * tt; d.position.set(q.site[0] + Math.cos(q.a) * tt * q.sp * q.tilt, 20 + h, q.site[1] + Math.sin(q.a) * tt * q.sp * q.tilt); d.material.opacity = tt > 3.6 ? (4.2 - tt) * 1.6 : 0.95; } } - }); - } - // falling leaves near the camera (a box that wraps the camera), when trees are about - if (spec.leaves && !red) { - const lv = []; for (let i = 0; i < Math.round(50 * k * 2); i++) { const p = sprite(spec.leaves === 'day' ? 0x6a5a30 : 0x2a2618, false, 0.9); p.scale.set(0.09, 0.06, 1); lv.push({ p, x: R.range(-12, 12), y: R.range(0, 9), z: R.range(-12, 12), ph: R() * 6 }); } - parts.push((t, dt, cam) => { const w = E.windDir ? E.windDir : { x: 1, z: 0.3 }; for (const q of lv) { q.y -= dt * (0.6 + 0.3 * Math.sin(t + q.ph)); q.x += dt * (0.5 * w.x + 0.3 * Math.sin(t * 1.7 + q.ph)); q.z += dt * 0.5 * (w.z || 0); if (q.y < -1) { q.y = 9; q.x = R.range(-12, 12); q.z = R.range(-12, 12); } let rx = ((q.x % 24) + 36) % 24 - 12, rz = ((q.z % 24) + 36) % 24 - 12; q.p.position.set(cam.position.x + rx, cam.position.y - 1.6 + q.y, cam.position.z + rz); q.p.material.rotation = t * 3 + q.ph; } }); - } - // aircraft: dark cross shapes crossing high, a drone event while overhead - if (spec.planes) { - const shape = new THREE.Group(); const mm = new THREE.MeshBasicMaterial({ color: 0x07080b, fog: false }); - shape.add(new THREE.Mesh(new THREE.BoxGeometry(14, 1.6, 1.8), mm)); const wing = new THREE.Mesh(new THREE.BoxGeometry(2.6, 0.35, 26), mm); wing.position.x = 1.5; shape.add(wing); const tail = new THREE.Mesh(new THREE.BoxGeometry(1.4, 0.3, 8), mm); tail.position.x = -6.2; shape.add(tail); - const planes = []; for (let i = 0; i < Math.round(3 * k + 1); i++) { const p = shape.clone(); p.userData.dynamic = true; group.add(p); planes.push({ p, t: R() * 40, z0: R.range(-500, 500), y: 260 + R() * 160, sp: 55 + R() * 20, dir: R() < 0.5 ? 1 : -1, said: false }); } - parts.push((t, dt, cam) => { for (const q of planes) { q.t += dt; const L = 2400, x = -1200 + ((q.t * q.sp) % L); q.p.position.set(x * q.dir, q.y, q.z0 + x * 0.25); q.p.rotation.y = q.dir > 0 ? -0.245 : Math.PI - 0.245; const near = Math.abs(q.p.position.x - cam.position.x) < 300; if (near && !q.said) { q.said = true; emit({ kind: 'drone', x: q.p.position.x, z: q.p.position.z }); } if (!near) q.said = false; } }); - } - // distant parachutes in the first minute - for (const [x, z] of spec.chutes || []) for (let i = 0; i < 3; i++) { - const c = new THREE.Mesh(new THREE.SphereGeometry(3, 8, 4, 0, 6.28, 0, 1.4), new THREE.MeshBasicMaterial({ color: 0x9a9890, fog: true })); c.userData.dynamic = true; group.add(c); - const ox = x + R.range(-40, 40), oz = z + R.range(-40, 40), y0 = 120 + R() * 60, d = R() * 8; parts.push((t) => { const tt = Math.max(0, t - d); c.position.set(ox + tt * 0.8, Math.max(-20, y0 - tt * 4.5), oz + Math.sin(tt * 0.4) * 4); c.visible = t < 70; }); - } - // bombing beyond the hills: an orange flash low on the horizon, rumble after the sound delay - if ((spec.bombing || []).length) { - const f = sprite(0xff9a50, true, 0); f.scale.set(160, 60, 1); let next = 4, life = 9; - parts.push((t, dt, cam) => { next -= dt; life += dt; if (next < 0) { const st = spec.bombing[(R() * spec.bombing.length) | 0]; f.position.set(st[0] + R.range(-60, 60), 25, st[1] + R.range(-60, 60)); life = 0; next = 6 + R() * 14; const dd = Math.hypot(f.position.x - cam.position.x, f.position.z - cam.position.z); emit({ kind: 'rumble', delay: dd / 343, x: f.position.x, z: f.position.z }); } - f.material.opacity = red ? 0.12 * Math.max(0, 1 - life / 2) : (life < 0.15 ? 0.6 : life < 0.3 ? 0.25 : life < 0.45 ? 0.5 : Math.max(0, 0.5 - (life - 0.45) * 0.6)); }); - } - // fires on the horizon: a glow and a smoke column lit from below - for (const [x, z, sc] of spec.fires || []) { - const y = opts.heightAt ? opts.heightAt(x, z) : 0, s0 = sc || 1, glow = sprite(0xff7a30, true, 0.55); glow.position.set(x, y + 6 * s0, z); glow.scale.set(40 * s0, 18 * s0, 1); - const puffs = []; for (let i = 0; i < Math.round(14 * k + 4); i++) { const p = sprite(0x1a1714, false, 0.5); puffs.push({ p, t: i / 14 * 30 }); } - parts.push((t, dt) => { glow.material.opacity = 0.45 + 0.15 * Math.sin(t * 7.3) * Math.sin(t * 3.1); for (const q of puffs) { q.t = (q.t + dt * (red ? 0.5 : 1)) % 30; const u = q.t / 30; q.p.position.set(x + u * 60 * s0, y + 8 * s0 + u * 140 * s0, z + Math.sin(u * 5) * 6); q.p.scale.setScalar((10 + u * 50) * s0); q.p.material.opacity = 0.55 * (1 - u) * Math.min(1, q.t * 2); q.p.material.color.setRGB(0.1 + 0.5 * Math.max(0, 0.25 - u) * 4 * 0.25, 0.09 + 0.15 * Math.max(0, 0.25 - u), 0.08); } }); - } - // flares: rise, hang, drift down burning, a pause, again - for (const [x, z] of spec.flares || []) { - const f = sprite(0xfff0d0, true, 0); f.scale.set(6, 6, 1); let t0 = R() * 20, ox = x, oz = z; - parts.push((t, dt) => { t0 += dt; const T = 26, u = t0 % T; if (u < dt) { ox = x + R.range(-80, 80); oz = z + R.range(-80, 80); } const y = u < 3 ? u * 45 : 135 - (u - 3) * 4; f.position.set(ox + (u > 3 ? (u - 3) * 1.2 : 0), y, oz); f.material.opacity = u < 3 ? 0.4 : u < 18 ? (red ? 0.4 : 0.85 + 0.15 * Math.sin(t * 23)) : 0; }); - } - // chimney smoke - for (const [x, y, z, dark] of spec.smoke || []) { - const puffs = []; for (let i = 0; i < Math.round(6 * k + 2); i++) puffs.push({ p: sprite(dark ? 0x3a3836 : 0x8a8a88, false, 0), t: i / 6 * 9 }); - parts.push((t, dt) => { for (const q of puffs) { q.t = (q.t + dt) % 9; const u = q.t / 9; q.p.position.set(x + u * 5, y + u * 9, z + Math.sin(u * 4 + x) * 0.8); q.p.scale.setScalar(0.8 + u * 4.5); q.p.material.opacity = 0.35 * (1 - u) * Math.min(1, q.t * 3); } }); - } - // birds and bats: dark specks wheeling - for (const [x, z, r, h, n] of (spec.birds || []).concat((spec.bats || []).map(b => [b[0], b[1], 14, 9, 5]))) { - const fl = []; for (let i = 0; i < Math.round((n || 12) * k); i++) { const p = sprite(0x0c0c0c, false, 0.9); p.scale.set(0.9, 0.35, 1); fl.push({ p, a: R() * 6.28, rr: r * (0.6 + R() * 0.5), hh: h + R() * 6, sp: 0.15 + R() * 0.2 }); } - parts.push((t) => { for (const q of fl) { const a = q.a + t * q.sp; q.p.position.set(x + Math.cos(a) * q.rr, q.hh + Math.sin(t * 2 + q.a) * 1.5, z + Math.sin(a * 1.3) * q.rr); q.p.scale.y = 0.2 + 0.25 * Math.abs(Math.sin(t * 9 + q.a)); } }); - } - // rain squalls on the far hills: tall soft grey curtains drifting - for (const [x, z] of spec.squalls || []) { - const m = new THREE.MeshBasicMaterial({ map: soft(), color: 0x5a6068, transparent: true, opacity: 0.32, depthWrite: false, side: THREE.DoubleSide, fog: false }); - const q = new THREE.Mesh(new THREE.PlaneGeometry(220, 140), m); q.position.set(x, 50, z); q.userData.dynamic = true; group.add(q); - parts.push((t, dt, cam) => { q.position.x = x + Math.sin(t * 0.01) * 60; q.lookAt(cam.position.x, 50, cam.position.z); }); - } - // a lorry on the far road - if (spec.truck && E.prop) { - const tr = E.prop('truck', 77).group; tr.userData.dynamic = true; group.add(tr); const P = spec.truck.path, L = []; let tot = 0; for (let i = 0; i < P.length - 1; i++) { const l = Math.hypot(P[i + 1][0] - P[i][0], P[i + 1][1] - P[i][1]); L.push(l); tot += l; } - parts.push((t) => { let d = (t * (spec.truck.speed || 6)) % (tot * 2); if (d > tot) d = 2 * tot - d; let i = 0; while (i < L.length - 1 && d > L[i]) { d -= L[i]; i++; } const a = P[i], b = P[i + 1], u = Math.min(1, d / L[i]), x = a[0] + (b[0] - a[0]) * u, z = a[1] + (b[1] - a[1]) * u; tr.position.set(x, spec.truck.heightAt ? spec.truck.heightAt(x, z) : 0, z); tr.rotation.y = Math.atan2(-(b[1] - a[1]), b[0] - a[0]); }); - } - // a plain pennant on the mast - if (spec.pennant) { - const g = new THREE.PlaneGeometry(1.8, 0.9, 10, 2); g.translate(0.9, 0, 0); const base = g.attributes.position.array.slice(); - const fl = new THREE.Mesh(g, new THREE.MeshStandardMaterial({ color: 0x3c4a34, side: THREE.DoubleSide, roughness: 0.9 })); fl.position.set(spec.pennant.x, spec.pennant.y, spec.pennant.z); fl.userData.dynamic = true; group.add(fl); - parts.push((t) => { const a = g.attributes.position.array; for (let i = 0; i < a.length; i += 3) { const u = base[i] / 1.8; a[i + 2] = Math.sin(t * (red ? 2 : 5) - u * 6) * 0.18 * u; a[i + 1] = base[i + 1] - u * 0.1; } g.attributes.position.needsUpdate = true; g.computeVertexNormals(); }); - } - // sound hooks for the game's audio - for (const sd of spec.sounds || []) { let next = sd.every[0] + R() * (sd.every[1] - sd.every[0]); parts.push((t, dt) => { next -= dt; if (next < 0) { next = sd.every[0] + R() * (sd.every[1] - sd.every[0]); emit({ kind: sd.kind, x: sd.x, z: sd.z }); } }); } - const upA = batch(pools.add, true), upN = batch(pools.norm, false); - scene.add(group); - let T = 0; - (E._updaters = E._updaters || []).push((dt, cam) => { if (!group.parent) return; T += dt; for (const f of parts) f(T, dt, cam); if (upA) upA(); if (upN) upN(); }); - return { group, info: () => ({ parts: parts.length, objects: group.children.length }) }; - }; -})(); diff --git a/e63334287a3deaa3/ironveil/env/build.js b/e63334287a3deaa3/ironveil/env/build.js deleted file mode 100644 index 9b865951..00000000 --- a/e63334287a3deaa3/ironveil/env/build.js +++ /dev/null @@ -1,1230 +0,0 @@ -/* Midnight Ops environment: buildings, field walls and fences. - IVEnv.building(spec) -> { group, colliders, doors, windows, lights } - spec = { kind, w, d, floors, seed, damage (0..1), lit (0..1 share of lit windows), roof ('tile'|'slate') } - kinds: farmhouse, barn, shed, cottage, office (long low camp hut), church, shoprow, ruin, bunker (alias pillbox) - Local space: origin on the ground at the centre of the footprint, front door faces +Z, Y up, metres. - colliders: [{ x, z, hx, hz, y0, y1, rot, surf, kind }] boxes in local space (rot about Y). - doors: [{ pivot (Object3D, rotate .rotation.y to open), width, x, z, open(angle) }] - windows: [{ x, y, z, nx, nz, w, h, lit }] ; lights: [{ x, y, z, color, r, power }] for lit windows and lamps. - IVEnv.wall(points, { type: 'stone'|'brick', h, t, gaps: [[from, to] metres along], brokenStart, brokenEnd, seed, - heightFn }) -> { group, colliders } (points are [x, z] in world or parent space) - IVEnv.fence(points, kind, { heightFn, seed }) -> { group, colliders } kinds: rail, picket, barbed, hurdle - Everything is built brick by brick where the outline shows it: arches, sills, quoins, ridge tiles, eaves, slipped - and missing tiles, broken wall tops with loose bricks, rubble. Wear decals are placed where wear happens. */ -(function () { - 'use strict'; - const E = window.IVEnv; - const TAU = Math.PI * 2; - - // ------------------------------------------------------------------ rocks / rubble geometry (cached) - const rockCache = {}; - E.rockGeo = function (seed, detail) { - const k = seed + ':' + (detail == null ? 1 : detail); if (rockCache[k]) return rockCache[k]; - const g = new THREE.IcosahedronGeometry(1, detail == null ? 1 : detail), p = g.attributes.position, R = E.rng(seed); - const sx = R.range(0.8, 1.3), sy = R.range(0.45, 0.8), sz = R.range(0.75, 1.2), o = [R() * 9, R() * 9, R() * 9]; - for (let i = 0; i < p.count; i++) { - const x = p.getX(i), y = p.getY(i), z = p.getZ(i), n = 0.78 + 0.35 * E.vnoise(x * 1.7 + o[0], z * 1.7 + y * 1.3 + o[1], seed) + 0.12 * E.vnoise(x * 4 + o[2], y * 4, seed + 1); - p.setXYZ(i, x * sx * n, Math.max(y * sy * n, -0.25 * sy), z * sz * n); - } - g.computeVertexNormals(); rockCache[k] = g; return g; - }; - const _M = new THREE.Matrix4(), _Q = new THREE.Quaternion(), _Eu = new THREE.Euler(), _P = new THREE.Vector3(), _S = new THREE.Vector3(); - function placeRock(B, mat, x, y, z, s, seed, rot, tint) { - _Eu.set(rot ? rot[0] : 0, rot ? rot[1] : 0, rot ? rot[2] : 0); _Q.setFromEuler(_Eu); _P.set(x, y, z); _S.set(s, s, s); - B.geo(mat, E.rockGeo(seed % 23, s > 0.35 ? 1 : 0), _M.compose(_P, _Q, _S), { tint }); - } - // a loose brick (or any small block) lying at a random angle - function looseBlock(B, mat, x, y, z, R, sx, sy, sz, tint) { - if (E.Q.name === 'low') { R(); R(); R(); return; } - B.det(2, () => B.box(mat, x, y, z, sx || 0.32, sy || 0.1, sz || 0.155, R() * TAU, { rx: R.range(-0.4, 0.4), rz: R.range(-0.4, 0.4), tint })); - } - E.looseBlock = looseBlock; - // rubble pile: bricks, stone lumps and dust, a low mound - function rubble(B, x, z, r, R, mats, n, y0) { - y0 = y0 || 0; - for (let i = 0; i < n; i++) { - const a = R() * TAU, d = Math.sqrt(R()) * r, hx = x + Math.cos(a) * d, hz = z + Math.sin(a) * d, hy = y0 + (1 - d / r) * r * 0.35 * R(); - if (R() < 0.6) looseBlock(B, mats.brick || 'brick_red', hx, hy, hz, R, null, null, null, tintJ(R, 0.12)); - else { const rs = R.range(0.08, 0.22), sd = (R() * 1000) | 0, rr = [R() * 3, R() * 3, R() * 3]; B.det(2, () => placeRock(B, mats.stone || 'fieldstone', hx, hy, hz, rs, sd, rr)); } - } - // the mound under it - placeRock(B, 'mud', x, y0 - r * 0.15, z, r * 0.8, (R() * 1000) | 0, [0, R() * 3, 0]); - } - const tintJ = (R, v, base) => { const k = 1 + R.range(-v, v); const c = new THREE.Color(base || 0xffffff); return new THREE.Color(c.r * k, c.g * k * (1 + R.range(-0.03, 0.03)), c.b * k); }; - - const recessTint = (t) => new THREE.Color(t ? t.r * 0.8 : 0.8, t ? t.g * 0.8 : 0.8, t ? t.b * 0.78 : 0.78); - // ------------------------------------------------------------------ walls with openings - // A straight wall: from local point (x0, z0) along unit dir (dx, dz) for length L; outward normal (nx, nz) = right of dir. - // ops: openings [{ a0, a1, y0, y1 }]; mats: { out, in }; uStart: perimeter u for the outer face (bricks wrap corners). - function wallRun(B, W) { - const { x0, z0, dx, dz, L, T, H, y0 = 0, ops = [], mats, uStart = 0 } = W; - const nx = -dz, nz = dx; // outward (left of the direction of travel) - const xs = new Set([0, L]), ys = new Set([y0, y0 + H]); - for (const o of ops) { xs.add(Math.max(0, Math.min(L, o.a0))); xs.add(Math.max(0, Math.min(L, o.a1))); ys.add(Math.max(y0, Math.min(y0 + H, o.y0))); ys.add(Math.max(y0, Math.min(y0 + H, o.y1))); } - const X = [...xs].sort((a, b) => a - b), Y = [...ys].sort((a, b) => a - b); - const isOpen = (a, y) => ops.some(o => a > o.a0 && a < o.a1 && y > o.y0 && y < o.y1); - const P = (a, y, side) => [x0 + dx * a + nx * side * T / 2, y, z0 + dz * a + nz * side * T / 2]; - const top = W.topAt; // optional broken top profile: topAt(a) -> y - for (let j = 0; j < Y.length - 1; j++) for (let i = 0; i < X.length - 1; i++) { - const a0 = X[i], a1 = X[i + 1], ya = Y[j], yb = Y[j + 1], am = (a0 + a1) / 2, ym = (ya + yb) / 2; - if (isOpen(am, ym) || a1 - a0 < 1e-4 || yb - ya < 1e-4) continue; - // outer face - B.quad(mats.out, P(a0, ya, 1), P(a1, ya, 1), P(a1, yb, 1), P(a0, yb, 1), [[uStart + a0, ya], [uStart + a1, ya], [uStart + a1, yb], [uStart + a0, yb]], W.tint, 0); - if (mats.in) B.quad(mats.in, P(a1, ya, -1), P(a0, ya, -1), P(a0, yb, -1), P(a1, yb, -1), [[L - a1, ya], [L - a0, ya], [L - a0, yb], [L - a1, yb]], null, W.inFoot != null ? W.inFoot : 0); - // reveals next to openings (and wall ends) - const rt = recessTint(W.tint); // reveals and soffits sit in shadow and gather dirt: darker - const rev = (aa, flip) => B.quad(mats.out, flip ? P(aa, ya, -1) : P(aa, ya, 1), flip ? P(aa, ya, 1) : P(aa, ya, -1), flip ? P(aa, yb, 1) : P(aa, yb, -1), flip ? P(aa, yb, -1) : P(aa, yb, 1), [[0, ya], [T, ya], [T, yb], [0, yb]], rt, 0); - if ((i > 0 && isOpen(a0 - 1e-3, ym)) || (i === 0 && W.capStart)) rev(a0, true); - if ((i < X.length - 2 && isOpen(a1 + 1e-3, ym)) || (i === X.length - 2 && W.capEnd)) rev(a1, false); - const hz = (yy, down) => { const p0 = P(a0, yy, 1), p1 = P(a1, yy, 1), p2 = P(a1, yy, -1), p3 = P(a0, yy, -1); if (down) B.quad(mats.out, p3, p2, p1, p0, [[a0, 0], [a1, 0], [a1, T], [a0, T]], rt, 0); else B.quad(mats.out, p0, p1, p2, p3, [[a0, 0], [a1, 0], [a1, T], [a0, T]], W.tint, 0); }; - if (j < Y.length - 2 && isOpen(am, yb + 1e-3)) hz(yb, true); // soffit over an opening - if (j > 0 && isOpen(am, ya - 1e-3)) hz(ya, false); // sill bed under a window - if (j === Y.length - 2 && W.capTop !== false) hz(yb, false); - } - // colliders: one box per run of solid columns at full height, and lintel/sill boxes around openings - const cx = (a) => x0 + dx * a, cz = (a) => z0 + dz * a, rot = Math.atan2(-dz, dx); - for (let i = 0; i < X.length - 1; i++) { - const a0 = X[i], a1 = X[i + 1], am = (a0 + a1) / 2; - const segs = []; let cur = null; - for (let j = 0; j < Y.length - 1; j++) { const solid = !isOpen(am, (Y[j] + Y[j + 1]) / 2); if (solid) { if (!cur) cur = [Y[j], Y[j + 1]]; else cur[1] = Y[j + 1]; } else if (cur) { segs.push(cur); cur = null; } } - if (cur) segs.push(cur); - for (const s of segs) B.col(cx(am), cz(am), a1 - a0, T, s[0], s[1], rot, W.surf || 'stone', 'wall'); - } - } - E._wallRun = wallRun; - - // ------------------------------------------------------------------ window and door dressing - // frame + glazing bars + glass + sill + head (brick arch, stone lintel or timber lintel) + optional shutters - function dressWindow(B, S, o) { - // o: { cx, cz (centre of the opening on the wall line), dx, dz, T, w, y0, y1, head: 'arch'|'lintel'|'timber'|'pointed', sill, shutters, lit, broken } - const R = S.R, nx = -o.dz, nz = o.dx, rot = Math.atan2(-o.dz, o.dx); - const out = (d) => [o.cx + nx * d, o.cz + nz * d]; - const inset = Math.min(0.12, o.T * 0.35), fp = out(o.T / 2 - inset - 0.03); - // frame (four bars) and glazing bars - const fw = 0.06, fd = 0.07, wood = 'wood_painted', tint = S.paintTint; - B.box(wood, fp[0], o.y0, fp[1], o.w, fw, fd, rot, { tint }); - B.box(wood, fp[0], o.y1 - fw, fp[1], o.w, fw, fd, rot, { tint }); - for (const s of [-1, 1]) { const q = [fp[0] + o.dx * s * (o.w / 2 - fw / 2), fp[1] + o.dz * s * (o.w / 2 - fw / 2)]; B.box(wood, q[0], o.y0, q[1], fw, o.y1 - o.y0, fd, rot, { tint }); } - const mid = (o.y0 + o.y1) / 2; - B.det(1, () => { B.box(wood, fp[0], mid - 0.02, fp[1], o.w, 0.035, 0.04, rot, { tint }); B.box(wood, fp[0], o.y0, fp[1], 0.035, o.y1 - o.y0, 0.04, rot, { tint }); }); - // glass panes (four), some broken out when damaged - const gp = out(o.T / 2 - inset - 0.03 - 0.01), hw = o.w / 2 - fw, panes = [[-1, 0], [1, 0], [-1, 1], [1, 1]]; - for (const [sx, sy] of panes) { - const broken = o.broken && R() < 0.5; - if (broken) continue; - const ax = sx < 0 ? -hw : 0.02, bx = sx < 0 ? -0.02 : hw, ya = sy ? mid + 0.015 : o.y0 + fw, yb = sy ? o.y1 - fw : mid - 0.02; - const P = (a, y) => [gp[0] + o.dx * a, y, gp[1] + o.dz * a]; - B.quad(o.lit ? 'glass_lit' : 'glass', P(ax, ya), P(bx, ya), P(bx, yb), P(ax, yb), [[ax, ya], [bx, ya], [bx, yb], [ax, yb]], null, null); - } - // boarded up: planks nailed across the frame at odd angles (empty or shot-up houses) - if (!o.lit && (o.boarded || (S.damage > 0.3 && R() < 0.35))) { const bp = out(o.T / 2 + 0.03); for (let k = 0; k < 3 + R.int(2); k++) { const yy = o.y0 + (o.y1 - o.y0) * (0.12 + 0.25 * k) + R.range(-0.05, 0.05); B.box('planks', bp[0] + nx * 0.01 * k, yy, bp[1] + nz * 0.01 * k, o.w + R.range(0.15, 0.35), R.range(0.13, 0.2), 0.025, rot, { rz: R.range(-0.25, 0.25), tint: tintJ(R, 0.15, 0xc8bca8) }); } } - // a dark backing so an unlit window does not show the sky through the building - if (!o.lit && !S.interior) { const bp = out(o.T / 2 - inset - 0.2), P = (a, y) => [bp[0] + o.dx * a, y, bp[1] + o.dz * a]; B.quad('timber', P(-o.w / 2, o.y0), P(o.w / 2, o.y0), P(o.w / 2, o.y1), P(-o.w / 2, o.y1), [[0, 0], [1, 0], [1, 1], [0, 1]], new THREE.Color(0.08, 0.08, 0.08), null); } - // sill: dressed stone, proud of the wall and wider than the opening, with a drip and a stain under it - const sp = out(o.T / 2 + 0.03); - if (o.sill !== false) { - B.box(o.sillMat || 'ashlar', sp[0] - nx * 0.06, o.y0 - 0.07, sp[1] - nz * 0.06, o.w + 0.16, 0.07, 0.2, rot, { tint: tintJ(R, 0.08) }); - B.decal('waterstain', [sp[0] + nx * 0.0, o.y0 - 0.32, sp[1] + nz * 0.0], [nx, 0, nz], o.w * 0.9, 0.45, 0); - if (B.drip) B.drip(sp[0], o.y0 - 0.07, sp[1], nx, nz, o.w + 0.1, 1.3, 0.26); // streaks run down from the sill ends and its drip - } - if (B.drip) { const hp0 = out(o.T / 2); B.drip(hp0[0], o.y1 + 0.32, hp0[1], nx, nz, o.w + 0.5, 0.55, 0.16); } // off the head, down past the frame - // head - const hp = out(o.T / 2); - if (o.head === 'arch' || o.head === 'pointed') { - // a segmental (or pointed) arch of individual bricks / voussoirs, rising over the opening - const span = o.w + 0.02, rise = o.head === 'pointed' ? span * 0.55 : span * 0.16, mat = o.head === 'pointed' ? 'ashlar' : S.brickMat || 'brick_red'; - const rad = o.head === 'pointed' ? span * 0.8 : (span * span / 4 + rise * rise) / (2 * rise), depth = o.head === 'pointed' ? 0.3 : 0.32; - const n = Math.max(7, Math.round((span + rise) / (o.head === 'pointed' ? 0.22 : 0.108))); - const cy = o.y1 + rise - rad; - if (E.Q.name === 'low') B.box(mat, hp[0] + nx * 0.02, o.y1, hp[1] + nz * 0.02, span + 0.1, o.head === 'pointed' ? rise * 0.7 : 0.24, 0.06, rot, {}); - B.det(2, () => { for (let i = 0; i < n; i++) { - const t = (i + 0.5) / n; - let ang, cxo; - if (o.head === 'pointed') { const side = t < 0.5 ? -1 : 1, tt = t < 0.5 ? t * 2 : (1 - t) * 2; const a0 = Math.acos((rad - span / 2) / rad); ang = Math.PI / 2 + side * (a0 * (1 - tt)); cxo = -side * (rad - span / 2); ang = side < 0 ? Math.PI - (a0 * (1 - tt)) : a0 * (1 - tt); } - const half = Math.asin(Math.min(1, span / 2 / rad)); - if (o.head !== 'pointed') ang = Math.PI / 2 + half - t * 2 * half; - let px, py; - if (o.head === 'pointed') { const side = t < 0.5 ? -1 : 1; const ccx = side < 0 ? span / 2 - rad : -span / 2 + rad; px = ccx + Math.cos(ang) * (rad + depth / 2); py = o.y1 + Math.sin(ang) * (rad + depth / 2); } - else { px = Math.cos(ang) * (rad + depth / 2); py = cy + Math.sin(ang) * (rad + depth / 2); } - const tang = ang - Math.PI / 2; - const wx = hp[0] + o.dx * px, wz = hp[1] + o.dz * px; - // each voussoir is a box turned in the wall plane: rotate about the wall normal - const bw = o.head === 'pointed' ? 0.2 : 0.098; - const g = new THREE.BoxGeometry(bw, depth, 0.1 + (o.head === 'pointed' ? 0.02 : 0)); - _Eu.set(0, rot, 0); _Q.setFromEuler(_Eu); - const q2 = new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(0, 0, 1), tang); - _Q.multiply(q2); _P.set(wx + nx * 0.035, py, wz + nz * 0.035); _S.set(1, 1, 1); - B.geo(mat, g, _M.compose(_P, _Q, _S), { tint: tintJ(R, 0.14) }); - } }); - } else if (o.head === 'lintel') { - // some lintels have dropped at one end: tilted, with a crack running up from the low end - const drop = S.old && R() < 0.35 ? R.range(0.03, 0.07) * (R() < 0.5 ? -1 : 1) : 0; - B.box('ashlar', hp[0] + nx * 0.015, o.y1 - Math.abs(drop) * 0.25, hp[1] + nz * 0.015, o.w + 0.36, 0.24, 0.12, rot, { tint: tintJ(R, 0.08), rz: drop }); - if (drop) B.decal('crack', [hp[0] + nx * 0.006 - o.dx * Math.sign(drop) * (o.w / 2 + 0.1), o.y1 + 0.5, hp[1] + nz * 0.006 - o.dz * Math.sign(drop) * (o.w / 2 + 0.1)], [nx, 0, nz], 0.45, 0.8, R.range(-0.3, 0.3)); - } else if (o.head === 'timber') { - B.box('timber', hp[0] + nx * 0.02, o.y1, hp[1] + nz * 0.02, o.w + 0.4, 0.18, 0.16, rot, { grain: 'long' }); - } - // shutters: open against the wall, one sometimes hanging off a hinge - if (o.shutters) for (const s of [-1, 1]) { - const hang = (S.damage > 0.3 && R() < S.damage * 0.5) || (S.old && R() < 0.12), sw = o.w / 2 + 0.02; - const q = [hp[0] + nx * 0.03 + o.dx * s * (o.w / 2 + sw / 2 + 0.02), hp[1] + nz * 0.03 + o.dz * s * (o.w / 2 + sw / 2 + 0.02)]; - B.box(wood, q[0], o.y0 + (hang ? -0.15 : 0), q[1], sw, o.y1 - o.y0, 0.035, rot, { rz: hang ? s * 0.35 : 0, tint }); - // ledges on the shutter - for (const yy of [0.15, 0.5, 0.85]) B.det(1, () => B.box(wood, q[0] + nx * 0.025, o.y0 + (o.y1 - o.y0) * yy + (hang ? -0.15 : 0), q[1] + nz * 0.025, sw * 0.9, 0.08, 0.02, rot, { rz: hang ? s * 0.35 : 0, tint })); - if (R() < 0.6) B.decal('chipped', [q[0] + nx * 0.05, o.y0 + (o.y1 - o.y0) * 0.4, q[1] + nz * 0.05], [nx, 0, nz], sw * 0.8, 0.5, R() * 3); - } - // soot streak over a lit / once-burnt window, crack from a corner - if (S.damage > 0.2 && R() < S.damage) B.decal('soot', [hp[0] + nx * 0.005, o.y1 + 0.45, hp[1] + nz * 0.005], [nx, 0, nz], o.w * 1.2, 0.9, 0); - if (R() < 0.35 + S.damage * 0.4) B.decal('crack', [hp[0] + nx * 0.005 + o.dx * (R() < 0.5 ? -1 : 1) * o.w * 0.55, o.y1 + 0.25, hp[1] + nz * 0.005], [nx, 0, nz], 0.5, 0.6, R.range(-0.4, 0.4)); - S.windows.push({ x: hp[0], y: (o.y0 + o.y1) / 2, z: hp[1], nx, nz, w: o.w, h: o.y1 - o.y0, lit: !!o.lit }); - if (o.lit) S.lights.push({ x: hp[0] - nx * 0.8, y: (o.y0 + o.y1) / 2, z: hp[1] - nz * 0.8, color: 0xffb060, r: 7, power: 0.9 }); - } - // door: frame, threshold stone, a hinged plank door (its own little group so it can swing), wear decals - function dressDoor(B, S, o, group) { - const R = S.R, nx = -o.dz, nz = o.dx, rot = Math.atan2(-o.dz, o.dx); - const fp = [o.cx + nx * (o.T / 2 - 0.1), o.cz + nz * (o.T / 2 - 0.1)]; - const tint = S.paintTint; - for (const s of [-1, 1]) B.box('timber', fp[0] + o.dx * s * (o.w / 2 - 0.05), 0, fp[1] + o.dz * s * (o.w / 2 - 0.05), 0.1, o.h, 0.12, rot, { grain: 'long' }); - B.box('timber', fp[0], o.h - 0.1, fp[1], o.w, 0.1, 0.12, rot, { grain: 'long' }); - const tp = [o.cx + nx * (o.T / 2), o.cz + nz * (o.T / 2)]; - if (o.threshold !== false) B.box('ashlar', tp[0] - nx * (o.T / 2 - 0.12), -0.02, tp[1] - nz * (o.T / 2 - 0.12), o.w + 0.2, 0.1, o.T + 0.24, rot, { tint: tintJ(R, 0.06, 0xb8b0a0) }); - B.decal('mud', [tp[0] + nx * 0.25, 0.09, tp[1] + nz * 0.25], [0, 1, 0], o.w * 1.1, 0.7, R() * 0.4); - B.decal('grime', [tp[0] + o.dx * (o.w / 2 + 0.1), 0.95, tp[1] + o.dz * (o.w / 2 + 0.1)], [nx, 0, nz], 0.35, 0.8, 0); - if (o.leaf !== false) { - // the door leaf: boards, ledges and braces, iron latch; built in its own builder, hinged at one side - const D = E.builder(S.seed + 77 + S.doors.length), lw = o.w - 0.12, lh = o.h - 0.12, th = 0.05; - D.box('wood_painted', lw / 2, 0, 0, lw, lh, th, 0, { tint }); - for (const yy of [0.12, 0.5, 0.86]) D.box('wood_painted', lw / 2, lh * yy - 0.06, -th / 2 - 0.012, lw - 0.06, 0.12, 0.025, 0, { tint }); - D.box('wood_painted', lw / 2, lh * 0.18, -th / 2 - 0.012, 0.1, lh * 0.66, 0.022, 0, { rz: Math.atan2(lw * 0.85, lh * 0.66) * 0.6, tint }); - D.box('metal_rust', lw - 0.12, lh * 0.48, th / 2 + 0.01, 0.03, 0.12, 0.03, 0, { noFoot: true }); - D.box('metal_rust', lw - 0.2, lh * 0.53, th / 2 + 0.01, 0.16, 0.025, 0.02, 0, { noFoot: true }); - D.decal('scratches', [lw - 0.12, lh * 0.5, th / 2 + 0.002], [0, 0, 1], 0.3, 0.35, R() * 3); - D.decal('chipped', [lw * 0.5, 0.25, th / 2 + 0.002], [0, 0, 1], lw * 0.9, 0.45, 0); - D.decal('scratches', [lw * 0.5, 0.18, th / 2 + 0.002], [0, 0, 1], lw * 0.9, 0.3, Math.PI / 2); - const leaf = D.finish(); const pivot = new THREE.Group(); - const hx = o.cx - o.dx * (lw / 2) + nx * (o.T / 2 - 0.12), hz = o.cz - o.dz * (lw / 2) + nz * (o.T / 2 - 0.12); - pivot.position.set(hx, 0.06, hz); pivot.rotation.y = rot; pivot.add(leaf); pivot.userData.dynamic = true; group.add(pivot); - const door = { pivot, width: lw, x: o.cx, z: o.cz, closedY: rot, open(a) { pivot.rotation.y = rot - a; } }; - if (o.ajar) door.open(o.ajar); - if (S.damage > 0.4 && R() < 0.6) { door.hang = true; door.open(R.range(0.9, 1.5)); leaf.rotation.z = R.range(0.08, 0.16); leaf.position.y = -0.04; } // torn off the top hinge - S.doors.push(door); - } - } - - // ------------------------------------------------------------------ roofs - // Gable roof over a rectangle centred on the origin: ridge along X. eave: wall top height; pitch in radians. - function gableRoof(B, S, P) { - const R = S.R, ov = P.over || 0.35, gov = P.gable || 0.25, w = P.w, d = P.d, eave = P.eave, pitch = P.pitch || 0.72, mat = P.mat, th = 0.07; - const run = d / 2 + ov, rise = run * Math.tan(pitch), ridge = eave + (d / 2) * Math.tan(pitch); - const x0 = -w / 2 - gov, x1 = w / 2 + gov, L = x1 - x0, slope = Math.hypot(run, rise); - const sag = (x) => -P.sag * Math.sin(Math.PI * (x - x0) / L), eaveW = (x, side) => (P.eaveWander != null ? P.eaveWander : 0.035) * Math.sin(x * 1.3 + side * 2.1) * Math.sin(x * 0.37 + 1.0); - const holes = new Set(); - const fine = S.damage >= 0.45 && !P.noShell, NX = Math.max(2, Math.round(L / (fine ? 0.45 : 1.0))), NS = Math.max(2, Math.round(slope / (fine ? 0.42 : 0.9))); - if (S.damage > 0.25) { const nh = Math.round(S.damage * S.damage * NX * NS * 0.12); for (let k = 0; k < nh; k++) holes.add(((1 + R.int(NX - 2)) + ':' + (R.int(NS - 1)) + ':' + (R() < 0.5 ? 1 : -1))); } - // a shell hole: a ragged opening through tiles and boards, rafters snapped and hanging into it (damage >= 0.45) - const shell = S.damage >= 0.45 && !P.noShell ? { x: R.range(x0 + 1.6, x1 - 1.6), t: R.range(0.3, 0.65), side: R() < 0.5 ? 1 : -1, r: R.range(1.0, 1.7) } : null; - const inShell = (x, t, side) => shell && side === shell.side && Math.hypot(x - shell.x, (t - shell.t) * slope) < shell.r * (0.75 + 0.5 * E.vnoise(x * 2.1, t * 6, 7)); - for (const side of [1, -1]) { - for (let i = 0; i < NX; i++) for (let j = 0; j < NS; j++) { - const xa = x0 + L * i / NX, xb = x0 + L * (i + 1) / NX, ta = j / NS, tb = (j + 1) / NS; - const yE = eave - (ov * Math.tan(pitch)); - const pt = (x, t, off) => { const z = side * (run - t * run), y = yE + t * (ridge - yE) + sag(x) * t + (1 - t) * eaveW(x, side) + off; return [x, y, z]; }; - const nOff = (p, k) => [p[0], p[1] + k * Math.cos(pitch), p[2] + side * k * Math.sin(pitch)]; - const hole = holes.has(i + ':' + j + ':' + side) || inShell((xa + xb) / 2, (ta + tb) / 2, side); - const a = pt(xa, ta, 0), b = pt(xb, ta, 0), c = pt(xb, tb, 0), dd = pt(xa, tb, 0); - const sa = slope * ta, sb = slope * tb; - if (!hole) { - const A = nOff(a, th), Bp = nOff(b, th), C = nOff(c, th), D = nOff(dd, th); - if (side > 0) B.quad(mat, A, Bp, C, D, [[xa, sa], [xb, sa], [xb, sb], [xa, sb]], null, null); - else B.quad(mat, Bp, A, D, C, [[-xb, sa], [-xa, sa], [-xa, sb], [-xb, sb]], null, null); - // underside: roof boards - if (side > 0) B.quad('planks', b, a, dd, c, [[xb, sa], [xa, sa], [xa, sb], [xb, sb]], new THREE.Color(0.7, 0.66, 0.6), null); - else B.quad('planks', a, b, c, dd, [[xa, sa], [xb, sa], [xb, sb], [xa, sb]], new THREE.Color(0.7, 0.66, 0.6), null); - } else { - // missing tiles: battens across the hole, a few broken tiles hanging at the edge - for (let k = 0; k < 4; k++) { const t = ta + (tb - ta) * (k + 0.5) / 4, p = pt((xa + xb) / 2, t, -0.01); B.box('timber', p[0], p[1] - 0.012, p[2], xb - xa, 0.025, 0.05, 0, { rx: side * pitch, noFoot: true }); } - for (let k = 0; k < 3; k++) { const p = pt(xa + (xb - xa) * R(), ta + (tb - ta) * R() * 0.3, th); looseBlock(B, mat, p[0], p[1], p[2], R, 0.165, 0.014, 0.26); } - } - // eave edge (the tile thickness shows as a fascia board) at j == 0; gable verge at the ends - if (j === 0) { const A = nOff(a, th), Bp = nOff(b, th); B.quad('timber', side > 0 ? a : b, side > 0 ? b : a, side > 0 ? Bp : A, side > 0 ? A : Bp, [[0, 0], [1, 0], [1, 0.1], [0, 0.1]], null, null); } - } - // rafters' ends and barge boards along the gable edges - for (const ex of [x0, x1]) { - const a = [ex, eave - ov * Math.tan(pitch), side * run], c = [ex, ridge + sag(ex), 0], len = Math.hypot(c[1] - a[1], c[2] - a[2]); - B.box('timber', ex - Math.sign(ex) * 0.02, (a[1] + c[1]) / 2 - 0.11, (a[2] + c[2]) / 2, 0.05, 0.22, len, 0, { rx: side * pitch, grain: 'long', noFoot: true }); - } - // a fascia board under the tiles along the eave - B.box('timber', 0, eave - ov * Math.tan(pitch) - 0.16, side * (run - 0.03), L, 0.18, 0.04, 0, { grain: 'long', noFoot: true }); - if (B.drip) B.drip((x0 + x1) / 2, eave, side * d / 2, 0, side, L, 1.6, 0.2); // run-off from the eave down the wall - // slipped tiles lying on the roof - for (let k = 0; k < Math.round(1 + S.damage * 6); k++) { - const t = R.range(0.1, 0.8), x = R.range(x0 + 0.5, x1 - 0.5), y = eave - ov * Math.tan(pitch) + t * (ridge - eave + ov * Math.tan(pitch)) + th + 0.02, z = side * (run - t * run); - B.box(mat, x, y, z, 0.17, 0.014, 0.27, R.range(-0.4, 0.4), { rx: side * pitch + R.range(-0.15, 0.15), noFoot: true }); - } - } - if (shell) { - // rafters every 0.45 m under the hole: the ones crossing it are snapped, the stubs splintered and the free ends - // hanging down into the room; charred boards round the edge - const yE = eave - ov * Math.tan(pitch), side = shell.side, P3 = (x, t) => [x, yE + t * (ridge - yE) + sag(x) * t - 0.08, side * (run - t * run)]; - for (let x = shell.x - shell.r - 0.2; x <= shell.x + shell.r + 0.2; x += 0.45) { - const dx = Math.abs(x - shell.x); if (dx > shell.r) continue; - const half = Math.sqrt(shell.r * shell.r - dx * dx) / slope, t0 = shell.t - half, t1 = shell.t + half; - for (const [ta, tb, dir] of [[Math.max(0, t0 - 0.25), t0 + R.range(0.02, 0.12), 1], [t1 - R.range(0.02, 0.12), Math.min(1, t1 + 0.25), -1]]) { - const a = P3(x, ta), b = P3(x, tb), len = Math.hypot(b[1] - a[1], b[2] - a[2]); - B.box('timber', x, (a[1] + b[1]) / 2 - 0.08, (a[2] + b[2]) / 2, 0.07, 0.16, len, 0, { rx: side * pitch, grain: 'long', noFoot: true, tint: new THREE.Color(0.55, 0.5, 0.45) }); - // splinters at the broken end - const e = dir > 0 ? b : a; for (let k = 0; k < 3; k++) B.box('timber', x + R.range(-0.03, 0.03), e[1] - 0.12, e[2], 0.02, 0.03, R.range(0.12, 0.3), R.range(-0.5, 0.5), { rx: side * pitch + R.range(-0.6, 0.6), noFoot: true, tint: new THREE.Color(0.7, 0.62, 0.5) }); - } - if (R() < 0.5) { const m = P3(x, shell.t); B.box('timber', x, m[1] - 1.2, m[2], 0.07, 0.16, R.range(1.2, 2.0), R.range(-0.3, 0.3), { rx: side * pitch + R.range(0.7, 1.1) * -side, grain: 'long', noFoot: true, tint: new THREE.Color(0.5, 0.45, 0.4) }); } - } - const c = P3(shell.x, shell.t); B.decal('soot', [c[0], c[1] + 0.2, c[2] + side * 0.05], [0, Math.cos(pitch), side * Math.sin(pitch)], shell.r * 3, shell.r * 2.6, R() * 3); - S.shellHole = { x: shell.x, y: c[1], z: c[2] }; - } - // ridge: a row of half-round ridge tiles, each a little out of line - const rN = Math.ceil(L / 0.42); - { const nr = Math.max(2, Math.round(L / 1.2)); for (let i = 0; i < nr; i++) { const xa = x0 + L * i / nr, xb = x0 + L * (i + 1) / nr, ya = ridge + sag(xa), yb = ridge + sag(xb); B.box(P.ridgeMat || 'roof_tile', (xa + xb) / 2, (ya + yb) / 2 + th - 0.04, 0, xb - xa + 0.02, 0.16, 0.22, 0, { noFoot: true, rz: Math.atan2(yb - ya, xb - xa) }); } } // plain ridge (all qualities), following the sag - B.det(2, () => { for (let i = 0; i < rN; i++) { - const x = x0 + (i + 0.5) * L / rN, g = new THREE.CylinderGeometry(0.13, 0.13, L / rN + 0.01, 8, 1, false, 0, Math.PI); - _Eu.set(R.range(-0.03, 0.03), 0, Math.PI / 2 + R.range(-0.02, 0.02)); _Q.setFromEuler(_Eu); - // cylinder axis is Y; turned to X, opening downward - const q2 = new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(1, 0, 0), -Math.PI / 2); - _Q.multiply(q2); - _P.set(x, ridge + sag(x) + th + 0.02, R.range(-0.01, 0.01)); _S.set(1, 1, 1); - B.geo(P.ridgeMat || 'roof_tile', g, _M.compose(_P, _Q, _S), { tint: tintJ(R, 0.1), noFoot: true }); - } }); - return { ridge, eave, x0, x1, run }; - } - // the triangular gable wall above the eaves (outer + inner faces), local x = +-w/2 - function gableWall(B, S, P, xSide) { - const x = xSide * P.w / 2, T = P.T, eave = P.eave, ridge = P.ridge, d = P.d; - for (const side of [1, -1]) { - const xx = x + xSide * side * T / 2 * (side > 0 ? 1 : 1) * 0 + (side > 0 ? xSide * T / 2 : -xSide * T / 2); - const mat = side > 0 ? P.out : P.in; if (!mat) continue; - const A = [xx, eave, -d / 2], Bp = [xx, eave, d / 2], C = [xx, ridge, 0]; - const fwd = (xSide > 0) === (side > 0); - const uA = P.uStart != null ? P.uStart : 0; - if (fwd) B.tri(mat, A, C, Bp, [[uA, eave], [uA + d / 2, ridge], [uA + d, eave]], null, 0); - else B.tri(mat, Bp, C, A, [[uA + d, eave], [uA + d / 2, ridge], [uA, eave]], null, 0); - } - } - // corner quoins: alternating long and short dressed stones, slightly proud - function quoins(B, S, w, d, H, T) { B.det(2, () => quoins0(B, S, w, d, H, T)); } - // brick corners: alternate stretchers and headers sit 1-2.5 cm proud, chipped (a little turned), a few missing, so the - // outline of a brick corner is stepped, not a ruler line with a picture wrapped round it - function brickCorners(B, S, w, d, H, mat) { B.det(2, () => { const R = S.R, C = 0.105; for (let y = 0, k = 0; y < H - 0.05; y += C, k++) for (const [sx, sz] of [[1, 1], [-1, 1], [1, -1], [-1, -1]]) { - if (R() < 0.07) continue; const o = R.range(0.008, 0.025), la = k % 2 ? 0.32 : 0.16, lb = k % 2 ? 0.16 : 0.32, t = tintJ(R, 0.12); - B.box(mat, sx * (w / 2 - la / 2 + o), y + 0.005, sz * (d / 2 + o / 2), la, C - 0.014, o + 0.01, R.range(-0.02, 0.02), { tint: t, uvOff: [R() * 7, y] }); - B.box(mat, sx * (w / 2 + o / 2), y + 0.005, sz * (d / 2 - lb / 2 + o), o + 0.01, C - 0.014, lb, R.range(-0.02, 0.02), { tint: t, uvOff: [R() * 7, y] }); } }); } - // brick jambs at an opening: headers proud by 1-2 cm every other course up both sides - function brickJambs(B, S, o, mat) { B.det(2, () => { const R = S.R, C = 0.105, nx = -o.dz, nz = o.dx, rot = Math.atan2(-o.dz, o.dx); for (const sd of [-1, 1]) for (let y = o.y0, k = 0; y < o.y1 - 0.05; y += C, k++) { if (k % 2 || R() < 0.1) continue; - const pr = R.range(0.008, 0.02), a = sd * (o.w / 2 + 0.08), px = o.cx + o.dx * a + nx * (o.T / 2 + pr / 2), pz = o.cz + o.dz * a + nz * (o.T / 2 + pr / 2); B.box(mat, px, y + 0.005, pz, 0.16, C - 0.014, pr + 0.01, rot + R.range(-0.03, 0.03), { tint: tintJ(R, 0.12), uvOff: [R() * 7, y] }); } }); } - function quoins0(B, S, w, d, H, T) { - const R = S.R; let y = 0, k = 0; - while (y < H - 0.1) { - const h = Math.min(0.3, H - y), long = k % 2 === 0; - for (const [sx, sz] of [[1, 1], [-1, 1], [1, -1], [-1, -1]]) { - const tint = tintJ(R, 0.1, 0xb0aaa0), la = long ? 0.42 : 0.24, lb = long ? 0.24 : 0.42; - B.box('ashlar', sx * (w / 2 - la / 2 + 0.015), y, sz * (d / 2 + 0.015) - sz * 0.0, la + 0.03, h - 0.012, 0.03 + 0.001, 0, { tint }); - B.box('ashlar', sx * (w / 2 + 0.015) - sx * 0.0, y, sz * (d / 2 - lb / 2 + 0.015), 0.03 + 0.001, h - 0.012, lb + 0.03, 0, { tint }); - } - y += h; k++; - } - } - function chimney(B, S, x, z, base, top, sooty) { - const R = S.R, mat = sooty ? 'brick_sooty' : 'brick_red'; - B.box(mat, x, base, z, 0.62, top - base, 0.5, 0, { noFoot: true }); - B.box(mat, x, top - 0.12, z, 0.72, 0.14, 0.6, 0, { noFoot: true }); - for (const s of [-0.13, 0.15]) B.det(2, () => { const g = new THREE.CylinderGeometry(0.075, 0.09, 0.32 + R() * 0.1, 10); B.geo('roof_tile', g, _M.compose(_P.set(x + s, top + 0.16, z), _Q.identity(), _S.set(1, 1, 1)), { noFoot: true, tint: tintJ(R, 0.1) }); }); - B.decal('soot', [x, top - 0.45, z + 0.252], [0, 0, 1], 0.6, 0.9, 0); B.decal('soot', [x, top - 0.45, z - 0.252], [0, 0, -1], 0.6, 0.9, 0); - B.decal('soot', [x + 0.312, top - 0.45, z], [1, 0, 0], 0.5, 0.9, 0); B.decal('soot', [x - 0.312, top - 0.45, z], [-1, 0, 0], 0.5, 0.9, 0); - } - - // ------------------------------------------------------------------ interiors - function furn(B, S, kind, x, z, rot) { B.det(1, () => furn0(B, S, kind, x, z, rot)); } - function furn0(B, S, kind, x, z, rot) { - const R = S.R, c = Math.cos(rot || 0), s = Math.sin(rot || 0), L = (lx, lz) => [x + lx * c + lz * s, z - lx * s + lz * c]; - const add = (mat, lx, y0, lz, sx, sy, sz, o) => { const p = L(lx, lz); B.box(mat, p[0], y0 + (S.fy || 0), p[1], sx, sy, sz, rot || 0, Object.assign({ grain: 'long', foot: S.fy || 0 }, o || {})); }; - const col = (sx, sz, h) => B.col(x, z, sx, sz, S.fy || 0, (S.fy || 0) + h, rot || 0, 'wood', 'furniture'); - if (kind === 'table') { add('timber', 0, 0.72, 0, 1.6, 0.06, 0.85); for (const [a, b] of [[-0.7, -0.35], [0.7, -0.35], [-0.7, 0.35], [0.7, 0.35]]) add('timber', a, 0, b, 0.07, 0.72, 0.07); add('timber', 0, 0.55, 0, 1.4, 0.08, 0.04); B.decal('scratches', [x, (S.fy || 0) + 0.783, z], [0, 1, 0], 0.8, 0.5, rot || 0); col(1.6, 0.85, 0.78); } - else if (kind === 'chair') { add('timber', 0, 0.44, 0, 0.42, 0.04, 0.42); for (const [a, b] of [[-0.18, -0.18], [0.18, -0.18], [-0.18, 0.18], [0.18, 0.18]]) add('timber', a, 0, b, 0.04, 0.44, 0.04); for (const a of [-0.18, 0.18]) add('timber', a, 0.44, -0.19, 0.04, 0.5, 0.04); add('timber', 0, 0.8, -0.19, 0.4, 0.08, 0.03); } - else if (kind === 'dresser') { add('planks', 0, 0, 0, 1.4, 0.9, 0.5, { tint: new THREE.Color(0.8, 0.7, 0.6) }); add('timber', 0, 0.9, 0, 1.46, 0.04, 0.54); add('planks', 0, 0.94, -0.2, 1.4, 1.0, 0.04, { tint: new THREE.Color(0.8, 0.7, 0.6) }); for (const yy of [1.2, 1.5]) add('timber', 0, yy, -0.1, 1.36, 0.03, 0.22); for (let k = 0; k < 5; k++) { const p = L(-0.5 + k * 0.25, -0.08); B.geo('roof_tile', new THREE.CylinderGeometry(0.06, 0.05, 0.12, 10), _M.compose(_P.set(p[0], (S.fy || 0) + 1.29, p[1]), _Q.identity(), _S.set(1, 1, 1)), { tint: new THREE.Color(0.9, 0.9, 0.85) }); } col(1.46, 0.54, 1.94); } - else if (kind === 'cupboard') { add('wood_painted', 0, 0, 0, 1.0, 1.9, 0.55, { tint: S.paintTint }); add('timber', 0, 1.9, 0, 1.06, 0.06, 0.6); B.decal('chipped', L(0, 0.28).concat([]).length ? [L(0, 0.28)[0], (S.fy || 0) + 0.6, L(0, 0.28)[1]] : [0, 0, 0], [s, 0, c], 0.8, 0.8, 0); col(1.06, 0.6, 1.96); } - else if (kind === 'bed') { add('timber', 0, 0, 0, 1.0, 0.4, 2.0); add('canvas', 0, 0.4, 0.05, 0.94, 0.14, 1.9, { tint: new THREE.Color(0.9, 0.88, 0.8) }); add('timber', 0, 0, -1.0, 1.06, 0.9, 0.06); col(1.0, 2.0, 0.55); } - else if (kind === 'desk') { add('timber', 0, 0.74, 0, 1.3, 0.05, 0.7); add('timber', -0.45, 0, 0, 0.4, 0.74, 0.66); add('timber', 0.6, 0, 0, 0.05, 0.74, 0.66); add('canvas', 0.1, 0.79, 0.05, 0.5, 0.004, 0.35, { tint: new THREE.Color(1.2, 1.15, 1.0) }); add('canvas', -0.2, 0.795, -0.1, 0.3, 0.004, 0.22, { tint: new THREE.Color(1.1, 1.05, 0.9), rz: 0 }); col(1.3, 0.7, 0.8); } - else if (kind === 'bench') { add('timber', 0, 0.42, 0, 1.6, 0.05, 0.3); for (const a of [-0.65, 0.65]) add('timber', a, 0, 0, 0.06, 0.42, 0.26); } - else if (kind === 'stove') { add('metal_rust', 0, 0, 0, 0.8, 0.75, 0.6, { noFoot: true }); add('metal_painted', 0, 0.75, 0, 0.84, 0.04, 0.64, { tint: new THREE.Color(0.25, 0.25, 0.25), noFoot: true }); const g = new THREE.CylinderGeometry(0.07, 0.07, 1.8, 10); const p = L(0.25, -0.2); B.geo('metal_rust', g, _M.compose(_P.set(p[0], (S.fy || 0) + 1.7, p[1]), _Q.identity(), _S.set(1, 1, 1)), { noFoot: true }); col(0.8, 0.6, 0.8); } - else if (kind === 'barrel') { const g = new THREE.CylinderGeometry(0.28, 0.28, 0.85, 14); g.attributes.position.array.forEach((v, i, a) => { if (i % 3 === 0 || i % 3 === 2) { const y = a[i - (i % 3) + 1]; a[i] = v * (1 + 0.12 * (1 - (y / 0.425) ** 2)); } }); g.computeVertexNormals(); B.geo('planks', g, _M.compose(_P.set(x, (S.fy || 0) + 0.425, z), _Q.identity(), _S.set(1, 1, 1)), { keepUv: true, uvW: 1.8, uvH: 0.85 }); for (const yy of [0.12, 0.73]) B.geo('metal_rust', new THREE.CylinderGeometry(0.315, 0.315, 0.04, 14, 1, true), _M.compose(_P.set(x, (S.fy || 0) + yy, z), _Q.identity(), _S.set(1, 1, 1)), {}); col(0.6, 0.6, 0.85); } - } - function fireplace(B, S, x, z, rot) { - const c = Math.cos(rot), s = Math.sin(rot), L = (lx, lz) => [x + lx * c + lz * s, z - lx * s + lz * c]; - const a = (mat, lx, y, lz, sx, sy, sz, o) => { const p = L(lx, lz); B.box(mat, p[0], y + (S.fy || 0), p[1], sx, sy, sz, rot, o); }; - a('fieldstone', -0.75, 0, 0.1, 0.4, 1.3, 0.55); a('fieldstone', 0.75, 0, 0.1, 0.4, 1.3, 0.55); - a('timber', 0, 1.3, 0.12, 1.95, 0.25, 0.6, { grain: 'long' }); - a('brick_sooty', 0, 0, -0.12, 1.1, 1.3, 0.1); - a('ashlar', 0, -0.02, 0.25, 2.0, 0.06, 0.8, { tint: new THREE.Color(0.55, 0.52, 0.48) }); - const p = L(0, 0.0); B.decal('scorch', [p[0], (S.fy || 0) + 0.06, p[1]], [0, 1, 0], 1.0, 0.7, rot); - const ps = L(0, 0.41); B.decal('soot', [ps[0], (S.fy || 0) + 1.75, ps[1]], [s, 0, c], 1.6, 0.9, 0); - for (let k = 0; k < 3; k++) { const q = L(-0.2 + k * 0.2, 0.05); B.box('bark_oak', q[0], (S.fy || 0) + 0.08 + k * 0.03, q[1], 0.6, 0.1, 0.1, rot + 0.3 * k, { noFoot: true, tint: new THREE.Color(0.5, 0.45, 0.4) }); } - B.col(x, z, 2.0, 0.8, S.fy || 0, (S.fy || 0) + 1.55, rot, 'stone', 'fireplace'); - } - function floorDeck(B, S, w, d, y, T, mat, hole) { - // boards on joists; hole = { x0, x1, z0, z1 } left open for the stairs - const iw = w - 2 * T, id = d - 2 * T; - const pieces = hole ? [[-iw / 2, hole.x0, -id / 2, id / 2], [hole.x1, iw / 2, -id / 2, id / 2], [hole.x0, hole.x1, -id / 2, hole.z0], [hole.x0, hole.x1, hole.z1, id / 2]] : [[-iw / 2, iw / 2, -id / 2, id / 2]]; - for (const [xa, xb, za, zb] of pieces) if (xb - xa > 0.01 && zb - za > 0.01) { B.box(mat, (xa + xb) / 2, y - 0.03, (za + zb) / 2, xb - xa, 0.03, zb - za, 0, { grain: 'long', noFoot: true }); B.col((xa + xb) / 2, (za + zb) / 2, xb - xa, zb - za, y - 0.25, y, 0, 'wood', 'floor'); } - // joists across the depth, seen from the room below - B.det(1, () => { for (let x = -iw / 2 + 0.3; x < iw / 2 - 0.1; x += 0.6) { if (hole && x > hole.x0 && x < hole.x1) continue; B.box('timber', x, y - 0.23, 0, 0.12, 0.2, id, 0, { grain: 'long', noFoot: true }); } }); - B.box('timber', 0, y - 0.3, 0, iw, 0.26, 0.24, 0, { grain: 'long', noFoot: true }); // the main beam - } - function stairs(B, S, x0, z0, dirX, y0, y1, width) { - const n = Math.round((y1 - y0) / 0.2), rise = (y1 - y0) / n, run = 0.25; - for (let i = 0; i < n; i++) { - const x = x0 + dirX * (i + 0.5) * run; - B.box('floorboards', x, y0 + i * rise + rise - 0.035, z0, run + 0.02, 0.035, width, 0, { noFoot: true }); - B.box('planks', x + dirX * run * 0.45, y0 + i * rise, z0, 0.02, rise, width, 0, { noFoot: true, tint: new THREE.Color(0.7, 0.65, 0.6) }); - B.col(x, z0, run, width, y0, y0 + i * rise + rise, 0, 'wood', 'stairs'); - } - for (const s of [-1, 1]) { const len = Math.hypot(n * run, y1 - y0); B.box('timber', x0 + dirX * n * run / 2, y0 + (y1 - y0) / 2 - 0.15, z0 + s * (width / 2 + 0.03), len, 0.25, 0.05, 0, { rz: -dirX * Math.atan2(y1 - y0, n * run), grain: 'long', noFoot: true }); } - } - - // ------------------------------------------------------------------ house-like buildings - // Shared by farmhouse, cottage, shop units, church nave: four walls with openings, gable roof, details. - function house(B, S, H) { - const { w, d, T, floors, storey } = H, R = S.R, wallH = floors * storey + (H.knee || 0); - const mats = { out: H.out, in: H.in }; - // plinth course - if (H.plinth) { B.box(H.plinth, 0, -0.3, 0, w + 0.08, 0.6, d + 0.08, 0, { tint: tintJ(R, 0.05) }); } - // openings per side from the layout - const sides = [ - { name: 'front', x0: -w / 2, z0: d / 2, dx: 1, dz: 0, L: w, ops: H.front || [] }, - { name: 'right', x0: w / 2, z0: d / 2, dx: 0, dz: -1, L: d, ops: H.right || [] }, - { name: 'back', x0: w / 2, z0: -d / 2, dx: -1, dz: 0, L: w, ops: H.back || [] }, - { name: 'left', x0: -w / 2, z0: -d / 2, dx: 0, dz: 1, L: d, ops: H.left || [] } - ]; - let u = 0; - for (const sd of sides) { - // walls on the sides are inset by the thickness so the corners overlap cleanly - const along = sd.name === 'front' || sd.name === 'back'; - const W = { - x0: sd.x0 + sd.dz * (T / 2) * 0 - sd.dz * 0, z0: sd.z0, dx: sd.dx, dz: sd.dz, L: sd.L, T, H: wallH, ops: sd.ops, mats, uStart: u, surf: H.surf, - capStart: false, capEnd: false - }; - // shift the wall inward by T/2 (its centre line) - const nx = -sd.dz, nz = sd.dx; W.x0 -= nx * T / 2; W.z0 -= nz * T / 2; - if (!along) { W.x0 += sd.dx * T; W.z0 += sd.dz * T; W.L -= 2 * T; } - wallRun(B, W); - // dress the openings - for (const o of sd.ops) { - const am = (o.a0 + o.a1) / 2 - (along ? 0 : T), cx = W.x0 + sd.dx * am, cz = W.z0 + sd.dz * am; - if (o.door) dressDoor(B, S, { cx, cz, dx: sd.dx, dz: sd.dz, T, w: o.a1 - o.a0, h: o.y1 - o.y0, ajar: o.ajar, leaf: o.leaf, threshold: o.threshold }, S.group); - else dressWindow(B, S, { cx, cz, dx: sd.dx, dz: sd.dz, T, w: o.a1 - o.a0, y0: o.y0, y1: o.y1, head: o.head || H.head, shutters: o.shutters != null ? o.shutters : H.shutters, lit: o.lit, broken: o.broken, sill: H.sill, sillMat: H.sillMat }); - if (o.door && H.head && H.head !== 'none') dressWindow; // (door heads use the same dressing below) - if (o.door && H.doorHead) { const nn = [-sd.dz, sd.dx], hp = [cx + nn[0] * T / 2, cz + nn[1] * T / 2]; if (H.doorHead === 'lintel') B.box('ashlar', hp[0] + nn[0] * 0.015, o.y1, hp[1] + nn[1] * 0.015, o.a1 - o.a0 + 0.4, 0.26, 0.12, Math.atan2(-sd.dz, sd.dx), { tint: tintJ(R, 0.06) }); else if (H.doorHead === 'timber') B.box('timber', hp[0] + nn[0] * 0.02, o.y1, hp[1] + nn[1] * 0.02, o.a1 - o.a0 + 0.4, 0.2, 0.16, Math.atan2(-sd.dz, sd.dx), { grain: 'long' }); } - } - // wear along the foot of the wall and the odd bullet pock - for (let k = 0; k < Math.round(sd.L / 3); k++) { - const a = R.range(0.3, sd.L - 0.3), p = [W.x0 + sd.dx * a + nx * (T / 2 + 0.001), W.z0 + sd.dz * a + nz * (T / 2 + 0.001)]; - if (sd.ops.some(o => a > o.a0 - 0.2 && a < o.a1 + 0.2 && o.door)) continue; - B.decal(R() < 0.5 ? 'moss' : 'mud', [p[0], R.range(0.1, 0.3), p[1]], [nx, 0, nz], R.range(0.6, 1.4), R.range(0.3, 0.6), 0); - if (R() < 0.3) B.decal('waterstain', [p[0], R.range(0.5, wallH - 0.5), p[1]], [nx, 0, nz], R.range(0.8, 1.6), R.range(0.8, 1.6), R() * 3); - } - // bursts: a machine-gun burst walks across a wall in a tight cluster; blast chips low down from a grenade - if (S.damage > 0.2) for (let k = 0; k < Math.round(S.damage * sd.L / 4); k++) { const ca = R.range(0.8, sd.L - 0.8), cy = R.range(0.6, Math.min(2.4, wallH - 0.3)); for (let q = 0; q < 6 + R.int(9); q++) { const a = ca + R.range(-0.55, 0.55) + q * 0.04, p = [W.x0 + sd.dx * a + nx * (T / 2), W.z0 + sd.dz * a + nz * (T / 2)]; B.decal(R() < 0.6 ? 'bullethole' : 'pocks', [p[0], cy + R.range(-0.3, 0.3), p[1]], [nx, 0, nz], R.range(0.12, 0.3), null, R() * 6); } - if (R() < 0.4) { const a = R.range(0.6, sd.L - 0.6), p = [W.x0 + sd.dx * a + nx * (T / 2), W.z0 + sd.dz * a + nz * (T / 2)]; B.decal('chipped', [p[0], 0.5, p[1]], [nx, 0, nz], R.range(1.0, 1.8), 1.0, R() * 6); B.decal('scorch', [p[0], 0.35, p[1]], [nx, 0, nz], 1.6, 0.9, 0); } } - const pocks = Math.round(S.damage * sd.L * 0.6); - for (let k = 0; k < pocks; k++) { const a = R.range(0.3, sd.L - 0.3), p = [W.x0 + sd.dx * a + nx * (T / 2), W.z0 + sd.dz * a + nz * (T / 2)]; B.decal(R() < 0.7 ? 'pocks' : 'bullethole', [p[0], R.range(0.4, wallH - 0.3), p[1]], [nx, 0, nz], R.range(0.25, 0.6), null, R() * 6); } - u += sd.L; - } - if (H.quoins) quoins(B, S, w, d, wallH, T); - else if (/brick/.test(H.out)) { brickCorners(B, S, w, d, wallH, H.out); for (const sd of sides) { const nx = -sd.dz, nz = sd.dx; for (const o of sd.ops) { const along = sd.name === 'front' || sd.name === 'back', am = (o.a0 + o.a1) / 2 - (along ? 0 : T), wx0 = sd.x0 - nx * T / 2 + (along ? 0 : sd.dx * T), wz0 = sd.z0 - nz * T / 2 + (along ? 0 : sd.dz * T); brickJambs(B, S, { cx: wx0 + sd.dx * am, cz: wz0 + sd.dz * am, dx: sd.dx, dz: sd.dz, T, w: o.a1 - o.a0, y0: o.y0, y1: o.y1 }, H.out); } } } - // roof and gables - const old = !H.trim, roof = gableRoof(B, S, { w, d, eave: wallH, pitch: H.pitch || 0.75, mat: H.roof, sag: H.sag != null ? H.sag : old ? 0.09 + S.damage * 0.12 + S.R() * 0.08 : 0.04 + S.R() * 0.03, over: H.over, gable: H.gableOver, ridgeMat: H.ridgeMat, eaveWander: old ? 0.09 : 0.03 }); - for (const xs of [1, -1]) gableWall(B, S, { w: w - T, d: d - 0.001, T, eave: wallH, ridge: roof.ridge - 0.05, out: H.out, in: H.in, uStart: 0 }, xs); - B.col(-w / 2 + T / 2, 0, T, d, wallH, roof.ridge, 0, H.surf || 'stone', 'gable'); B.col(w / 2 - T / 2, 0, T, d, wallH, roof.ridge, 0, H.surf || 'stone', 'gable'); - S.roofTop = roof.ridge; S.eaveH = wallH; S.footX = w; S.footZ = d; S.outMat = H.out; - return { wallH, ridge: roof.ridge }; - } - // window / door layout along a wall of length L for n bays - function bays(L, n, y0, y1, extra) { const out = []; for (let i = 0; i < n; i++) { const c = L * (i + 0.5) / n, w = (extra && extra.w) || 0.9; out.push(Object.assign({ a0: c - w / 2, a1: c + w / 2, y0, y1 }, extra || {})); } return out; } - - // ------------------------------------------------------------------ the kinds - const KINDS = {}; - KINDS.farmhouse = function (B, S, sp) { - const w = sp.w || 12, d = sp.d || 7.5, floors = sp.floors || 2, storey = 2.8, T = 0.5, R = S.R; - const litW = (i) => R() < (sp.lit || 0); - const front = []; - const nb = Math.max(3, Math.round(w / 3)), mid = Math.floor(nb / 2); - for (let f = 0; f < floors; f++) for (let i = 0; i < nb; i++) { - const c = w * (i + 0.5) / nb; - if (f === 0 && i === mid) front.push({ a0: c - 0.55, a1: c + 0.55, y0: 0, y1: 2.15, door: true, ajar: sp.doorAjar || 0 }); - else front.push({ a0: c - 0.5, a1: c + 0.5, y0: f * storey + 0.9, y1: f * storey + 2.25 - (f ? 0.15 : 0), lit: litW(), broken: R() < sp.damage * 0.6, shutters: true }); - } - const back = []; for (let f = 0; f < floors; f++) for (let i = 0; i < nb - 1; i++) { const c = w * (i + 0.5) / (nb - 1); if (f === 0 && i === 0) back.push({ a0: c - 0.45, a1: c + 0.45, y0: 0, y1: 2.05, door: true }); else back.push({ a0: c - 0.45, a1: c + 0.45, y0: f * storey + 0.95, y1: f * storey + 2.15, lit: litW(), broken: R() < sp.damage * 0.6, shutters: true }); } - const right = [{ a0: d / 2 - 0.4 - 0.5, a1: d / 2 - 0.4 + 0.5, y0: storey + 0.95, y1: storey + 2.1, lit: litW() }]; - const H = { w, d, T, floors, storey, out: sp.out || 'fieldstone', in: 'plaster_interior', roof: sp.roof === 'slate' ? 'slate' : 'roof_tile', head: 'lintel', doorHead: 'lintel', shutters: true, quoins: true, front, back, right, left: [], pitch: 0.78, surf: 'stone' }; - const r = house(B, S, H); - chimney(B, S, -w / 2 + T + 0.31, -0.3, 0, r.ridge + 0.9, true); - if (w > 10) chimney(B, S, w / 2 - T - 0.31, 0.4, 0, r.ridge + 0.75, false); - // interior: ground floor flags, upper floor, stairs, a partition with a doorway, fireplace, furniture - B.box('ashlar', 0, -0.05, 0, w - 2 * T, 0.06, d - 2 * T, 0, { tint: new THREE.Color(0.62, 0.6, 0.56), noFoot: true }); - const sx0 = w / 2 - T - 0.35 - 3.8, hole = { x0: sx0, x1: w / 2 - T, z0: -d / 2 + T, z1: -d / 2 + T + 1.0 }; - for (let f = 1; f < floors; f++) floorDeck(B, S, w, d, f * storey, T, 'floorboards', f === 1 ? hole : null); - stairs(B, S, w / 2 - T - 0.2, -d / 2 + T + 0.5, -1, 0, storey, 0.9); - // partition wall (plaster both sides) with a doorway, splitting off the office at the right end - const px = w / 2 - T - 3.6; - wallRun(B, { x0: px, z0: d / 2 - T, dx: 0, dz: -1, L: d - 2 * T - 1.2, T: 0.14, H: storey - 0.32, ops: [{ a0: 0.6, a1: 1.5, y0: 0, y1: 2.0 }], mats: { out: 'plaster_interior', in: 'plaster_interior' }, surf: 'stone', capStart: true, capEnd: true }); - fireplace(B, S, -w / 2 + T + 0.45, -0.3, Math.PI / 2); - S.fy = 0; - furn(B, S, 'table', -1.2, 0.6, 0); furn(B, S, 'chair', -1.6, 1.25, Math.PI); furn(B, S, 'chair', -0.6, 0.0, 0.2); furn(B, S, 'bench', -1.2, -0.2, 0); - furn(B, S, 'dresser', -2.2, -d / 2 + T + 0.3, 0); furn(B, S, 'stove', 0.9, -d / 2 + T + 0.4, 0); - furn(B, S, 'desk', w / 2 - T - 1.0, d / 2 - T - 0.8, Math.PI); furn(B, S, 'chair', w / 2 - T - 1.0, d / 2 - T - 1.4, 0.3); furn(B, S, 'cupboard', px + 0.45, -d / 2 + T + 1.6, -Math.PI / 2); - furn(B, S, 'barrel', -w / 2 + T + 1.6, d / 2 - T - 0.5); - if (floors > 1) { S.fy = storey; furn(B, S, 'bed', -w / 2 + T + 2.0, -d / 2 + T + 1.1, 0); furn(B, S, 'bed', -0.5, -d / 2 + T + 1.1, 0); furn(B, S, 'cupboard', 1.8, d / 2 - T - 0.35, Math.PI); furn(B, S, 'chair', -2.5, 1.5, 1.0); S.fy = 0; } - S.lights.push({ x: -1.2, y: 2.1, z: 0.6, color: 0xffa860, r: 10, power: sp.lit ? 2.4 : 0, interior: true }); if (sp.lit) lantern(B, -1.2, 0.78, 0.6); - }; - KINDS.cottage = function (B, S, sp) { - const w = sp.w || 8, d = sp.d || 6, T = 0.3, storey = 2.6, R = S.R, floors = sp.floors || 1; - const front = [{ a0: w / 2 - 0.5, a1: w / 2 + 0.5, y0: 0, y1: 2.05, door: true }, ...bays(w, 2, 0.9, 2.05, { w: 0.9 }).map((o, i) => Object.assign(o, { a0: i ? w * 0.8 - 0.45 : w * 0.2 - 0.45, a1: i ? w * 0.8 + 0.45 : w * 0.2 + 0.45, lit: R() < (sp.lit || 0), broken: R() < sp.damage * 0.6 }))]; - const back = bays(w, 2, 0.95, 2.0, { w: 0.8 }).map(o => Object.assign(o, { lit: R() < (sp.lit || 0) })); - const r = house(B, S, { w, d, T, floors, storey, knee: floors === 1 ? 0.4 : 0, out: sp.out || 'brick_red', in: 'plaster_interior', roof: sp.roof === 'tile' ? 'roof_tile' : 'slate', head: 'arch', doorHead: 'timber', shutters: false, quoins: false, front, back, right: [{ a0: d / 2 - 0.4, a1: d / 2 + 0.4, y0: storey * floors - 0.2, y1: storey * floors + 0.8 }], left: [], pitch: 0.8, plinth: 'brick_sooty', sill: true, surf: 'stone' }); - chimney(B, S, w / 2 - T - 0.31, 0, 0, r.ridge + 0.8, true); - B.box('floorboards', 0, -0.03, 0, w - 2 * T, 0.03, d - 2 * T, 0, { noFoot: true }); - }; - // a long, low camp office hut: brick walls (sp.out for another wall material) on a sooty plinth, a shallow slate roof, a row of sash windows, a short stack - KINDS.office = function (B, S, sp) { - const w = sp.w || 14, d = sp.d || 7, T = 0.25, storey = 2.7, R = S.R; - // sp.doorEnd: the door is in the +X gable end (local), not the middle of the front - const nf = Math.max(2, Math.round(w / 3.2)), front = sp.doorEnd ? [] : [{ a0: w / 2 - 0.55, a1: w / 2 + 0.55, y0: 0, y1: 2.1, door: true }]; - for (let i = 0; i < nf; i++) { const c = w * (i + 0.5) / nf; if (sp.doorEnd || Math.abs(c - w / 2) > 1.4) front.push({ a0: c - 0.55, a1: c + 0.55, y0: 0.95, y1: 2.25, lit: R() < (sp.lit || 0) }); } - const back = bays(w, nf, 0.95, 2.25, { w: 1.1 }).map(o => Object.assign(o, { lit: R() < (sp.lit || 0) })); - const end = [{ a0: d / 2 - 0.5, a1: d / 2 + 0.5, y0: 0.95, y1: 2.25 }], dEnd = [{ a0: d / 2 - 0.6, a1: d / 2 + 0.6, y0: 0, y1: 2.1, door: true }]; - const r = house(B, S, { w, d, T, floors: 1, storey, out: sp.out || 'brick_red', in: 'plaster_interior', plinth: 'brick_sooty', roof: 'slate', pitch: 0.3, over: 0.45, head: 'lintel', doorHead: 'timber', shutters: false, quoins: false, front, back, right: sp.doorEnd ? dEnd : end, left: end }); - chimney(B, S, -w / 2 + 2.2, 0, 0, r.ridge + 0.6, true); - // door step, a boot scraper, the stains rain makes under the sills and along the plinth - if (sp.doorEnd) { B.box('concrete', w / 2 + 0.35, 0, 0, 0.6, 0.16, 1.6, 0, { tint: new THREE.Color(0.85, 0.83, 0.8) }); B.box('metal_rust', w / 2 + 0.5, 0.16, 1.0, 0.05, 0.12, 0.35, 0, { noFoot: true }); } - else { B.box('concrete', 0, 0, d / 2 + 0.35, 1.5, 0.16, 0.6, 0, { tint: new THREE.Color(0.85, 0.83, 0.8) }); B.box('metal_rust', 0.95, 0.16, d / 2 + 0.5, 0.35, 0.12, 0.05, 0, { noFoot: true }); } - for (const z of [d / 2 + 0.01, -d / 2 - 0.01]) { B.decal('waterstain', [0, 0.45, z], [0, 0, Math.sign(z)], w * 0.95, 0.9, 0); B.decal(R() < 0.5 ? 'moss' : 'grime', [R.range(-w / 3, w / 3), 0.25, z], [0, 0, Math.sign(z)], 2.5, 0.5, 0); } - B.box('floorboards', 0, -0.03, 0, w - 2 * T, 0.03, d - 2 * T, 0, { noFoot: true }); - }; - KINDS.shoprow = function (B, S, sp) { - const n = sp.units || 3, uw = sp.w ? sp.w / n : 5.4, d = sp.d || 8, R = S.R, T = 0.3, storey = 3.0; - const NAMES = ['BOULANGERIE', 'EPICERIE', 'QUINCAILLERIE', 'CAFE DU PONT', 'MERCERIE', 'TABAC', 'BOUCHERIE', 'HORLOGERIE']; - for (let i = 0; i < n; i++) { - const ox = (i - (n - 1) / 2) * uw, Bu = E.builder(S.seed + i * 13), floors = 2 + (R() < 0.3 ? 1 : 0); - const Su = Object.assign({}, S, { R: E.rng(S.seed + i * 13), windows: [], lights: [], doors: [], group: new THREE.Group() }); - const plaster = R() < 0.35; - const front = [{ a0: uw * 0.72 - 0.5, a1: uw * 0.72 + 0.5, y0: 0, y1: 2.3, door: true }, { a0: 0.45, a1: uw * 0.55, y0: 0.6, y1: 2.5, lit: R() < (sp.lit || 0), broken: R() < sp.damage * 0.7, head: 'timber' }]; - for (let f = 1; f < floors; f++) for (const c of [uw * 0.27, uw * 0.73]) front.push({ a0: c - 0.45, a1: c + 0.45, y0: f * storey + 0.9, y1: f * storey + 2.2, lit: R() < (sp.lit || 0) * 0.6, broken: R() < sp.damage * 0.5, shutters: plaster }); - const r = house(Bu, Su, { w: uw, d, T, floors, storey, out: plaster ? 'plaster' : (R() < 0.3 ? 'brick_sooty' : 'brick_red'), in: 'plaster_interior', roof: R() < 0.6 ? 'slate' : 'roof_tile', head: plaster ? 'lintel' : 'arch', doorHead: 'timber', front, back: bays(uw, 2, storey + 0.9, storey + 2.1, { w: 0.8 }), left: [], right: [], pitch: 0.7 + R() * 0.15, quoins: plaster, sag: 0.03 + R() * 0.05, gableOver: 0.02, over: 0.3 }); - // fascia sign with a painted name (invented shop words only) - // (one label atlas when env/labels.js is loaded: the board is part of the level's single label draw call) - if (E.label) Bu.label(NAMES[(S.seed + i * 3) % NAMES.length], { kind: 'paint', ground: '#2c3a33', color: '#e8dcb4', distress: 0.35, size: 72, aspect: (uw - 0.5) / 0.58 }, [0, 2.6, d / 2 + 0.056], [0, 0, 1], uw - 0.5); - else { const sign = signMesh(NAMES[(S.seed + i * 3) % NAMES.length], uw - 0.5, 0.58, Su.R); sign.position.set(ox, 2.6, d / 2 + 0.06); S.group.add(sign); } - Bu.box('timber', 0, 2.55, d / 2 + 0.02, uw - 0.4, 0.62, 0.06, 0, { grain: 'long', tint: new THREE.Color(0.55, 0.5, 0.45) }); - chimney(Bu, Su, uw / 2 - 0.35, -1, r.wallH - 1, r.ridge + 1.0, true); - const g = Bu.finish(); g.position.x = ox; S.group.add(g); - Su.colliders = Bu.colliders.map(c => Object.assign(c, { x: c.x + ox })); S.extraCols.push(...Su.colliders); - for (const wv of Su.windows) S.windows.push(Object.assign(wv, { x: wv.x + ox })); for (const l of Su.lights) S.lights.push(Object.assign(l, { x: l.x + ox })); - for (const dr of Su.doors) { dr.pivot.parent.remove(dr.pivot); dr.pivot.position.x += ox; S.group.add(dr.pivot); S.doors.push(dr); } - for (const c of Su.group.children.slice()) { c.position.x += ox; S.group.add(c); } - } - }; - function signMesh(text, w, h, R) { - const c = document.createElement('canvas'); c.width = 512; c.height = Math.round(512 * h / w); - const g = c.getContext('2d'); g.fillStyle = '#2c3a33'; g.fillRect(0, 0, c.width, c.height); - g.font = 'bold ' + Math.round(c.height * 0.72) + 'px Georgia, "Times New Roman", serif'; g.textAlign = 'center'; g.textBaseline = 'middle'; g.fillStyle = '#e8dcb4'; g.fillText(text, c.width / 2, c.height * 0.55, c.width * 0.92); g.strokeStyle = '#bba873'; g.lineWidth = 2; g.strokeRect(6, 6, c.width - 12, c.height - 12); - // weathering: flaked paint and grime - for (let i = 0; i < 160; i++) { g.fillStyle = `rgba(${R() < 0.5 ? '20,18,14' : '90,80,64'},${R() * 0.25})`; g.fillRect(R() * c.width, R() * c.height, R() * 5, R() * 2); } - const t = new THREE.CanvasTexture(c); t.encoding = THREE.sRGBEncoding; t.anisotropy = 4; - const m = new THREE.MeshStandardMaterial({ map: t, roughness: 0.85, emissive: 0xffffff, emissiveMap: t, emissiveIntensity: 0.12 }); m.userData.linear = true; - const mesh = new THREE.Mesh(new THREE.PlaneGeometry(w, h), m); mesh.receiveShadow = true; return mesh; - } - KINDS.barn = function (B, S, sp) { - const w = sp.w || 10, d = sp.d || 16, R = S.R, T = 0.45, base = 1.1, eave = 4.6; - // a stone plinth wall, then vertical boards on a timber frame; the long side faces +Z (big doors) - // here the ridge runs along the barn's length: we build it rotated so the length is local X - const L = d, Wd = w; - const dw = 3.4, dh = 3.6; - // stone lower walls - const sides = [ - { x0: -L / 2, z0: Wd / 2, dx: 1, dz: 0, len: L, ops: [{ a0: L / 2 - dw / 2, a1: L / 2 + dw / 2, y0: 0, y1: 3.0 }] }, - { x0: L / 2, z0: Wd / 2, dx: 0, dz: -1, len: Wd, ops: [{ a0: Wd / 2 - 0.5, a1: Wd / 2 + 0.5, y0: 0, y1: 2.0 }] }, - { x0: L / 2, z0: -Wd / 2, dx: -1, dz: 0, len: L, ops: [] }, - { x0: -L / 2, z0: -Wd / 2, dx: 0, dz: 1, len: Wd, ops: [] } - ]; - let u = 0; - for (const sd of sides) { - const nx = -sd.dz, nz = sd.dx, along = sd.dx !== 0; - const W = { x0: sd.x0 - nx * T / 2, z0: sd.z0 - nz * T / 2, dx: sd.dx, dz: sd.dz, L: sd.len, T, H: base, ops: sd.ops.map(o => Object.assign({}, o, { y1: Math.min(o.y1, base + 0.01) })), mats: { out: 'fieldstone', in: 'fieldstone' }, uStart: u, surf: 'stone' }; - if (!along) { W.x0 += sd.dx * T; W.z0 += sd.dz * T; W.L -= 2 * T; } - wallRun(B, W); - // boarded upper walls: vertical planks on the outside of a timber frame - const bt = 0.04, H2 = eave - base, plankMat = sp.lit ? 'planks|gaplit' : 'planks'; - const W2 = { x0: sd.x0 - nx * bt / 2, z0: sd.z0 - nz * bt / 2, dx: sd.dx, dz: sd.dz, L: sd.len, T: bt, H: H2, y0: base, ops: sd.ops.concat(along && sd.z0 > 0 ? [{ a0: L * 0.2 - 0.6, a1: L * 0.2 + 0.6, y0: 3.0, y1: 4.1 }] : []).map(o => Object.assign({}, o)), mats: { out: plankMat, in: 'planks' }, uStart: u, surf: 'wood', capTop: true }; - wallRun(B, W2); - // posts of the frame inside, every 2.5 m, and a wall plate - for (let a = 0; a <= sd.len + 0.01; a += sd.len / Math.round(sd.len / 2.5)) { - if (sd.ops.some(o => a > o.a0 - 0.1 && a < o.a1 + 0.1)) continue; - const px = sd.x0 + sd.dx * a - nx * (bt + 0.1), pz = sd.z0 + sd.dz * a - nz * (bt + 0.1); - B.box('timber', px, base, pz, 0.2, H2, 0.2, 0, { grain: 'long', noFoot: true }); - } - B.box('timber', sd.x0 + sd.dx * sd.len / 2 - nx * (bt + 0.1), eave - 0.22, sd.z0 + sd.dz * sd.len / 2 - nz * (bt + 0.1), along ? sd.len : 0.22, 0.22, along ? 0.22 : sd.len, 0, { grain: 'long', noFoot: true }); - // wear on the lower boards - for (let k = 0; k < Math.round(sd.len / 2); k++) B.decal(R() < 0.5 ? 'mud' : 'grime', [sd.x0 + sd.dx * R.range(0.5, sd.len - 0.5) + nx * 0.025, base + R.range(0.2, 0.6), sd.z0 + sd.dz * R.range(0.5, sd.len - 0.5) + nz * 0.025], [nx, 0, nz], R.range(0.6, 1.4), 0.5, 0); - u += sd.len; - } - // big doors: two leaves hung open, frame, and the loft hatch - for (const s of [-1, 1]) { - const D = E.builder(S.seed + 40 + s), lw = dw / 2 - 0.05; - D.box('planks', lw / 2, 0, 0, lw, dh - 0.05, 0.05, 0, {}); - for (const yy of [0.15, 0.5, 0.85]) D.box('timber', lw / 2, (dh - 0.05) * yy - 0.08, 0.04, lw - 0.05, 0.16, 0.04, 0, { grain: 'long' }); - D.box('timber', lw / 2, 0.4, 0.04, 0.14, dh - 0.9, 0.035, 0, { rz: s * 0.62, grain: 'long' }); - D.decal('mud', [lw / 2, 0.25, 0.03], [0, 0, 1], lw * 0.9, 0.5, 0); D.decal('scratches', [lw / 2, 1.0, 0.03], [0, 0, 1], lw * 0.7, 0.6, 0.3); - const leaf = D.finish(), pv = new THREE.Group(); pv.add(leaf); pv.userData.dynamic = true; - if (s < 0) { pv.position.set(-dw / 2, 0.02, Wd / 2 + 0.03); } else { pv.position.set(dw / 2, 0.02, Wd / 2 + 0.03); pv.scale.x = -1; } - S.group.add(pv); - const door = { pivot: pv, width: lw, x: s * dw / 4, z: Wd / 2, open(a) { pv.rotation.y = -s * a; } }; - door.open(sp.doorOpen != null ? sp.doorOpen : 1.4 + R() * 0.3); S.doors.push(door); - } - B.box('timber', 0, dh, Wd / 2 + 0.02, dw + 0.5, 0.25, 0.25, 0, { grain: 'long' }); - // interior: posts, tie beams, half loft with ladder, hay, stalls - for (let x = -L / 2 + 2.5; x < L / 2 - 1; x += 2.5) { - for (const z of [-Wd / 2 + 2.2, Wd / 2 - 2.2]) { B.box('timber', x, 0, z, 0.24, eave - 0.2, 0.24, 0, { grain: 'long' }); B.col(x, z, 0.26, 0.26, 0, eave, 0, 'wood', 'post'); B.decal('scratches', [x, 0.9, z + 0.121], [0, 0, 1], 0.2, 0.5, Math.PI / 2); } - B.box('timber', x, eave - 0.25, 0, 0.22, 0.26, Wd - 0.2, 0, { grain: 'long', noFoot: true }); - } - const loftX0 = 1.0, loftY = 2.7; - B.box('floorboards', (loftX0 + L / 2 - T) / 2, loftY, 0, L / 2 - T - loftX0, 0.05, Wd - 0.2, 0, { noFoot: true, grain: 'long' }); - B.col((loftX0 + L / 2 - T) / 2, 0, L / 2 - T - loftX0, Wd - 0.2, loftY - 0.2, loftY + 0.05, 0, 'wood', 'floor'); - for (let z = -Wd / 2 + 0.6; z < Wd / 2 - 0.3; z += 0.6) B.box('timber', (loftX0 + L / 2 - T) / 2, loftY - 0.2, z, L / 2 - T - loftX0, 0.2, 0.12, 0, { grain: 'long', noFoot: true }); - // ladder up to the loft - const lx = loftX0 - 0.05, lz = 1.0; - for (const s of [-0.22, 0.22]) B.box('timber', lx - 0.45, 0, lz + s, 0.06, 3.0, 0.06, 0, { rz: 0.28, grain: 'long', noFoot: true }); - for (let k = 1; k < 10; k++) B.box('timber', lx - 0.45 + k * 0.08, k * 0.29, lz, 0.04, 0.04, 0.5, 0, { noFoot: true }); - // hay in the loft and on the floor, a stall partition, a cart wheel against the wall - for (let k = 0; k < 14; k++) { const x = R.range(loftX0 + 0.8, L / 2 - T - 0.7), z = R.range(-Wd / 2 + 0.8, Wd / 2 - 0.8); E.hayBale(B, x, loftY + 0.05 + (k > 9 ? 0.4 : 0), z, R.range(-0.2, 0.2) + (R() < 0.5 ? 0 : Math.PI / 2), R); } - for (let k = 0; k < 5; k++) E.hayBale(B, -L / 2 + T + 0.8 + (k % 2) * 0.95, (k > 2 ? 0.4 : 0), -Wd / 2 + T + 0.6 + Math.floor(k / 2) * 0.0, 0, R); - B.decal('leaves', [-1.5, 0.01, 0.5], [0, 1, 0], 3.5, 2.5, 0.3); B.decal('mud', [0, 0.01, Wd / 2 - 0.8], [0, 1, 0], 3.2, 1.6, 0); - for (let k = 0; k < 4; k++) B.box('planks', -L / 2 + T + 3.2 + k * 0.0, 0, -Wd / 2 + T + 1.3, 0.05, 1.3, 2.4, 0, { noFoot: true }); - // straw on the floor - B.box('earth', 0, -0.04, 0, L - 2 * T, 0.05, Wd - 2 * T, 0, { noFoot: true, tint: new THREE.Color(0.7, 0.65, 0.55) }); - // roof along the barn's length (local X) - const roof = gableRoof(B, S, { w: L, d: Wd, eave, pitch: 0.82, mat: sp.roof === 'tile' ? 'roof_tile' : 'slate', sag: 0.12 + S.damage * 0.12 + R() * 0.08, over: 0.4, gable: 0.3, eaveWander: 0.08 }); - // boarded gables - for (const xs of [1, -1]) gableWall(B, S, { w: L - 0.04, d: Wd, T: 0.04, eave, ridge: roof.ridge - 0.05, out: 'planks', in: 'planks' }, xs); - S.lights.push({ x: -2.5, y: 2.2, z: 0.8, color: 0xffa050, r: 13, power: sp.lit ? 2.8 : 0, interior: true }); if (sp.lit) lantern(B, -2.5, 1.9, 0.8, true); - S.roofTop = roof.ridge; S.eaveH = eave; S.footX = L; S.footZ = Wd; S.outMat = 'fieldstone'; - }; - KINDS.shed = function (B, S, sp) { - const w = sp.w || 4, d = sp.d || 3, R = S.R, h1 = 2.4, h2 = 1.9, bt = 0.04; - const sides = [ - { x0: -w / 2, z0: d / 2, dx: 1, dz: 0, len: w, ops: [{ a0: w * 0.3, a1: w * 0.3 + 0.9, y0: 0, y1: 1.95 }], h: h1 }, - { x0: w / 2, z0: d / 2, dx: 0, dz: -1, len: d, ops: [{ a0: d / 2 - 0.3, a1: d / 2 + 0.3, y0: 1.1, y1: 1.6 }], h: h2 }, - { x0: w / 2, z0: -d / 2, dx: -1, dz: 0, len: w, ops: [], h: h2 }, - { x0: -w / 2, z0: -d / 2, dx: 0, dz: 1, len: d, ops: [], h: h2 } - ]; - let u = 0; - for (const sd of sides) { const nx = -sd.dz, nz = sd.dx; wallRun(B, { x0: sd.x0 - nx * bt / 2, z0: sd.z0 - nz * bt / 2, dx: sd.dx, dz: sd.dz, L: sd.len, T: bt, H: sd.h, ops: sd.ops, mats: { out: 'planks', in: 'planks' }, uStart: u, surf: 'wood' }); u += sd.len; } - // gaps up the sides between front (taller) and back: triangles of boards - for (const xs of [-1, 1]) for (const io of [1, -1]) { const x = xs * w / 2 + xs * io * 0.0; const A = [x, h2, -d / 2], Bq = [x, h2, d / 2], C = [x, h1, d / 2]; const uz = (z) => xs > 0 ? w + (d / 2 - z) : 2 * w + d + (z + d / 2); // the same u the wall run below uses, so boards continue - if ((xs > 0) === (io > 0)) B.tri('planks', A, C, Bq, [[uz(-d / 2), h2], [uz(d / 2), h1], [uz(d / 2), h2]], null, 0); else B.tri('planks', A, Bq, C, [[uz(-d / 2), h2], [uz(d / 2), h2], [uz(d / 2), h1]], null, 0); } - // posts in the corners, a mono-pitch roof of slates (corrugated sheets would need a new material) - for (const [a, b] of [[-1, -1], [1, -1], [-1, 1], [1, 1]]) B.box('timber', a * (w / 2 - 0.06), 0, b * (d / 2 - 0.06), 0.1, b > 0 ? h1 : h2, 0.1, 0, { grain: 'long' }); - const pitch = Math.atan2(h1 - h2, d), len = Math.hypot(d + 0.5, h1 - h2); - B.box(sp.roof === 'tile' ? 'roof_tile' : 'slate', 0, (h1 + h2) / 2 + 0.02, 0, w + 0.4, 0.05, len, 0, { rx: -pitch, noFoot: true }); - B.box('planks', 0, (h1 + h2) / 2 - 0.01, 0, w + 0.3, 0.025, len - 0.05, 0, { rx: -pitch, noFoot: true, tint: new THREE.Color(0.6, 0.55, 0.5) }); - for (let k = 0; k < 3; k++) B.box('timber', -w / 2 + 0.2 + k * (w - 0.4) / 2, (h1 + h2) / 2 - 0.12, 0, 0.08, 0.1, len - 0.1, 0, { rx: -pitch, noFoot: true }); - // door leaf - dressDoor(B, S, { cx: -w / 2 + w * 0.3 + 0.45, cz: d / 2 - bt / 2, dx: 1, dz: 0, T: bt, w: 0.9, h: 1.95, ajar: 0.5, threshold: false }, S.group); - E.prop && null; - for (let k = 0; k < 3; k++) B.decal(R() < 0.5 ? 'mud' : 'moss', [R.range(-w / 2 + 0.3, w / 2 - 0.3), 0.2, d / 2 + 0.003], [0, 0, 1], 0.8, 0.35, 0); - S.roofTop = h1 + 0.1; - }; - KINDS.church = function (B, S, sp) { - const w = sp.w || 16, d = sp.d || 8, R = S.R, T = 0.7, nave = 5.6; - const side = []; for (let i = 0; i < 4; i++) { const c = w * (i + 0.5) / 4; side.push({ a0: c - 0.45, a1: c + 0.45, y0: 1.8, y1: 4.4, head: 'pointed', lit: R() < (sp.lit || 0) * 0.5, broken: R() < sp.damage * 0.6 }); } - const r = house(B, S, { w, d, T, floors: 1, storey: nave, out: 'fieldstone', in: 'plaster_interior', roof: 'slate', head: 'pointed', shutters: false, quoins: true, front: side, back: side.map(o => Object.assign({}, o, { lit: false })), right: [{ a0: d / 2 - 0.9, a1: d / 2 + 0.9, y0: 2.0, y1: 4.8, head: 'pointed' }], left: [], pitch: 0.95, sag: 0.03 + S.damage * 0.1, plinth: 'ashlar', sillMat: 'ashlar' }); - // stepped buttresses between the nave windows, with sloped weatherings - for (let i = 0; i <= 4; i++) { const x = -w / 2 + i * w / 4; for (const sz of [-1, 1]) { const z = sz * (d / 2 + 0.35); B.box('fieldstone', x, 0, z, 0.75, 2.6, 0.7, 0, {}); B.box('fieldstone', x, 2.6, sz * (d / 2 + 0.22), 0.65, 1.6, 0.45, 0, {}); B.box('ashlar', x, 4.1, sz * (d / 2 + 0.2), 0.7, 0.12, 0.5, 0, { rx: -sz * 0.6, noFoot: true }); B.col(x, z, 0.75, 0.7, 0, 3.5, 0, 'stone', 'buttress'); } } - // the tower at the west end (local -X), with a pointed door, louvred belfry openings and a pyramid spire - const tw = 4.4, th = 15, tx = -w / 2 - tw / 2 + 0.2, Tt = 0.8; - const T2 = E.builder(S.seed + 9), S2 = Object.assign({}, S, { R: E.rng(S.seed + 9), windows: S.windows, lights: S.lights, doors: S.doors }); - const bell = (o) => Object.assign({ y0: th - 3.4, y1: th - 1.2, head: 'pointed', a0: tw / 2 - 0.5, a1: tw / 2 + 0.5 }, o || {}); - const sidesT = [ - { x0: -tw / 2, z0: tw / 2, dx: 1, dz: 0, ops: [{ a0: tw / 2 - 0.7, a1: tw / 2 + 0.7, y0: 0, y1: 2.8, door: true }, bell()] }, - { x0: tw / 2, z0: tw / 2, dx: 0, dz: -1, ops: [bell()] }, - { x0: tw / 2, z0: -tw / 2, dx: -1, dz: 0, ops: [bell()] }, - { x0: -tw / 2, z0: -tw / 2, dx: 0, dz: 1, ops: [bell(), { a0: tw / 2 - 0.3, a1: tw / 2 + 0.3, y0: 6, y1: 7.6 }] } - ]; - let u = 0; - for (const sd of sidesT) { - const nx = -sd.dz, nz = sd.dx, along = sd.dx !== 0, Wt = { x0: sd.x0 - nx * Tt / 2, z0: sd.z0 - nz * Tt / 2, dx: sd.dx, dz: sd.dz, L: tw, T: Tt, H: th, ops: sd.ops, mats: { out: 'fieldstone', in: 'fieldstone' }, uStart: u, surf: 'stone' }; - if (!along) { Wt.x0 += sd.dx * Tt; Wt.z0 += sd.dz * Tt; Wt.L -= 2 * Tt; } - wallRun(T2, Wt); - for (const o of sd.ops) { - const am = (o.a0 + o.a1) / 2 - (along ? 0 : Tt), cx = Wt.x0 + sd.dx * am, cz = Wt.z0 + sd.dz * am; - if (o.door) dressDoor(T2, S2, { cx, cz, dx: sd.dx, dz: sd.dz, T: Tt, w: 1.4, h: 2.8 }, S.group); - else if (o.y0 > 10) { // belfry: louvre boards instead of glass - const nn = [-sd.dz, sd.dx], hp = [cx + nn[0] * (Tt / 2 - 0.2), cz + nn[1] * (Tt / 2 - 0.2)]; - for (let k = 0; k < 7; k++) T2.box('planks', hp[0], o.y0 + 0.15 + k * 0.28, hp[1], 0.95, 0.03, 0.22, Math.atan2(-sd.dz, sd.dx), { rx: 0.6, noFoot: true, tint: new THREE.Color(0.5, 0.48, 0.45) }); - dressWindow(T2, S2, { cx, cz, dx: sd.dx, dz: sd.dz, T: Tt, w: 1.0, y0: o.y0, y1: o.y1, head: 'pointed', sill: true, shutters: false, lit: false, broken: true }); - } else dressWindow(T2, S2, { cx, cz, dx: sd.dx, dz: sd.dz, T: Tt, w: o.a1 - o.a0, y0: o.y0, y1: o.y1, head: 'lintel', sill: true }); - } - u += tw; - } - quoins(T2, S2, tw, tw, th, Tt); - // string course and a parapet-less pyramid spire of slate - T2.box('ashlar', 0, th - 0.2, 0, tw + 0.12, 0.2, tw + 0.12, 0, { noFoot: true }); - const sh = 6.5, cone = new THREE.ConeGeometry((tw + 0.4) * 0.707, sh, 4, 3); cone.rotateY(Math.PI / 4); - T2.geo('slate', cone, _M.compose(_P.set(0, th + sh / 2, 0), _Q.identity(), _S.set(1, 1, 1)), { noFoot: true }); - T2.box('metal_rust', 0, th + sh - 0.1, 0, 0.05, 1.4, 0.05, 0, { noFoot: true }); T2.box('metal_rust', 0, th + sh + 0.8, 0, 0.5, 0.05, 0.05, 0, { noFoot: true }); - // a weathervane arrow, a clock face on the tower (plain numerals, no maker's name) - T2.box('metal_rust', 0.35, th + sh + 0.86, 0, 0.32, 0.18, 0.015, 0, { noFoot: true, rz: 0.78 }); - { const cy = th - 4.6, cz = tw / 2 + 0.03; T2.geo('wood_painted', new THREE.CircleGeometry(0.62, 20), _M.compose(_P.set(0, cy, cz), _Q.identity(), _S.set(1, 1, 1)), { noFoot: true, tint: new THREE.Color(1.5, 1.45, 1.35) }); - T2.geo('metal_rust', new THREE.TorusGeometry(0.64, 0.035, 4, 24), _M.compose(_P.set(0, cy, cz + 0.01), _Q.identity(), _S.set(1, 1, 1)), { noFoot: true }); - for (let k = 0; k < 12; k++) { const a = k / 12 * TAU; T2.box('metal_painted', Math.cos(a) * 0.5, cy + Math.sin(a) * 0.5 - 0.04, cz + 0.02, 0.03, 0.08, 0.01, 0, { noFoot: true, rz: a, tint: new THREE.Color(0.15, 0.15, 0.15) }); } - T2.box('metal_painted', 0.12, cy - 0.02, cz + 0.03, 0.32, 0.04, 0.01, 0, { noFoot: true, rz: 0.5, tint: new THREE.Color(0.1, 0.1, 0.1) }); T2.box('metal_painted', 0, cy - 0.02, cz + 0.035, 0.03, 0.46, 0.01, 0, { noFoot: true, rz: -0.3, tint: new THREE.Color(0.1, 0.1, 0.1) }); } - // a gabled porch on the tower door - { const pz = tw / 2 + 1.1; for (const sx of [-1, 1]) T2.box('fieldstone', sx * 1.15, 0, pz, 0.35, 2.3, 2.2, 0, {}); T2.box('timber', 0, 2.3, pz + 1.0, 2.7, 0.2, 0.2, 0, { noFoot: true }); - const pr = new THREE.ConeGeometry(1.0, 1, 4, 1).rotateY(Math.PI / 4); T2.geo('slate', pr, _M.compose(_P.set(0, 2.85, pz), _Q.identity(), _S.set(2.1, 1.1, 1.75)), { noFoot: true }); - T2.col(-1.15, pz, 0.35, 2.2, 0, 2.3, 0, 'stone', 'porch'); T2.col(1.15, pz, 0.35, 2.2, 0, 2.3, 0, 'stone', 'porch'); } - const g2 = T2.finish(); g2.position.x = tx; S.group.add(g2); - for (const c of T2.colliders) S.extraCols.push(Object.assign(c, { x: c.x + tx })); - for (const dr of S.doors) if (dr.pivot.parent === S.group && !dr._moved && dr.x < 0) { } - S.roofTop = th + sh; - }; - KINDS.ruin = function (B, S, sp) { - // a burnt-out brick house: walls with stepped broken tops and loose bricks, no roof, charred beams, rubble - const w = sp.w || 9, d = sp.d || 7, R = S.R, T = 0.33, H = 5.4, dmg = Math.max(0.5, S.damage); - const sides = [ - { x0: -w / 2, z0: d / 2, dx: 1, dz: 0, L: w, ops: [{ a0: w / 2 - 0.5, a1: w / 2 + 0.5, y0: 0, y1: 2.1 }, { a0: 1.0, a1: 1.9, y0: 0.9, y1: 2.1 }, { a0: w - 1.9, a1: w - 1.0, y0: 0.9, y1: 2.1 }, { a0: 1.0, a1: 1.9, y0: 3.4, y1: 4.5 }] }, - { x0: w / 2, z0: d / 2, dx: 0, dz: -1, L: d, ops: [{ a0: d / 2 - 0.45, a1: d / 2 + 0.45, y0: 0.9, y1: 2.1 }] }, - { x0: w / 2, z0: -d / 2, dx: -1, dz: 0, L: w, ops: [{ a0: 2.0, a1: 2.9, y0: 0.9, y1: 2.1 }] }, - { x0: -w / 2, z0: -d / 2, dx: 0, dz: 1, L: d, ops: [] } - ]; - let u = 0; const course = 0.105, bw = 0.33; - for (let si = 0; si < 4; si++) { - const sd = sides[si], nx = -sd.dz, nz = sd.dx, along = sd.dx !== 0; - // broken top profile: a smooth random line, quantised to brick courses and half-bricks, with a deep bite - const prof = (a) => { const n = E.fbm2(a * 0.35 + si * 7, si * 3.1, 900 + S.seed, 3); const bite = Math.exp(-((a - sd.L * (0.3 + 0.4 * E.hash(si, 1, S.seed))) ** 2) / 2.5) * 2.5 * dmg; return Math.max(0.6, H * (1 - dmg * 0.55 * n) - bite); }; - let x0 = sd.x0 - nx * T / 2, z0 = sd.z0 - nz * T / 2, L = sd.L; if (!along) { x0 += sd.dx * T; z0 += sd.dz * T; L -= 2 * T; } - // split the wall into columns of one brick length; each column has its own height, rounded to courses - for (let a = 0; a < L - 1e-3; a += bw) { - const a1 = Math.min(L, a + bw), top = Math.floor(prof(a + bw / 2) / course) * course; - const ops = sd.ops.map(o => ({ a0: o.a0 - a, a1: o.a1 - a, y0: o.y0, y1: o.y1 })).filter(o => o.a1 > 0 && o.a0 < a1 - a); - wallRun(B, { x0: x0 + sd.dx * a, z0: z0 + sd.dz * a, dx: sd.dx, dz: sd.dz, L: a1 - a, T, H: top, ops, mats: { out: 'brick_red', in: 'brick_sooty' }, uStart: u + a, surf: 'stone' }); - // ragged course on top: some bricks of the next course still sitting there, half-bricks proud - if (R() < 0.6) B.det(2, () => B.box('brick_red', x0 + sd.dx * (a + bw / 2) + R.range(-0.02, 0.02), top, z0 + sd.dz * (a + bw / 2), along ? 0.32 : T * 0.9, 0.1, along ? T * 0.9 : 0.32, R.range(-0.08, 0.08), { tint: tintJ(R, 0.12), uvOff: [R() * 3, R() * 3] })); - if (R() < 0.25) looseBlock(B, 'brick_red', x0 + sd.dx * (a + bw / 2) + nx * R.range(-0.1, 0.1), top + 0.07, z0 + sd.dz * (a + bw / 2) + nz * R.range(-0.1, 0.1), R, null, null, null, tintJ(R, 0.12)); - } - // soot above the openings, scorch, pocks, a big crack - for (const o of sd.ops) { const am = (o.a0 + o.a1) / 2 - (along ? 0 : T); B.decal('soot', [x0 + sd.dx * am + nx * (T / 2 + 0.003), o.y1 + 0.6, z0 + sd.dz * am + nz * (T / 2 + 0.003)], [nx, 0, nz], 1.4, 1.4, 0); B.decal('soot', [x0 + sd.dx * am - nx * (T / 2 + 0.003), o.y1 + 0.6, z0 + sd.dz * am - nz * (T / 2 + 0.003)], [-nx, 0, -nz], 1.4, 1.6, 0); } - for (let k = 0; k < Math.round(L * 0.8); k++) { const a = R.range(0.3, L - 0.3); B.decal(R() < 0.6 ? 'pocks' : 'bullethole', [x0 + sd.dx * a + nx * (T / 2 + 0.002), R.range(0.5, 2.5), z0 + sd.dz * a + nz * (T / 2 + 0.002)], [nx, 0, nz], R.range(0.25, 0.5), null, R() * 6); } - B.decal('crack', [x0 + sd.dx * L * 0.6 + nx * (T / 2 + 0.002), 1.6, z0 + sd.dz * L * 0.6 + nz * (T / 2 + 0.002)], [nx, 0, nz], 1.2, 1.6, 0.2); - B.decal('scorch', [x0 + sd.dx * L * 0.4 - nx * (T / 2 + 0.002), 1.2, z0 + sd.dz * L * 0.4 - nz * (T / 2 + 0.002)], [-nx, 0, -nz], 2.4, 2.4, 0); - // loose bricks fallen at the foot, both sides - for (let k = 0; k < Math.round(L * 2.5); k++) { const a = R.range(0, L), side = R() < 0.5 ? 1 : -1; looseBlock(B, 'brick_red', x0 + sd.dx * a + nx * side * R.range(0.25, 1.4), 0.03, z0 + sd.dz * a + nz * side * R.range(0.25, 1.4), R, null, null, null, tintJ(R, 0.14)); } - u += sd.L; - } - // rubble piles inside, charred beams fallen across, a burnt floor - rubble(B, -w * 0.15, -d * 0.1, 1.8, R, {}, 70); rubble(B, w * 0.25, d * 0.15, 1.3, R, {}, 40); - for (let k = 0; k < 3; k++) B.box('timber', R.range(-w / 4, w / 4), 0.2 + k * 0.25, R.range(-d / 4, d / 4), w * 0.7, 0.22, 0.24, R.range(-0.6, 0.6), { rz: R.range(-0.35, 0.35), tint: new THREE.Color(0.18, 0.16, 0.15), grain: 'long', noFoot: true }); - B.box('timber', -w / 2 + 0.6, 2.4, 0, 0.24, 0.24, d * 0.8, 0, { rx: 0.35, tint: new THREE.Color(0.15, 0.13, 0.12), grain: 'long', noFoot: true }); - B.decal('scorch', [0, 0.02, 0], [0, 1, 0], Math.min(w, d) * 0.8, Math.min(w, d) * 0.8, 0); - B.box('earth', 0, -0.04, 0, w - 2 * T, 0.05, d - 2 * T, 0, { tint: new THREE.Color(0.45, 0.42, 0.4), noFoot: true }); - S.roofTop = H; - }; - KINDS.bunker = function (B, S, sp) { - // a concrete pillbox with board-marked walls, a firing slit on each face, a thick roof slab, sandbags and earth - const w = sp.w || 5, d = sp.d || 5, R = S.R, T = 0.9, H = 2.2; - const slit = (L) => [{ a0: L / 2 - 0.7, a1: L / 2 + 0.7, y0: 1.15, y1: 1.45 }]; - const sides = [ - { x0: -w / 2, z0: d / 2, dx: 1, dz: 0, L: w, ops: slit(w) }, { x0: w / 2, z0: d / 2, dx: 0, dz: -1, L: d, ops: slit(d) }, - { x0: w / 2, z0: -d / 2, dx: -1, dz: 0, L: w, ops: [{ a0: w / 2 - 0.45, a1: w / 2 + 0.45, y0: 0, y1: 1.9 }] }, { x0: -w / 2, z0: -d / 2, dx: 0, dz: 1, L: d, ops: slit(d) } - ]; - let u = 0; - for (const sd of sides) { - const nx = -sd.dz, nz = sd.dx, along = sd.dx !== 0, W = { x0: sd.x0 - nx * T / 2, z0: sd.z0 - nz * T / 2, dx: sd.dx, dz: sd.dz, L: sd.L, T, H, ops: sd.ops, mats: { out: 'concrete', in: 'concrete' }, uStart: u, surf: 'stone' }; - if (!along) { W.x0 += sd.dx * T; W.z0 += sd.dz * T; W.L -= 2 * T; } - wallRun(B, W); - for (let k = 0; k < Math.round(sd.L * 1.2 * (0.3 + S.damage)); k++) { const a = R.range(0.3, sd.L - 0.3); B.decal(R() < 0.7 ? 'pocks' : 'gouges', [W.x0 + sd.dx * a + nx * (T / 2 + 0.002), R.range(0.6, H - 0.2), W.z0 + sd.dz * a + nz * (T / 2 + 0.002)], [nx, 0, nz], R.range(0.3, 0.7), null, R() * 6); } - const am = sd.L / 2; B.decal('scorch', [W.x0 + sd.dx * am + nx * (T / 2 + 0.003), 1.3, W.z0 + sd.dz * am + nz * (T / 2 + 0.003)], [nx, 0, nz], 1.8, 1.2, 0); - B.decal('waterstain', [W.x0 + sd.dx * am * 0.6 + nx * (T / 2 + 0.002), H - 0.5, W.z0 + sd.dz * am * 0.6 + nz * (T / 2 + 0.002)], [nx, 0, nz], 1.5, 1.2, 0); - u += sd.L; - } - B.box('concrete', 0, H, 0, w + 0.6, 0.6, d + 0.6, 0, { noFoot: true }); B.col(0, 0, w + 0.6, d + 0.6, H, H + 0.6, 0, 'stone', 'roof'); - // earth and grass sods on the roof, sandbags round the entrance - placeRock(B, 'mud', 0, H + 0.45, 0, Math.min(w, d) * 0.45, 77, [0, 0.4, 0]); - for (let k = 0; k < 2; k++) for (let i = 0; i < 6; i++) E.sandbag(B, -1.4 + i * 0.5 + (k % 2) * 0.25, k * 0.17, -d / 2 - 1.3, (k ? 0.1 : -0.1), R); - B.box('concrete', 0, -0.05, 0, w - 2 * T, 0.06, d - 2 * T, 0, { noFoot: true, tint: new THREE.Color(0.7, 0.7, 0.7) }); - S.roofTop = H + 1; - }; - KINDS.pillbox = KINDS.bunker; - - // small helpers other files use too - E.hayBale = function (B, x, y, z, rot, R) { - B.box('straw', x, y, z, 0.9, 0.4, 0.48, rot, { noFoot: true, tint: tintJ(R, 0.12) }); - for (const s of [-0.25, 0.25]) { const c = Math.cos(rot), sn = Math.sin(rot); B.box('canvas', x + c * s, y - 0.001, z - sn * s, 0.012, 0.402, 0.482, rot, { noFoot: true, tint: new THREE.Color(0.7, 0.62, 0.45) }); } - B.col(x, z, 0.9, 0.48, y, y + 0.4, rot, 'wood', 'hay'); - }; - E.sandbag = function (B, x, y, z, rot, R) { - const g = new THREE.SphereGeometry(0.5, E.Q.name === 'low' ? 6 : 8, E.Q.name === 'low' ? 3 : 4); const p = g.attributes.position; - for (let i = 0; i < p.count; i++) { const X = p.getX(i), Y = p.getY(i), Z = p.getZ(i); p.setXYZ(i, Math.sign(X) * Math.pow(Math.abs(X) * 2, 0.45) / 2, Y * (Y < 0 ? 0.7 : 1), Math.sign(Z) * Math.pow(Math.abs(Z) * 2, 0.6) / 2); } - g.computeVertexNormals(); - _Eu.set(R.range(-0.05, 0.05), rot + R.range(-0.08, 0.08), R.range(-0.04, 0.04)); _Q.setFromEuler(_Eu); _P.set(x, y + 0.085, z); _S.set(0.56, 0.17, 0.32); - B.geo('sandbag', g, _M.compose(_P, _Q, _S), { tint: tintJ(R, 0.1), uvOff: [R() * 5, R() * 5] }); - B.col(x, z, 0.55, 0.33, y, y + 0.17, rot, 'cloth', 'sandbag'); - }; - E.placeRock = placeRock; E.rubble = rubble; E.tintJ = tintJ; - // a hanging oil lantern (lit glass, iron frame) at an interior light - function lantern(B, x, y, z, hook) { B.box('metal_rust', x, y, z, 0.16, 0.03, 0.16, 0, { noFoot: true }); B.geo('glass_lit', new THREE.CylinderGeometry(0.06, 0.06, 0.16, 10), _M.compose(_P.set(x, y + 0.11, z), _Q.identity(), _S.set(1, 1, 1)), { noFoot: true }); B.box('metal_rust', x, y + 0.19, z, 0.14, 0.04, 0.14, 0, { noFoot: true }); if (hook) B.box('metal_rust', x, y + 0.23, z, 0.01, 0.6, 0.01, 0, { noFoot: true }); } - // ivy climbing one end wall: leaf cards flat against the stone, ragged top, thicker at the foot - function ivy(spec, R, kind) { - const w = spec.w || 10, d = spec.d || 8, x = (kind === 'church' ? 1 : -1) * (w / 2 + 0.03), z0 = R.range(-d / 2 + 0.6, 0), wd = R.range(1.8, 3.2), top = R.range(2.6, 4.2); - const P = [], N = [], U = [], C = [], Wd = [], I = [], cu = 0.0, cv = 0.5; - for (let k = 0; k < 220; k++) { - const zz = z0 + R() * wd, yy = Math.pow(R(), 1.4) * top * (0.7 + 0.3 * Math.sin(zz * 3.1)), s = R.range(0.35, 0.6), base = P.length / 3, a = R() * 6.283, ca = Math.cos(a), sa = Math.sin(a); - for (const [i, j] of [[-1, -1], [1, -1], [1, 1], [-1, 1]]) { P.push(x + Math.sign(x) * R.range(0, 0.06), yy + (i * sa + j * ca) * s / 2, zz + (i * ca - j * sa) * s / 2); N.push(Math.sign(x), 0.3, 0); U.push(0.0 + (i * 0.5 + 0.5) * 0.25, 0.5 + (j * 0.5 + 0.5) * 0.5); const sh = 0.55 + 0.4 * R(); C.push(sh * 0.9, sh, sh * 0.85); Wd.push(R() * 6, 0.1, 0.4, 0.2); } - I.push(base, base + 1, base + 2, base, base + 2, base + 3); - } - const g = new THREE.BufferGeometry(); g.setAttribute('position', new THREE.Float32BufferAttribute(P, 3)); g.setAttribute('normal', new THREE.Float32BufferAttribute(N, 3)); g.setAttribute('uv', new THREE.Float32BufferAttribute(U, 2)); g.setAttribute('color', new THREE.Float32BufferAttribute(C, 3)); g.setAttribute('aWind', new THREE.Float32BufferAttribute(Wd, 4)); g.setIndex(I); - const m = new THREE.Mesh(g, E.leafMaterial('ivy', { stiff: 0.05, trans: 0.6 })); m.receiveShadow = true; m.name = 'ivy'; E.registerDetail(m, 60); return m; - } - - // ------------------------------------------------------------------ the public building call - // ------------------------------------------------------------------ rugged, grown-over-time buildings - // Old country buildings were added to for a century: a wing at the back (L or T plan) in another material, a lean-to - // or outshot with a rusty sheet roof, a porch, outside stone steps to a loft door, a doorway bricked up in odd brick, - // patches of repair, render fallen off the foot of the wall, buttresses and tie plates where a wall moved. - // spec.rugged (0..1, default 0 = none; IVEnv.settle passes opts.rugged) picks how many. Extra footprints are returned - // as building.extraFoot [{ x, z, hx, hz, h }] (local) so a settlement gives them colliders and shells. - function mergeB(B, B2, x, z, rot, y) { - if (B2.flushPending) B2.flushPending(); // (wall quads held back for the baked wear) - const c = Math.cos(rot), s = Math.sin(rot); y = y || 0; - for (const k in B2.buckets) { - const src = B2.buckets[k], dst = B.buckets[k] || (B.buckets[k] = { p: [], n: [], u: [], a: [], i: [] }), base = dst.p.length / 3; - for (let i = 0; i < src.p.length; i += 3) { const px = src.p[i], pz = src.p[i + 2], nx = src.n[i], nz = src.n[i + 2]; dst.p.push(x + px * c + pz * s, src.p[i + 1] + y, z - px * s + pz * c); dst.n.push(nx * c + nz * s, src.n[i + 1], -nx * s + nz * c); } - for (let i = 0; i < src.u.length; i++) dst.u.push(src.u[i]); - for (let i = 0; i < src.a.length; i += 4) dst.a.push(src.a[i], src.a[i + 1], src.a[i + 2], src.a[i + 3] ? src.a[i + 3] + y : 0); - for (let i = 0; i < src.i.length; i++) dst.i.push(src.i[i] + base); - } - for (const d of B2.decals) { const p = d.p, n = d.n; B.decals.push(Object.assign({}, d, { p: [x + p[0] * c + p[2] * s, p[1] + y, z - p[0] * s + p[2] * c], n: [n[0] * c + n[2] * s, n[1], -n[0] * s + n[2] * c] })); } - for (const k of B2.colliders) B.colliders.push(Object.assign({}, k, { x: x + k.x * c + k.z * s, z: z - k.x * s + k.z * c, rot: (k.rot || 0) + rot, y0: k.y0 + y, y1: k.y1 + y })); - } - E._mergeB = mergeB; - const OTHER = { fieldstone: ['brick_red', 'planks', 'brick_sooty'], plaster: ['fieldstone', 'brick_red', 'planks'], brick_red: ['fieldstone', 'planks', 'plaster'], brick_sooty: ['fieldstone', 'planks', 'brick_red'], planks: ['fieldstone', 'brick_red'] }; - // a frame on one side of the footprint: a along the wall, b outward from it; r0 = box rotation, sg = which way box z points - function sideFrame(side, X, Z) { - if (side === 'back') return { P: (a, b) => [a, -Z / 2 - b], r0: 0, sg: -1, len: X }; - if (side === 'right') return { P: (a, b) => [X / 2 + b, -a], r0: Math.PI / 2, sg: 1, len: Z }; - if (side === 'left') return { P: (a, b) => [-X / 2 - b, a], r0: -Math.PI / 2, sg: 1, len: Z }; - return { P: (a, b) => [a, Z / 2 + b], r0: Math.PI, sg: -1, len: X }; - } - function leanTo(B, S, side, X, Z, eave, mat, foot) { - const R = S.R, F = sideFrame(side, X, Z), Lt = Math.min(F.len - 0.6, F.len * R.range(0.38, 0.72)), oa = R.range(-1, 1) * (F.len - Lt) / 2; - const Dt = R.range(2.0, 3.0), hi = Math.min(eave - 0.25, R.range(2.7, 3.3)), lo = Math.max(1.85, hi - Dt * R.range(0.32, 0.45)), t = mat === 'planks' ? 0.06 : 0.24; - const yAt = (b) => hi + (lo - hi) * b / Dt; - // outer wall and two end walls built in vertical strips that follow the slope (planks: boards; masonry: stepped) - const P0 = F.P(oa, Dt - t / 2); B.box(mat, P0[0], 0, P0[1], Lt, lo, t, F.r0, { tint: tintJ(R, 0.06) }); - const open = R() < 0.5 ? 1 : -1; - for (const e of [-1, 1]) { - const step = mat === 'planks' ? 0.22 : 0.3; - for (let b = 0; b < Dt - t; b += step) { - if (e === open && b < Dt * 0.55) continue; // one end open for a door or a woodpile - const bb = Math.min(step, Dt - t - b), hh = yAt(b + bb * (mat === 'planks' ? 0.5 : 0)), p = F.P(oa + e * (Lt / 2 - t / 2), b + bb / 2); - B.box(mat, p[0], 0, p[1], t, hh + (mat === 'planks' ? R.range(-0.04, 0.03) : 0), bb + 0.002, F.r0, { tint: tintJ(R, 0.05) }); - } - } - // the roof: a rusty sheet or old slates on rafters, a little bent - const pitch = Math.atan2(hi - lo, Dt), len = Math.hypot(Dt + 0.35, hi - lo), pc = F.P(oa, Dt / 2 + 0.1), roofMat = R() < 0.55 ? 'metal_rust' : 'slate'; - B.box(roofMat, pc[0], (hi + lo) / 2 + 0.02, pc[1], Lt + 0.3, 0.035, len, F.r0, { rx: F.sg * pitch, rz: R.range(-0.025, 0.025), noFoot: true, tint: roofMat === 'metal_rust' ? tintJ(R, 0.12, 0x9a8a7a) : null }); - for (let k = 0; k < 3; k++) { const p = F.P(oa - Lt / 2 + 0.15 + k * (Lt - 0.3) / 2, Dt / 2); B.box('timber', p[0], (hi + lo) / 2 - 0.1, p[1], 0.08, 0.1, len - 0.1, F.r0, { rx: F.sg * pitch, noFoot: true }); } - // a wall plate on the main wall and the flashing stain where the roof meets it - const pw = F.P(oa, 0.06); B.box('timber', pw[0], hi - 0.12, pw[1], Lt + 0.2, 0.12, 0.1, F.r0, { grain: 'long', noFoot: true }); - const nn = sideFrame(side, X, Z), pn = nn.P(oa, 0.005), dn = nn.P(0, 1), d0 = nn.P(0, 0), N = [dn[0] - d0[0], 0, dn[1] - d0[1]]; - B.decal('waterstain', [pn[0], hi + 0.25, pn[1]], N, Lt * 0.9, 0.6, 0); - const c = F.P(oa, Dt / 2); foot.push({ x: c[0], z: c[1], hx: side === 'back' || side === 'front' ? Lt / 2 : Dt / 2, hz: side === 'back' || side === 'front' ? Dt / 2 : Lt / 2, h: hi }); - } - function porch(B, S, door) { - const R = S.R, ang = door.closedY != null ? door.closedY : 0, dx = Math.cos(ang), dz = -Math.sin(ang), nx = -dz, nz = dx; - const w = R.range(1.7, 2.3), dp = R.range(1.0, 1.3), y = R.range(2.45, 2.7), rot = Math.atan2(-dz, dx); - for (const s of [-1, 1]) { const px = door.x + dx * s * (w / 2 - 0.08) + nx * (dp - 0.08), pz = door.z + dz * s * (w / 2 - 0.08) + nz * (dp - 0.08); B.box('timber', px, 0, pz, 0.12, y - 0.05 + R.range(-0.04, 0), 0.12, rot, { grain: 'long', rz: R.range(-0.03, 0.03) }); } - const pc = [door.x + nx * dp / 2, door.z + nz * dp / 2]; - B.box(R() < 0.5 ? 'roof_tile' : 'slate', pc[0], y + 0.12, pc[1], w + 0.3, 0.05, dp + 0.35, rot, { rx: -0.32, rz: R.range(-0.04, 0.04), noFoot: true }); - B.box('timber', pc[0] + nx * (dp / 2 - 0.08), y - 0.05, pc[1] + nz * (dp / 2 - 0.08), w, 0.14, 0.12, rot, { grain: 'long', noFoot: true }); - B.box('ashlar', pc[0], -0.05, pc[1], w - 0.1, 0.12, dp, rot, { tint: tintJ(R, 0.06, 0xa8a090) }); - } - function outsideStairs(B, S, X, Z, eave, foot) { - // stone steps up a gable end to a loft door: no rail, worn treads, a dark door at the top - const R = S.R, xs = R() < 0.5 ? 1 : -1, rise = Math.min(eave - 0.6, 3.0), n = Math.round(rise / 0.24), run = n * 0.3, wdt = 0.9, z0 = R.range(-Z / 2 + run / 2 + 0.3, Z / 2 - run / 2 - 0.3) - run / 2; - for (let k = 0; k < n; k++) B.box('fieldstone', xs * (X / 2 + wdt / 2 + 0.02), 0, z0 + k * 0.3 + 0.15 + R.range(-0.02, 0.02), wdt + R.range(-0.06, 0.06), (k + 1) * 0.24, 0.32, R.range(-0.03, 0.03), { tint: tintJ(R, 0.08) }); - B.box('fieldstone', xs * (X / 2 + wdt / 2 + 0.02), 0, z0 + run + 0.45, wdt + 0.1, rise, 0.9, 0, { tint: tintJ(R, 0.06) }); // the landing - B.box('wood_painted', xs * (X / 2 + 0.03), rise, z0 + run + 0.45, 0.06, 1.85, 0.85, 0, { tint: S.paintTint }); - B.box('timber', xs * (X / 2 + 0.04), rise + 1.85, z0 + run + 0.45, 0.08, 0.14, 1.15, 0, { grain: 'long' }); - B.decal('moss', [xs * (X / 2 + wdt + 0.03), 0.3, z0 + run / 2], [xs, 0, 0], 1.6, 0.5, 0); - foot.push({ x: xs * (X / 2 + wdt / 2 + 0.02), z: z0 + (run + 0.9) / 2, hx: wdt / 2 + 0.05, hz: (run + 0.9) / 2, h: rise }); - } - // a patch of different brick or stone set into a wall face, with a ragged stepped edge (repairs, a bricked-up door) - function patch(B, S, side, X, Z, a, y0, w, h, mat, lintel) { - const R = S.R, F = sideFrame(side, X, Z), rows = Math.max(2, Math.round(h / 0.3)); - for (let r = 0; r < rows; r++) { - const jag = lintel ? 0 : R.range(-0.2, 0.2), ww = w + (lintel ? 0 : R.range(-0.25, 0.15)), p = F.P(a + jag * 0.5, 0.012); - B.box(mat, p[0], y0 + r * h / rows, p[1], Math.max(0.3, ww), h / rows + 0.004, 0.03, F.r0, { tint: tintJ(R, 0.07), uvOff: [R() * 5, 0] }); - } - if (lintel) { const p = F.P(a, 0.03), dr = R() < 0.5 ? R.range(-0.06, 0.06) : 0; B.box('ashlar', p[0], y0 + h, p[1], w + 0.36, 0.24, 0.1, F.r0, { tint: tintJ(R, 0.08), rz: dr }); B.box('ashlar', p[0], -0.02, p[1], w + 0.2, 0.08, 0.2, F.r0, { tint: tintJ(R, 0.06) }); } - const pn = F.P(a, 0.05), q0 = F.P(a, 0), N = [pn[0] - q0[0], 0, pn[1] - q0[1]], l = Math.hypot(N[0], N[2]); N[0] /= l; N[2] /= l; - B.decal(R() < 0.5 ? 'grime' : 'damp', [pn[0] - N[0] * 0.03, y0 + h * 0.4, pn[1] - N[2] * 0.03], N, w * 1.3, h * 0.9, 0); - } - // render fallen off a wall low down: the stone underneath shows through in a soft-edged blotch (overlapping panes, - // the outer ones smaller and set back, with a damp stain over the edge so there is no hard outline) - function renderLoss(B, S, side, X, Z, a, w, h) { - const R = S.R, F = sideFrame(side, X, Z), q0 = F.P(a, 0), q1 = F.P(a, 1), N = [q1[0] - q0[0], 0, q1[1] - q0[1]]; - for (let k = 0; k < 7; k++) { const ww = w * R.range(0.35, 0.8), hh = h * R.range(0.3, 0.75), aa = a + R.range(-0.5, 0.5) * (w - ww), yy = R.range(0, h - hh) * (k < 3 ? 0.2 : 1), p = F.P(aa, 0.006 + k * 0.0006); - B.box('fieldstone', p[0], yy, p[1], ww, hh, 0.012, F.r0, { tint: tintJ(R, 0.05, 0xc8c0b4), uvOff: [aa * 0.37, 0] }); } - B.decal('damp', [q0[0] + N[0] * 0.02, h * 0.55, q0[1] + N[2] * 0.02], N, w * 1.25, h * 1.1, 0); - B.decal('mud', [q0[0] + N[0] * 0.02, 0.2, q0[1] + N[2] * 0.02], N, w * 1.1, 0.5, 0); - } - function buttress(B, S, side, X, Z, a, h, mat) { - const R = S.R, F = sideFrame(side, X, Z), dep = R.range(0.7, 1.0), p = F.P(a, dep / 2 - 0.05); - B.box(mat, p[0], 0, p[1], 0.6, h * 0.55, dep, F.r0, { tint: tintJ(R, 0.05) }); - const p2 = F.P(a, dep * 0.3); B.box(mat, p2[0], h * 0.5, p2[1], 0.56, h * 0.32, dep * 0.6, F.r0, { tint: tintJ(R, 0.05), rx: -F.sg * 0.22 }); - } - function tiePlates(B, S, side, X, Z, y, n) { - const R = S.R, F = sideFrame(side, X, Z); - for (let k = 0; k < n; k++) { const a = (k - (n - 1) / 2) * F.len / (n + 0.4) + R.range(-0.2, 0.2), p = F.P(a, 0.025); const g = new THREE.CylinderGeometry(0.13, 0.13, 0.03, 10).rotateX(Math.PI / 2); - _Eu.set(0, F.r0, 0); _Q.setFromEuler(_Eu); B.geo('metal_rust', g, _M.compose(_P.set(p[0], y + R.range(-0.08, 0.08), p[1]), _Q, _S.set(1, 1, 1)), { noFoot: true }); - const q = F.P(a, 0.0); B.decal('rust', [q[0], y - 0.35, q[1]], (() => { const o = F.P(a, 1), z = F.P(a, 0); return [o[0] - z[0], 0, o[1] - z[1]]; })(), 0.3, 0.7, 0); } - } - function rugged(B, S, sp, kind) { - const R = E.rng(sp.seed * 13 + 5), k = sp.rugged, X = S.footX, Z = S.footZ, eave = S.eaveH || 3, out = S.outMat || 'fieldstone', foot = S.extraFoot = []; - if (!X || !Z) return; - const S2 = Object.assign({}, S, { R }); - const alt = (OTHER[out] || OTHER.fieldstone)[R.int(3) % (OTHER[out] || OTHER.fieldstone).length]; - const used = {}, free = sp.free || ['back', 'left', 'right']; // sides that may grow outward (a street row: only the back) - // a wing behind (L or T plan) for houses big enough to have grown - if ((kind === 'farmhouse' || kind === 'cottage') && R() < 0.55 * k && !sp.noWing && free.includes('back')) { - const Lw = R.range(4.5, sp.wingMax || 7.5), dw = R.range(4.0, Math.min(5.4, X * 0.6)), tee = R() < 0.3, ox = tee ? R.range(-0.6, 0.6) : (R() < 0.5 ? -1 : 1) * (X / 2 - dw / 2 - R.range(0, 0.6)); - const W2 = buildParts({ kind: 'cottage', w: Lw, d: dw, floors: 1, seed: sp.seed + 101, out: alt === 'planks' ? 'brick_red' : alt, roof: R() < 0.5 ? 'tile' : 'slate', damage: sp.damage * 0.6, lit: 0 }); - mergeB(B, W2.B, ox, -Z / 2 - Lw / 2 + 0.25, Math.PI / 2, 0); - foot.push({ x: ox, z: -Z / 2 - Lw / 2 + 0.25, hx: dw / 2, hz: Lw / 2, h: W2.S.eaveH || 3, roof: W2.S.roofTop, wall: alt === 'planks' ? 'brick_red' : alt, axis: 'z' }); - used.back = true; - } - // lean-tos and outshots: at the back, or on a gable end - { const opts = free.filter(sd => !used[sd]); if (kind !== 'church' && kind !== 'shoprow' && opts.length && R() < 0.75 * k) { const side = opts.includes('back') && R() < 0.6 ? 'back' : opts[R.int(opts.length)]; leanTo(B, S2, side, X, Z, eave, R() < 0.5 ? 'planks' : alt, foot); used[side] = true; } } - // a porch over the front door - if ((kind === 'cottage' || kind === 'farmhouse') && S.doors[0] && R() < 0.4 * k) porch(B, S2, S.doors[0]); - // outside stairs to a loft door (barns, farmhouses) on a free gable - if ((kind === 'barn' || kind === 'farmhouse') && R() < 0.5 * k && free.includes('left') && free.includes('right') && !(used.left || used.right)) outsideStairs(B, S2, X, Z, eave, foot); - // a bricked-up doorway on a side or back wall, repairs in odd brick or stone, render fallen off low down - const sides = ['back', 'left', 'right'].filter(s => !used[s]); - if (sides.length && R() < 0.6 * k) { const sd = sides[R.int(sides.length)], F = sideFrame(sd, X, Z); patch(B, S2, sd, X, Z, R.range(-0.3, 0.3) * F.len, 0, 1.0, 2.05, out === 'brick_red' ? 'brick_sooty' : 'brick_red', true); } - for (let n = 0; n < Math.round(R.range(1, 3) * k); n++) { const sd = ['front', 'back', 'left', 'right'][R.int(4)], F = sideFrame(sd, X, Z); if (used[sd]) continue; patch(B, S2, sd, X, Z, R.range(-0.38, 0.38) * F.len, R.range(0.3, Math.max(0.4, eave - 1.6)), R.range(0.7, 1.6), R.range(0.5, 1.1), out === 'brick_red' ? 'brick_sooty' : out === 'fieldstone' ? 'brick_red' : 'brick_red', false); } - if (out === 'plaster') for (let n = 0; n < 2 + R.int(3); n++) { const sd = ['front', 'back', 'left', 'right'][R.int(4)], F = sideFrame(sd, X, Z); if (used[sd] && sd !== 'front') continue; renderLoss(B, S2, sd, X, Z, R.range(-0.4, 0.4) * F.len, R.range(1.0, 2.4), R.range(0.6, 1.3)); } - // a wall that moved: buttresses and tie plates (barns and long houses) - if ((kind === 'barn' || X > 10) && R() < 0.45 * k) { const sd = used.back ? 'front' : 'back', F = sideFrame(sd, X, Z); if (sd !== 'front') for (const a of [-0.3, 0.3]) buttress(B, S2, sd, X, Z, a * F.len + R.range(-0.4, 0.4), Math.min(eave, 3.2), kind === 'barn' ? 'fieldstone' : out === 'plaster' ? 'fieldstone' : out); } - if (kind !== 'shed' && R() < 0.5 * k && eave > 3.5) tiePlates(B, S2, R() < 0.5 ? 'left' : 'right', X, Z, eave - 2.6 > 1 ? 2.75 : eave - 0.4, 2); - } - - // ------------------------------------------------------------------ the camp hut (Boot Camp barrack hut) - // A timber barrack hut on a brick plinth: ridge along local X (sp.w long), the door in the +X gable end with a framed, - // set-back doorway, two concrete steps and a number board; a stove pipe through the roof; fire buckets on a board. - KINDS.hut = function (B, S, sp) { - const w = sp.w || 10, d = sp.d || 6, R = S.R, T = 0.14, storey = 2.5, lift = 0.45; - const B2 = E.builder(sp.seed + 3), S2 = Object.assign({}, S, { doors: [], windows: [], lights: [], group: new THREE.Group() }); - const nf = Math.max(2, Math.round(w / 2.6)), sideW = []; for (let i = 0; i < nf; i++) { const c = w * (i + 0.5) / nf; sideW.push({ a0: c - 0.5, a1: c + 0.5, y0: 0.95, y1: 2.05, lit: R() < (sp.lit || 0) }); } - const door = [{ a0: d / 2 - 0.5, a1: d / 2 + 0.5, y0: 0, y1: 2.0, door: true, leaf: false, threshold: false }], end = [{ a0: d / 2 - 0.4, a1: d / 2 + 0.4, y0: 1.0, y1: 1.9 }]; - house(B2, S2, { w, d, T, floors: 1, storey, out: 'planks', in: 'plaster_interior', roof: 'slate', ridgeMat: 'slate', pitch: 0.42, over: 0.4, gableOver: 0.3, head: 'timber', doorHead: 'timber', shutters: false, quoins: false, front: sideW, back: sideW.map(o => Object.assign({}, o)), right: door, left: end, sill: false, trim: true, sag: 0.03 }); - mergeB(B, B2, 0, 0, 0, lift); - S.windows.push(...S2.windows.map(o => Object.assign({}, o, { y: o.y + lift }))); - // inside: tie beams across at the eaves, a pair of rafters on each, a ridge board (no flat black ceiling) - { const rise = d / 2 * Math.tan(0.42), y0 = lift + storey, len = Math.hypot(d / 2, rise), nb = Math.max(3, Math.round(w / 1.8)); - for (let i = 0; i < nb; i++) { const x = -w / 2 + T + 0.3 + (w - 2 * T - 0.6) * i / (nb - 1); - B.box('timber', x, y0 - 0.16, 0, 0.1, 0.15, d - 2 * T, 0, { grain: 'long', noFoot: true }); - for (const side of [1, -1]) B.box('timber', x, y0 + rise / 2 - 0.2, side * d / 4, 0.08, 0.13, len - 0.1, 0, { rx: side * 0.42, grain: 'long', noFoot: true }); } - B.box('timber', 0, y0 + rise - 0.24, 0, w - 2 * T, 0.16, 0.05, 0, { grain: 'long', noFoot: true }); } - // plinth with air bricks, and the floor - B.box('brick_red', 0, -0.25, 0, w + 0.06, lift + 0.25, d + 0.06, 0, { tint: tintJ(R, 0.05) }); - for (let i = 0; i < 4; i++) for (const s of [-1, 1]) B.box('metal_rust', -w / 2 + (i + 0.5) * w / 4, 0.18, s * (d / 2 + 0.035), 0.22, 0.07, 0.01, 0, { noFoot: true, tint: new THREE.Color(0.4, 0.4, 0.4) }); - B.box('floorboards', 0, lift - 0.02, 0, w - 2 * T, 0.03, d - 2 * T, 0, { noFoot: true }); - // the doorway: a deep timber surround proud of the wall, the door set back in it, a little canopy, steps - const ex = w / 2, dy = lift; - for (const s of [-1, 1]) B.box('timber', ex + 0.09, dy, s * 0.62, 0.2, 2.15, 0.16, 0, { grain: 'long' }); - B.box('timber', ex + 0.09, dy + 2.1, 0, 0.2, 0.16, 1.4, 0, { grain: 'long' }); - B.box('wood_painted', ex - 0.12, dy, 0, 0.05, 1.98, 0.98, 0, { tint: S.paintTint }); - for (const yy of [0.25, 1.0, 1.7]) B.box('wood_painted', ex - 0.09, dy + yy, 0, 0.03, 0.1, 0.9, 0, { tint: S.paintTint }); - B.box('metal_rust', ex - 0.07, dy + 0.98, -0.36, 0.03, 0.03, 0.14, 0, { noFoot: true }); - B.box('slate', ex + 0.45, dy + 2.35, 0, 0.9, 0.04, 1.6, 0, { rz: 0.3, noFoot: true }); - for (const s of [-1, 1]) B.box('timber', ex + 0.55, dy + 1.95, s * 0.6, 0.6, 0.08, 0.08, 0, { rz: -0.6, noFoot: true }); - B.box('concrete', ex + 0.35, 0, 0, 0.7, 0.3, 1.5, 0, { tint: tintJ(R, 0.05, 0xb8b4ac) }); - B.box('concrete', ex + 0.85, 0, 0, 0.36, 0.15, 1.4, 0, { tint: tintJ(R, 0.05, 0xb0aca4) }); - B.decal('mud', [ex + 0.7, 0.31, 0], [0, 1, 0], 0.8, 1.1, 0); B.decal('chipped', [ex + 1.03, 0.08, 0], [1, 0, 0], 1.2, 0.2, 0); - // number board beside the door - if (sp.num != null) { try { if (E.label) B.label(String(sp.num), { kind: 'paint', ground: '#2c3a33', color: '#e8dcb4', distress: 0.3, size: 72, aspect: 0.42 / 0.32 }, [ex + 0.2, dy + 1.65, 0.95], [1, 0, 0], 0.42); else { const sg = signMesh(String(sp.num), 0.42, 0.32, R); sg.position.set(ex + 0.2, dy + 1.65, 0.95); sg.rotation.y = Math.PI / 2; S.group.add(sg); } B.box('timber', ex + 0.18, dy + 1.47, 0.95, 0.02, 0.38, 0.48, 0, {}); } catch (e) {} } - // stove pipe through the roof (with a collar and a cap), soot on the roof round it - const rise = d / 2 * Math.tan(0.42), sx = -w / 2 + 2.0 + R() * 1.0, sz = R() < 0.5 ? -0.8 : 0.8; - const py = lift + storey + rise * (1 - Math.abs(sz) / (d / 2)) - 0.1; - B.geo('metal_rust', new THREE.CylinderGeometry(0.08, 0.08, 1.5, 10), _M.compose(_P.set(sx, py + 0.6, sz), _Q.identity(), _S.set(1, 1, 1)), { noFoot: true }); - B.geo('metal_rust', new THREE.ConeGeometry(0.2, 0.16, 10), _M.compose(_P.set(sx, py + 1.45, sz), _Q.identity(), _S.set(1, 1, 1)), { noFoot: true }); - B.geo('metal_rust', new THREE.CylinderGeometry(0.16, 0.2, 0.12, 10), _M.compose(_P.set(sx, py + 0.02, sz), _Q.identity(), _S.set(1, 1, 1)), { noFoot: true }); - B.decal('soot', [sx, py + 0.08, sz], [0, 1, 0], 0.8, 0.8, 0); - // fire buckets on a board on the gable - const bz = -d / 2 + 0.9; B.box('timber', ex + 0.04, dy + 0.9, bz, 0.04, 0.5, 1.1, 0, {}); - for (let i = 0; i < 3; i++) { const z = bz - 0.36 + i * 0.36; B.geo('metal_painted', new THREE.CylinderGeometry(0.13, 0.1, 0.28, 10), _M.compose(_P.set(ex + 0.2, dy + 0.85, z), _Q.identity(), _S.set(1, 1, 1)), { noFoot: true, tint: new THREE.Color(1.6, 0.42, 0.3) }); B.box('metal_rust', ex + 0.08, dy + 1.03, z, 0.06, 0.03, 0.03, 0, { noFoot: true }); } - B.geo('metal_painted', new THREE.CylinderGeometry(0.17, 0.15, 0.32, 10), _M.compose(_P.set(ex + 0.35, 0.16, -d / 2 + 0.4), _Q.identity(), _S.set(1, 1, 1)), { tint: new THREE.Color(1.5, 0.45, 0.32) }); - // rain stains under the eaves, mud splash on the plinth - for (const z of [d / 2 + 0.01, -d / 2 - 0.01]) { B.decal('waterstain', [0, lift + 0.4, z + Math.sign(z) * 0.04], [0, 0, Math.sign(z)], w * 0.9, 0.7, 0); B.decal('mud', [R.range(-w / 3, w / 3), 0.25, z + Math.sign(z) * 0.035], [0, 0, Math.sign(z)], 3, 0.4, 0); } - S.roofTop = lift + storey + rise; S.eaveH = lift + storey; S.footX = w; S.footZ = d; S.outMat = 'planks'; - }; - function buildParts(spec) { - spec = Object.assign({ kind: 'farmhouse', seed: 1, damage: 0, lit: 0 }, spec || {}); - const kind = spec.kind === 'church with tower' ? 'church' : spec.kind === 'village shop row' || spec.kind === 'shop' ? 'shoprow' : spec.kind === 'ruined shell' || spec.kind === 'ruined' ? 'ruin' : spec.kind; - const fn = KINDS[kind]; if (!fn) throw new Error('IVEnv.building: unknown kind ' + spec.kind); - const B = E.builder(spec.seed), group = new THREE.Group(); - const R = E.rng(spec.seed * 7 + 3); - const paints = [0x5a6b5c, 0x4d5a66, 0x6b4a3e, 0x6a6a5a, 0x3e4a40]; - const S = { R, seed: spec.seed, damage: spec.damage || 0, group, windows: [], lights: [], doors: [], extraCols: [], paintTint: new THREE.Color(paints[spec.seed % paints.length]).multiplyScalar(1 / 0.36), interior: kind === 'farmhouse' || kind === 'barn', old: kind !== 'office' && kind !== 'hut' && kind !== 'bunker' }; - // paint tint is relative to the texture's own paint (about 0.36 of white): keep it near 1 - S.paintTint.r = E.clamp(S.paintTint.r * 0.36 / 0.3, 0.6, 1.5); S.paintTint.g = E.clamp(S.paintTint.g * 0.36 / 0.36, 0.6, 1.5); S.paintTint.b = E.clamp(S.paintTint.b * 0.36 / 0.32, 0.6, 1.5); - fn(B, S, spec); - if (kind !== 'shed' && kind !== 'bunker' && kind !== 'hut') E.ageMesh(B, { w: S.footX || spec.w || 10, d: S.footZ || spec.d || 8, eave: S.eaveH || (S.roofTop || 6) * 0.62, ridge: S.roofTop, seed: spec.seed, amount: spec.age != null ? spec.age : (kind === 'office' ? 0.4 : 1) }); - // old walls are not true: a slight lean and a bulge at mid height on the long walls (house-like kinds) - if (kind === 'farmhouse' || kind === 'cottage' || kind === 'church' || kind === 'barn') { - const lx = R.range(-0.008, 0.008), lz = R.range(-0.006, 0.006), bul = R.range(0.02, 0.045), H = Math.max(2, (S.roofTop || 6) * 0.7), w = spec.w || 10, d = spec.d || 8; - const D2 = kind === 'barn' ? w / 2 : d / 2, W2 = kind === 'barn' ? d / 2 : w / 2; - if (B.flushPending) B.flushPending(); - for (const k in B.buckets) { const p = B.buckets[k].p; for (let i = 0; i < p.length; i += 3) { const y = p[i + 1]; if (y <= 0.05) continue; p[i] += lx * y; p[i + 2] += lz * y; if (Math.abs(Math.abs(p[i + 2]) - D2) < 0.8 && y < H) p[i + 2] += Math.sign(p[i + 2]) * bul * Math.sin(Math.PI * y / H) * Math.cos(Math.PI * 0.5 * E.clamp(p[i] / W2, -1, 1)); } } - } - if (spec.rugged && kind !== 'church' && kind !== 'ruin' && kind !== 'bunker' && kind !== 'hut' && kind !== 'office') rugged(B, S, spec, kind); - if (kind === 'farmhouse' || kind === 'cottage' || kind === 'church') group.add(ivy(spec, R, kind)); - return { B, S, kind, group, spec, R }; - } - E.building = function (spec0) { - const { B, S, kind, group } = buildParts(spec0); - // a settled building is one closed box (no interior to walk into): drop the inner faces, floors and furniture - if (B.flushPending) B.flushPending(); - if (spec0 && spec0.closed) for (const k in B.buckets) if (/^(plaster_interior|floorboards|straw)(#d)?$/.test(k) || (k.endsWith('#d') && /^(wood_painted|timber|planks)#d$/.test(k) && S.interior)) delete B.buckets[k]; - const g = B.finish(); group.add(g); - group.name = 'IVEnv.building:' + kind; group.userData.kind = kind; - const colliders = B.colliders.concat(S.extraCols); - return { group, colliders, doors: S.doors, windows: S.windows, lights: S.lights, height: S.roofTop || 0, extraFoot: S.extraFoot || [] }; - }; - - // ------------------------------------------------------------------ age: nothing old is true - // IVEnv.ageMesh(builder, { w, d, eave, seed, amount, cx, cz }) bends the drawn mesh of one building (colliders are not - // touched): walls a little out of plumb with a slow wobble, a bulge mid-height, wall tops that wander, a swaybacked - // roof that sags between the gables and droops at one end. Coordinates are relative to (cx, cz) (default 0, 0). - E.ageMesh = function (B, o) { - if (B.flushPending) B.flushPending(); - const R = E.rng((o.seed || 1) * 31 + 7), a = o.amount == null ? 1 : o.amount, cx = o.cx || 0, cz = o.cz || 0, rot = o.rot || 0, c = Math.cos(rot), s = Math.sin(rot); - const lx = R.range(-0.024, 0.024) * a, lz = R.range(-0.018, 0.018) * a, ph = R() * 9, sag = R.range(0.08, 0.18) * a, droop = R.range(-0.14, 0.14) * a, ridge = o.ridge || 1e9, cl = R.range(-0.09, 0.09) * a, cl2 = R.range(-0.07, 0.07) * a, W2 = Math.max(o.w || 8, o.d || 6) / 2, eave = o.eave || 4, base = o.y0 || 0; - for (const k in B.buckets) { - const p = B.buckets[k].p; - for (let i = 0; i < p.length; i += 3) { - const X = p[i] - cx, Z = p[i + 2] - cz, y = p[i + 1] - base; if (y <= 0.05) continue; - const u = X * c - Z * s, v = X * s + Z * c; // building-local: u along the ridge - let dx = lx * y + 0.04 * a * Math.sin(y * 0.9 + v * 0.6 + ph) * Math.min(1, y / 2), dz = lz * y + 0.04 * a * Math.sin(y * 0.8 + u * 0.5 + ph * 1.7) * Math.min(1, y / 2); - if (y > ridge - 0.6) { dx += cl * (y - ridge + 0.6); dz += cl2 * (y - ridge + 0.6); } // stacks lean on their own - let dy = 0.08 * a * Math.sin(u * 0.45 + ph) * Math.min(1, y / eave); // tops wander - if (y > eave * 0.9) { const t = IVc(u / W2); dy -= sag * (1 - t * t) * Math.min(1, (y - eave * 0.9) / 1.5 + 0.4) + droop * Math.max(0, t) * 0.5; } // swayback, one end drooping - p[i] += dx * c + dz * s; p[i + 1] += dy; p[i + 2] += -dx * s + dz * c; - } - } - }; - const IVc = (v) => v < -1 ? -1 : v > 1 ? 1 : v; - - // ------------------------------------------------------------------ settlements: many buildings, cheap at range - // IVEnv.settle(specs, { heightFn, near, shellOnly, seed }) -> { group, colliders, lights, chimneys } - // spec = { kind, x, z, rot, w, d, floors, seed, damage, lit (0..1), roof, units, y, shellOnly, solid, eave, pitch } - // Every building gets a SHELL: its walls set 12 cm inside the real walls, a roof just under the real roof, and its - // windows as dark or lit panes, all merged into a handful of meshes for the whole settlement and always drawn. A - // building the player can reach also gets the full IVEnv building, merged per 40 m cell and drawn only within `near` - // metres; up close it hides the shell, and through its windows you see the shell's closed interior. Doors are shut - // and the colliders are one closed box per footprint (no interiors). Lights: lit windows, for practical lights. - function shellDims(sp) { - const k = sp.kind, f = sp.floors || (k === 'farmhouse' ? 2 : 1); - if (k === 'barn') return { X: sp.d || 16, Z: sp.w || 10, eave: 4.6, rise: (sp.w || 10) / 2 * 0.9, wall: 'planks', roof: 'roof_tile', win: 0 }; - if (k === 'church') return { X: sp.w || 16, Z: sp.d || 8, eave: 5.6, rise: (sp.d || 8) / 2 * 1.0, wall: 'fieldstone', roof: 'slate', win: 0.2, tower: true }; - if (k === 'shoprow') { const n = sp.units || 3; return { X: n * (sp.w ? sp.w / n : 5.4), Z: sp.d || 8, eave: 3.0 * 2 + 0.2, rise: (sp.d || 8) / 2 * 0.75, wall: 'plaster', roof: 'slate', win: 1, floors: 2 }; } - if (k === 'hut') return { X: sp.w || 10, Z: sp.d || 6, eave: 2.95, rise: (sp.d || 6) / 2 * Math.tan(0.42), wall: 'planks', roof: 'slate', win: 1, floors: 1 }; - if (k === 'shed') return { X: sp.w || 4, Z: sp.d || 3, eave: 2.1, rise: 0.4, wall: 'planks', roof: 'slate', win: 0 }; - if (k === 'ruin') return { X: sp.w || 9, Z: sp.d || 7, eave: 3.2, rise: 0, wall: 'brick_sooty', roof: null, win: 0 }; - if (k === 'office') return { X: sp.w || 14, Z: sp.d || 7, eave: 2.7, rise: (sp.d || 7) / 2 * Math.tan(0.3), wall: sp.out || 'brick_red', roof: 'slate', win: 1, floors: 1 }; - if (k === 'farmhouse') return { X: sp.w || 12, Z: sp.d || 7.5, eave: f * 2.8, rise: (sp.d || 7.5) / 2 * 0.85, wall: 'fieldstone', roof: sp.roof === 'tile' ? 'roof_tile' : 'slate', win: 1, floors: f }; - return { X: sp.w || 8, Z: sp.d || 6, eave: f * 2.6 + (f === 1 ? 0.4 : 0), rise: (sp.d || 6) / 2 * 0.88, wall: 'brick_red', roof: sp.roof === 'tile' ? 'roof_tile' : 'slate', win: 1, floors: f }; - } - const prismGeo = (() => { const g = new THREE.BufferGeometry(); const P = [-0.5, 0, -0.5, 0.5, 0, -0.5, 0.5, 1, 0, -0.5, 1, 0, -0.5, 0, 0.5, 0.5, 0, 0.5, 0.5, 1, 0, -0.5, 1, 0, -0.5, 0, -0.5, -0.5, 1, 0, -0.5, 0, 0.5, 0.5, 0, -0.5, 0.5, 0, 0.5, 0.5, 1, 0]; - g.setAttribute('position', new THREE.Float32BufferAttribute(P, 3)); g.setIndex([0, 3, 2, 0, 2, 1, 4, 5, 6, 4, 6, 7, 8, 10, 9, 11, 13, 12]); g.computeVertexNormals(); return g; })(); - // warm light spilling from lit windows and doorways onto the ground in front: one additive mesh of soft pools draped - // on the terrain (cheap: no extra lights), faded by fog. list: [[x, z, nx, nz, r, k]] (nx, nz: outward from the wall) - let poolTex = null; - E.glowPools = function (list, hf) { - if (!poolTex) { const c = document.createElement('canvas'); c.width = c.height = 64; const g = c.getContext('2d'), gr = g.createRadialGradient(32, 32, 0, 32, 32, 32); gr.addColorStop(0, 'rgba(255,255,255,1)'); gr.addColorStop(0.35, 'rgba(255,255,255,0.5)'); gr.addColorStop(1, 'rgba(255,255,255,0)'); g.fillStyle = gr; g.fillRect(0, 0, 64, 64); poolTex = new THREE.CanvasTexture(c); } - const P = [], U = [], C = [], I = [], N = 4; - for (const [x, z, nx, nz, r, k] of list) { - const cx = x + nx * r * 0.55, cz = z + nz * r * 0.55, base = P.length / 3, tx = -nz, tz = nx; - for (let j = 0; j <= N; j++) for (let i = 0; i <= N; i++) { const u = i / N - 0.5, v = j / N - 0.5, px = cx + tx * u * r * 1.6 + nx * v * r * 1.3, pz = cz + tz * u * r * 1.6 + nz * v * r * 1.3; P.push(px, hf(px, pz) + 0.04, pz); U.push(i / N, j / N); C.push(k, k * 0.62, k * 0.3); } - for (let j = 0; j < N; j++) for (let i = 0; i < N; i++) { const a = base + j * (N + 1) + i; I.push(a, a + N + 1, a + 1, a + 1, a + N + 1, a + N + 2); } - } - const g = new THREE.BufferGeometry(); g.setAttribute('position', new THREE.Float32BufferAttribute(P, 3)); g.setAttribute('uv', new THREE.Float32BufferAttribute(U, 2)); g.setAttribute('color', new THREE.Float32BufferAttribute(C, 3)); g.setIndex(I); g.computeBoundingSphere(); - const m = new THREE.MeshBasicMaterial({ map: poolTex, vertexColors: true, transparent: true, blending: THREE.AdditiveBlending, depthWrite: false, polygonOffset: true, polygonOffsetFactor: -2, polygonOffsetUnits: -4, fog: true }); - m.userData.linear = true; const mesh = new THREE.Mesh(g, m); mesh.name = 'glow-pools'; mesh.renderOrder = 2; return mesh; - }; - E.settle = function (specs, opts) { - opts = opts || {}; - const Q = E.Q.name, near = opts.near || (Q === 'low' ? 26 : Q === 'high' ? 55 : 34), hf = opts.heightFn || (() => 0); - const SB = E.builder(opts.seed || 77), detailRoot = new THREE.Group(), group = new THREE.Group(); group.name = 'IVEnv.settlement'; SB.wear = false; // far shells: no baked wear - const colliders = [], lights = [], chimneys = [], RR = E.rng((opts.seed || 77) * 3 + 1); - for (const sp0 of specs) { - const sp = Object.assign({ seed: 1 + ((sp0.x * 13 + sp0.z * 7) | 0) % 997, rot: 0 }, sp0), D = shellDims(sp), rot = sp.rot; - const y = sp.y != null ? sp.y : Math.min(hf(sp.x, sp.z), hf(sp.x + D.X / 2, sp.z), hf(sp.x - D.X / 2, sp.z), hf(sp.x, sp.z + D.Z / 2), hf(sp.x, sp.z - D.Z / 2)); - const c = Math.cos(rot), s = Math.sin(rot), W = (lx, lz) => [sp.x + lx * c + lz * s, sp.z - lx * s + lz * c]; - const eave = sp.eave || D.eave, X = D.X - 0.24, Z = D.Z - 0.24, tint = E.tintJ(RR, 0.06); - // shell: walls (sunk into the ground on slopes), roof prism, windows - SB.box(sp.out || sp.wall || D.wall, sp.x, y - 0.8, sp.z, X, eave + 0.8 - 0.05, Z, rot, { tint, uvOff: [RR() * 9, 0] }); - if (D.roof && !(sp.damage > 0.85)) { const m = new THREE.Matrix4().compose(new THREE.Vector3(sp.x, y + eave - 0.42, sp.z), new THREE.Quaternion().setFromEuler(new THREE.Euler(0, rot, 0)), new THREE.Vector3(X + 0.75, Math.max(0.3, (sp.rise || D.rise) - 0.2), Z + 1.1)); SB.geo(D.roof, prismGeo, m, { noFoot: true, tint: E.tintJ(RR, 0.05) }); - // eaves read as a dark line under the roof edge (fascia and shadow), a plinth band at the foot - for (const sd of [-1, 1]) { const p = W(0, sd * (Z / 2 + 0.06)); SB.box('timber', p[0], y + eave - 0.5, p[1], X + 0.3, 0.2, 0.1, rot, { noFoot: true, tint: new THREE.Color(0.25, 0.23, 0.21) }); } } - if (D.win || sp.kind === 'barn' || sp.kind === 'shed') { // a door recess on the front, framed, with a step - const dw = sp.kind === 'barn' ? 3.2 : 1.0, dh = sp.kind === 'barn' ? 3.4 : 2.05, p = W(sp.kind === 'barn' ? 0 : X * 0.12, Z / 2 + 0.015); - SB.box('timber', p[0], y, p[1], dw, dh, 0.05, rot, { noFoot: true, tint: new THREE.Color(0.1, 0.09, 0.085) }); - const q = W(sp.kind === 'barn' ? 0 : X * 0.12, Z / 2 + 0.04); SB.box('timber', q[0], y + dh, q[1], dw + 0.3, 0.16, 0.07, rot, { noFoot: true }); -} - if (D.tower) { const p = W(-X / 2 - 2.0, 0); SB.box('fieldstone', p[0], y - 0.5, p[1], 4.2, 15.5, 4.2, rot, { tint }); const m = new THREE.Matrix4().compose(new THREE.Vector3(p[0], y + 15, p[1]), new THREE.Quaternion().setFromEuler(new THREE.Euler(0, rot + Math.PI / 4, 0)), new THREE.Vector3(3.2, 6.5, 3.2)); SB.geo('slate', new THREE.ConeGeometry(1, 1, 4, 1).translate(0, 0.5, 0), m, { noFoot: true }); } - if (D.win) { - const fl = D.floors || 1, nW = Math.max(1, Math.floor(X / 2.8)); - for (const side of [-1, 1]) for (let f = 0; f < fl; f++) for (let i = 0; i < nW; i++) { - const lx = -X / 2 + (i + 0.5) * X / nW, lit = RR() < (sp.lit || 0) * (side > 0 ? 1 : 0.6), p = W(lx, side * (Z / 2 + 0.01)); - SB.box(lit ? 'glass_lit' : 'timber', p[0], y + 0.95 + f * 2.7, p[1], 0.85, 1.25, 0.03, rot, { noFoot: true, tint: lit ? null : new THREE.Color(0.06, 0.06, 0.06) }); - { const q = W(lx, side * (Z / 2 + 0.04)); SB.box('ashlar', q[0], y + 0.86 + f * 2.7, q[1], 1.05, 0.09, 0.07, rot, { noFoot: true, tint: new THREE.Color(0.75, 0.73, 0.68) }); SB.box('ashlar', q[0], y + 2.2 + f * 2.7, q[1], 1.15, 0.16, 0.08, rot, { noFoot: true, tint: new THREE.Color(0.7, 0.68, 0.64) }); } // sill and lintel - if (lit) lights.push({ x: p[0] + s * side * 1.0, y: y + 1.4 + f * 2.7, z: p[1] + c * side * 1.0, wx: p[0], wz: p[1], nx: s * side, nz: c * side, f }); - } - } - if (sp.lit && D.win && D.roof) { const p = W(X * 0.3, 0); chimneys.push({ x: p[0], y: y + eave + (sp.rise || D.rise) + 0.8, z: p[1] }); } - // the full building near the player - if (!opts.shellOnly && !sp.shellOnly) { - try { - const b = E.building(Object.assign({ rugged: opts.rugged || 0 }, sp, { lit: sp.lit || 0, closed: true })); - for (const f of b.extraFoot) { // wings, lean-tos and stairs: a collider and a shell each - const p = W(f.x, f.z); - if (sp.solid !== false) colliders.push({ x: p[0], z: p[1], hx: f.hx, hz: f.hz, y0: y - 1, y1: y + f.h, rot, kind: 'building' }); - if (f.roof) { SB.box(f.wall || 'brick_red', p[0], y - 0.8, p[1], f.hx * 2 - 0.24, f.h + 0.75, f.hz * 2 - 0.24, rot, { tint: E.tintJ(RR, 0.06) }); const m = new THREE.Matrix4().compose(new THREE.Vector3(p[0], y + f.h - 0.3, p[1]), new THREE.Quaternion().setFromEuler(new THREE.Euler(0, rot + Math.PI / 2, 0)), new THREE.Vector3(f.hz * 2 + 0.1, Math.max(0.3, f.roof - f.h - 0.35), f.hx * 2 + 0.3)); SB.geo('slate', prismGeo, m, { noFoot: true }); } - } - for (const d of b.doors) { try { if (d.open && !d.hang) d.open(0); } catch (e) {} } - b.group.traverse(o => { o.userData.dynamic = false; }); - b.group.position.set(sp.x, y, sp.z); b.group.rotation.y = rot; detailRoot.add(b.group); - } catch (e) { console.warn('IVEnv.settle building', sp.kind, e); } - } - if (sp.solid !== false) colliders.push({ x: sp.x, z: sp.z, hx: D.X / 2, hz: D.Z / 2, y0: y - 1, y1: y + eave + 0.3, rot, kind: 'building' }); - } - let shells = SB.finish({ castShadow: false }); shells.name = 'IVEnv.shells'; - // shell-only settlements (far skylines) in one plain vertex-coloured mesh: one draw call instead of one per material - if (opts.shellOnly && E.mergeStatic && E.Q.name !== 'high') { const wrap = new THREE.Group(); wrap.add(shells); const m = E.mergeStatic(wrap, { flat: true }); m.traverse(o => { if (o.isMesh) o.castShadow = false; }); shells = m; shells.name = 'IVEnv.shells'; } - group.add(shells); - if (opts.pools !== false && lights.length) { try { group.add(E.glowPools(lights.filter(l => l.nx != null && l.f === 0).map(l => [l.wx, l.wz, l.nx, l.nz, 3.4, 0.16]), hf)); } catch (e) { console.warn('pools', e); } } - if (detailRoot.children.length) { - const merged = E.mergeStatic ? E.mergeStatic(detailRoot, { cell: 80 }) : detailRoot; merged.name = 'IVEnv.settlement-detail'; group.add(merged); - // only walls and roofs cast shadows (Low and Medium): frames, glass, doors, metal and timber trim each cost a - // shadow draw call per cell for shadows nobody reads at night - if (E.Q.name !== 'high') { const BIG = { fieldstone: 1, brick_red: 1, brick_sooty: 1, plaster: 1, roof_tile: 1, slate: 1, planks: 1, ashlar: 0 }; merged.traverse(o => { if (o.isMesh && o.material && o.material.userData && !BIG[o.material.userData.ivenv]) o.castShadow = false; }); } - if (merged !== detailRoot && detailRoot.children.length) group.add(detailRoot); // anything that could not merge - const list = []; merged.traverse(o => { if (o.isMesh) { if (!o.geometry.boundingSphere) o.geometry.computeBoundingSphere(); list.push(o); } }); - const v = new THREE.Vector3(); - (E._updaters = E._updaters || []).push((dt, cam) => { if (!group.parent) return; for (const o of list) { const bs = o.geometry.boundingSphere; v.copy(bs.center).applyMatrix4(o.matrixWorld); o.visible = v.distanceTo(cam.position) < near + bs.radius * 0.5; } }); - } - return { group, colliders, lights, chimneys }; - }; - - // ------------------------------------------------------------------ field walls - E.wall = function (points, opts) { - opts = Object.assign({ type: 'stone', h: 1.2, t: 0.55, gaps: [], seed: 11 }, opts || {}); - const B = E.builder(opts.seed), R = E.rng(opts.seed * 3 + 1), hf = opts.heightFn || (() => 0), stone = opts.type !== 'brick'; - B.wear = false; B.bevelAuto = false; // field walls: the shader's damp foot is enough, and kilometres of bevelled coping cost too much - const mat = stone ? 'fieldstone' : 'brick_red'; - let total = 0; const segs = []; - for (let i = 0; i < points.length - 1; i++) { const a = points[i], b = points[i + 1], L = Math.hypot(b[0] - a[0], b[1] - a[1]); segs.push({ a, b, L, s0: total }); total += L; } - const inGap = (s) => opts.gaps.some(g => s > g[0] && s < g[1]); - const STEP = 1.2; - for (const sg of segs) { - const dx = (sg.b[0] - sg.a[0]) / sg.L, dz = (sg.b[1] - sg.a[1]) / sg.L, rot = Math.atan2(-dz, dx), n = Math.max(1, Math.round(sg.L / STEP)); - for (let k = 0; k < n; k++) { - const s0 = sg.s0 + sg.L * k / n, s1 = sg.s0 + sg.L * (k + 1) / n, sm = (s0 + s1) / 2; if (inGap(sm)) continue; - // height falls off toward broken ends and gap edges in steps - let h = opts.h * (0.92 + 0.16 * E.vnoise(sm * 0.4, 3, opts.seed)); - const dEnd = Math.min(opts.brokenStart ? sm : 1e9, opts.brokenEnd ? total - sm : 1e9, ...opts.gaps.map(g => sm < g[0] ? g[0] - sm : sm > g[1] ? sm - g[1] : 1e9)); - if (dEnd < 3) h *= E.clamp(0.25 + dEnd / 3, 0.25, 1); - const len = (s1 - s0) + 0.02, cx = sg.a[0] + dx * (sm - sg.s0), cz = sg.a[1] + dz * (sm - sg.s0), y = Math.min(hf(sg.a[0] + dx * (s0 - sg.s0), sg.a[1] + dz * (s0 - sg.s0)), hf(sg.a[0] + dx * (s1 - sg.s0), sg.a[1] + dz * (s1 - sg.s0)), hf(cx, cz)); - // coping as separate weathered slabs 0.45-0.9 m long, grey, each sitting a little askew, the odd one missing - // or slipped (one long plank-like box read as boards from the lane) - const copingSlabs = (ccx, cy, ccz, L, t, fy) => { let a = -L / 2; while (a < L / 2 - 0.05) { const sl = Math.min(L / 2 - a, R.range(0.45, 0.9)), mid = a + sl / 2; a += sl; if (R() < 0.04) continue; - const slip = R() < 0.06 ? R.range(0.04, 0.1) : 0; B.box('ashlar', ccx + dx * mid - dz * slip, cy + R.range(-0.012, 0.012), ccz + dz * mid + dx * slip, sl - 0.012, R.range(0.11, 0.15), t + R.range(0, 0.04), rot, { foot: fy, tint: tintJ(R, 0.1, 0x9c9a94), rx: R.range(-0.04, 0.04), rz: R.range(-0.025, 0.025) + (slip ? 0.08 : 0), uvOff: [R() * 9, R() * 9] }); } }; - // battered wall: wide base course, narrower body, coping - B.box(mat, cx, y - 0.25, cz, len, h * 0.45 + 0.25, opts.t, rot, { foot: y, uvOff: [sm, 0] }); - B.box(mat, cx, y + h * 0.45, cz, len, h * 0.45, opts.t * 0.82, rot, { foot: y, uvOff: [sm, 0] }); - B.col(cx, cz, len, opts.t, y - 0.2, y + h * 0.9, rot, 'stone', 'wall'); - if (stone) { // coping: stones set on edge ("cock and hen"), each tilted a little; a plain cap on Low - if (opts.coping !== 'cock') copingSlabs(cx, y + h * 0.9 - 0.02, cz, len, opts.t * 1.05, y); // dressed coping slabs (churchyards, garden walls) - else if (E.Q.name === 'low') B.box('fieldstone', cx, y + h * 0.9 - 0.02, cz, len, 0.22, opts.t * 0.8, rot, { foot: y }); - else for (let c = 0; c < Math.round(len / 0.16); c++) { - const off = -len / 2 + (c + 0.5) * len / Math.round(len / 0.16), px = cx + dx * off, pz = cz + dz * off, tall = R() < 0.35; - B.box('fieldstone', px, y + h * 0.9 - 0.02, pz, R.range(0.09, 0.15), tall ? R.range(0.26, 0.34) : R.range(0.17, 0.24), opts.t * R.range(0.7, 0.9), rot, { rz: R.range(-0.15, 0.15), tint: tintJ(R, 0.14), foot: y, uvOff: [R() * 9, R() * 9] }); - } - } else copingSlabs(cx, y + h * 0.9, cz, len, opts.t * 0.95, y); - // moss and damp along the foot, a pock or two - if (R() < 0.5) B.decal('moss', [cx + dz * (opts.t / 2 + 0.003), y + 0.2, cz - dx * (opts.t / 2 + 0.003)], [dz, 0, -dx], len * 0.9, 0.4, 0); - if (R() < 0.3) B.decal('moss', [cx - dz * (opts.t / 2 + 0.003), y + 0.25, cz + dx * (opts.t / 2 + 0.003)], [-dz, 0, dx], len * 0.8, 0.45, 0); - // fallen stones at broken ends - if (dEnd < 3) for (let r = 0; r < 6; r++) placeRock(B, mat === 'brick_red' ? 'brick_red' : 'fieldstone', cx + dz * R.range(-1, 1) * 0.9 + dx * R.range(-0.5, 0.5), y + 0.02, cz - dx * R.range(-1, 1) * 0.9 + dz * R.range(-0.5, 0.5), R.range(0.1, 0.2), (R() * 999) | 0, [R() * 3, R() * 3, R() * 3], tintJ(R, 0.12)); - } - } - const g = B.finish(); g.name = 'IVEnv.wall'; - return { group: g, colliders: B.colliders }; - }; - - // ------------------------------------------------------------------ fences - E.fence = function (points, kind, opts) { - opts = Object.assign({ seed: 5 }, opts || {}); kind = kind || 'rail'; - const B = E.builder(opts.seed), R = E.rng(opts.seed * 5 + 2), hf = opts.heightFn || (() => 0); - B.bevelAuto = false; // fences run for kilometres: sharp rails and posts - const wires = []; - for (let i = 0; i < points.length - 1; i++) { - const a = points[i], b = points[i + 1], L = Math.hypot(b[0] - a[0], b[1] - a[1]), dx = (b[0] - a[0]) / L, dz = (b[1] - a[1]) / L, rot = Math.atan2(-dz, dx); - const sp = kind === 'picket' ? 2.0 : kind === 'barbed' ? 3.0 : 2.4, n = Math.max(1, Math.round(L / sp)); - for (let k = 0; k <= n; k++) { - if (k === n && i < points.length - 2) continue; - const px = a[0] + dx * L * k / n, pz = a[1] + dz * L * k / n, y = hf(px, pz), lean = R.range(-0.06, 0.06); - const ph = kind === 'picket' ? 1.1 : kind === 'barbed' ? 1.25 : 1.3; - B.box('timber', px, y - 0.3, pz, 0.11, ph + 0.3, 0.11, rot + R.range(-0.2, 0.2), { rz: lean, rx: R.range(-0.04, 0.04), foot: y, grain: 'long', tint: tintJ(R, 0.15, 0xc0b8b0) }); - B.col(px, pz, 0.12, 0.12, y, y + ph, 0, 'wood', 'post'); - if (R() < 0.4) B.decal('moss', [px + dz * 0.056, y + 0.2, pz - dx * 0.056], [dz, 0, -dx], 0.1, 0.3, 0); - if (k < n) { - const qx = a[0] + dx * L * (k + 1) / n, qz = a[1] + dz * L * (k + 1) / n, y2 = hf(qx, qz), len = L / n, mx = (px + qx) / 2, mz = (pz + qz) / 2, ym = (y + y2) / 2, slope = Math.atan2(y2 - y, len); - if (kind === 'rail') for (const hh of [0.45, 1.0]) { const broken = R() < (opts.damage || 0) * 0.5; B.box('timber', mx, ym + hh + (broken ? -0.35 : 0), mz, len + 0.15, 0.1, 0.05, rot, { rz: slope + (broken ? R.range(-0.4, 0.4) : 0), foot: ym, grain: 'long', tint: tintJ(R, 0.15, 0xc0b8b0) }); } - if (kind === 'picket') { B.box('timber', mx, ym + 0.25, mz, len, 0.07, 0.04, rot, { rz: slope, grain: 'long' }); B.box('timber', mx, ym + 0.85, mz, len, 0.07, 0.04, rot, { rz: slope, grain: 'long' }); for (let p = 0; p < Math.round(len / 0.14); p++) { if (R() < (opts.damage || 0) * 0.3) continue; const o = -len / 2 + (p + 0.5) * len / Math.round(len / 0.14), x = mx + dx * o, z = mz + dz * o; B.box('wood_painted', x + dz * 0.03, hf(x, z) + 0.05, z - dx * 0.03, 0.08, 1.0 + R.range(-0.03, 0.03), 0.02, rot, { rz: R.range(-0.03, 0.03), tint: new THREE.Color(1.5, 1.5, 1.45) }); } } - if (kind === 'hurdle') { for (let p = 0; p < 8; p++) B.box('bark_oak', mx, ym + 0.15 + p * 0.12, mz, len, 0.05, 0.05, rot, { rz: slope, grain: 'long', tint: new THREE.Color(0.75, 0.7, 0.62) }); } - if (kind === 'barbed') for (const hh of [0.4, 0.75, 1.1]) wires.push([px, y + hh, pz, qx, y2 + hh, qz]); - B.col(mx, mz, len, 0.1, ym, ym + 1.0, rot, 'wood', 'fence'); - } - } - } - const g = B.finish(); g.name = 'IVEnv.fence:' + kind; - if (wires.length) g.add(E.wireMesh(wires, 0.004, 0.08)); - return { group: g, colliders: B.colliders }; - }; - // sagging wires (telegraph, barbed): thin tubes, each sagging between its ends - E.wireMesh = function (list, radius, sag) { - // fine wire (barbed, under 1 cm) is drawn as lines: a 6 mm tube is under a pixel past a few metres, and a perimeter - // of tubes cost ~75k triangles. Thicker wire (telegraph) stays a tube, 6 segments per span. - if ((radius || 0.006) < 0.01) { - const P = []; for (const w of list) { let prev = null; for (let i = 0; i <= 8; i++) { const t = i / 8, p = [w[0] + (w[3] - w[0]) * t, w[1] + (w[4] - w[1]) * t - Math.sin(Math.PI * t) * (sag != null ? sag : 0.3), w[2] + (w[5] - w[2]) * t]; if (prev) P.push(...prev, ...p); prev = p; } } - const g = new THREE.BufferGeometry(); g.setAttribute('position', new THREE.Float32BufferAttribute(P, 3)); g.computeBoundingSphere(); - const m = new THREE.LineSegments(g, new THREE.LineBasicMaterial({ color: 0x1a1714, transparent: true, opacity: 0.85 })); m.material.userData.linear = true; m.name = 'wires'; - const grp = new THREE.Group(); grp.add(m); return grp; - } - const B = E.builder(3); - for (const w of list) { - const pts = []; for (let i = 0; i <= 10; i++) { const t = i / 10; pts.push(new THREE.Vector3(w[0] + (w[3] - w[0]) * t, w[1] + (w[4] - w[1]) * t - Math.sin(Math.PI * t) * (sag != null ? sag : 0.3), w[2] + (w[5] - w[2]) * t)); } - const g = new THREE.TubeGeometry(new THREE.CatmullRomCurve3(pts), 6, radius || 0.006, 3, false); - B.geo('metal_rust', g, new THREE.Matrix4(), { noFoot: true }); - } - return B.finish({ castShadow: false }); - }; -})(); diff --git a/e63334287a3deaa3/ironveil/env/builder.js b/e63334287a3deaa3/ironveil/env/builder.js deleted file mode 100644 index 08488590..00000000 --- a/e63334287a3deaa3/ironveil/env/builder.js +++ /dev/null @@ -1,446 +0,0 @@ -/* Midnight Ops environment: geometry builder shared by buildings, walls, fences and props. - Everything is merged into one mesh per material (UVs in metres so texel density is the same everywhere; per-piece - UV offsets so no two planks or stones line up). Wear decals from the atlas are merged in the same way. - const B = IVEnv.builder(seed); B.box('brick_red', cx, y0, cz, sx, sy, sz, rotY, opts); ... const g = B.finish(); - opts: { tint: THREE.Color, foot: ground y for damp (default 0 = the builder's local ground), grain: 'long' (wood - grain along the longest side), uvOff: [u, v], rx, rz (extra rotations), noFoot, sides: {top:false, ...} } */ -(function () { - 'use strict'; - const E = window.IVEnv; - const _m = new THREE.Matrix4(), _n = new THREE.Matrix3(), _q = new THREE.Quaternion(), _e = new THREE.Euler(), _p = new THREE.Vector3(), _s = new THREE.Vector3(), _v = new THREE.Vector3(), _w = new THREE.Vector3(); - // unit cube faces: normal, then 4 corners (counter-clockwise seen from outside), u axis, v axis - const FACES = [ - { n: [1, 0, 0], c: [[0.5, -0.5, 0.5], [0.5, -0.5, -0.5], [0.5, 0.5, -0.5], [0.5, 0.5, 0.5]], k: 'px' }, - { n: [-1, 0, 0], c: [[-0.5, -0.5, -0.5], [-0.5, -0.5, 0.5], [-0.5, 0.5, 0.5], [-0.5, 0.5, -0.5]], k: 'nx' }, - { n: [0, 1, 0], c: [[-0.5, 0.5, 0.5], [0.5, 0.5, 0.5], [0.5, 0.5, -0.5], [-0.5, 0.5, -0.5]], k: 'top' }, - { n: [0, -1, 0], c: [[-0.5, -0.5, -0.5], [0.5, -0.5, -0.5], [0.5, -0.5, 0.5], [-0.5, -0.5, 0.5]], k: 'bottom' }, - { n: [0, 0, 1], c: [[-0.5, -0.5, 0.5], [0.5, -0.5, 0.5], [0.5, 0.5, 0.5], [-0.5, 0.5, 0.5]], k: 'pz' }, - { n: [0, 0, -1], c: [[0.5, -0.5, -0.5], [-0.5, -0.5, -0.5], [-0.5, 0.5, -0.5], [0.5, 0.5, -0.5]], k: 'nz' } - ]; - - function Builder(seed) { - this.R = E.rng(seed || 1); this.buckets = {}; this.colliders = []; this.decals = []; - this.seed = seed || 1; this.drips = []; - // +-8 % per copy (each builder is one building, wall run or prop) and a slight warm/cool shift, baked into the tint - const r = E.rng((seed || 1) * 7 + 3); this.copyK = [1 + (r() - 0.5) * 0.16, 0, 0]; const h = (r() - 0.5) * 0.04; this.copyK[1] = this.copyK[0] * (1 + h * 0.3); this.copyK[2] = this.copyK[0] * (1 - h); - // trim bevels by default (sills, lintels, quoins, coping, frames, posts and rails); props set bevelAuto = true - this.bevelAuto = E.Q.name === 'low' || E.noBevel ? false : TRIM_BEVEL; - } - E.noBevel = typeof location !== 'undefined' && /[?&]nobevel\b/.test(location.search); // ?nobevel / ?nowear: for measuring what they cost - E.noWear = typeof location !== 'undefined' && /[?&]nowear\b/.test(location.search); - const TRIM_BEVEL = /^(ashlar|wood_painted|concrete|metal_painted|metal_rust|planks)$/; // (not timber: beams and heads by the hundred put it over the 15 % triangle budget) - const P = Builder.prototype; - const WEAR_MATS = /^(brick_red|brick_sooty|fieldstone|ashlar|plaster|planks|concrete)$/; - // A drip source: rain runs off a sill, eave or window head at (x, y, z) on a wall facing (nx, nz) and stains the - // wall below it in 1-4 streaks across `width` (5-15 cm wide each), up to `len` metres long, darkness k (0..1). - P.drip = function (x, y, z, nx, nz, width, len, k) { - const r = E.rng(((x * 73.1 + z * 41.7 + y * 13.3) * 100) | 0), L = Math.hypot(nx, nz) || 1; - const d = { x, y, z, nx: nx / L, nz: nz / L, s: [], len: len || 1 }, n = Math.max(1, Math.min(width > 2.5 ? 6 : 3, Math.round(width / 1.6 + r() * 1.5))); // (each streak adds grid lines: few, well chosen) - for (let i = 0; i < n; i++) d.s.push({ c: (r() - 0.5) * width * 0.92, hw: 0.025 + r() * 0.05, len: (len || 1) * (0.35 + r() * 0.65), k: (k || 0.22) * (0.6 + r() * 0.5), top: r() * 0.04 }); - this.drips.push(d); - }; - // Detail pieces (arch voussoirs, quoins, loose bricks, ridge tiles, glazing bars, furniture...) go into separate - // meshes that IVEnv.update hides beyond Q.detailDist. detail 2 = also left out entirely on Low. - P.bucket = function (mat) { if (this.detail) mat += '#d'; return this.buckets[mat] || (this.buckets[mat] = { p: [], n: [], u: [], a: [], i: [] }); }; - P.det = function (level, fn) { const prev = this.detail; if (level === 2 && E.Q.name === 'low') return; this.detail = level; try { fn(); } finally { this.detail = prev; } }; - // push one vertex - function vtx(B, x, y, z, nx, ny, nz, u, v, t, foot) { - B.p.push(x, y, z); B.n.push(nx, ny, nz); B.u.push(u, v); - B.a.push(t ? t.r : 0, t ? t.g : 0, t ? t.b : 0, foot == null ? 0 : 1 + Math.max(0, y - foot)); - } - // A quad from 4 world points (counter-clockwise), uv per corner, normal computed. - P.quad = function (mat, a, b, c, d, uv, tint, foot) { - if (this.wear !== false && !E.noWear && foot != null && !this.detail && WEAR_MATS.test(mat) && E.Q.name !== 'low') { - _v.set(b[0] - a[0], b[1] - a[1], b[2] - a[2]); _w.set(d[0] - a[0], d[1] - a[1], d[2] - a[2]); - const n = _v.clone().cross(_w), area = n.length(); n.normalize(); - if (Math.abs(n.y) < 0.35 && area > 0.5) { (this.pend || (this.pend = [])).push({ mat, a, b, c, d, uv, tint, foot, n: [n.x, n.y, n.z] }); return; } - } - const B = this.bucket(mat), base = B.p.length / 3; - _v.set(b[0] - a[0], b[1] - a[1], b[2] - a[2]); _w.set(d[0] - a[0], d[1] - a[1], d[2] - a[2]); const n = _v.clone().cross(_w).normalize(); - [a, b, c, d].forEach((p, k) => vtx(B, p[0], p[1], p[2], n.x, n.y, n.z, uv[k][0], uv[k][1], tint, foot)); - B.i.push(base, base + 1, base + 2, base, base + 2, base + 3); - }; - P.tri = function (mat, a, b, c, uv, tint, foot) { - const B = this.bucket(mat), base = B.p.length / 3; - _v.set(b[0] - a[0], b[1] - a[1], b[2] - a[2]); _w.set(c[0] - a[0], c[1] - a[1], c[2] - a[2]); const n = _v.clone().cross(_w).normalize(); - [a, b, c].forEach((p, k) => vtx(B, p[0], p[1], p[2], n.x, n.y, n.z, uv[k][0], uv[k][1], tint, foot)); - B.i.push(base, base + 1, base + 2); - }; - // Box: centre x, bottom y0, centre z, sizes, rotation about Y (plus optional rx, rz). UVs in metres per face. - // Bevel (o.bevel, metres): the faces are inset and joined by thin edge strips and corner triangles (44 triangles - // instead of 12). Every vertex keeps its own face's flat normal, so a strip blends between the two faces it joins and - // catches a thin highlight under a lamp: what stops a box reading as a sharp CG block. o.bevel true or the builder's - // bevelAuto = auto size: min(1.2 cm, a quarter of the smallest side), 2.5 cm on dressed stone; 0 = sharp (walls that - // butt together). Auto skips boxes over 3.5 m (walls, slabs) and paper-thin ones (< 1.5 cm). - const STONE_BEVEL = /^(ashlar|fieldstone|concrete)/; - P.bevelFor = function (mat, sx, sy, sz, o) { - let b = o.bevel; - const mn = Math.min(sx, sy, sz), mx = Math.max(sx, sy, sz); - if (b === undefined) { const A = this.bevelAuto; if (!A || (A instanceof RegExp && !A.test(mat)) || mx > 3.5 || mn < 0.03) return 0; b = true; } // (under 3 cm the bevel would be under 7.5 mm: not worth 32 triangles) - if (b === true) b = Math.min(STONE_BEVEL.test(mat) ? 0.025 : 0.012, mn * 0.25); - return Math.max(0, Math.min(+b || 0, mn * 0.45)); - }; - const BEV_AX = [[1, 2], [0, 2], [0, 1]]; // in-plane axes of the face on axis a - P.boxBevel = function (mat, cx, y0, cz, sx, sy, sz, ry, o, bv) { - const B = this.bucket(mat), base = B.p.length / 3; - _e.set(o.rx || 0, ry || 0, o.rz || 0, 'YXZ'); _q.setFromEuler(_e); _p.set(cx, y0 + sy / 2, cz); _s.set(1, 1, 1); - _m.compose(_p, _q, _s); const e = _m.elements; - const tint = o.tint || null, foot = o.noFoot ? null : (o.foot != null ? o.foot : 0); - const uo = o.uvOff || [this.R() * 7, this.R() * 7], long = o.grain === 'long', S = [sx, sy, sz], h = [sx / 2, sy / 2, sz / 2]; - const vis = (a, s) => !(o.sides && o.sides[['px', 'nx', 'top', 'bottom', 'pz', 'nz'][a * 2 + (s > 0 ? 0 : 1)]] === false); - const idx = {}, wpos = [], fn = []; - // world normals of the six faces - for (let a = 0; a < 3; a++) for (const s of [1, -1]) { const n = [0, 0, 0]; n[a] = s; fn[a * 2 + (s > 0 ? 0 : 1)] = [e[0] * n[0] + e[4] * n[1] + e[8] * n[2], e[1] * n[0] + e[5] * n[1] + e[9] * n[2], e[2] * n[0] + e[6] * n[1] + e[10] * n[2]]; } - const put = (a, s, si, sj) => { // the corner (si, sj) of face (a, s), inset by the bevel toward each visible neighbour - const [i, j] = BEV_AX[a], L = [0, 0, 0]; - L[a] = s * h[a]; L[i] = si * (h[i] - (vis(i, si) ? bv : 0)); L[j] = sj * (h[j] - (vis(j, sj) ? bv : 0)); - const wx = e[0] * L[0] + e[4] * L[1] + e[8] * L[2] + e[12], wy = e[1] * L[0] + e[5] * L[1] + e[9] * L[2] + e[13], wz = e[2] * L[0] + e[6] * L[1] + e[10] * L[2] + e[14]; - // the same metric UVs the sharp box uses (unit-cube coordinates times size) - const x = L[0] / sx, y = L[1] / sy, z = L[2] / sz; let u, v; - if (a === 0) { u = (s > 0 ? -z : z) * sz; v = y * sy; if (long && sz > sy) { const t = u; u = v; v = t; } } - else if (a === 2) { u = (s > 0 ? x : -x) * sx; v = y * sy; if (long && sx > sy) { const t = u; u = v; v = t; } } - else { u = x * sx; v = (s > 0 ? -z : z) * sz; if (long && sx > sz) { const t = u; u = v; v = t; } } - const n = fn[a * 2 + (s > 0 ? 0 : 1)]; - vtx(B, wx, wy, wz, n[0], n[1], n[2], u + uo[0], v + uo[1], tint, foot); - wpos.push([wx, wy, wz]); - return base + wpos.length - 1; - }; - const key = (a, s, si, sj) => a + ':' + s + ':' + si + ':' + sj; - for (let a = 0; a < 3; a++) for (const s of [1, -1]) { if (!vis(a, s)) continue; for (const si of [-1, 1]) for (const sj of [-1, 1]) idx[key(a, s, si, sj)] = put(a, s, si, sj); } - // a polygon with the winding that faces 'out' (local direction, rotated) - const tri = (A, Bb, C, out) => { - const pa = wpos[A - base], pb = wpos[Bb - base], pc = wpos[C - base]; - const ux = pb[0] - pa[0], uy = pb[1] - pa[1], uz = pb[2] - pa[2], vx = pc[0] - pa[0], vy = pc[1] - pa[1], vz = pc[2] - pa[2]; - const nx = uy * vz - uz * vy, ny = uz * vx - ux * vz, nz = ux * vy - uy * vx; - if (nx * out[0] + ny * out[1] + nz * out[2] >= 0) B.i.push(A, Bb, C); else B.i.push(A, C, Bb); - }; - const outDir = (L) => [e[0] * L[0] + e[4] * L[1] + e[8] * L[2], e[1] * L[0] + e[5] * L[1] + e[9] * L[2], e[2] * L[0] + e[6] * L[1] + e[10] * L[2]]; - const get = (a, s, ci) => { const [i, j] = BEV_AX[a]; return idx[key(a, s, ci[i], ci[j])]; }; // face (a,s)'s vertex nearest the corner ci - // faces - for (let a = 0; a < 3; a++) for (const s of [1, -1]) { - if (!vis(a, s)) continue; const L = [0, 0, 0]; L[a] = s; const out = outDir(L); - const q = [key(a, s, -1, -1), key(a, s, 1, -1), key(a, s, 1, 1), key(a, s, -1, 1)].map(k => idx[k]); - tri(q[0], q[1], q[2], out); tri(q[0], q[2], q[3], out); - } - // edge strips between two visible faces (a, sa) and (b, sb), running along the third axis c - for (let a = 0; a < 3; a++) for (let b = a + 1; b < 3; b++) { - const c = 3 - a - b; - for (const sa of [1, -1]) for (const sb of [1, -1]) { - if (!vis(a, sa) || !vis(b, sb)) continue; - const L = [0, 0, 0]; L[a] = sa; L[b] = sb; const out = outDir(L); - const ci0 = [0, 0, 0], ci1 = [0, 0, 0]; ci0[a] = ci1[a] = sa; ci0[b] = ci1[b] = sb; ci0[c] = -1; ci1[c] = 1; - const A0 = get(a, sa, ci0), A1 = get(a, sa, ci1), B0 = get(b, sb, ci0), B1 = get(b, sb, ci1); - tri(A0, A1, B1, out); tri(A0, B1, B0, out); - } - } - // corner triangles where three visible faces meet - for (const sx_ of [1, -1]) for (const sy_ of [1, -1]) for (const sz_ of [1, -1]) { - if (!vis(0, sx_) || !vis(1, sy_) || !vis(2, sz_)) continue; - const ci = [sx_, sy_, sz_]; tri(get(0, sx_, ci), get(1, sy_, ci), get(2, sz_, ci), outDir(ci)); - } - this.bevelTris = (this.bevelTris || 0) + 32; - }; - P.box = function (mat, cx, y0, cz, sx, sy, sz, ry, o) { - o = o || {}; - if (!mat) return; - const bv = this.bevelFor(mat, sx, sy, sz, o); - if (bv > 0.0005) return this.boxBevel(mat, cx, y0, cz, sx, sy, sz, ry, o, bv); - const B = this.bucket(mat); - _e.set(o.rx || 0, ry || 0, o.rz || 0, 'YXZ'); _q.setFromEuler(_e); _p.set(cx, y0 + sy / 2, cz); _s.set(sx, sy, sz); - _m.compose(_p, _q, _s); _n.getNormalMatrix(_m); - const e = _m.elements, ne = _n.elements, tint = o.tint || null, foot = o.noFoot ? null : (o.foot != null ? o.foot : 0); - const uo = o.uvOff || [this.R() * 7, this.R() * 7], long = o.grain === 'long'; - // big vertical faces of wall materials go through P.quad, which holds them back for the baked wear (grime, drips) - const wearBox = this.wear !== false && !E.noWear && !this.detail && foot != null && WEAR_MATS.test(mat) && E.Q.name !== 'low' && Math.max(sx, sz) * sy > 0.5; - for (const F of FACES) { - if (o.sides && o.sides[F.k] === false) continue; - if (wearBox && F.k !== 'top' && F.k !== 'bottom') { - const pts = [], uvs = []; - for (const c of F.c) { - const x = c[0], y = c[1], z = c[2]; - pts.push([e[0] * x + e[4] * y + e[8] * z + e[12], e[1] * x + e[5] * y + e[9] * z + e[13], e[2] * x + e[6] * y + e[10] * z + e[14]]); - let u, v; if (F.k === 'px' || F.k === 'nx') { u = (F.k === 'px' ? -z : z) * sz; v = y * sy; } else { u = (F.k === 'pz' ? x : -x) * sx; v = y * sy; } - if (long && ((F.k === 'px' || F.k === 'nx') ? sz > sy : sx > sy)) { const t = u; u = v; v = t; } - uvs.push([u + uo[0], v + uo[1]]); - } - const before = this.pend ? this.pend.length : 0; this.quad(mat, pts[0], pts[1], pts[2], pts[3], uvs, tint, foot); - if ((this.pend ? this.pend.length : 0) > before) continue; // held back; otherwise P.quad already wrote it - continue; - } - const base = B.p.length / 3; - const nx = ne[0] * F.n[0] + ne[3] * F.n[1] + ne[6] * F.n[2], ny = ne[1] * F.n[0] + ne[4] * F.n[1] + ne[7] * F.n[2], nz = ne[2] * F.n[0] + ne[5] * F.n[1] + ne[8] * F.n[2]; - const nl = Math.hypot(nx, ny, nz) || 1; - for (const c of F.c) { - const x = c[0], y = c[1], z = c[2]; - const wx = e[0] * x + e[4] * y + e[8] * z + e[12], wy = e[1] * x + e[5] * y + e[9] * z + e[13], wz = e[2] * x + e[6] * y + e[10] * z + e[14]; - // face-local metric UVs: u along the face's horizontal axis, v along its vertical (or depth for top/bottom) - let u, v; - if (F.k === 'px' || F.k === 'nx') { u = (F.k === 'px' ? -z : z) * sz; v = y * sy; if (long && sz > sy) { const t = u; u = v; v = t; } } - else if (F.k === 'pz' || F.k === 'nz') { u = (F.k === 'pz' ? x : -x) * sx; v = y * sy; if (long && sx > sy) { const t = u; u = v; v = t; } } - else { u = x * sx; v = (F.k === 'top' ? -z : z) * sz; if (long && sx > sz) { const t = u; u = v; v = t; } } - vtx(B, wx, wy, wz, nx / nl, ny / nl, nz / nl, u + uo[0], v + uo[1], tint, foot); - } - B.i.push(base, base + 1, base + 2, base, base + 2, base + 3); - } - }; - // Any three.js geometry, transformed; UVs box-projected in metres from the transformed positions. - P.geo = function (mat, geo, matrix, o) { - o = o || {}; - const B = this.bucket(mat), g = geo.index ? geo.toNonIndexed() : geo, pa = g.attributes.position, na = g.attributes.normal; - _n.getNormalMatrix(matrix); const e = matrix.elements, ne = _n.elements, tint = o.tint || null, foot = o.noFoot ? null : (o.foot != null ? o.foot : 0); - const uo = o.uvOff || [this.R() * 7, this.R() * 7], keepUv = o.keepUv && g.attributes.uv, uva = g.attributes.uv, us = o.uvScale || 1; - const base = B.p.length / 3; - for (let i = 0; i < pa.count; i++) { - const x = pa.getX(i), y = pa.getY(i), z = pa.getZ(i); - const wx = e[0] * x + e[4] * y + e[8] * z + e[12], wy = e[1] * x + e[5] * y + e[9] * z + e[13], wz = e[2] * x + e[6] * y + e[10] * z + e[14]; - let nx = ne[0] * na.getX(i) + ne[3] * na.getY(i) + ne[6] * na.getZ(i), ny = ne[1] * na.getX(i) + ne[4] * na.getY(i) + ne[7] * na.getZ(i), nz = ne[2] * na.getX(i) + ne[5] * na.getY(i) + ne[8] * na.getZ(i); - const l = Math.hypot(nx, ny, nz) || 1; nx /= l; ny /= l; nz /= l; - let u, v; - if (keepUv) { u = uva.getX(i) * (o.uvW || 1) * us; v = uva.getY(i) * (o.uvH || 1) * us; } - else { const ax = Math.abs(nx), ay = Math.abs(ny), az = Math.abs(nz); if (ay >= ax && ay >= az) { u = wx; v = wz; } else if (ax >= az) { u = wz; v = wy; } else { u = wx; v = wy; } } - vtx(B, wx, wy, wz, nx, ny, nz, u + uo[0], v + uo[1], tint, foot); - B.i.push(base + i); - } - }; - // Axis-aligned or oriented collider box in the group's local space (same layout the game uses for W.addBox). - P.col = function (x, z, sx, sz, y0, y1, rot, surf, kind) { this.colliders.push({ x, z, hx: sx / 2, hz: sz / 2, y0, y1, rot: rot || 0, surf: surf || 'stone', kind: kind || '' }); }; - // A wear decal from the atlas, laid flat on a surface: centre p, outward normal n, size w x h, rotation in plane. - P.decal = function (type, p, n, w, h, rot) { this.decals.push({ type, p, n, w, h: h || w, rot: rot || 0 }); }; - // painted text (env/labels.js): text, style, centre p, outward normal n, width w (m), in the builder's space. The - // finished group carries them (userData.labels); IV.art.flush puts them into the one label atlas in world space. - P.label = function (text, style, p, n, w, o) { (this.labels || (this.labels = [])).push({ text, style, p, n, w, o: o || {} }); }; - - // Merge into meshes. Decals go into one extra mesh with the atlas material. - // the wear multiplier at local point p (y = height of the point, hf = height above the foot) on a face with normal n - P.wearAt = function (p, n, hf, out) { - let k = 1, gk = 1; - if (hf != null) { // grime band: 0-0.55 m, darkest at the bottom, a ragged top edge that wanders along the wall - const al = p[0] * n[2] - p[2] * n[0], top = 0.4 + 0.3 * E.vnoise(al * 1.3, 0.5, this.seed) + 0.12 * E.vnoise(al * 5.1, 1.5, this.seed + 1); - const g = 1 - E.sstep(0.02, top, hf); k *= 1 - 0.24 * g; gk *= 1 - 0.05 * g; - } - for (const d of this.drips) { - if (n[0] * d.nx + n[2] * d.nz < 0.8) continue; - const off = (p[0] - d.x) * d.nx + (p[2] - d.z) * d.nz; if (Math.abs(off) > 0.4) continue; - const t = (p[0] - d.x) * -d.nz + (p[2] - d.z) * d.nx, below = d.y - p[1]; - if (below < -0.02) continue; - for (const st of d.s) { - const across = 1 - Math.abs(t - st.c) / st.hw; if (across <= 0) continue; - const down = below / st.len; if (down > 1) continue; - const dk = st.k * across * Math.pow(1 - down, 1.4) * E.sstep(-0.02, 0.03 + st.top, below); - k *= 1 - dk; gk *= 1 + dk * 0.15; // a faint green-brown cast in the streak - } - } - out[0] = k; out[1] = k * gk; out[2] = k / gk; return out; - }; - // write the held-back wall quads: a grid of about 0.75 x 1.5 m whose lines also fall on the drip streaks (centre and - // both edges) and on the grime band, so the vertex tint can draw them - P.flushWear = function () { - const list = this.pend || []; this.pend = null; const wk = [1, 1, 1], dv = [0, 0, 0]; - for (const q of list) { - const { a, b, d, uv, n } = q, du = [b[0] - a[0], b[1] - a[1], b[2] - a[2]], dvv = [d[0] - a[0], d[1] - a[1], d[2] - a[2]]; - const Lu = Math.hypot(du[0], du[1], du[2]), Lv = Math.hypot(dvv[0], dvv[1], dvv[2]); - const us = new Set([0, 1]), vs = new Set([0, 1]); - for (let i = 1; i < Math.ceil(Lu / 1.1); i++) us.add(i / Math.ceil(Lu / 1.1)); - for (let i = 1; i < Math.ceil(Lv / 1.5); i++) vs.add(i / Math.ceil(Lv / 1.5)); // rows only where wear needs them (grime band, drips) - // u runs along the wall (horizontal), v up it: true for every wall quad the kit makes (wallRun, gables use tri) - const vy = dvv[1] / (Lv || 1); - if (Math.abs(vy) > 0.9) { - for (const h of [0.2, 0.62]) { const t = (q.foot + h - a[1]) / dvv[1]; if (t > 0.01 && t < 0.99) vs.add(t); } - let used = false; - for (const dr of this.drips) { - if (n[0] * dr.nx + n[2] * dr.nz < 0.8) continue; - const off = (a[0] - dr.x) * dr.nx + (a[2] - dr.z) * dr.nz; if (Math.abs(off) > 0.4) continue; - // along-wall coordinate of the quad's corner a, and the direction of u in that coordinate - const ta = (a[0] - dr.x) * -dr.nz + (a[2] - dr.z) * dr.nx, tu = (du[0] * -dr.nz + du[2] * dr.nx) / (Lu || 1); - if (Math.abs(tu) < 0.5) continue; - for (const st of dr.s) for (const e of [-1, 0, 1]) { const t = (st.c + e * st.hw - ta) / (tu * Lu); if (t > 0.002 && t < 0.998) { us.add(t); used = true; } } - if (used) for (const h of [0.02, 0.4, 0.95]) { const t = (dr.y - h * dr.len - a[1]) / dvv[1]; if (t > 0.01 && t < 0.99) vs.add(t); } // rows per drip, not per streak - } - } - let U = [...us].sort((x, y) => x - y), V = [...vs].sort((x, y) => x - y); - // hard caps per quad (a wall face between openings): at most 26 columns and 9 rows - const thin = (A, n) => { while (A.length > n) A = A.filter((x, i) => i === 0 || i === A.length - 1 || i % 2 === 1); return A; }; - U = thin(U, 26); V = thin(V, 9); - const B = this.bucket(q.mat), base = B.p.length / 3, nu = U.length; - for (const tv of V) for (const tu of U) { - const x = a[0] + du[0] * tu + dvv[0] * tv, y = a[1] + du[1] * tu + dvv[1] * tv, z = a[2] + du[2] * tu + dvv[2] * tv; - // bilinear uv between the four corner uvs (a, b, c, d) - const u0 = uv[0][0] + (uv[1][0] - uv[0][0]) * tu, u1 = uv[3][0] + (uv[2][0] - uv[3][0]) * tu, v0 = uv[0][1] + (uv[1][1] - uv[0][1]) * tu, v1 = uv[3][1] + (uv[2][1] - uv[3][1]) * tu; - this.wearAt([x, y, z], n, Math.max(0, y - q.foot), wk); - const t = q.tint; dv[0] = (t ? t.r : 1) * wk[0]; dv[1] = (t ? t.g : 1) * wk[1]; dv[2] = (t ? t.b : 1) * wk[2]; - B.p.push(x, y, z); B.n.push(n[0], n[1], n[2]); B.u.push(u0 + (u1 - u0) * tv, v0 + (v1 - v0) * tv); - B.a.push(Math.max(dv[0], 1e-3), Math.max(dv[1], 1e-3), Math.max(dv[2], 1e-3), 1 + Math.max(0, y - q.foot)); - } - for (let j = 0; j < V.length - 1; j++) for (let i = 0; i < nu - 1; i++) { const k0 = base + j * nu + i; B.i.push(k0, k0 + 1, k0 + nu + 1, k0, k0 + nu + 1, k0 + nu); } - this.wearTris = (this.wearTris || 0) + (V.length - 1) * (nu - 1) * 2 - 2; - } - }; - // anything that edits or merges the buckets before finish() (mergeB, ageMesh, the lean pass) flushes first - P.flushPending = function () { if (this.pend && this.pend.length) this.flushWear(); }; - P.finish = function (o) { - o = o || {}; - if (this.pend) this.flushWear(); - // the per-copy shift on every vertex of this builder (tint 0 = 'none' becomes the shift itself) - if (E.Q.name !== 'low') for (const mat in this.buckets) { if (/^glass/.test(mat)) continue; const A = this.buckets[mat].a; for (let i = 0; i < A.length; i += 4) { const none = A[i] + A[i + 1] + A[i + 2] <= 0; for (let c = 0; c < 3; c++) A[i + c] = (none ? 1 : A[i + c]) * this.copyK[c]; } } - const g = new THREE.Group(); - for (const mat in this.buckets) { - const B = this.buckets[mat]; if (!B.i.length) continue; - const geo = new THREE.BufferGeometry(); - geo.setAttribute('position', new THREE.Float32BufferAttribute(B.p, 3)); geo.setAttribute('normal', new THREE.Float32BufferAttribute(B.n, 3)); - geo.setAttribute('uv', new THREE.Float32BufferAttribute(B.u, 2)); geo.setAttribute('aEnv', new THREE.Float32BufferAttribute(B.a, 4)); - geo.setIndex(B.p.length / 3 > 65535 ? new THREE.Uint32BufferAttribute(B.i, 1) : new THREE.Uint16BufferAttribute(B.i, 1)); - geo.computeBoundingSphere(); - const det = mat.endsWith('#d'), mn = det ? mat.slice(0, -2) : mat; - const mv = mn.split('|'), m = new THREE.Mesh(geo, mn === 'glass_lit' ? E.mat('glass', 'lit') : E.mat(mv[0], mv[1])); - m.castShadow = o.castShadow !== false && !det && mn !== 'glass' && mn !== 'glass_lit'; m.receiveShadow = true; m.name = mn; - if (det) E.registerDetail(m); - g.add(m); - } - if (this.decals.length) { const dm = E.decalMesh(this.decals); E.registerDetail(dm, 40); g.add(dm); } - if (this.labels) g.userData.labels = this.labels; - return g; - }; - E.builder = (seed) => new Builder(seed); - E._detail = []; - E.registerDetail = function (mesh, dist) { mesh.userData.detail = dist || true; E._detail.push(mesh); }; - const _c = new THREE.Vector3(); let _last = 0; - E._updaters = E._updaters || []; - E._updaters.push(function (dt, cam) { - const now = performance.now(); if (now - _last < 200) return; _last = now; - const D = E.Q.detailDist || 25, list = E._detail; - for (let i = list.length - 1; i >= 0; i--) { - const m = list[i]; if (!m.parent) { if (m.userData.dead) list.splice(i, 1); continue; } - if (!m.geometry.boundingSphere) m.geometry.computeBoundingSphere(); - _c.copy(m.geometry.boundingSphere.center).applyMatrix4(m.matrixWorld); - const d2 = _c.distanceToSquared(cam.position); - if (m.userData.shadowNear) { const sl = m.userData.shadowNear + m.geometry.boundingSphere.radius; m.castShadow = d2 < sl * sl; if (!m.userData.detail) continue; } - const lim = (m.userData.detail === true ? D : m.userData.detail) + m.geometry.boundingSphere.radius; - m.visible = d2 < lim * lim; - } - }); - E.Builder = Builder; - - // ------------------------------------------------------------------ static decal mesh (atlas, merged) - // Atlas cells (4 x 4, row 0 at v = 0): see texgen.js G.decals. - E.DECALS = { scratches: 0, gouges: 1, chipped: 2, pocks: 3, scorch: 4, soot: 5, damp: 6, moss: 7, rust: 8, mud: 9, crack: 10, bullethole: 11, leaves: 12, waterstain: 13, chalk: 14, grime: 15 }; - let decalMat = null; - E.decalMaterial = function () { - if (decalMat) return decalMat; - const T = E.tex.decals; - const m = new THREE.MeshStandardMaterial({ map: T.alb, normalMap: T.nri, transparent: true, depthWrite: false, polygonOffset: true, polygonOffsetFactor: -2, polygonOffsetUnits: -4, roughness: 1, metalness: 0, alphaTest: 0.02 }); - m.customProgramCacheKey = () => 'ivdecalsatlas'; - m.onBeforeCompile = function (sh) { // r187: the atlas UV is vMapUv (r128's vUv) - // the atlas is raw sRGB (env/core.js makeTex): decoded after filtering, as r128 did - E.patch(sh, 'fragment', '#include ', 'vec4 sampledDiffuseColor = sRGBTransferEOTF(texture2D(map, vMapUv)); diffuseColor *= sampledDiffuseColor;', 'env/builder decals'); - E.patch(sh, 'fragment', '#include ', 'float roughnessFactor = texture2D(normalMap, vMapUv).b;', 'env/builder decals'); - E.patch(sh, 'fragment', '#include ', `vec4 dn = texture2D(normalMap, vMapUv); vec3 mapN = vec3(dn.xy * 2.0 - 1.0, 0.0); mapN.z = sqrt(max(0.05, 1.0 - dot(mapN.xy, mapN.xy))); - normal = ivPerturbNormal2Arb(-vViewPosition, normal, mapN, faceDirection, vMapUv);`, 'env/builder decals'); - sh.fragmentShader = E.withPerturb(sh.fragmentShader); - }; - m.userData.linear = true; decalMat = m; return m; - }; - E.decalMesh = function (list) { - const p = [], n = [], u = [], idx = []; const t = new THREE.Vector3(), b = new THREE.Vector3(), N = new THREE.Vector3(), up = new THREE.Vector3(); - for (const d of list) { - const cell = typeof d.type === 'number' ? d.type : E.DECALS[d.type]; if (cell == null) continue; - N.set(d.n[0], d.n[1], d.n[2]).normalize(); - up.set(0, 1, 0); if (Math.abs(N.y) > 0.9) up.set(0, 0, -1); - t.crossVectors(up, N).normalize(); b.crossVectors(N, t).normalize(); - const c = Math.cos(d.rot), s = Math.sin(d.rot), tx = t.clone().multiplyScalar(c).addScaledVector(b, s), bx = b.clone().multiplyScalar(c).addScaledVector(t, -s); - const ox = (cell % 4) / 4, oy = Math.floor(cell / 4) / 4, inset = 0.004; - const base = p.length / 3; - [[-1, -1], [1, -1], [1, 1], [-1, 1]].forEach(([i, j]) => { - p.push(d.p[0] + tx.x * i * d.w / 2 + bx.x * j * d.h / 2 + N.x * 0.004, d.p[1] + tx.y * i * d.w / 2 + bx.y * j * d.h / 2 + N.y * 0.004, d.p[2] + tx.z * i * d.w / 2 + bx.z * j * d.h / 2 + N.z * 0.004); - n.push(N.x, N.y, N.z); u.push(ox + inset + (i * 0.5 + 0.5) * (0.25 - 2 * inset), oy + inset + (j * 0.5 + 0.5) * (0.25 - 2 * inset)); - }); - idx.push(base, base + 1, base + 2, base, base + 2, base + 3); - } - const g = new THREE.BufferGeometry(); - g.setAttribute('position', new THREE.Float32BufferAttribute(p, 3)); g.setAttribute('normal', new THREE.Float32BufferAttribute(n, 3)); g.setAttribute('uv', new THREE.Float32BufferAttribute(u, 2)); - g.setIndex(idx); g.computeBoundingSphere(); - const m = new THREE.Mesh(g, E.decalMaterial()); m.receiveShadow = true; m.renderOrder = 2; m.name = 'decals'; - return m; - }; -})(); - -/* IVEnv.mergeStatic(root, opts) -> Group: merges every static mesh under root (buildings, walls, fences, props) that - shares a material into one mesh per material, in root's space. Door pivots (objects with userData.dynamic or named - in opts.keep) are left alone. Cuts draw calls from one per material per object to one per material. */ -(function () { - 'use strict'; - const E = window.IVEnv; - // Low: small and minor surfaces share ONE plain material (their texture's mean colour goes into the vertex tint), - // which cuts a draw call per material per cell. Big surfaces (walls, roofs, ground) keep their textures. - const LOW_MINOR = new Set(['metal_rust', 'metal_painted', 'canvas', 'sandbag', 'straw', 'bark_pine', 'ashlar', 'timber', 'wood_painted', 'brick_sooty', 'floorboards', 'concrete', 'cobbles', 'gravel']); - const meanCache = {}; - function meanColour(name) { - if (meanCache[name]) return meanCache[name]; - const R = E.RECIPES[name], T = R && E.tex[R.tex]; const c = new THREE.Color(0.3, 0.3, 0.3); - if (T && T.alb.image && T.alb.image.data) { const d = T.alb.image.data; let r = 0, g = 0, b = 0, n = 0; for (let i = 0; i < d.length; i += 64) { r += d[i]; g += d[i + 1]; b += d[i + 2]; n++; } c.setRGB(r / n / 255, g / n / 255, b / n / 255).convertSRGBToLinear(); } - return meanCache[name] = c; - } - let lowMat = null; - E.lowMinorMaterial = function () { - if (lowMat) return lowMat; - const m = new THREE.MeshStandardMaterial({ roughness: 0.85, metalness: 0 }); - m.onBeforeCompile = (sh) => { - E.patch(sh, 'vertex', '#include ', '#include \n vTint = aEnv.rgb;', 'env/builder low minor'); - E.patch(sh, 'fragment', '#include ', 'diffuseColor.rgb = vTint;', 'env/builder low minor'); - sh.vertexShader = 'attribute vec4 aEnv;\nvarying vec3 vTint;\n' + sh.vertexShader; - sh.fragmentShader = 'varying vec3 vTint;\n' + sh.fragmentShader; - }; - m.customProgramCacheKey = () => 'ivlowminor'; m.userData.linear = true; lowMat = m; return m; - }; - E.mergeStatic = function (root, opts) { - opts = opts || {}; - const lowMinor = (E.Q.name === 'low' || opts.flat) && opts.lowMinor !== false; // opts.flat: everything takes the plain material (far shells) - if (E.Q.name === 'low' && opts.cell) opts = Object.assign({}, opts, { cell: Math.max(opts.cell, 160) }); // Low: bigger cells, fewer draw calls - root.updateMatrixWorld(true); - const inv = new THREE.Matrix4().copy(root.matrixWorld).invert(); - const groups = new Map(), victims = []; - const nm = new THREE.Matrix3(), m = new THREE.Matrix4(), v = new THREE.Vector3(); - root.traverse(o => { - if (!o.isMesh || o.isInstancedMesh || o.userData.dynamic || !o.geometry.index) return; - let p = o.parent; while (p && p !== root) { if (p.userData.dynamic) return; p = p.parent; } - const mat = o.material; if (Array.isArray(mat)) return; - // merge per material AND per spatial cell (opts.cell metres), so frustum culling still drops what is out of view - const minor = lowMinor && mat.userData && (opts.flat ? !!mat.userData.ivenv : LOW_MINOR.has(mat.userData.ivenv)) && !o.userData.detail; - let k = (minor ? 'lowminor' : mat.uuid) + (o.userData.detail ? '#d' : ''); - const cellSize = o.userData.detail ? Math.min(opts.cell || 32, 32) : opts.cell; - if (cellSize) { if (!o.geometry.boundingSphere) o.geometry.computeBoundingSphere(); const c = o.geometry.boundingSphere.center.clone().applyMatrix4(o.matrixWorld); k += ':' + Math.floor(c.x / cellSize) + ':' + Math.floor(c.z / cellSize); } - if (!groups.has(k)) groups.set(k, { mat: minor ? E.lowMinorMaterial() : mat, minor, list: [], cast: o.castShadow, order: o.renderOrder, depth: o.customDepthMaterial, detail: o.userData.detail, shadowNear: o.userData.shadowNear }); - groups.get(k).list.push(o); victims.push(o); - }); - const out = new THREE.Group(); out.name = 'IVEnv.merged'; - for (const [, G] of groups) { - let nv = 0, ni = 0; const names = {}; - for (const o of G.list) { nv += o.geometry.attributes.position.count; ni += o.geometry.index.count; for (const k in o.geometry.attributes) names[k] = o.geometry.attributes[k].itemSize; } - const arr = {}; for (const k in names) arr[k] = new Float32Array(nv * names[k]); - const idx = nv > 65535 ? new Uint32Array(ni) : new Uint16Array(ni); - let vo = 0, io = 0; - for (const o of G.list) { - const g = o.geometry, I = g.index, cnt = g.attributes.position.count; - m.multiplyMatrices(inv, o.matrixWorld); nm.getNormalMatrix(m); - for (const k in names) { - const A = g.attributes[k], sz = names[k], out = arr[k]; if (!A) continue; - for (let i = 0; i < cnt; i++) { - if (k === 'position') { v.fromBufferAttribute(A, i).applyMatrix4(m); out[(vo + i) * 3] = v.x; out[(vo + i) * 3 + 1] = v.y; out[(vo + i) * 3 + 2] = v.z; } - else if (k === 'normal') { v.fromBufferAttribute(A, i).applyMatrix3(nm).normalize(); out[(vo + i) * 3] = v.x; out[(vo + i) * 3 + 1] = v.y; out[(vo + i) * 3 + 2] = v.z; } - else if (k === 'aEnv' && G.minor) { const mc = meanColour(o.material.userData.ivenv); for (let c = 0; c < 3; c++) { const t = A.array[i * 4 + c]; out[(vo + i) * 4 + c] = (t > 0 ? t : 1) * (c === 0 ? mc.r : c === 1 ? mc.g : mc.b); } out[(vo + i) * 4 + 3] = A.array[i * 4 + 3]; } - else for (let c = 0; c < sz; c++) out[(vo + i) * sz + c] = A.array[i * sz + c]; - } - } - for (let i = 0; i < I.count; i++) idx[io + i] = I.getX(i) + vo; - vo += cnt; io += I.count; - } - const geo = new THREE.BufferGeometry(); - for (const k in names) geo.setAttribute(k, new THREE.BufferAttribute(arr[k], names[k])); - geo.setIndex(new THREE.BufferAttribute(idx, 1)); - geo.computeBoundingSphere(); - const mesh = new THREE.Mesh(geo, G.mat); mesh.castShadow = G.cast; if (G.depth) mesh.customDepthMaterial = G.depth; if (G.detail) E.registerDetail(mesh, G.detail); if (G.shadowNear && G.cast) { mesh.userData.shadowNear = G.shadowNear; E._detail.push(mesh); } mesh.receiveShadow = true; mesh.renderOrder = G.order; mesh.name = 'merged:' + (G.mat.userData.ivenv || G.mat.type); - out.add(mesh); - } - for (const o of victims) { o.parent.remove(o); o.userData.dead = true; if (opts.dispose !== false) o.geometry.dispose(); } - return out; - }; -})(); diff --git a/e63334287a3deaa3/ironveil/env/decals.js b/e63334287a3deaa3/ironveil/env/decals.js deleted file mode 100644 index 1620804f..00000000 --- a/e63334287a3deaa3/ironveil/env/decals.js +++ /dev/null @@ -1,55 +0,0 @@ -/* Midnight Ops environment: runtime decals (impacts, scorch) from one pooled instanced mesh = one draw call. - IVEnv.decal(type, position, normal, size, seed) -> index types: scratches, gouges, chipped, pocks, scorch, soot, - damp, moss, rust, mud, crack, bullethole, leaves, waterstain, chalk, grime (see IVEnv.DECALS). position / normal - are THREE.Vector3 or [x, y, z] in world space. The pool holds IVEnv.Q.decals; the oldest is reused. - IVEnv.impact(surface, position, normal) picks a decal for a bullet hit by surface: 'stone' | 'brick' | 'concrete' | - 'wood' | 'metal' | 'glass' | 'dirt' | 'cloth' (returns the decal index or -1 for surfaces that take none). - IVEnv.clearDecals() empties the pool (level change). Decals are offset 4 mm and use polygon offset (no z-fighting). */ -(function () { - 'use strict'; - const E = window.IVEnv; - let pool = null; - function makePool(scene) { - const n = (E.Q && E.Q.decals) || 128; - const g = new THREE.PlaneGeometry(1, 1); g.translate(0, 0, 0.004); - const cell = new THREE.InstancedBufferAttribute(new Float32Array(n * 2), 2); g.setAttribute('aCell', cell); - const base = E.decalMaterial(), m = base.clone(); - m.onBeforeCompile = function (sh) { - base.onBeforeCompile.call(this, sh); - // r187: the atlas cell goes into the map's and the normal map's UVs (r128 had the one vUv) - E.patch(sh, 'vertex', '#include ', 'vMapUv = (uv * (0.25 - 0.008) + 0.004) + aCell; vNormalMapUv = vMapUv;', 'env/decals pool'); - sh.vertexShader = 'attribute vec2 aCell;\n' + sh.vertexShader; - }; - m.customProgramCacheKey = () => 'ivdecalpool'; - const mesh = new THREE.InstancedMesh(g, m, n); mesh.count = 0; mesh.frustumCulled = false; mesh.renderOrder = 3; mesh.receiveShadow = true; mesh.name = 'IVEnv.decals'; - pool = { mesh, cell, n, next: 0, used: 0 }; - (scene || E.atmo && E.atmo.scene).add(mesh); - return pool; - } - const _o = new THREE.Object3D(), _n = new THREE.Vector3(), _p = new THREE.Vector3(); - E.decal = function (type, position, normal, size, seed) { - if (!pool) makePool(); - const c = typeof type === 'number' ? type : E.DECALS[type]; if (c == null) return -1; - _p.set(position.x != null ? position.x : position[0], position.y != null ? position.y : position[1], position.z != null ? position.z : position[2]); - _n.set(normal.x != null ? normal.x : normal[0], normal.y != null ? normal.y : normal[1], normal.z != null ? normal.z : normal[2]).normalize(); - const i = pool.next; pool.next = (pool.next + 1) % pool.n; pool.used = Math.min(pool.n, pool.used + 1); - _o.position.copy(_p); _o.lookAt(_p.x + _n.x, _p.y + _n.y, _p.z + _n.z); - const r = seed != null ? E.hash(seed, 3, 7) : Math.random(); _o.rotateZ(r * Math.PI * 2); - const s = size || 0.3; _o.scale.set(s, s, 1); _o.updateMatrix(); - pool.mesh.setMatrixAt(i, _o.matrix); pool.mesh.instanceMatrix.needsUpdate = true; - pool.cell.setXY(i, (c % 4) / 4, Math.floor(c / 4) / 4); pool.cell.needsUpdate = true; - pool.mesh.count = pool.used; - return i; - }; - E.impact = function (surface, position, normal) { - const s = String(surface || '').toLowerCase(), R = Math.random; - if (s === 'stone' || s === 'brick' || s === 'concrete') return E.decal(R() < 0.65 ? 'bullethole' : 'pocks', position, normal, 0.12 + R() * 0.1); - if (s === 'wood') return E.decal(R() < 0.7 ? 'bullethole' : 'gouges', position, normal, 0.1 + R() * 0.08); - if (s === 'metal') return E.decal('bullethole', position, normal, 0.07 + R() * 0.04); - if (s === 'glass') return E.decal('crack', position, normal, 0.35 + R() * 0.2); - if (s === 'dirt' || s === 'mud' || s === 'grass' || s === 'gravel') return E.decal('mud', position, normal, 0.25 + R() * 0.2); - return -1; - }; - E.clearDecals = function () { if (pool) { pool.used = 0; pool.next = 0; pool.mesh.count = 0; } }; - E.decalPoolMesh = () => pool ? pool.mesh : null; -})(); diff --git a/e63334287a3deaa3/ironveil/env/grass.js b/e63334287a3deaa3/ironveil/env/grass.js deleted file mode 100644 index 95ad0ec6..00000000 --- a/e63334287a3deaa3/ironveil/env/grass.js +++ /dev/null @@ -1,501 +0,0 @@ -/* Midnight Ops environment: blade grass. - IVEnv.grass(surfaceAt, heightFn, opts) -> { group, update(camera), info(), dispose() } (also driven by IVEnv.update) - - Real triangle blades bent along a curve in the vertex shader (no camera-facing cards), one instanced mesh per ring. - - Placement is a hash of WORLD coordinates in fixed 8 m tiles: stratified jitter, Voronoi clumps (0.9 m) with their own - height, lean, facing and colour and a pull toward the clump centre; a slow patch noise picks the grass type and - shifts young green toward dry straw. The same field comes out in the game and on the test page. - - Rings: near (all blades, 3 segments on High), mid (a fixed random quarter-ish subset of the SAME blades, fewer - vertices, wider), then nothing: the ground shader carries the colour (see ground.js, which calls IVEnv.grassCarry). - The near ring thins to exactly the mid subset over its last metres, so the hand-over shows no line. - - Lighting: root AO, root colour from the ground, translucency (light from behind comes through, warmer), gloss on - the upper blade only, rounded "V" normal blended to up at the tip and with distance. Receives shadows, casts none. - - One wind field (IVEnv.setWind) with gust fronts; up to 8 pushers (IVEnv.setPushers) bend blades away and down. - surfaceAt(x, z) returns a kind name; kinds with grass: see KINDS below. opts.longAt(x, z) -> 0..1 adds length - (hedge feet, wall bases, fence lines, ditch edges). opts.densityAt(x, z) -> 0..1 multiplies density. - opts.nearMul / opts.carpetMul widen the near ring and the carpet for a world that wants a fuller field (Boot Camp). */ -(function () { - 'use strict'; - const E = window.IVEnv; - const TS = 8; // tile size, metres - - // Kinds: d = density multiplier, h = [min, max] height in metres, long = share of long meadow blades, tus = share of - // tussock, dead = share of dead blades, dry = dryness bias, ground = root colour (sRGB). - const KINDS = E.GRASS_KINDS = { - grass: { d: 0.95, fill: 0.15, h: [0.1, 0.26], long: 0.03, tus: 0.04, dead: 0.06, dry: 0.0, ground: 0x38331f, c: 1.0, ch: 1.0 }, - pasture: { d: 0.7, h: [0.08, 0.2], long: 0.02, tus: 0.03, dead: 0.06, dry: 0.0, ground: 0x38331f, c: 1.0, ch: 0.9 }, - meadow: { d: 1.0, h: [0.3, 0.7], long: 0.5, tus: 0.12, dead: 0.08, dry: 0.04, ground: 0x38331f, c: 0.85, ch: 1.2 }, - tussock: { d: 1.05, h: [0.45, 0.95], long: 0.45, tus: 0.4, dead: 0.2, dry: 0.1, ground: 0x34301e, c: 0.8, ch: 1.3 }, - verge: { d: 1.0, h: [0.25, 0.65], long: 0.35, tus: 0.3, dead: 0.15, dry: 0.06, ground: 0x35301f, c: 0.9, ch: 1.2 }, - lanemid: { d: 0.5, h: [0.08, 0.22], long: 0.03, tus: 0.1, dead: 0.2, dry: 0.1, ground: 0x2a2218, c: 0.7, ch: 0.8 }, - worn: { d: 0.6, h: [0.06, 0.16], long: 0.0, tus: 0.04, dead: 0.25, dry: 0.15, ground: 0x30281c, c: 0.9, ch: 0.75 }, - leaves: { d: 0.15, h: [0.1, 0.25], long: 0.1, tus: 0.0, dead: 0.3, dry: 0.2, ground: 0x2a2016, c: 0.2, ch: 0.8 }, - // lawn: well-kept camp turf, thick and green, a little longer than mown grass (Boot Camp) - lawn: { d: 1.0, fill: 0.3, h: [0.16, 0.36], long: 0.07, tus: 0.05, dead: 0.04, dry: 0.0, ground: 0x4f5a2c, c: 1.05, ch: 1.05 }, - // scorched: round shell holes and burnt ground, short dead stubble flattened outward, dark roots - scorched:{ d: 0.75, fill: 0.2, h: [0.03, 0.1], long: 0.0, tus: 0.0, dead: 0.75, dry: 0.6, ground: 0x1c1915, c: 0.7, ch: 0.45 }, - yardedge:{ d: 0.3, h: [0.06, 0.18], long: 0.0, tus: 0.1, dead: 0.25, dry: 0.15, ground: 0x2e2a22, c: 0.45, ch: 0.7 } - }; - // Blade colours (sRGB) shared by the shader and the ground's far colour - const PAL = E.GRASS_PAL = { young: 0x4f7434, green: 0x3f5a26, olive: 0x575a30, dry: 0x857246, dead: 0x5f5240 }; - - // ------------------------------------------------------------------ the field (JS, deterministic) - const H = (i, j, s) => IVEnvTexGen.hash2(i | 0, j | 0, s | 0); - const F = E.grassField = {}; - F.patch = (x, z) => E.fbm2(x / 11 + 31.7, z / 11 - 7.3, 501, 3); // grass type / dryness patches - F.dens = (x, z) => E.fbm2(x / 4.3 - 2.1, z / 4.3 + 9.4, 502, 2); // bare spots - F.clump = function (x, z, o) { // nearest clump centre on a 0.9 m jittered grid - const C = 0.9, ix = Math.floor(x / C), iz = Math.floor(z / C); let best = 1e9; - for (let j = -1; j <= 1; j++) for (let i = -1; i <= 1; i++) { - const cx = (ix + i + 0.15 + 0.7 * H(ix + i, iz + j, 71)) * C, cz = (iz + j + 0.15 + 0.7 * H(ix + i, iz + j, 72)) * C, d = (cx - x) ** 2 + (cz - z) ** 2; - if (d < best) { best = d; o.x = cx; o.z = cz; o.id = H(ix + i, iz + j, 73); o.d = Math.sqrt(d); } - } - return o; - }; - F.dry = (kind, x, z) => { const K = KINDS[kind] || KINDS.grass; return E.clamp(E.sstep(0.6, 0.85, F.patch(x, z) + K.dry), 0, 1) * 0.8; }; - // average colour of the grass as seen from a distance (linear), for the ground's far ring - const _c1 = new THREE.Color(), _c2 = new THREE.Color(); - F.carry = function (kind, x, z, out) { - const K = KINDS[kind]; if (!K) return out.setRGB(0, 0, 0); - const dry = F.dry(kind, x, z), p = F.patch(x * 1.7, z * 1.7); - out.copy(E.lin(PAL.green)).lerp(_c1.copy(E.lin(PAL.olive)), E.clamp(p, 0, 1) * 0.6); - out.lerp(_c1.copy(E.lin(PAL.dry)), dry * 0.85); - out.lerp(_c2.copy(E.lin(PAL.dead)), K.dead * 0.5); - out.lerp(_c2.copy(E.lin(K.ground)), 0.35); // soil between blades and the dark roots - return out; - }; - - // Generate one tile. Returns { full: Float32Array|null, mid: Float32Array, seed: Float32Array }, 12 floats per blade: - // x, y, z, facing | height, width, lean, type + rnd*0.99 | root r, g, b (linear), dry - const _cl = { x: 0, z: 0, id: 0, d: 0 }, _root = new THREE.Color(); - const rootCache = {}; - // cached surface kinds (0.5 m) and heights (0.25 m, bilinear) for one tile, so surfaceAt/heightFn run a few - // hundred times per tile instead of once per blade - function tileCache(G, x0, z0) { - const SN = TS * 2 + 1, HN = TS * 4 + 1, sk = new Array(SN * SN), hs = new Float32Array(HN * HN); - for (let j = 0; j < SN; j++) for (let i = 0; i < SN; i++) sk[j * SN + i] = G.surfaceAt(x0 + i * 0.5, z0 + j * 0.5); - for (let j = 0; j < HN; j++) for (let i = 0; i < HN; i++) hs[j * HN + i] = G.heightFn(x0 + i * 0.25, z0 + j * 0.25); - return { - kind(x, z) { const i = Math.min(SN - 1, Math.max(0, Math.round((x - x0) * 2))), j = Math.min(SN - 1, Math.max(0, Math.round((z - z0) * 2))); return sk[j * SN + i]; }, - h(x, z) { const fx = Math.min(HN - 1.001, Math.max(0, (x - x0) * 4)), fz = Math.min(HN - 1.001, Math.max(0, (z - z0) * 4)), i = fx | 0, j = fz | 0, u = fx - i, v = fz - j, k = j * HN + i; - return (hs[k] * (1 - u) + hs[k + 1] * u) * (1 - v) + (hs[k + HN] * (1 - u) + hs[k + HN + 1] * u) * v; } - }; - } - // genTileIter yields after every few rows, so the update can build a tile over several frames (no hitch); - // genTile runs one to the end in one go - function genTile(G, tx, tz, wantFull) { const it = genTileIter(G, tx, tz, wantFull); let r; while (!(r = it.next()).done); return r.value; } - function* genTileIter(G, tx, tz, wantFull) { - const Q = E.Q, dens = Q.grassDens, n = Math.ceil(Math.sqrt(dens * TS * TS)), cell = TS / n, midFrac = Math.min(1, Q.grassMidDens * (E._grassMidMul || 1) / Q.grassDens); - const full = wantFull ? [[], [], [], []] : null, mid = [], seed = [], carpet = wantFull ? [[], [], [], []] : null; - const x0 = tx * TS, z0 = tz * TS, TC = tileCache(G, x0, z0); - for (let j = 0; j < n; j++) { if (j % 4 === 3) yield; for (let i = 0; i < n; i++) { - const gi = tx * n + i, gj = tz * n + j; - const rnd = H(gi, gj, 11); - if (!wantFull && rnd >= midFrac) continue; - let x = x0 + (i + H(gi, gj, 12)) * cell, z = z0 + (j + H(gi, gj, 13)) * cell; - const kind = TC.kind(x, z), K = KINDS[kind]; if (!K) continue; - let d = K.d * E.sstep(0.18, 0.45, F.dens(x, z) + 0.12 + (K.fill || 0)); - if (G.densityAt) d *= G.densityAt(x, z); - if (H(gi, gj, 14) > d) continue; - F.clump(x, z, _cl); - const pull = 0.3 + 0.35 * _cl.id; x += (_cl.x - x) * pull; z += (_cl.z - z) * pull; - const y = TC.h(x, z); - const longK = G.longAt ? G.longAt(x, z) : 0; - // grass type: 0 short, 1 long meadow, 2 tussock, 3 dead - const tr = H(gi, gj, 15), pt = F.patch(x, z); - const pLong = E.clamp(K.long + longK * 0.6 + (pt - 0.5) * 0.4, 0, 1), pTus = K.tus + longK * 0.2, pDead = K.dead + (pt > 0.65 ? 0.12 : 0); - let type = 0; - if (tr < pDead) type = 3; else if (tr < pDead + pTus) type = 2; else if (tr < pDead + pTus + pLong) type = 1; - const hm = 0.72 + 0.6 * _cl.id, distC = _cl.d; - let h = (K.h[0] + (K.h[1] - K.h[0]) * Math.pow(H(gi, gj, 16), 0.8)) * hm * (1 + longK * 0.9) * (0.45 + 0.75 * Math.pow(H(gi, gj, 21), 0.6)); - if (type === 1) h *= 1.5; else if (type === 2) h *= 1.25; else if (type === 3) h *= 0.9; - h *= 1 - 0.25 * E.clamp(distC / 0.6, 0, 1); // taller in the middle of a clump - if (H(gi, gj, 22) < (type === 1 ? 0.3 : 0.5)) { h *= 0.22 + 0.3 * H(gi, gj, 23); if (type === 1) type = 0; } // undergrowth: short blades fill the base - const w = (type === 2 ? 0.04 : type === 1 ? 0.03 : type === 3 ? 0.025 : 0.032) * (0.75 + 0.5 * H(gi, gj, 17)) * (H(gi, gj, 24) < 0.15 ? 1.7 : 1); - // facing: blades of a clump fan out from its centre, with some randomness - const fan = Math.atan2(z - _cl.z, x - _cl.x); - const facing = fan + (H(gi, gj, 18) - 0.5) * 2.2 + _cl.id * 3; - const lean = (type === 3 ? 0.6 : type === 2 ? 0.5 : type === 1 ? 0.42 : 0.3) * (0.4 + 0.9 * H(gi, gj, 19)) + 0.3 * E.clamp(distC / 0.6, 0, 1) + (h > 0.5 ? (h - 0.5) * 0.6 : 0); - let rc = rootCache[kind]; if (!rc) rc = rootCache[kind] = E.lin(K.ground); - const dry = E.clamp(F.dry(kind, x, z) + (_cl.id - 0.5) * 0.25 + (type === 3 ? 0.6 : 0), 0, 1); - const rec = [x, y, z, facing, h, w, lean, type + rnd * 0.99, rc.r, rc.g, rc.b, dry]; - if (full) { const qd = (x - x0 >= TS / 2 ? 1 : 0) + (z - z0 >= TS / 2 ? 2 : 0); for (let k = 0; k < 12; k++) full[qd].push(rec[k]); } - if (rnd < midFrac) for (let k = 0; k < 12; k++) mid.push(rec[k]); - if (type === 1 && h > 0.35 && H(gi, gj, 20) < 0.09) for (let k = 0; k < 12; k++) seed.push(rec[k]); - } } - // the low carpet: many short broad-ish blades so no bare soil shows near the camera (3 vertices each) - if (carpet) { - const cn = Math.ceil(Math.sqrt(Q.carpetDens * TS * TS)), cc = TS / cn; - for (let j = 0; j < cn; j++) { if (j % 6 === 5) yield; for (let i = 0; i < cn; i++) { - const gi = tx * cn + i, gj = tz * cn + j; - let x = x0 + (i + H(gi, gj, 31)) * cc, z = z0 + (j + H(gi, gj, 32)) * cc; - { const ti = Math.floor(x / 0.42), tj = Math.floor(z / 0.42), tcx = (ti + 0.05 + 0.9 * H(ti, tj, 41)) * 0.42, tcz = (tj + 0.05 + 0.9 * H(ti, tj, 42)) * 0.42; x += (tcx - x) * 0.3; z += (tcz - z) * 0.3; } - const kind = TC.kind(x, z), K = KINDS[kind]; if (!K || !K.c) continue; - if (H(gi, gj, 33) > K.c * E.sstep(0.12, 0.4, F.dens(x, z) + 0.15)) continue; - const rnd = H(gi, gj, 34), y = TC.h(x, z); - const h = (0.05 + 0.11 * Math.pow(H(gi, gj, 35), 0.7)) * K.ch; - const w = 0.014 + 0.014 * H(gi, gj, 36); - let rc = rootCache[kind]; if (!rc) rc = rootCache[kind] = E.lin(K.ground); - const dry = E.clamp(F.dry(kind, x, z) * 0.8 + (H(gi, gj, 37) < 0.12 ? 0.5 : 0), 0, 1); - const rec = [x, y, z, H(gi, gj, 38) * 6.283, h, w, 0.35 + 0.6 * H(gi, gj, 39), 0 + rnd * 0.99, rc.r, rc.g, rc.b, dry]; - const qd = (x - x0 >= TS / 2 ? 1 : 0) + (z - z0 >= TS / 2 ? 2 : 0); for (let k = 0; k < 12; k++) carpet[qd].push(rec[k]); - } } - } - yield; - // carpet blades sorted by their random value: far quadrants upload only the first 55% (the shader keeps the same ones) - const sortRec = (a) => { const n = a.length / 12, idx = []; for (let i = 0; i < n; i++) idx.push(i); idx.sort((p, q) => (a[p * 12 + 7] % 1) - (a[q * 12 + 7] % 1)); const o = new Float32Array(a.length); idx.forEach((k, i) => { for (let c = 0; c < 12; c++) o[i * 12 + c] = a[k * 12 + c]; }); return o; }; - // packed a quadrant at a time, with a pause between, so the tail of a tile is no longer one long step - const fullF = full ? [] : null, carpetF = carpet ? [] : null; - if (full) for (const a of full) { fullF.push(new Float32Array(a)); yield; } - if (carpet) for (const a of carpet) { carpetF.push(sortRec(a)); yield; } - return { full: fullF, carpet: carpetF, mid: new Float32Array(mid), seed: new Float32Array(seed), ymin: 0, ymax: 0 }; - } - - // ------------------------------------------------------------------ blade geometry (per ring) - function bladeGeo(segs) { - // rows packed toward the tip, two vertices per row, one tip vertex - const rows = segs === 3 ? [0, 0.38, 0.7] : segs === 2 ? [0, 0.55] : [0]; - const t = [], s = [], idx = []; - rows.forEach(r => { t.push(r, r); s.push(-1, 1); }); - t.push(1); s.push(0); - for (let i = 0; i < rows.length - 1; i++) { const a = i * 2; idx.push(a, a + 1, a + 2, a + 1, a + 3, a + 2); } - const L = (rows.length - 1) * 2; idx.push(L, L + 1, L + 2); - const g = new THREE.InstancedBufferGeometry(); - g.setAttribute('position', new THREE.Float32BufferAttribute(new Float32Array(t.length * 3), 3)); - g.setAttribute('aT', new THREE.Float32BufferAttribute(t, 1)); g.setAttribute('aS', new THREE.Float32BufferAttribute(s, 1)); - // the shader makes the normal (beginnormal_vertex below); three r187 builds a flat-shaded program, without vNormal, - // for any geometry that has no normal attribute, so the blades carry an unused one - g.setAttribute('normal', new THREE.Float32BufferAttribute(new Float32Array(t.length * 3), 3)); - g.setIndex(idx); g.userData.tris = idx.length / 3; - return g; - } - function seedGeo() { // a loose drooping panicle: thin stem tip and narrow spikelets hanging off it - const o = [], idx = []; let v = 0; - const tri = (ax, ay, az, bx, by, bz, cx, cy, cz) => { o.push(ax, ay, az, bx, by, bz, cx, cy, cz); idx.push(v, v + 1, v + 2); v += 3; }; - tri(-0.0015, 0, 0, 0.0015, 0, 0, 0.004, 0.11, 0.002); - for (let k = 0; k < 7; k++) { - const y = 0.02 + k * 0.013, a = k * 2.4, len = 0.035 - k * 0.003, dx = Math.cos(a), dz = Math.sin(a); - const bx = dx * 0.003, bz = dz * 0.003, tx = dx * len * 0.8, tz = dz * len * 0.8, ty = y - len * 0.45; - tri(bx - dz * 0.0025, y, bz + dx * 0.0025, bx + dz * 0.0025, y, bz - dx * 0.0025, tx, ty, tz); - } - const g = new THREE.InstancedBufferGeometry(), n = o.length / 3; - g.setAttribute('position', new THREE.Float32BufferAttribute(o, 3)); - g.setAttribute('aT', new THREE.Float32BufferAttribute(new Array(n).fill(1), 1)); g.setAttribute('aS', new THREE.Float32BufferAttribute(new Array(n).fill(0), 1)); - g.setAttribute('normal', new THREE.Float32BufferAttribute(new Float32Array(n * 3), 3)); // unused (see bladeGeo) - g.setIndex(idx); g.userData.tris = idx.length / 3; return g; - } - - // ------------------------------------------------------------------ material - const BLADE_VS = ` - attribute float aT; attribute float aS; attribute vec4 iA; attribute vec4 iB; attribute vec4 iC; - uniform vec4 uPush[8]; uniform vec4 uRing; uniform float uWidthFar; - varying float vT; varying float vDry; varying float vType; varying vec3 vRoot; varying float vRnd; varying float vDist; varying float vEdge; varying vec3 vSideW; - ${E.GLSL.wind} - vec3 ivBlade(float t, float side, out vec3 N, out float keep) { - vec3 base = iA.xyz; float face = iA.w; float h = iB.x, w = iB.y, lean = iB.z; float type = floor(iB.w), rnd = fract(iB.w); - vec2 d2 = base.xz - cameraPosition.xz; float dist = length(d2); - // ring ownership + thinning: near ring hands over to the mid subset (rnd < uRing.w) over its last uRing.z metres - float fo = smoothstep(uRing.y - uRing.z, uRing.y, dist); - keep = step(uRing.x, dist) * step(dist, uRing.y); - #ifdef IV_CARPET - // full density right at the lens, thinning to 55% past 4 m; close blades broader, lower, leaning more - keep *= step(rnd, mix(1.0, 0.55, smoothstep(2.5, 4.5, dist))); - float nearK = 1.0 - smoothstep(2.0, 4.0, dist); - float broad = step(fract(rnd * 7.7), 0.35); - w *= 1.0 + nearK * broad * 1.4; h *= 1.0 - nearK * 0.2; lean += nearK * 0.25; - #endif - #ifdef IV_NEAR - keep *= step(rnd, mix(1.0, uRing.w, fo)); - #else - keep *= step(rnd / uRing.w, 1.0 - fo); - h *= 1.0 - fo * 0.85; - #endif - h *= keep; - vec2 fd = vec2(cos(face), sin(face)); - vec2 toCam = dist > 1e-3 ? -d2 / dist : vec2(1.0, 0.0); - float e = dot(fd, toCam); - // nearly edge-on blades twist toward the viewer so they do not vanish - fd = mix(fd, toCam * (e < 0.0 ? -1.0 : 1.0), 0.45 * (1.0 - abs(e))); fd = length(fd) > 1e-4 ? normalize(fd) : vec2(1.0, 0.0); - vec2 sd = vec2(-fd.y, fd.x); - // wind + pushers + the blade's own lean (squared along the blade so the root stays put) - vec2 wv = ivWind(base.xz) * (0.55 + 0.6 * rnd) * (type > 2.5 ? 0.6 : 1.0); - vec2 pv = vec2(0.0); float flat_ = 0.0; - for (int i = 0; i < 8; i++) { - vec4 P = uPush[i]; if (P.z <= 0.0) continue; - vec2 dd = base.xz - P.xy; float l = length(dd); float f = clamp(1.0 - l / P.z, 0.0, 1.0); f = f * f * P.w; - pv += dd / max(l, 1e-3) * f * 1.6; flat_ = max(flat_, f); - } - vec2 off = fd * lean + wv * 0.9 + pv; - float ol = length(off); if (ol > 0.9) off *= 0.9 / ol; ol = min(ol, 0.9); - float tt = t * t; - float y = h * t * sqrt(max(0.05, 1.0 - 0.55 * ol * ol * t)) * (1.0 - flat_ * 0.55 * t); - float fold = step(0.955, fract(rnd * 31.7)) * step(0.15, h) * max(t - 0.55, 0.0); // a few broken blades flop over - vec2 xz = off * h * (0.45 * tt + 0.4 * tt * t); - y -= fold * h * 1.6; xz += fd * fold * h * 1.2; - float wm = 1.0 + (uWidthFar - 1.0) * smoothstep(4.0, 45.0, dist); - float hw = w * wm * 0.5 * (1.0 - pow(t, 1.3)) * (type > 1.5 && type < 2.5 ? 1.2 : 1.0) * keep; - vec3 p = base + vec3(xz.x, y, xz.y) + vec3(sd.x, 0.0, sd.y) * side * hw; - // normal: across-blade rounding ("V"), tangent from the curve, blended to up at the tip and with distance - vec3 T = normalize(vec3(off.x * (0.9 * t + 1.2 * tt), 1.0, off.y * (0.9 * t + 1.2 * tt))); - vec3 S = vec3(sd.x, 0.0, sd.y); - vec3 n = normalize(cross(S, T)); - if (dot(n.xz, toCam) < 0.0) n.xz = -n.xz; - vSideW = S; - n = normalize(mix(n, vec3(0.0, 1.0, 0.0), clamp(0.55 + 0.3 * tt + 0.4 * smoothstep(6.0, 35.0, dist), 0.0, 0.95))); - N = n; - vT = t; vDry = iC.w; vType = type; vRoot = iC.rgb; vRnd = rnd; vDist = dist; vEdge = side; - return p; - } - `; - function bladeMaterial(near, seedHeads, carpet) { - const m = new THREE.MeshStandardMaterial({ side: THREE.DoubleSide, roughness: 0.6, metalness: 0, envMapIntensity: 0.6 }); - m.userData.linear = true; - const uni = { - uTime: E.U.uTime, uWind: E.U.uWind, uPush: E.U.uPush, uWet: E.U.uWet, - uRing: { value: new THREE.Vector4(0, 15, 3, 0.2) }, uWidthFar: { value: 2.6 }, - cYoung: { value: E.lin(PAL.young) }, cGreen: { value: E.lin(PAL.green) }, cOlive: { value: E.lin(PAL.olive) }, cDry: { value: E.lin(PAL.dry) }, cDead: { value: E.lin(PAL.dead) }, - uTrans: { value: 1.0 } - }; - m.userData.uniforms = uni; - m.defines = { IV_GRASS: '' }; if (near) m.defines.IV_NEAR = ''; if (carpet) m.defines.IV_CARPET = ''; if (seedHeads) m.defines.IV_SEED = ''; - m.onBeforeCompile = function (sh) { - Object.assign(sh.uniforms, uni); - const P = (stage, a, b) => E.patch(sh, stage, a, b, 'env/grass ' + (near ? 'near' : 'mid') + (carpet ? ' carpet' : '') + (seedHeads ? ' seeds' : '')); - P('vertex', '#include ', ` - vec3 ivN; float ivKeep; - #ifdef IV_SEED - vec3 ivTip = ivBlade(1.0, 0.0, ivN, ivKeep); - vec3 ivTip2 = ivBlade(0.9, 0.0, ivN, ivKeep); - vec3 ivUp = normalize(ivTip - ivTip2); vec3 ivX = normalize(cross(ivUp, vec3(0.0, 0.0, 1.0) + 0.001)); vec3 ivZ = cross(ivX, ivUp); - vec3 ivP = ivTip + (ivX * position.x + ivUp * position.y + ivZ * position.z) * (0.7 + 0.6 * vRnd) * ivKeep; - ivN = normalize(ivZ + ivUp * 0.3); vT = 1.0; - #else - vec3 ivP = ivBlade(aT, aS, ivN, ivKeep); - #endif - vec3 objectNormal = ivN;`); - P('vertex', '#include ', 'vec3 transformed = ivP;'); - sh.vertexShader = BLADE_VS + sh.vertexShader; - // r187: the light's colour already carries r128's factor PI (lib/three's compat layer), so the light through - // the blade is not multiplied by PI again; geometry.normal / .viewDir are geometryNormal / geometryViewDir, and - // normal_fragment_begin declares nonPerturbedNormal (r128: geometryNormal) - P('fragment', '#include ', THREE.ShaderChunk.lights_physical_pars_fragment); - P('fragment', 'vec3 irradiance = dotNL * directLight.color;', `vec3 irradiance = dotNL * directLight.color; - { - // light coming through the blade from behind (relative to the viewer): warmer, more saturated - float back = saturate(dot(-geometryNormal, directLight.direction)); - float scat = pow(saturate(dot(-geometryViewDir, directLight.direction)), 3.0); - vec3 tr = ivTransCol * directLight.color * (back * 0.55 + scat * 0.9) * ivTransAmt; - reflectedLight.directDiffuse += tr * RECIPROCAL_PI; - }`); - const HEAD = ` - uniform vec3 cYoung, cGreen, cOlive, cDry, cDead; uniform float uWet, uTrans; - varying float vT; varying float vDry; varying float vType; varying vec3 vRoot; varying float vRnd; varying float vDist; varying float vEdge; varying vec3 vSideW; - vec3 ivTransCol; float ivTransAmt; - `; - P('fragment', '#include ', ` - float faceDirection = gl_FrontFacing ? 1.0 : -1.0; - vec3 normal = normalize(vNormal); - // folded leaf: each half of the blade tilts away from the midrib, so the highlight shows the crease - vec3 sideV = normalize((viewMatrix * vec4(vSideW, 0.0)).xyz); - float crease = 0.55 * (1.0 - smoothstep(4.0, 14.0, vDist)); - normal = normalize(normal + sideV * clamp(vEdge * 4.0, -1.0, 1.0) * crease); - vec3 nonPerturbedNormal = normal;`); - P('fragment', '#include ', ` - vec3 tip = mix(cGreen, cYoung, smoothstep(0.55, 0.95, vRnd)); - tip = mix(tip, cOlive, smoothstep(0.3, 0.7, fract(vRnd * 7.3)) * 0.6); - tip = mix(tip, cDry, vDry * 0.9); - tip = mix(tip, cDead, step(2.5, vType) * 0.7); - tip = mix(tip, cDry * 0.9, smoothstep(0.82, 0.97, vT) * step(0.6, fract(vRnd * 13.1)) * 0.8); - tip *= 0.86 + 0.24 * (1.0 - abs(vEdge)); - tip = mix(tip, tip * 1.25 + vec3(0.012, 0.01, 0.0), smoothstep(0.6, 1.0, vT)); // lighter, slightly yellowed toward the tip - vec3 col = mix(vRoot, tip, smoothstep(0.0, 0.6, vT)); - float ao = mix(0.42, 1.0, pow(clamp(vT, 0.0, 1.0), 0.55)); - col *= ao * (1.0 - uWet * 0.3); - diffuseColor.rgb = col; - ivTransCol = tip * vec3(1.25, 1.4, 0.55) * smoothstep(0.1, 0.7, vT) * (1.0 - vDry * 0.4); - ivTransAmt = uTrans; - `); - P('fragment', '#include ', ` - float roughnessFactor = mix(0.95, 0.5, smoothstep(0.35, 0.85, vT)); - roughnessFactor = mix(roughnessFactor, 0.9, smoothstep(8.0, 30.0, vDist)); - roughnessFactor = mix(roughnessFactor, 0.85, smoothstep(2.0, 0.6, vDist)); // no glare right at the lens - roughnessFactor = mix(roughnessFactor, roughnessFactor * 0.55, uWet);`); - P('fragment', '#include ', 'reflectedLight.indirectDiffuse *= ao; reflectedLight.indirectSpecular *= ao;'); - sh.fragmentShader = HEAD + sh.fragmentShader; - }; - m.customProgramCacheKey = () => 'ivgrass' + (near ? 'n' : 'm') + (seedHeads ? 's' : '') + (carpet ? 'c' : ''); - return m; - } - - // ------------------------------------------------------------------ the system - function Ring(G, name, segs, cap, near, seed) { - const geo = seed ? seedGeo() : bladeGeo(segs); - const buf = new THREE.InstancedInterleavedBuffer(new Float32Array(cap * 12), 12, 1); - buf.setUsage(THREE.DynamicDrawUsage); - geo.setAttribute('iA', new THREE.InterleavedBufferAttribute(buf, 4, 0)); - geo.setAttribute('iB', new THREE.InterleavedBufferAttribute(buf, 4, 4)); - geo.setAttribute('iC', new THREE.InterleavedBufferAttribute(buf, 4, 8)); - geo.instanceCount = 0; - const mat = bladeMaterial(near, seed, name === 'carpet'); - const mesh = new THREE.Mesh(geo, mat); - mesh.frustumCulled = false; mesh.receiveShadow = true; mesh.castShadow = false; mesh.name = 'grass-' + name; - return { name, geo, buf, cap, mesh, mat, count: 0, key: '' }; - } - - E.grass = function (surfaceAt, heightFn, opts) { - const lowQ = E.Q.name === 'low'; if (lowQ && opts) opts = Object.assign({}, opts, { nearMul: 1, carpetMul: 1, midMul: 1 }); // Low keeps the plain rings - E._grassMidMul = (opts && opts.midMul) || 1; // opts.midMul thickens the mid ring (same blades, a larger share kept) - opts = opts || {}; - const Q = E.Q; - const G = { - surfaceAt, heightFn, longAt: opts.longAt, densityAt: opts.densityAt, - group: new THREE.Group(), tiles: new Map(), pending: [], - rNear: opts.near || Q.grassNear * (opts.nearMul || 1), rMid: opts.mid || Q.grassMid - }; - G.group.name = 'IVEnv.grass'; - const nearCap = Math.ceil(Math.PI * (G.rNear + TS * 1.5) ** 2 * Q.grassDens * 0.9); - const midCap = Math.ceil(Math.PI * (G.rMid + TS * 1.5) ** 2 * Q.grassMidDens * (E._grassMidMul || 1) * 0.9); - G.near = Ring(G, 'near', Q.bladeSegs, nearCap, true, false); - G.rCarpet = Math.min(G.rNear, Q.carpetR * (opts.carpetMul || 1)); - G.carpet = Ring(G, 'carpet', Q.carpetSegs || (Q.name === 'low' ? 1 : 2), Math.ceil(Math.PI * (G.rCarpet + 6) ** 2 * Q.carpetDens * 0.75), true, false); - G.mid = Ring(G, 'mid', 1, midCap, false, false); - G.rings = [G.carpet, G.near, G.mid]; - if (Q.seedHeads) { G.seedN = Ring(G, 'seedNear', 0, Math.ceil(nearCap * 0.15), true, true); G.rings.push(G.seedN); } - const midFrac = Math.min(1, Q.grassMidDens * (E._grassMidMul || 1) / Q.grassDens), fadeN = Math.min(4, G.rNear * 0.3), fadeM = Math.min(10, G.rMid * 0.3); - for (const r of G.rings) { - const u = r.mat.userData.uniforms.uRing.value; - if (r.name === 'carpet') { u.set(0, G.rCarpet, Math.min(3, G.rCarpet * 0.4), 0); G.group.add(r.mesh); continue; } - if (r.name.indexOf('ear') >= 0 || r.name === 'near') u.set(0, G.rNear, fadeN, midFrac); - else u.set(G.rNear, G.rMid, fadeM, midFrac); - u.w = midFrac; - G.group.add(r.mesh); - } - - const frustum = new THREE.Frustum(), pm = new THREE.Matrix4(), box = new THREE.Box3(), v0 = new THREE.Vector3(), v1 = new THREE.Vector3(); - function tileKey(tx, tz) { return tx + ',' + tz; } - function getTile(tx, tz, wantFull) { - const k = tileKey(tx, tz); let t = G.tiles.get(k); - if (t && (!wantFull || t.full)) return t; - return null; - } - function keepTile(tx, tz, t) { - // vertical bounds for culling - let y0 = 1e9, y1 = -1e9; for (let i = 0; i < 9; i++) { const y = heightFn(tx * TS + (i % 3) * TS / 2, tz * TS + Math.floor(i / 3) * TS / 2); y0 = Math.min(y0, y); y1 = Math.max(y1, y); } - t.ymin = y0 - 0.5; t.ymax = y1 + 1.5; t.tx = tx; t.tz = tz; - G.tiles.set(tileKey(tx, tz), t); return t; - } - function makeTile(tx, tz, wantFull) { return keepTile(tx, tz, genTile(G, tx, tz, wantFull)); } - // Tiles are built ahead of the camera, a few rows at a time within a small budget per frame (G.jobs), so walking - // or sprinting into new ground never builds several whole tiles in one frame (that was a 20-140 ms hitch each - // time you crossed a tile edge). Full (near) tiles are made out to half a tile beyond the near ring, so they are - // ready before you reach them; only a tile right under the camera with nothing at all (a teleport, a respawn) - // is still made at once. - G.jobs = new Map(); - const JOB_MS = 1.5, PREFETCH = TS / 2; - function request(tx, tz, full, pri) { - const k = tileKey(tx, tz) + (full ? 'f' : 'm'); let j = G.jobs.get(k); - if (!j) { j = { tx, tz, full, it: null, pri }; G.jobs.set(k, j); } - j.pri = Math.min(j.pri, pri); j.seen = G.frameNo; - } - function pumpJobs(budget) { - if (!G.jobs.size) return; - const list = [...G.jobs.values()].filter(j => j.seen === G.frameNo || j.it); // drop requests we no longer need (unless started) - for (const [k, j] of G.jobs) if (j.seen !== G.frameNo && !j.it) G.jobs.delete(k); - list.sort((a, b) => a.pri - b.pri); - const t0 = performance.now(); - for (const j of list) { - const have = G.tiles.get(tileKey(j.tx, j.tz)); - if (have && (have.full || !j.full)) { G.jobs.delete(tileKey(j.tx, j.tz) + (j.full ? 'f' : 'm')); continue; } - if (!j.it) j.it = genTileIter(G, j.tx, j.tz, j.full); - let r; - while (!(r = j.it.next()).done) if (performance.now() - t0 > budget) return; - keepTile(j.tx, j.tz, r.value); G.jobs.delete(tileKey(j.tx, j.tz) + (j.full ? 'f' : 'm')); G.built = (G.built || 0) + 1; - if (performance.now() - t0 > budget) return; - } - } - G.genMs = 0; G.frameNo = 0; - G._genIter = (tx, tz, full) => genTileIter(G, tx, tz, full); // tests: time one tile's steps - G.update = function (camera, budgetMs) { - const t0 = performance.now(); budgetMs = budgetMs == null ? 6 : budgetMs; - camera.updateMatrixWorld(); pm.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse); frustum.setFromProjectionMatrix(pm); - const cx = camera.position.x, cz = camera.position.z; - const lists = { near: [], mid: [] }; - G.frameNo++; let nearMissing = 0; - const R = G.rMid + TS, i0 = Math.floor((cx - R) / TS), i1 = Math.floor((cx + R) / TS), j0 = Math.floor((cz - R) / TS), j1 = Math.floor((cz + R) / TS); - for (let tz = j0; tz <= j1; tz++) for (let tx = i0; tx <= i1; tx++) { - // distance from the camera to the tile rectangle - const dx = Math.max(tx * TS - cx, 0, cx - (tx + 1) * TS), dz = Math.max(tz * TS - cz, 0, cz - (tz + 1) * TS), d = Math.hypot(dx, dz); - if (d > G.rMid) continue; - const inNear = d <= G.rNear; - // build ahead: full detail out to half a tile past the near ring - if (d <= G.rNear + PREFETCH && !getTile(tx, tz, true)) request(tx, tz, true, d - (inNear ? 100 : 0)); - let t = getTile(tx, tz, inNear); - if (!t) { - if (!G.warm || (inNear && d < 2.5 && !G.tiles.get(tileKey(tx, tz)))) t = makeTile(tx, tz, inNear); // loading, or nothing at all under the camera - else { - t = G.tiles.get(tileKey(tx, tz)); // a mid tile still works for the mid ring while its full version is built - if (!inNear) request(tx, tz, false, d + 50); - if (!t) { if (inNear) nearMissing++; G.pending++; continue; } - if (inNear && !t.full) { nearMissing++; if (d + TS * 1.5 > G.rNear) lists.mid.push(t); continue; } - } - } - box.min.set(tx * TS - 1.5, t.ymin, tz * TS - 1.5); box.max.set((tx + 1) * TS + 1.5, t.ymax, (tz + 1) * TS + 1.5); - if (d > 3 && !frustum.intersectsBox(box)) continue; - if (inNear) for (let qd = 0; qd < 4; qd++) { - const qx = tx * TS + (qd & 1) * TS / 2, qz = tz * TS + (qd >> 1) * TS / 2; - const ddx = Math.max(qx - cx, 0, cx - qx - TS / 2), ddz = Math.max(qz - cz, 0, cz - qz - TS / 2), dq = Math.hypot(ddx, ddz); - if (dq > G.rNear) continue; - box.min.set(qx - 1.2, t.ymin, qz - 1.2); box.max.set(qx + TS / 2 + 1.2, t.ymax, qz + TS / 2 + 1.2); - if (dq > 2 && !frustum.intersectsBox(box)) continue; - lists.near.push({ t, qd, dq, tx: t.tx * 2 + (qd & 1), tz: t.tz * 2 + (qd >> 1) }); - } - if (d + TS * 1.5 > G.rNear) lists.mid.push(t); - } - const tJ = performance.now(); pumpJobs(nearMissing ? JOB_MS * 2 : JOB_MS); // (the first update builds what it draws itself, above; the ring ahead follows over the next frames) // catch up faster when near grass is missing (after a teleport) - G.tJobs = performance.now() - tJ; const tF = performance.now(); - fill(G.near, lists.near, 'full'); - fill(G.carpet, lists.near.filter(e => e.dq <= G.rCarpet), 'carpet'); - lists.nearT = []; { const seen = new Set(); for (const e of lists.near) if (!seen.has(e.t)) { seen.add(e.t); lists.nearT.push(e.t); } } - fill(G.mid, lists.mid, 'mid'); - if (G.seedN) fill(G.seedN, lists.nearT, 'seed'); if (G.seedM) fill(G.seedM, lists.mid, 'seed', 'mid'); - G.tFill = performance.now() - tF; - // forget tiles far away - if (G.tiles.size > 600) for (const [k, t] of G.tiles) { if (Math.hypot((t.tx + 0.5) * TS - cx, (t.tz + 0.5) * TS - cz) > G.rMid + 40) G.tiles.delete(k); } - G.warm = true; G.genMs = performance.now() - t0; - }; - function fill(ring, tiles, field, alt) { - const key = field + tiles.map(t => t.tx + ':' + t.tz + (t.qd != null ? 'q' + t.qd + (field === 'carpet' && t.dq > 4.5 ? 'f' : '') : '')).join('|'); - if (key === ring.key) return; ring.key = key; - const arr = ring.buf.array; let n = 0; - const midFrac2 = midFrac; - for (const t of tiles) { - let src = (field === 'full' || field === 'carpet') ? t.t[field][t.qd] : t[field]; - if (field === 'carpet' && t.dq > 4.5) src = src.subarray(0, Math.floor(src.length / 12 * 0.55) * 12); - if (field === 'seed' && alt === 'mid') { // seed heads of mid blades only (rnd < midFrac) - const out = []; for (let i = 0; i < src.length; i += 12) if (src[i + 7] % 1 < midFrac2) for (let k = 0; k < 12; k++) out.push(src[i + k]); src = out; - } - const cnt = Math.min(src.length / 12, ring.cap - n); if (cnt <= 0) break; - if (src.subarray) arr.set(src.subarray(0, cnt * 12), n * 12); else arr.set(src.slice(0, cnt * 12), n * 12); - n += cnt; - } - ring.count = n; ring.geo.instanceCount = n; - ring.buf.updateRange.offset = 0; ring.buf.updateRange.count = n * 12; ring.buf.needsUpdate = true; - } - G.info = function () { - const o = { drawCalls: 0, triangles: 0, rings: {} }; - for (const r of G.rings) { const tris = r.count * r.geo.userData.tris; o.rings[r.name] = { blades: r.count, triangles: tris }; if (r.count) { o.drawCalls++; o.triangles += tris; } } - return o; - }; - G.setVisible = (v) => { G.group.visible = v; }; - // For the game's automatic quality scaling: 0.4..1 shrinks every ring (mid first, carpet last) without a reload. - G.baseR = { near: G.rNear, mid: G.rMid, carpet: G.rCarpet }; - G.setScale = function (k) { - k = E.clamp(k, 0.3, 1); G.scale = k; - G.rMid = G.baseR.mid * k; G.rNear = Math.min(G.baseR.near, G.baseR.near * (0.5 + 0.5 * k)); G.rCarpet = Math.min(G.rNear, G.baseR.carpet * (0.7 + 0.3 * k)); - for (const r of G.rings) { const u = r.mat.userData.uniforms.uRing.value; if (r.name === 'carpet') u.set(0, G.rCarpet, Math.min(3, G.rCarpet * 0.4), 0); else if (r.name === 'near' || r.name === 'seedNear') { u.x = 0; u.y = G.rNear; } else { u.x = G.rNear; u.y = G.rMid; } r.key = ''; } - }; - G.counts = () => ({ near: G.rNear, mid: G.rMid, carpet: G.rCarpet, dens: E.Q.grassDens, midDens: E.Q.grassMidDens, carpetDens: E.Q.carpetDens }); - G.dispose = function () { for (const r of G.rings) { r.geo.dispose(); r.mat.dispose(); } G.tiles.clear(); }; - (E._systems = E._systems || []).push(G); - return G; - }; -})(); diff --git a/e63334287a3deaa3/ironveil/env/ground.js b/e63334287a3deaa3/ironveil/env/ground.js deleted file mode 100644 index dc8b8ba1..00000000 --- a/e63334287a3deaa3/ironveil/env/ground.js +++ /dev/null @@ -1,435 +0,0 @@ -/* Midnight Ops environment: the ground. - IVEnv.ground(heightFn, opts) -> { group, material, meshes, heightFn } - opts: { surfaceAt(x,z) -> kind, x0, z0, x1, z1 (or size, centred on 0), step (m, default 1 / 1.5 / 2 by quality), - chunk (m, default 64) } - Kinds: grass, lawn, pasture, meadow, tussock, verge, lanemid, worn, leaves, yardedge (grass kinds, see grass.js) and - lane, mud, yard, road, gravel, cobbles, field, water, floor, none. - Five height-blended layers (turf, mud, ploughed earth, gravel, leaf litter), each sampled at two unrelated scales and - mixed by slow noise so nothing tiles; large-scale colour variation; standing water in low wet spots (ruts, puddles) - that reflects the sky and the lamps; and where there is grass, the far ground takes on the grass colour so the - field does not change where blades end. Normals come from the height function, not the triangles. */ -(function () { - 'use strict'; - const E = window.IVEnv; - // weights: [turf, mud, earth, gravel, leaves, wet] - const W = E.GROUND_KINDS = { - grass: [1, 0.15, 0, 0, 0, 0], lawn: [1, 0.06, 0, 0, 0, 0], pasture: [1, 0.1, 0, 0, 0, 0], meadow: [1, 0.1, 0, 0, 0.05, 0], tussock: [1, 0.2, 0, 0, 0.1, 0.1], verge: [1, 0.25, 0, 0, 0.1, 0.1], - lanemid: [0.6, 0.6, 0, 0.1, 0, 0.2], scorched: [0.3, 0.75, 0.25, 0, 0, 0.25], worn: [0.45, 0.7, 0, 0.1, 0, 0.2], leaves: [0.2, 0.2, 0, 0, 1, 0.1], yardedge: [0.35, 0.6, 0, 0.4, 0, 0.3], - lane: [0, 1, 0, 0.12, 0, 0.85], mud: [0, 1, 0, 0, 0, 0.9], yard: [0.06, 0.8, 0.12, 0.55, 0, 0.6], road: [0, 0.25, 0, 1, 0, 0.35], gravel: [0, 0.2, 0, 1, 0, 0.3], - cobbles: [0, 0.3, 0, 1, 0, 0.4], field: [0, 0.15, 1, 0, 0, 0.1], water: [0, 1, 0, 0.3, 0, 1.0], floor: [0, 0.4, 0, 0.6, 0, 0], none: [0, 0.6, 0, 0.4, 0, 0] - }; - const LAYERS = ['grass_ground', 'mud', 'earth', 'gravel', 'leaves']; - - // average linear luminance (0.3, 0.5, 0.2) of an sRGB DataTexture, sampled sparsely - function meanLum(t) { - const d = t && t.image && t.image.data; if (!d) return 0.045; let s = 0, n = 0; - const L = (v) => { v /= 255; return v <= 0.04045 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4); }; - for (let i = 0; i < d.length; i += 4 * 97) { s += 0.3 * L(d[i]) + 0.5 * L(d[i + 1]) + 0.2 * L(d[i + 2]); n++; } - return Math.max(0.01, s / n); - } - // water depth at a point, metres (negative = below the water line): level from the wet map + three octaves of the - // macro noise texture (about 40, 15 and 5 cm features) + rain. E_WD_GLSL and E.wetMap.depth do the same sums. - const E_WD_GLSL = '(wm.r - 0.55) + (texture2D(uMacro, gp * 0.31).r - 0.5) * 0.12 + (texture2D(uMacro, gp * 0.83 + 0.21).g - 0.5) * 0.06 + (texture2D(uMacro, gp * 2.6 + 0.57).b - 0.5) * 0.03 + uWet * 0.04'; - function groundMaterial() { - const T = LAYERS.map(n => E.tex[n]); - const m = new THREE.MeshStandardMaterial({ roughness: 1, metalness: 0, normalMap: T[0].nri, envMapIntensity: 1 }); - m.userData.linear = true; - const uni = { - uMacro: E.U.uMacro, uWet: E.U.uWet, uRain: E.U.uRain, uTime: E.U.uTime, uNight: E.U.uNight, - uA0: { value: T[0].alb }, uA1: { value: T[1].alb }, uA2: { value: T[2].alb }, uA3: { value: T[3].alb }, uA4: { value: T[4].alb }, - uN0: { value: T[0].nri }, uN1: { value: T[1].nri }, uN2: { value: T[2].nri }, uN3: { value: T[3].nri }, uN4: { value: T[4].nri }, - uSz: { value: LAYERS.map((n, i) => 1 / ((E.RECIPES[n] && E.RECIPES[n].size) || [2.5, 3.0, 3.0, 0.85, 2.0][i])) }, // each layer at its real size - uMarks: { value: E.marks.tex() }, uMarksRect: { value: E.marks.rect }, - uWetMap: { value: E.wetMap.tex() }, uWetRect: { value: E.wetMap.rect }, - uCarry: { value: new THREE.Vector2(E.Q.grassNear * 0.45, E.Q.grassMid * 0.95) }, - uTl0: { value: meanLum(T[0].alb) } // the grass layer's own average brightness (scans differ from the generator's) - }; - m.userData.uniforms = uni; - const LOW = E.Q.name === 'low'; - m.onBeforeCompile = function (sh) { - Object.assign(sh.uniforms, uni); - const P = (stage, a, b) => E.patch(sh, stage, a, b, 'env/ground'); - P('vertex', '#include ', '#include \n vW0 = aW0; vW1 = aW1; vGC = aGC; vGW = (modelMatrix * vec4(transformed, 1.0)).xyz;'); - sh.vertexShader = 'attribute vec4 aW0; attribute vec4 aW1; attribute vec4 aGC;\nvarying vec4 vW0; varying vec4 vW1; varying vec4 vGC; varying vec3 vGW;\n' + sh.vertexShader; - // the sRGB layers are sampled raw and decoded here (sRGBTransferEOTF is r128's sRGBToLinear); the ground's normal - // map UV is vNormalMapUv (r128's vUv) - const HEAD = (LOW ? "#define IV_GROUND_LOW\n" : "") + ` - uniform sampler2D uMarks; uniform vec4 uMarksRect; uniform sampler2D uWetMap; uniform vec4 uWetRect; - uniform sampler2D uMacro, uA0, uA1, uA2, uA3, uA4, uN0, uN1, uN2, uN3, uN4; uniform float uSz[5]; uniform float uWet, uRain, uTime, uTl0, uNight; uniform vec2 uCarry; - vec2 ivRipple(vec2 p, float t) { vec2 cell = floor(p), f = fract(p) - 0.5; float r = fract(sin(dot(cell, vec2(12.9898, 78.233))) * 43758.5453); float ph = fract(t * 1.4 + r * 7.0); - vec2 d = f - (vec2(fract(r * 13.1), fract(r * 27.7)) - 0.5) * 0.5; float dist = length(d); float ring = sin((dist - ph * 0.45) * 45.0) * smoothstep(0.06, 0.0, abs(dist - ph * 0.45)) * (1.0 - ph); return normalize(d + 1e-5) * ring; } - varying vec4 vW0; varying vec4 vW1; varying vec4 vGC; varying vec3 vGW; - void ivLay(sampler2D A, sampler2D N, float s, vec2 p, float m, out vec4 a, out vec4 n) { - vec2 uv = p * s; - a = texture2D(A, uv); n = texture2D(N, uv); - ${LOW ? '' : ` - vec2 uv2 = vec2(p.x * 0.8 - p.y * 0.6, p.x * 0.6 + p.y * 0.8) * s * 0.37 + vec2(0.31, 0.73); - vec4 a2 = texture2D(A, uv2), n2 = texture2D(N, uv2); float t = smoothstep(0.3, 0.7, m); - a = mix(a, a2, t); n = mix(n, n2, t);`} - } - `; - P('fragment', '#include ', ` - vec2 gp = vGW.xz; - float mA = texture2D(uMacro, gp * 0.012).r, mB = texture2D(uMacro, gp * 0.047 + 0.4).g, mC = texture2D(uMacro, gp * 0.21).b; - vec4 a0, a1, a2, a3, a4, n0, n1, n2, n3, n4; - ivLay(uA0, uN0, uSz[0], gp, mA, a0, n0); ivLay(uA1, uN1, uSz[1], gp, mB, a1, n1); ivLay(uA2, uN2, uSz[2], gp, mA, a2, n2); - ivLay(uA3, uN3, uSz[3], gp, mB, a3, n3); ivLay(uA4, uN4, uSz[4], gp, mA, a4, n4); - // weights wander with noise so borders are ragged, then height-blend (stones and clumps poke through) - vec4 w0 = vW0; float w4 = vW1.x; - w0 += (vec4(mB, 1.0 - mB, mA, mC) - 0.5) * 0.5 * step(0.02, w0); - w4 += (mC - 0.5) * 0.4 * step(0.02, w4); - float b0 = a0.a * 0.6 + w0.x, b1 = a1.a * 0.6 + w0.y, b2 = a2.a * 0.6 + w0.z, b3 = a3.a * 0.6 + w0.w, b4 = a4.a * 0.6 + w4; - float mx = max(max(max(b0, b1), max(b2, b3)), b4) - 0.22; - b0 = max(b0 - mx, 0.0) * step(0.01, w0.x); b1 = max(b1 - mx, 0.0) * step(0.01, w0.y); b2 = max(b2 - mx, 0.0) * step(0.01, w0.z); - b3 = max(b3 - mx, 0.0) * step(0.01, w0.w); b4 = max(b4 - mx, 0.0) * step(0.01, w4); - float bs = max(1e-4, b0 + b1 + b2 + b3 + b4); - // bare soil and mud: dark, cool and less red (the scans are warm; under the moon earth is barely lighter than grass shade) - { float l1 = dot(a1.rgb, vec3(0.3, 0.55, 0.15)), l2 = dot(a2.rgb, vec3(0.3, 0.55, 0.15)); a1.rgb = mix(a1.rgb, vec3(l1) * vec3(0.98, 0.96, 0.95), 0.45) * 0.86; a2.rgb = mix(a2.rgb, vec3(l2) * vec3(0.98, 0.96, 0.94), 0.5) * 0.8; } - vec4 ga = (a0 * b0 + a1 * b1 + a2 * b2 + a3 * b3 + a4 * b4) / bs; - vec4 gn = (n0 * b0 + n1 * b1 + n2 * b2 + n3 * b3 + n4 * b4) / bs; - vec3 galb = sRGBTransferEOTF(vec4(ga.rgb, 1.0)).rgb; - float gh = ga.a, grough = gn.b; - galb *= mix(0.72, 1.18, mA) * mix(0.9, 1.08, mC); - // at night the soil reads as dark, damp earth: darker and warmer (pale ground under a blue sky light read as snow) - galb *= mix(vec3(1.0), vec3(0.7, 0.64, 0.55), uNight); - // far grass colour carried by the ground (blades end, colour does not) - float gd = length(vGW - cameraPosition); - float carry = vGC.a * 0.95; - float under = vGC.a * (1.0 - smoothstep(uCarry.x, uCarry.y, gd)); - float tl = dot(sRGBTransferEOTF(vec4(a0.rgb, 1.0)).rgb, vec3(0.3, 0.5, 0.2)); - float clumpN = texture2D(uMacro, gp * 0.9 + 0.17).b; - float midN = texture2D(uMacro, gp * 0.31 + 0.61).g; - vec3 gcol = vGC.rgb * mix(0.7, 1.25, mB) * clamp(tl / uTl0, 0.35, 2.2) * mix(0.45, 1.45, clumpN * clumpN * 1.4) * mix(0.65, 1.3, midN); - // past the blades: stronger patchiness, darker hollows and long wind-combed streaks so the field is not one tint - float farK = carry * smoothstep(uCarry.x, uCarry.x * 2.0 + 6.0, gd); - float streak = texture2D(uMacro, vec2(gp.x * 0.09 + gp.y * 0.03, gp.y * 0.9 - gp.x * 0.2)).g; - gcol *= mix(1.0, mix(0.5, 1.25, smoothstep(0.2, 0.8, mA * 0.55 + midN * 0.45)) * mix(0.82, 1.12, streak), farK); - galb = mix(galb, gcol, carry); - grough = mix(grough, 0.88, carry); - // inside the blade rings the soil between blades is in the blades' shade: dark thatch and roots, never a - // bright flat colour (the blades carry the green there) - galb = mix(galb, galb * vec3(0.3, 0.28, 0.22), under * 0.9); - grough = mix(grough, 1.0, under); - // standing water from the shared wet map (IVEnv.wetMap: the same texture footsteps and splashes read): - // water depth wd in metres = map level + small noise + rain; one continuous gradient from dry through a - // damp ring and a soaked band to standing water that ramps in over 3.5 cm - vec4 wm = texture2D(uWetMap, (vGW.xz - uWetRect.xy) / uWetRect.zw); - float wd = ${E_WD_GLSL}; - float pud = smoothstep(0.0, 0.035, wd), soak = smoothstep(-0.1, 0.0, wd); - float damp = max(max(wm.g, smoothstep(-0.32, -0.1, wd)), clamp(vW1.y * 0.5 + uWet * 0.55, 0.0, 1.0)); - galb *= 1.0 - damp * 0.26 - soak * 0.18; - galb = mix(galb, vec3(0.05, 0.038, 0.026), wm.b * 0.7); grough = mix(grough, mix(0.62, 0.35, uNight), wm.b * 0.6); // churned mud along ruts and through gateways (by day drier: a low sun turned it to an oily sheen) - grough = mix(grough, mix(0.68, 0.46, uNight) + 0.1 * mB, damp); grough = mix(grough, 0.15, soak); - galb = mix(galb, galb * 0.6, pud); - grough = mix(grough, 0.055 - 0.02 * smoothstep(0.035, 0.22, wd), pud); - float ivPud = pud; - { vec2 mu = (vGW.xz - uMarksRect.xy) / uMarksRect.zw; if (mu.x > 0.0 && mu.y > 0.0 && mu.x < 1.0 && mu.y < 1.0) { vec4 mk = texture2D(uMarks, mu); - galb = mix(galb, vec3(0.05, 0.038, 0.026), mk.r * 0.55); galb *= 1.0 - mk.r * 0.3; grough = mix(grough, mix(0.58, 0.3, uNight), mk.r * 0.6); galb = mix(galb, vec3(0.06, 0.045, 0.03), mk.b * 0.55); grough = mix(grough, 0.25, mk.g); } } // stamped marks: prints in mud, tracked mud, wet ruts - diffuseColor.rgb *= galb;`); - P('fragment', '#include ', 'float roughnessFactor = clamp(grough, 0.03, 1.0);'); - P('fragment', '#include ', ` - vec3 mapN = vec3(gn.xy * 2.0 - 1.0, 0.0); - mapN.xy *= (1.0 - ivPud * 0.97) * (1.0 - vGC.a * 0.2) * (1.0 - 0.45 * b3 / bs); - { float fk = vGC.a * smoothstep(uCarry.x, uCarry.x * 2.0 + 6.0, length(vGW - cameraPosition)); float sn = texture2D(uMacro, vec2(vGW.x * 0.35 + vGW.z * 0.1, vGW.z * 1.6 - vGW.x * 0.35)).b - 0.5; mapN.x += sn * 0.6 * fk; mapN.y += (texture2D(uMacro, vGW.xz * 0.6 + 0.3).r - 0.5) * 0.3 * fk; } - mapN.z = sqrt(max(0.05, 1.0 - dot(mapN.xy, mapN.xy))); - normal = ivPerturbNormal2Arb(-vViewPosition, normal, normalize(mapN), faceDirection, vNormalMapUv); - if (uRain > 0.0 && ivPud > 0.01) { vec2 rp = ivRipple(vGW.xz * 3.0, uTime) + ivRipple(vGW.xz * 5.3 + 7.0, uTime * 1.13) * 0.7; normal = normalize(normal + (viewMatrix * vec4(rp.x, 0.0, rp.y, 0.0)).xyz * 0.35 * ivPud * uRain); }`); - P('fragment', '#include ', ` - float gao = 0.45 + 0.55 * smoothstep(0.05, 0.6, gh); - reflectedLight.indirectDiffuse *= gao; reflectedLight.indirectSpecular *= mix(gao, 2.2 + 7.0 * uNight, ivPud); // (the sky cube is stored dimmed; standing water shows the sky at its own brightness, and at night a little more, so a puddle reads as water and not a hole) - // at night the moon's sheen on damp (not flooded) ground is held down: a broad pale sheen read as frost or snow - reflectedLight.directSpecular *= mix(1.0, mix(0.55, 0.85, ivPud), uNight); - // by day a low sun behind thin cloud: a soft sheen on the ground toward it, not a glare across the whole field - reflectedLight.directSpecular *= mix(mix(0.5, 1.0, ivPud), 1.0, uNight); - #ifndef USE_SHADOWMAP - // Low (no shadow map): the moon lights everything, so its sheen and the soil's brightness come down further - reflectedLight.directSpecular *= mix(1.0, 0.35, uNight); reflectedLight.directDiffuse *= mix(1.0, 0.8, uNight); - #endif - // standing water mirrors the lamps: a soft reflected image of each pooled light (the GGX highlight alone is a - // pin-prick at this roughness), so a puddle shows the lamp instead of going black - #if NUM_POINT_LIGHTS > 0 && !defined(IV_GROUND_LOW) - if (ivPud > 0.02) { vec3 ivR = reflect(normalize(-vViewPosition), normal); - for (int i = 0; i < NUM_POINT_LIGHTS; i++) { vec3 ld = pointLights[i].position + vViewPosition; float dl = length(ld); - float c = dot(ivR, ld / dl); reflectedLight.indirectSpecular += pointLights[i].color * exp((c - 1.0) * 700.0) * ivPud * 0.6 / (1.0 + dl * dl * 0.004); } } - #endif`); - sh.fragmentShader = E.withPerturb(HEAD + sh.fragmentShader); - }; - m.customProgramCacheKey = () => 'ivground' + (LOW ? 'L' : ''); - return m; - } - - // For the game's footsteps and splashes: how wet / muddy the ground is here, 0..1, and its kind (from the wet map). - E.wetnessAt = function (x, z) { const g = E._ground; if (!g) return E.U.uWet.value; return E.groundInfo(x, z).wet; }; - // the ground kind for footsteps, slowdown and cover: the map's kinds, plus 'puddle' where water stands and 'leaves' - // under trees (litter). Mud depth, wetness and puddle amount: IVEnv.groundInfo(x, z). - E.surfaceAt = function (x, z) { const g = E._ground; if (!g) return 'grass'; const i = E.groundInfo(x, z); if (i.puddle > 0.5) return 'puddle'; if (E.GRASS_KINDS[i.kind] && E._treeNear && E._treeNear(x, z, 3.2)) return 'leaves'; return i.kind; }; - E.ground = function (heightFn, opts) { - opts = opts || {}; - const surfaceAt = opts.surfaceAt || (() => 'grass'); - const step = opts.step || (E.Q.name === 'low' ? 3.5 : E.Q.name === 'medium' ? 2.5 : 2); - const half = (opts.size || 200) / 2; - const x0 = opts.x0 != null ? opts.x0 : -half, z0 = opts.z0 != null ? opts.z0 : -half, x1 = opts.x1 != null ? opts.x1 : half, z1 = opts.z1 != null ? opts.z1 : half; - const CH = opts.chunk || (E.Q.name === 'high' ? 64 : E.Q.name === 'medium' ? 96 : 128); - const mat = groundMaterial(); - const group = new THREE.Group(); group.name = 'IVEnv.ground'; - const meshes = [], c = new THREE.Color(), cs = new THREE.Color(); - const e = 0.5; - const weights = (x, z, out) => { // averaged over a small footprint so borders are soft - for (let k = 0; k < 6; k++) out[k] = 0; - const o = step * 0.45, pts = [[0, 0], [o, 0], [-o, 0], [0, o], [0, -o]]; - for (const p of pts) { const w = W[surfaceAt(x + p[0], z + p[1])] || W.none; for (let k = 0; k < 6; k++) out[k] += w[k] / pts.length; } - return out; - }; - const wv = [0, 0, 0, 0, 0, 0]; - const chunk = (cx, cz, step) => { - const ex = Math.min(cx + CH, x1), ez = Math.min(cz + CH, z1); - const nx = Math.round((ex - cx) / step) + 1, nz = Math.round((ez - cz) / step) + 1; - const N = nx * nz, pos = new Float32Array(N * 3), nor = new Float32Array(N * 3), uv = new Float32Array(N * 2), w0 = new Float32Array(N * 4), w1 = new Float32Array(N * 4), gc = new Float32Array(N * 4); - for (let j = 0; j < nz; j++) for (let i = 0; i < nx; i++) { - const k = j * nx + i, x = cx + (ex - cx) * i / (nx - 1), z = cz + (ez - cz) * j / (nz - 1), y = heightFn(x, z); - pos[k * 3] = x; pos[k * 3 + 1] = y; pos[k * 3 + 2] = z; uv[k * 2] = x; uv[k * 2 + 1] = z; - const gx = heightFn(x - e, z) - heightFn(x + e, z), gz = heightFn(x, z - e) - heightFn(x, z + e), l = Math.hypot(gx, 2 * e, gz); - nor[k * 3] = gx / l; nor[k * 3 + 1] = 2 * e / l; nor[k * 3 + 2] = gz / l; - weights(x, z, wv); - w0[k * 4] = wv[0]; w0[k * 4 + 1] = wv[1]; w0[k * 4 + 2] = wv[2]; w0[k * 4 + 3] = wv[3]; w1[k * 4] = wv[4]; w1[k * 4 + 1] = wv[5]; - // grass colour carried far away, weighted by how much grass grows here - const kind = surfaceAt(x, z), K = E.GRASS_KINDS[kind]; - if (K) { E.grassField.carry(kind, x, z, c); const dens = K.d * E.sstep(0.18, 0.45, E.grassField.dens(x, z) + 0.12 + (K.fill || 0)); gc[k * 4] = c.r; gc[k * 4 + 1] = c.g; gc[k * 4 + 2] = c.b; gc[k * 4 + 3] = E.clamp(dens * 1.7 * Math.min(1, 0.45 + K.h[1] * 3), 0, 1); } - } - const idx = new Uint32Array((nx - 1) * (nz - 1) * 6); let q = 0; - for (let j = 0; j < nz - 1; j++) for (let i = 0; i < nx - 1; i++) { - const a = j * nx + i, b = a + 1, cc = a + nx, d = cc + 1; - // split each quad along the diagonal that follows the surface better - const ya = pos[a * 3 + 1], yb = pos[b * 3 + 1], yc = pos[cc * 3 + 1], yd = pos[d * 3 + 1]; - if (Math.abs(ya - yd) < Math.abs(yb - yc)) { idx[q++] = a; idx[q++] = cc; idx[q++] = d; idx[q++] = a; idx[q++] = d; idx[q++] = b; } - else { idx[q++] = a; idx[q++] = cc; idx[q++] = b; idx[q++] = b; idx[q++] = cc; idx[q++] = d; } - } - const g = new THREE.BufferGeometry(); - g.setAttribute('position', new THREE.BufferAttribute(pos, 3)); g.setAttribute('normal', new THREE.BufferAttribute(nor, 3)); g.setAttribute('uv', new THREE.BufferAttribute(uv, 2)); - g.setAttribute('aW0', new THREE.BufferAttribute(w0, 4)); g.setAttribute('aW1', new THREE.BufferAttribute(w1, 4)); g.setAttribute('aGC', new THREE.BufferAttribute(gc, 4)); - g.setIndex(new THREE.BufferAttribute(idx, 1)); g.computeBoundingSphere(); g.computeBoundingBox(); - return g; - }; - // two levels per chunk: the full mesh near the camera, a 2.5x coarser one beyond (swapped in IVEnv.update) - const lods = []; - for (let cz = z0; cz < z1 - 1e-6; cz += CH) for (let cx = x0; cx < x1 - 1e-6; cx += CH) { - const fine = new THREE.Mesh(chunk(cx, cz, step), mat), coarse = new THREE.Mesh(chunk(cx, cz, step * 2.5), mat); - for (const m of [fine, coarse]) { m.receiveShadow = true; m.name = 'ground'; group.add(m); meshes.push(m); } - coarse.visible = false; lods.push({ fine, coarse, x: Math.min(cx + CH / 2, (cx + x1) / 2), z: Math.min(cz + CH / 2, (cz + z1) / 2) }); - } - const near = opts.lodNear || 70; - (E._updaters = E._updaters || []).push((dt, cam) => { for (const L of lods) { const d = Math.hypot(L.x - cam.position.x, L.z - cam.position.z) - CH * 0.71; const f = d < near; L.fine.visible = f; L.coarse.visible = !f; } }); - - // the height of the DRAWN ground (the fine level) at x, z: the mesh's flat triangles sit above the true height in - // dips (by up to ~0.3 m with a 2.5 m step), so anything that must stay above what the player sees (the - // first-person eye) asks this. Same grid, same diagonal choice as chunk(). - const heightAt = (x, z) => { - if (x < x0 || z < z0 || x > x1 || z > z1) return heightFn(x, z); - const cx = Math.min(x0 + Math.floor((x - x0) / CH) * CH, x1 - 1e-6), cz = Math.min(z0 + Math.floor((z - z0) / CH) * CH, z1 - 1e-6); - const ex = Math.min(cx + CH, x1), ez = Math.min(cz + CH, z1), nx = Math.round((ex - cx) / step) + 1, nz = Math.round((ez - cz) / step) + 1; - const sx = (ex - cx) / (nx - 1), sz = (ez - cz) / (nz - 1); - const i = Math.min(nx - 2, Math.max(0, Math.floor((x - cx) / sx))), j = Math.min(nz - 2, Math.max(0, Math.floor((z - cz) / sz))); - const ax = cx + (ex - cx) * i / (nx - 1), az = cz + (ez - cz) * j / (nz - 1), bx = cx + (ex - cx) * (i + 1) / (nx - 1), cz2 = cz + (ez - cz) * (j + 1) / (nz - 1); - const fx = (x - ax) / (bx - ax), fz = (z - az) / (cz2 - az); - const ya = heightFn(ax, az), yb = heightFn(bx, az), yc = heightFn(ax, cz2), yd = heightFn(bx, cz2); - if (Math.abs(ya - yd) < Math.abs(yb - yc)) return fz >= fx ? ya + fz * (yc - ya) + fx * (yd - yc) : ya + fx * (yb - ya) + fz * (yd - yb); - return fx + fz <= 1 ? ya + fx * (yb - ya) + fz * (yc - ya) : yd + (1 - fx) * (yc - yd) + (1 - fz) * (yb - yd); - }; - group.userData.heightAt = heightAt; - E._ground = { surfaceAt, heightAt }; - return { group, material: mat, meshes, heightFn, surfaceAt, heightAt }; - }; - - // ------------------------------------------------------------------ ground marks (for the game's code) - // IVEnv.marks.area(x0, z0, size, res) one persistent top-down mark texture over the play area (default the map) - // IVEnv.marks.stamp(x, z, kind, rot, strength) kind 'boot' (a print pressed into mud), 'track' (brown mud carried - // onto hard ground, fades), 'rut' (a wet wheel rut segment, rot = direction); strength 0..1 - // IVEnv.marks.fade(dt) 'track' marks fade over about two minutes (call each frame or now and then) - // channels: R = pressed depth (darkens), G = wetness (glossy), B = tracked mud (brown) - E.marks = (function () { - let S = 512, data = null, tex = null; const rect = new THREE.Vector4(-190, -190, 380, 380); let dirty = false; - const M = { rect, tex() { if (!tex) M.area(rect.x, rect.y, rect.z, S); return tex; }, - area(x0, z0, size, res) { S = res || S; rect.set(x0, z0, size, size); data = new Uint8Array(S * S * 4); if (!tex) { tex = new THREE.DataTexture(data, S, S, THREE.RGBAFormat); tex.magFilter = tex.minFilter = THREE.LinearFilter; } else { if (tex.image.width !== S) tex.dispose(); tex.image = { data, width: S, height: S }; } tex.needsUpdate = true; return M; }, - stamp(x, z, kind, rot, k) { if (!data) M.area(rect.x, rect.y, rect.z, S); k = k == null ? 1 : k; const px = (x - rect.x) / rect.z * S, pz = (z - rect.y) / rect.w * S, m = S / rect.z, c = Math.cos(rot || 0), s = Math.sin(rot || 0); - const L = kind === 'rut' ? 1.2 : 0.28, Wd = kind === 'rut' ? 0.14 : 0.11, ch = kind === 'boot' ? 0 : kind === 'rut' ? 1 : 2, r = Math.ceil(Math.max(L, Wd) * m) + 1; - for (let j = -r; j <= r; j++) for (let i = -r; i <= r; i++) { const X = Math.round(px + i), Z = Math.round(pz + j); if (X < 0 || Z < 0 || X >= S || Z >= S) continue; const u = (i * c + j * s) / m, v = (-i * s + j * c) / m; const e = (u / L) ** 2 + (v / Wd) ** 2; if (e > 1) continue; const q = (Z * S + X) * 4 + ch, val = Math.round(255 * k * (1 - e * 0.6)); data[q] = Math.max(data[q], val); if (kind === 'rut') data[(Z * S + X) * 4] = Math.max(data[(Z * S + X) * 4], val >> 1); } - dirty = true; }, - fade(dt) { if (!data) return; const f = Math.max(1, Math.round(dt * 2)); for (let i = 2; i < data.length; i += 4) if (data[i]) data[i] = Math.max(0, data[i] - f); dirty = true; }, - update() { if (dirty && tex) { tex.needsUpdate = true; dirty = false; } } - }; - (E._updaters = E._updaters || []).push(() => M.update()); - return M; - })(); - // IVEnv.groundInfo(x, z) -> { kind, mud 0..1 (how deep the mud is), wet 0..1, puddle 0..1 } - E.groundInfo = function (x, z) { - const g = E._ground; const kind = g ? g.surfaceAt(x, z) : 'grass', w = W[kind] || W.none; - const s = E.wetMap.sample(x, z); - if (!s) { const wet = Math.min(1, w[5] + E.U.uWet.value * 0.5); return { kind, mud: Math.min(1, w[1]), wet, puddle: 0, depth: -1 }; } - // mud stays the ground kind's own (it slows the player: the map's churned ruts and gateways must not change timing - // on the stealth routes); the map's churn is given separately as churn, for effects - return { kind, mud: Math.min(1, w[1]), churn: s.mud, wet: Math.min(1, Math.max(s.damp, s.soak, w[5] * 0.5 + E.U.uWet.value * 0.5)), puddle: s.water, depth: s.depth }; - }; - - // ------------------------------------------------------------------ the shared wet map (puddles and ruts) - // IVEnv.wetMap.build({ heightFn, kindAt, x0, z0, size, puddles: [[x, z, rx, rz, rot, depth]], ruts: [{ pts: [[x, z]...], - // gauge, w, k }], gates: [[x, z, r]] }) makes ONE data texture over the playable area (about 0.22 m a pixel): - // R = water level (0.55 = the water line), G = damp, B = churned mud, A = trodden. The ground shader draws water - // from it and IVEnv.groundInfo / surfaceAt / wetnessAt (footsteps, splashes, slowdown) read the same bytes with the - // same noise, so where the picture shows water the game hears and splashes water, and nowhere else. - // Puddles collect in cart ruts, trampled gateways, the hand-placed hollows, and low spots (ground minus the - // blurred ground) on wet kinds of ground. - // (both data textures can change size after their first upload: three r187 allocates a texture's storage once, so a - // resize goes through dispose(), which makes it allocate again at the new size; r128 reallocated on every upload) - E.wetMap = (function () { - let S = 4, data = new Uint8Array(4 * 4 * 4), tex = null; const rect = new THREE.Vector4(-1e5, -1e5, 2e5, 2e5); - const mk = () => { if (!tex) { tex = new THREE.DataTexture(data, S, S, THREE.RGBAFormat); tex.magFilter = tex.minFilter = THREE.LinearFilter; tex.generateMipmaps = false; tex.wrapS = tex.wrapT = THREE.ClampToEdgeWrapping; tex.flipY = false; } else { if (tex.image.width !== S) tex.dispose(); tex.image = { data, width: S, height: S }; } tex.needsUpdate = true; }; - for (let i = 0; i < 16; i++) { data[i * 4] = 0; data[i * 4 + 1] = 0; } - const M = { rect, built: false, tex() { if (!tex) mk(); return tex; } }; - // the macro noise texture, sampled like the GPU does (bilinear, repeat, level 0) - function mac(u, v, ch) { - const T = E.tex.macro && E.tex.macro.alb, d = T && T.image && T.image.data; if (!d) return 0.5; const N = T.image.width; - const x = u * N - 0.5, y = v * N - 0.5, x0 = Math.floor(x), y0 = Math.floor(y), fx = x - x0, fy = y - y0; - const at = (i, j) => d[((((j % N) + N) % N) * N + (((i % N) + N) % N)) * 4 + ch] / 255; - return (at(x0, y0) * (1 - fx) + at(x0 + 1, y0) * fx) * (1 - fy) + (at(x0, y0 + 1) * (1 - fx) + at(x0 + 1, y0 + 1) * fx) * fy; - } - function tap(x, z) { // bilinear over the map's own bytes, like the GPU's linear filter - const u = (x - rect.x) / rect.z * S - 0.5, v = (z - rect.y) / rect.w * S - 0.5, i0 = Math.floor(u), j0 = Math.floor(v), fx = u - i0, fy = v - j0, o = [0, 0, 0, 0]; - for (let c = 0; c < 4; c++) { const at = (i, j) => data[(Math.min(S - 1, Math.max(0, j)) * S + Math.min(S - 1, Math.max(0, i))) * 4 + c] / 255; o[c] = (at(i0, j0) * (1 - fx) + at(i0 + 1, j0) * fx) * (1 - fy) + (at(i0, j0 + 1) * (1 - fx) + at(i0 + 1, j0 + 1) * fx) * fy; } - return o; - } - M.depth = function (x, z) { // the GLSL E_WD_GLSL, in JS - const w = tap(x, z); - return (w[0] - 0.55) + (mac(x * 0.31, z * 0.31, 0) - 0.5) * 0.12 + (mac(x * 0.83 + 0.21, z * 0.83 + 0.21, 1) - 0.5) * 0.06 + (mac(x * 2.6 + 0.57, z * 2.6 + 0.57, 2) - 0.5) * 0.03 + E.U.uWet.value * 0.04; - }; - M.sample = function (x, z) { - if (!M.built || x < rect.x || z < rect.y || x > rect.x + rect.z || z > rect.y + rect.w) return null; - const w = tap(x, z), d = M.depth(x, z), ss = E.sstep; - return { depth: d, water: ss(0, 0.035, d), soak: ss(-0.1, 0, d), damp: Math.max(w[1], ss(-0.32, -0.1, d)), mud: w[2], trod: w[3] }; - }; - M.build = function (o) { - const size = o.size, x0 = o.x0, z0 = o.z0, cap = E.Q.name === 'high' ? 2048 : E.Q.name === 'medium' ? 1536 : 768; - S = Math.min(cap, Math.ceil(size / 0.22)); const px = size / S; - rect.set(x0, z0, size, size); - const L = new Float32Array(S * S), G = new Float32Array(S * S), B = new Float32Array(S * S), A = new Float32Array(S * S); - const kindAt = o.kindAt || (() => 'grass'), hf = o.heightFn || (() => 0); - // base level by ground kind (a kind's wet weight: lanes and mud sit near the water line, grass well above it); - // sampled on a 1 m grid and spread (kind lookups are the slow part) - const C = Math.max(1, Math.round(1 / px)), cw = Math.ceil(S / C); - const kb = new Float32Array(cw * cw), hh = new Float32Array(cw * cw); - for (let j = 0; j < cw; j++) for (let i = 0; i < cw; i++) { const x = x0 + (i + 0.5) * C * px, z = z0 + (j + 0.5) * C * px, k = W[kindAt(x, z)] || W.none; kb[j * cw + i] = k[5]; hh[j * cw + i] = hf(x, z); } - // low spots: the ground minus the ground blurred over ~7 m (box blur, two passes) - const blur = (src, r) => { const t = new Float32Array(src.length), out = new Float32Array(src.length); for (let pass = 0; pass < 2; pass++) { const a = pass ? t : src, b = pass ? out : t; for (let j = 0; j < cw; j++) for (let i = 0; i < cw; i++) { let s = 0, n = 0; for (let q = -r; q <= r; q++) { const ii = pass ? i : Math.min(cw - 1, Math.max(0, i + q)), jj = pass ? Math.min(cw - 1, Math.max(0, j + q)) : j; s += a[jj * cw + ii]; n++; } b[j * cw + i] = s / n; } } return out; }; - const hb = blur(hh, Math.max(2, Math.round(3.5 / (C * px)))); - // the 1 m grid interpolated (bilinear between cell centres): sampled nearest, the water's edges followed the grid - const bil = (A, fi, fj) => { const i0 = Math.max(0, Math.min(cw - 2, Math.floor(fi))), j0 = Math.max(0, Math.min(cw - 2, Math.floor(fj))), fx = E.clamp(fi - i0, 0, 1), fy = E.clamp(fj - j0, 0, 1); - return (A[j0 * cw + i0] * (1 - fx) + A[j0 * cw + i0 + 1] * fx) * (1 - fy) + (A[(j0 + 1) * cw + i0] * (1 - fx) + A[(j0 + 1) * cw + i0 + 1] * fx) * fy; }; - for (let j = 0; j < S; j++) for (let i = 0; i < S; i++) { - const fi = (i + 0.5) / C - 0.5, fj = (j + 0.5) / C - 0.5, kw = bil(kb, fi, fj); - const low = Math.max(0, bil(hb, fi, fj) - bil(hh, fi, fj)); - // base level well below the water line even on lanes (-0.23 m on a lane): water stands only where ruts, hollows, - // gateways and the hand-placed puddles add to it - L[j * S + i] = 0.55 - 0.42 + kw * 0.22 + Math.min(0.16, low * 0.5) * (0.3 + kw); - G[j * S + i] = kw * 0.35; - } - const R = E.rng(o.seed || 31); - // paint helper: f(dx, dz) over the pixels within r metres of (x, z) - const paint = (x, z, r, f) => { const i0 = Math.max(0, Math.floor((x - r - x0) / px)), i1 = Math.min(S - 1, Math.ceil((x + r - x0) / px)), j0 = Math.max(0, Math.floor((z - r - z0) / px)), j1 = Math.min(S - 1, Math.ceil((z + r - z0) / px)); for (let j = j0; j <= j1; j++) for (let i = i0; i <= i1; i++) f(j * S + i, x0 + (i + 0.5) * px - x, z0 + (j + 0.5) * px - z); }; - // cart ruts: two wheel tracks either side of the line, broken up along their length - for (const rt of o.ruts || []) { - const gauge = rt.gauge || 1.45, w = rt.w || 0.42, k = rt.k == null ? 1 : rt.k; - for (let s = 0; s < rt.pts.length - 1; s++) { - const a = rt.pts[s], b = rt.pts[s + 1], len = Math.hypot(b[0] - a[0], b[1] - a[1]), dx = (b[0] - a[0]) / len, dz = (b[1] - a[1]) / len, n = Math.ceil(len / (px * 2)); - for (let t = 0; t <= n; t++) { - const al = len * t / n, cx = a[0] + dx * al, cz = a[1] + dz * al, wander = (E.vnoise(cx * 0.21, cz * 0.21, 77) - 0.5) * 0.5; - for (const sd of [-1, 1]) { - const ox = cx - dz * (sd * gauge / 2 + wander), oz = cz + dx * (sd * gauge / 2 + wander), brk = E.sstep(0.28, 0.6, E.vnoise(ox * 0.35, oz * 0.35, 5 + sd)); - paint(ox, oz, w, (q, ex, ez) => { const across = Math.abs(-ex * dz + ez * dx) / (w / 2); if (across > 1.6) return; const prof = Math.max(0, 1 - across * across); - L[q] += prof * 0.17 * k * brk; B[q] = Math.max(B[q], prof * k * 0.9); G[q] = Math.max(G[q], Math.min(1, (1.6 - across) * 0.7) * k); A[q] = Math.max(A[q], 0.6 * k); }); - } - } - } - } - // gateways and trampled spots: churned, lower, puddled in the middle - for (const g of o.gates || []) paint(g[0], g[1], g[2], (q, ex, ez) => { const d = Math.hypot(ex, ez) / g[2]; if (d > 1) return; const f = 1 - d * d; L[q] += f * 0.09 * E.sstep(0.35, 0.75, E.vnoise((g[0] + ex) * 0.9, (g[1] + ez) * 0.9, 61)); /* churned in patches, not a flooded disc */ B[q] = Math.max(B[q], f * 0.8); A[q] = Math.max(A[q], f); G[q] = Math.max(G[q], f); }); - // hand-placed puddles: ellipses with their own depth - for (const p of o.puddles || []) { const [px0, pz0, rx, rz, rot, dep] = p, c = Math.cos(rot || 0), sn = Math.sin(rot || 0); - paint(px0, pz0, Math.max(rx, rz) * 1.3, (q, ex, ez) => { const u = (ex * c + ez * sn) / rx, v = (-ex * sn + ez * c) / rz, e = u * u + v * v; if (e > 1.7) return; L[q] = Math.max(L[q], 0.55 - 0.1 + ((dep || 0.2) + 0.1) * (1 - e)); G[q] = Math.max(G[q], Math.min(1, (1.7 - e) * 1.2)); }); } - // the damp ring: about a metre round anything near the water line - { const r = Math.max(1, Math.round(1 / px)), T = new Float32Array(S * S); - for (let j = 0; j < S; j++) { let run = 0; for (let i = 0; i < S; i++) { run = Math.max(L[j * S + i] - 0.45, run - 1 / r); T[j * S + i] = run; } run = 0; for (let i = S - 1; i >= 0; i--) { run = Math.max(L[j * S + i] - 0.45, run - 1 / r); T[j * S + i] = Math.max(T[j * S + i], run); } } - for (let i = 0; i < S; i++) { let run = 0; for (let j = 0; j < S; j++) { run = Math.max(T[j * S + i], run - 1 / r); G[j * S + i] = Math.max(G[j * S + i], Math.min(1, run * 4)); } run = 0; for (let j = S - 1; j >= 0; j--) { run = Math.max(T[j * S + i], run - 1 / r); G[j * S + i] = Math.max(G[j * S + i], Math.min(1, run * 4)); } } } - data = new Uint8Array(S * S * 4); - for (let q = 0; q < S * S; q++) { data[q * 4] = Math.round(E.clamp(L[q], 0, 1) * 255); data[q * 4 + 1] = Math.round(E.clamp(G[q], 0, 1) * 255); data[q * 4 + 2] = Math.round(E.clamp(B[q], 0, 1) * 255); data[q * 4 + 3] = Math.round(E.clamp(A[q], 0, 1) * 255); } - mk(); M.built = true; M.res = S; M.mPerPx = px; - E.extraTexBytes = (E.extraTexBytes || 0) - (M.bytes || 0) + S * S * 4; M.bytes = S * S * 4; - return M; - }; - M.reset = function () { M.built = false; }; - return M; - })(); - - // ------------------------------------------------------------------ the land beyond the map - // IVEnv.skirt(heightFn, { half, outer, hills, woods, seed, day, fogK, landFogK }) -> group - // fogK / landFogK (0..1) thin the scene's fog on the woods / the land beyond ~120 m (1 = same fog as the map) - // A cheap ring of land from the square edge of the playable ground (+-half) out to `outer` metres, rising into - // rolling hills (`hills` metres), with a ring of dark wood masses on it. One mesh for the land, one for the woods, - // no textures, always drawn (not subject to the tree draw range), so from any height the land never stops in a - // straight line: it rolls away into hills and woods and then into fog. - E.skirt = function (heightFn, opts) { - opts = Object.assign({ half: 190, outer: 1400, hills: 30, woods: 1, seed: 5, day: false, fogK: 0.8, landFogK: 1 }, opts || {}); - // the far land sits in thinner fog than the scene's (fogK scales the exp2 density) so its woods and hills keep a - // silhouette against the sky instead of fading to the fog colour - const thinFog = (m, k) => { - if (k >= 0.999) return m; - const k2 = (k * k).toFixed(4); - m.onBeforeCompile = (sh) => { - const ch = THREE.ShaderChunk.fog_fragment.split('fd * fd').join('fd * fd * mix(1.0, ' + k2 + ', smoothstep(120.0, 520.0, fogDepth))').split('fogDensity * fogDensity').join('fogDensity * fogDensity * mix(1.0, ' + k2 + ', smoothstep(120.0, 520.0, fogDepth))'); // IVEnv's fog chunk names the density fd - E.patch(sh, 'fragment', '#include ', ch, 'env/ground skirt fog'); - }; - m.customProgramCacheKey = () => 'ivskirt' + k2; return m; - }; - const group = new THREE.Group(); group.name = 'IVEnv.skirt'; - const LOWQ = E.Q && E.Q.name === 'low', A = LOWQ ? 64 : 160, NR = LOWQ ? 10 : 22, half = opts.half, P = [], C = [], I = [], col = new THREE.Color(); - const base = opts.day ? [0.055, 0.07, 0.035] : [0.035, 0.042, 0.03]; - const hill = (x, z, t) => opts.hills * t * (0.55 * E.fbm2(x / 420 + 3, z / 420, opts.seed, 4) + 0.45 * E.fbm2(x / 140, z / 140 + 9, opts.seed + 3, 3)) + t * t * opts.hills * 0.25; - const ring = []; - for (let j = 0; j <= NR; j++) { - const t = j / NR, tt = Math.pow(t, 1.8); - for (let i = 0; i < A; i++) { - const a = i / A * Math.PI * 2, ca = Math.cos(a), sa = Math.sin(a), k = 1 / Math.max(Math.abs(ca), Math.abs(sa)); - const ri = half * k - 0.5, r = ri + (opts.outer - ri) * tt, x = ca * r, z = sa * r; - const y0 = heightFn(E.clamp(x, -half, half), E.clamp(z, -half, half)); - const blend = E.sstep(0, 0.08, tt), y = y0 * (1 - blend) + (y0 * 0.3 + hill(x, z, Math.min(1, tt * 3))) * blend - 0.06 - tt * 2; - ring.push([x, y, z]); P.push(x, y, z); - const v = E.fbm2(x / 90, z / 90, opts.seed + 7, 2); - col.setRGB(base[0] * (0.75 + 0.5 * v), base[1] * (0.75 + 0.5 * v), base[2] * (0.8 + 0.4 * v)); C.push(col.r, col.g, col.b); - } - } - for (let j = 0; j < NR; j++) for (let i = 0; i < A; i++) { const a = j * A + i, b = j * A + (i + 1) % A, c = a + A, d = b + A; I.push(a, b, c, b, d, c); } // wound to face up - const g = new THREE.BufferGeometry(); g.setAttribute('position', new THREE.Float32BufferAttribute(P, 3)); g.setAttribute('color', new THREE.Float32BufferAttribute(C, 3)); g.setIndex(I); g.computeVertexNormals(); - const land = new THREE.Mesh(g, thinFog(new THREE.MeshLambertMaterial({ vertexColors: true }), opts.landFogK)); land.name = 'skirt-land'; land.receiveShadow = false; land.frustumCulled = false; group.add(land); - const sample = (x, z) => { const r = Math.hypot(x, z), a = Math.atan2(z, x), ca = Math.cos(a), sa = Math.sin(a), ri = half / Math.max(Math.abs(ca), Math.abs(sa)); const tt = E.clamp((r - ri) / (opts.outer - ri), 0, 1); const blend = E.sstep(0, 0.08, tt), y0 = heightFn(E.clamp(x, -half, half), E.clamp(z, -half, half)); return y0 * (1 - blend) + (y0 * 0.3 + hill(x, z, Math.min(1, tt * 3))) * blend - 0.06 - tt * 2; }; - E.skirtHeightAt = sample; // the far land's height, for far villages and woods placed by a mission - if (opts.woods && !LOWQ) { // Low: no wood masses (fog hides most of them; saves a draw call and ~10k triangles) - // wood masses: clusters of squashed low-poly blobs on the hills, thicker in a band just outside the map - const R = E.rng(opts.seed + 11), WP = [], WC = [], WI = [], blob = new THREE.IcosahedronGeometry(1, 0), bp = blob.attributes.position, m = new THREE.Matrix4(), v = new THREE.Vector3(); - const bi = blob.index ? blob.index.array : null, wcol = opts.day ? [0.045, 0.06, 0.04] : [0.0035, 0.0045, 0.004]; - const n = Math.round(150 * opts.woods * (LOWQ ? 0.45 : 1)); - for (let k = 0; k < n; k++) { - const a = R() * Math.PI * 2, ca = Math.cos(a), sa = Math.sin(a), ri = half / Math.max(Math.abs(ca), Math.abs(sa)), r = ri + 15 + Math.pow(R(), 1.8) * 300; - if (E.fbm2(ca * 6, sa * 6, opts.seed + 21, 2) < 0.38 && r > ri + 60) continue; // open gaps between the woods - const cx = ca * r, cz = sa * r; - for (let q = 0; q < 6; q++) { - const x = cx + R.range(-16, 16), z = cz + R.range(-16, 16), w = R.range(4, 7), h = R.range(6, 11), y = sample(x, z); - m.compose(v.set(x, y + h * 0.75, z), new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(0, 1, 0), R() * 6.28), new THREE.Vector3(w, h, w * R.range(0.8, 1.2))); - const b0 = WP.length / 3, sh = R.range(0.8, 1.2); - for (let i = 0; i < bp.count; i++) { v.fromBufferAttribute(bp, i); const top = v.y; v.applyMatrix4(m); WP.push(v.x, v.y, v.z); const s2 = sh * (0.55 + 0.6 * Math.max(0, top)); WC.push(wcol[0] * s2, wcol[1] * s2, wcol[2] * s2); } - if (bi) for (let i = 0; i < bi.length; i++) WI.push(b0 + bi[i]); else for (let i = 0; i < bp.count; i++) WI.push(b0 + i); - } - } - const wg = new THREE.BufferGeometry(); wg.setAttribute('position', new THREE.Float32BufferAttribute(WP, 3)); wg.setAttribute('color', new THREE.Float32BufferAttribute(WC, 3)); wg.setIndex(WI); wg.computeVertexNormals(); - const woods = new THREE.Mesh(wg, thinFog(new THREE.MeshBasicMaterial({ vertexColors: true }), opts.fogK)); // unlit: a dark mass against the sky at any light level woods.name = 'skirt-woods'; woods.frustumCulled = false; group.add(woods); - } - return group; - }; -})(); diff --git a/e63334287a3deaa3/ironveil/env/index.js b/e63334287a3deaa3/ironveil/env/index.js deleted file mode 100644 index 90f1247d..00000000 --- a/e63334287a3deaa3/ironveil/env/index.js +++ /dev/null @@ -1,104 +0,0 @@ -/* Midnight Ops environment kit: window.IVEnv. Everything the player looks at that is not a person. - Units: metres, Y up. three.js r187 global build (/lib/three/r187/, with its r128 compatibility layer). Every edit of a built-in - three shader goes through IVEnv.patch (env/core.js), which logs an error when the text it looks for is missing. No modules, no build step, no downloads: every texture is made in - code at load time (env/texgen.js, in Web Workers when the page is served over http). - - Load order (plain script tags, after three.min.js): - env/texgen.js env/core.js env/rooms.js env/atmosphere.js env/grass.js env/ground.js env/builder.js env/build.js env/nature.js - env/props.js env/decals.js env/post.js env/index.js - Typical frame: IVEnv.update(dt, camera); post ? post.render(dt) : renderer.render(scene, camera); - - ---------------------------------------------------------------- setup - IVEnv.init(renderer, quality) quality 'low' | 'medium' | 'high'. Call once, before load. - IVEnv.load(onProgress) -> Promise makes every texture; onProgress(fraction 0..1, lastName). IVEnv.genMs after. - IVEnv.update(dt, camera) every frame: time, wind, grass rings, tree LOD swaps, atmosphere, decals. - IVEnv.info { drawCalls, triangles, textureMB, genMs, grass:{...} } (refreshed by update - when a renderer was given to init; renderer.info.autoReset must stay true). - - ---------------------------------------------------------------- materials - IVEnv.mat(name) -> shared MeshStandardMaterial with albedo, normal, roughness and AO (cavity from height). - names: brick_red, brick_sooty, fieldstone, ashlar, plaster, plaster_interior, planks, floorboards, wood_painted, - timber, roof_tile, slate, cobbles, mud, grass_ground, earth, gravel, leaves, bark_oak, bark_pine, concrete, - metal_painted, metal_rust, sandbag, canvas, glass, straw (friendly aliases such as 'red brick' also work). - IVEnv.mat('glass', 'lit') is the warm lit-window variant. - Geometry for these materials must have UVs in METRES (IVEnv.uvMetres(geometry) box-projects any geometry). - Optional vertex attribute aEnv (vec4): rgb tint (0 = none), w = 1 + height above ground for damp/moss at the - foot of walls (IVEnv.setEnvAttr(geometry, tint, groundY) fills it). - All IVEnv materials carry userData.linear = true (the game's linearize() must skip them). - - ---------------------------------------------------------------- ground and grass - IVEnv.ground(heightFn, { surfaceAt, x0, z0, x1, z1 | size, step, chunk }) -> { group, material, meshes } - surfaceAt(x, z) -> 'grass' | 'pasture' | 'meadow' | 'tussock' | 'verge' | 'lanemid' | 'worn' | 'leaves' | - 'yardedge' | 'lane' | 'mud' | 'yard' | 'road' | 'gravel' | 'cobbles' | 'field' | 'water' | 'floor' | 'none' - IVEnv.grass(surfaceAt, heightFn, { longAt(x,z)->0..1, densityAt(x,z)->0..1, near, mid }) -> { group, info() } - follows the camera by itself inside IVEnv.update. Add .group to the scene. - IVEnv.setPushers([{ x, z, r, s }]) up to 8 things that flatten grass (r metres, s strength 0..1). - IVEnv.setWind(dirX, dirZ, strength) one wind for grass, crops, hedges and trees. - - ---------------------------------------------------------------- atmosphere and post - IVEnv.atmosphere(scene, renderer, preset, { mistBase, shadows, shadowRadius, fogMul }) -> { sun, hemi, update, - set(preset), setBrightness(k) } presets: night_moon, night_overcast, dawn_mist, dusk_rain, day_overcast. - Sets sky, stars, moon, cloud, fog + ground mist, lights, environment map, exposure, wetness and rain. - IVEnv.post(renderer, scene, camera, quality) -> { render(dt), setSize(w, h) } or null on low. - - grass.setScale(0.3..1) shrinks every ring without a reload (for autores.js: lower grass range first when the - frame time is bad); grass.counts() gives the current radii and densities; grass.info() draw calls / triangles. - IVEnv.setPushers([{ x, z, r, s }]) up to 8 things that flatten grass (r metres, s strength 0..1). - - ---------------------------------------------------------------- buildings, walls, fences (env/build.js) - IVEnv.building({ kind, w, d, floors, seed, damage 0..1, lit 0..1, roof 'tile'|'slate', units (shoprow) }) - -> { group, colliders, doors, windows, lights, height } - kinds: farmhouse, barn, shed, cottage, church (with tower), shoprow, ruin, bunker (= pillbox). Farmhouse and barn - have interiors. Local space: origin on the ground at the footprint centre, front door faces +Z. - colliders: [{ x, z, hx, hz, y0, y1, rot, surf, kind }] (local, rot about Y) ready for the game's W.addBox. - doors: [{ pivot, width, open(angle) }] windows: [{ x, y, z, nx, nz, w, h, lit }] - lights: [{ x, y, z, color, r, power, interior? }] for the game's pooled point lights (power 0 = unlit). - IVEnv.wall(points [[x,z]...], { type 'stone'|'brick', h, t, gaps [[from,to]], brokenStart, brokenEnd, seed, heightFn }) - IVEnv.fence(points, 'rail'|'picket'|'barbed'|'hurdle', { heightFn, seed, damage }) -> { group, colliders } - IVEnv.mergeStatic(root, { cell: 48 }) -> Group: one mesh per material per 48 m cell for everything static under - root (skips objects with userData.dynamic, e.g. door pivots). Call after placing buildings, walls, props, hedges. - Small detail pieces (arch voussoirs, quoins, ridge tiles, loose bricks, glazing bars, furniture, decals, ivy) are - kept in separate meshes (32 m cells) that IVEnv.update hides beyond IVEnv.Q.detailDist (Low 18 m, Medium 25 m, - High 35 m); on Low the purely decorative ones are not built at and a plain ridge / lintel stands in. - IVEnv.wetnessAt(x, z) -> 0..1 and IVEnv.surfaceAt(x, z) -> kind: for footstep sounds and splash effects. - - ---------------------------------------------------------------- nature (env/nature.js) - IVEnv.tree(kind, seed) -> Group kinds: oak, ash, poplar, apple, pine, dead, sapling - IVEnv.trees([{ kind, x, y, z, rot, scale, seed }]) -> { group, colliders, info() } instanced, LOD swaps every 0.25 s - (full mesh, reduced mesh, crossed-quad impostor baked once at load). Needs IVEnv.init(renderer) first. - IVEnv.hedge(points, { h, w, gaps, seed, heightFn }) -> { group, colliders } (colliders: kind 'hedge', sight only) - IVEnv.scatter(kind, areaTest(x,z)->0..1, { heightFn, density, radius, bounds [x0,z0,x1,z1], seed }) - plants that stream round the camera: wheat, reeds, ferns, brambles, nettles, dock, flowers - objects placed once over bounds: rocks, logs, stumps, litter, puddles (-> { group, colliders }) - IVEnv.stream(points, { width, heightFn, waterY(x,z) | level, flow }) -> { group } - IVEnv.puddleMesh([[x, y, z, rx, rz, rot]...]) -> Mesh standing water that reflects lamps and sky. - - ---------------------------------------------------------------- props and decals - IVEnv.prop(kind, seed, opts) -> { group, colliders, lights, door? } kinds: crate, crates, barrel, barrels, drums, - sandbags ({ length, rows }), cart, haybale, haystack, well, trough, telegraph (group.userData.wireTop), lamppost - (lights[0]), gate ({ width, open }), ladder, ammo, truck (no markings), logpile, tarp, bottles. - IVEnv.wireMesh([[x0,y0,z0,x1,y1,z1]...], radius, sag) -> Group wires between telegraph poles, barbed wire. - IVEnv.decal(type, position, normal, size, seed) -> index pooled runtime decals, one draw call. - types: scratches, gouges, chipped, pocks, scorch, soot, damp, moss, rust, mud, crack, bullethole, leaves, - waterstain, chalk, grime. IVEnv.impact(surface, position, normal) picks one per material for a bullet hit. - IVEnv.clearDecals() on level change. -*/ -(function () { - 'use strict'; - const E = window.IVEnv; - E.info = { drawCalls: 0, triangles: 0, textureMB: 0, genMs: 0 }; - E.update = function (dt, camera) { - E.U.uTime.value += dt; - if (E._systems) for (const s of E._systems) if (s.update && s.group.visible !== false) s.update(camera); - if (E._updaters) for (const f of E._updaters) f(dt, camera); - if (E.atmo) E.atmo.update(dt, camera); - const r = E.renderer; - if (E.sceneInfo) { E.info.drawCalls = E.sceneInfo.calls; E.info.triangles = E.sceneInfo.triangles; } - else if (r) { E.info.drawCalls = r.info.render.calls; E.info.triangles = r.info.render.triangles; } - E.info.textureMB = +(E.texMemory() / 1048576).toFixed(1); - E.info.genMs = Math.round(E.genMs || 0); - }; - // painted text and signs (env/labels.js): loaded from here while the textures are made, unless the page's own script - // list already loaded it - if (!E.labels && typeof document !== 'undefined') { const s = document.createElement('script'); s.src = (E.BASE || '') + 'labels.js'; s.async = false; document.head.appendChild(s); } -})(); diff --git a/e63334287a3deaa3/ironveil/env/labels.js b/e63334287a3deaa3/ironveil/env/labels.js deleted file mode 100644 index 52787a28..00000000 --- a/e63334287a3deaa3/ironveil/env/labels.js +++ /dev/null @@ -1,151 +0,0 @@ -/* Midnight Ops environment: painted text, signs and stencils in ONE atlas and ONE draw call. - IVEnv.label(text, style) -> a cached label (a canvas drawn once per distinct text + style) - style: { kind: 'stencil' | 'paint' | 'enamel' | 'carved' | 'gable', color, ground (plate / board colour or null = - transparent), font, distress 0..1, lines (text with '\n'), pxPerM, seed } - IVEnv.labels.place(label, [x, y, z], [nx, ny, nz], width, opts) puts it on a surface (world space, 3 mm out along the - normal; opts.rot turns it in its plane, opts.up overrides 'up'). Its height follows the label's aspect. - IVEnv.labels.finish() -> Mesh: packs every label used since the last finish into one atlas (2048 wide, height a power - of two up to 4096, 4 px padded gutters), remaps the UVs, and returns one transparent mesh (no depth write, polygon - offset) with one material. Call once per level after the build (IV.art.flush does). - Text is drawn at about 420 px a metre (capped at 640 px a label), so it is crisp at 2 m on a 1080p screen. */ -(function () { - 'use strict'; - const E = window.IVEnv; - const cache = new Map(); - let pending = []; - const FONTS = { - stencil: '900 {S}px "Arial Black", "Helvetica Neue", Arial, sans-serif', - paint: '700 {S}px Georgia, "Times New Roman", serif', - enamel: '700 {S}px "Arial Narrow", Arial, sans-serif', - carved: '700 {S}px Georgia, "Times New Roman", serif', - gable: '900 {S}px Georgia, "Times New Roman", serif' - }; - function rng(seed) { let s = (seed >>> 0) || 1; return () => { s ^= s << 13; s ^= s >>> 17; s ^= s << 5; return (s >>> 0) / 4294967296; }; } - function hashStr(t) { let h = 2166136261; for (let i = 0; i < t.length; i++) { h ^= t.charCodeAt(i); h = Math.imul(h, 16777619); } return h >>> 0; } - - // draw one label: returns { canvas, w, h (pixels), aspect } - function draw(text, st) { - const kind = st.kind || 'paint', lines = String(text).split('\n'), R = rng(hashStr(text + kind + (st.seed || 0))); - const S = st.size || 64; // cap height basis in pixels - const font = (st.font || FONTS[kind]).replace('{S}', S); - const c0 = document.createElement('canvas').getContext('2d'); c0.font = font; - const tw = Math.max(...lines.map(l => c0.measureText(l).width)), lh = S * 1.12; - const padX = kind === 'enamel' ? S * 0.55 : kind === 'carved' ? S * 0.5 : S * 0.3, padY = kind === 'enamel' ? S * 0.45 : S * 0.3; - let W = Math.ceil(Math.min(640, tw + padX * 2)), H = Math.ceil(lh * lines.length + padY * 2); - const sx = Math.min(1, (640 - padX * 2) / tw); - // style.aspect: the label must fill a board of that shape (width / height): pad the canvas to it - if (st.aspect) { if (W / H < st.aspect) W = Math.min(1024, Math.ceil(H * st.aspect)); else H = Math.ceil(W / st.aspect); } - const cv = document.createElement('canvas'); cv.width = W; cv.height = H; const g = cv.getContext('2d'); - // ground: enamel plate (rounded, bordered), a painted board, a stone face, or nothing (paint straight on the wall) - if (st.ground) { - g.fillStyle = st.ground; - const r = kind === 'enamel' ? S * 0.25 : kind === 'carved' ? S * 0.6 : 2; - g.beginPath(); g.moveTo(r, 0); g.lineTo(W - r, 0); g.quadraticCurveTo(W, 0, W, r); g.lineTo(W, H - r); g.quadraticCurveTo(W, H, W - r, H); g.lineTo(r, H); g.quadraticCurveTo(0, H, 0, H - r); g.lineTo(0, r); g.quadraticCurveTo(0, 0, r, 0); g.fill(); - if (kind === 'enamel') { g.strokeStyle = st.color; g.lineWidth = S * 0.09; const m = S * 0.18; g.strokeRect(m, m, W - 2 * m, H - 2 * m); } - if (kind === 'paint' || kind === 'carved') { const id = g.getImageData(0, 0, W, H), d = id.data; for (let i = 0; i < d.length; i += 4) { const n = (R() - 0.5) * (kind === 'carved' ? 34 : 18), gr = kind === 'paint' ? Math.sin((i / 4 % W) * 0.05 + ((i / 4 / W) | 0) * 0.9) * 6 : 0; d[i] += n + gr; d[i + 1] += n + gr; d[i + 2] += n + gr; } g.putImageData(id, 0, 0); } - } - // the letters - const ty = (H - lh * lines.length) / 2; - g.save(); g.translate(W / 2, ty + lh / 2); g.scale(sx, 1); - g.font = font; g.textAlign = 'center'; g.textBaseline = 'middle'; - lines.forEach((l, i) => { - const y = i * lh; - if (kind === 'carved') { g.fillStyle = 'rgba(255,255,255,0.25)'; g.fillText(l, 1.5, y + 1.5); g.fillStyle = st.color; g.fillText(l, 0, y); } - else { g.fillStyle = st.color; g.fillText(l, 0, y); } - }); - g.restore(); - // stencil: the bridges a cut-out stencil leaves, one or two thin gaps through each letter - if (kind === 'stencil') { - g.save(); g.globalCompositeOperation = 'destination-out'; g.font = font; - lines.forEach((l, i) => { - let x = W / 2 - c0.measureText(l).width * sx / 2; const y = ty + i * lh; - for (const ch of l) { const cw = c0.measureText(ch).width * sx; if (ch !== ' ' && !/[.\-]/.test(ch)) { g.fillRect(x + cw * 0.47, y + lh * 0.12, Math.max(2, S * 0.06), lh * 0.76); if (/[BDOPQR0689AE]/.test(ch)) g.fillRect(x, y + lh * 0.48, cw, Math.max(2, S * 0.05)); } x += cw; } - }); - g.restore(); - } - // distress: worn patches, scratches and specks taken out of the paint (and chips out of enamel, to dark iron) - const dst = st.distress != null ? st.distress : 0.3; - if (dst > 0) { - const id = g.getImageData(0, 0, W, H), d = id.data, ox = R() * 50, oy = R() * 50; - const vn = (x, y) => { const xi = Math.floor(x), yi = Math.floor(y), fx = x - xi, fy = y - yi, h = (a, b) => { let t = Math.imul(a * 374761393 + b * 668265263, 1274126177); t ^= t >>> 13; return ((t >>> 0) % 1000) / 1000; }; const ux = fx * fx * (3 - 2 * fx), uy = fy * fy * (3 - 2 * fy); return (h(xi, yi) * (1 - ux) + h(xi + 1, yi) * ux) * (1 - uy) + (h(xi, yi + 1) * (1 - ux) + h(xi + 1, yi + 1) * ux) * uy; }; - for (let y = 0; y < H; y++) for (let x = 0; x < W; x++) { - const i = (y * W + x) * 4; if (!d[i + 3]) continue; - const n = vn(x / 22 + ox, y / 22 + oy) * 0.6 + vn(x / 6 + oy, y / 6 + ox) * 0.3 + vn(x / 2, y / 2) * 0.1; - const wear = n + (R() - 0.5) * 0.08; - if (kind === 'enamel') { if (wear > 1 - dst * 0.35) { d[i] = 38; d[i + 1] = 30; d[i + 2] = 24; } } // chips to the iron - else if (kind === 'carved') { if (wear > 1 - dst * 0.5) d[i + 3] *= 0.55; } // weathered, shallower letters - else if (wear > 1 - dst * 0.55) d[i + 3] = 0; - else if (wear > 1 - dst * 0.8) d[i + 3] *= 0.45; - // grime toward the bottom edge - const gb = Math.max(0, y / H - 0.65) * dst; d[i] *= 1 - gb; d[i + 1] *= 1 - gb; d[i + 2] *= 1 - gb * 1.1; - } - g.putImageData(id, 0, 0); - } - return { canvas: cv, w: W, h: H, aspect: W / H }; - } - E.label = function (text, style) { - style = style || {}; - const key = text + '|' + JSON.stringify(style); - let L = cache.get(key); - if (!L) { L = draw(text, style); L.key = key; cache.set(key, L); } - return L; - }; - const V = THREE.Vector3; - E.labels = { - // world-space quad: centre p, outward normal n, width w (m); height from the label's aspect - place(L, p, n, w, o) { - o = o || {}; - const N = new V(n[0], n[1], n[2]).normalize(), up = o.up ? new V(o.up[0], o.up[1], o.up[2]) : (Math.abs(N.y) > 0.9 ? new V(0, 0, -1) : new V(0, 1, 0)); - const t = new V().crossVectors(up, N).normalize(), b = new V().crossVectors(N, t).normalize(); - if (o.rot) { const c = Math.cos(o.rot), s = Math.sin(o.rot), t2 = t.clone().multiplyScalar(c).addScaledVector(b, s); b.multiplyScalar(c).addScaledVector(t, -s); t.copy(t2); } - const h = w / L.aspect, c = new V(p[0], p[1], p[2]).addScaledVector(N, o.off != null ? o.off : 0.003); - pending.push({ L, c, t, b, N, w, h, curve: o.curve || 0 }); - return h; - }, - count() { return pending.length; }, - finish() { - if (!pending.length) return null; - // pack each distinct label once: shelf packing into 2048 wide, rows sorted by height - const used = [...new Set(pending.map(q => q.L))].sort((a, b) => b.h - a.h); - const AW = 2048, PAD = 4; let x = 0, y = 0, rowH = 0; - for (const L of used) { if (x + L.w + PAD * 2 > AW) { x = 0; y += rowH; rowH = 0; } L.ax = x + PAD; L.ay = y + PAD; x += L.w + PAD * 2; rowH = Math.max(rowH, L.h + PAD * 2); } - let AH = 64; while (AH < y + rowH && AH < 4096) AH *= 2; - const scale = (y + rowH) > 4096 ? 4096 / (y + rowH) : 1; // (never with today's text: shrink rather than drop) - const cv = document.createElement('canvas'); cv.width = AW; cv.height = AH; const g = cv.getContext('2d'); - for (const L of used) { - // padded gutter: the label's edge pixels smeared outward so mip levels do not bleed in neighbours - const X = L.ax * scale, Y = L.ay * scale, w = L.w * scale, h = L.h * scale; - g.drawImage(L.canvas, 0, 0, 1, L.h, X - PAD, Y, PAD, h); g.drawImage(L.canvas, L.w - 1, 0, 1, L.h, X + w, Y, PAD, h); - g.drawImage(L.canvas, X, Y, w, h); - L.u0 = X / AW; L.u1 = (X + w) / AW; L.v0 = 1 - (Y + h) / AH; L.v1 = 1 - Y / AH; - } - const tex = new THREE.CanvasTexture(cv); tex.encoding = THREE.sRGBEncoding; tex.anisotropy = Math.min(8, E.maxAniso || 1); - tex.minFilter = THREE.LinearMipmapLinearFilter; tex.generateMipmaps = true; - const P = [], Nn = [], U = [], I = []; - for (const q of pending) { - const base = P.length / 3, L = q.L, n = q.curve ? 8 : 1; - // a strip of n columns; with opts.curve (radius) it wraps round a cylinder (fuel drums) instead of a flat card - for (let i = 0; i <= n; i++) { - const f = i / n, s = (f - 0.5) * q.w, a = q.curve ? s / q.curve : 0, along = q.curve ? Math.sin(a) * q.curve : s, sink = q.curve ? (1 - Math.cos(a)) * q.curve : 0; - const nx = q.N.x * Math.cos(a) + q.t.x * Math.sin(a), ny = q.N.y * Math.cos(a) + q.t.y * Math.sin(a), nz = q.N.z * Math.cos(a) + q.t.z * Math.sin(a); - for (const j of [-1, 1]) { - P.push(q.c.x + q.t.x * along - q.N.x * sink + q.b.x * j * q.h / 2, q.c.y + q.t.y * along - q.N.y * sink + q.b.y * j * q.h / 2, q.c.z + q.t.z * along - q.N.z * sink + q.b.z * j * q.h / 2); - Nn.push(nx, ny, nz); U.push(L.u0 + (L.u1 - L.u0) * f, j < 0 ? L.v0 : L.v1); - } - } - for (let i = 0; i < n; i++) { const k = base + i * 2; I.push(k, k + 2, k + 3, k, k + 3, k + 1); } - } - const geo = new THREE.BufferGeometry(); - geo.setAttribute('position', new THREE.Float32BufferAttribute(P, 3)); geo.setAttribute('normal', new THREE.Float32BufferAttribute(Nn, 3)); geo.setAttribute('uv', new THREE.Float32BufferAttribute(U, 2)); - geo.setIndex(I); geo.computeBoundingSphere(); - const m = new THREE.MeshStandardMaterial({ map: tex, transparent: true, depthWrite: false, polygonOffset: true, polygonOffsetFactor: -2, polygonOffsetUnits: -4, roughness: 0.78, metalness: 0, alphaTest: 0.04 }); - m.userData.linear = true; - const mesh = new THREE.Mesh(geo, m); mesh.name = 'IVEnv.labels'; mesh.renderOrder = 3; mesh.receiveShadow = true; mesh.userData.dynamic = true; // (kept out of mergeStatic: it is already one mesh) - E.labels.stats = { labels: pending.length, distinct: used.length, atlas: AW + 'x' + AH }; - E.extraTexBytes = (E.extraTexBytes || 0) - (E.labels.bytes || 0) + AW * AH * 4 * 1.33; E.labels.bytes = AW * AH * 4 * 1.33; - pending = []; - return mesh; - }, - reset() { pending = []; } - }; -})(); diff --git a/e63334287a3deaa3/ironveil/env/nature.js b/e63334287a3deaa3/ironveil/env/nature.js deleted file mode 100644 index ee79667f..00000000 --- a/e63334287a3deaa3/ironveil/env/nature.js +++ /dev/null @@ -1,667 +0,0 @@ -/* Midnight Ops environment: trees, hedgerows, scattered plants and objects, and the stream. - IVEnv.tree(kind, seed) -> Group (one tree, LOD0; for a hero tree or a single prop) - IVEnv.trees(list) -> { group, update(camera), info() } list: [{ kind, x, y, z, rot, scale, seed }] - kinds: oak, ash, poplar, apple, pine, dead, sapling. Two variants per kind, instanced per kind + variant + LOD - (full mesh near, a reduced mesh in the middle distance, crossed-quad impostors far). LODs swap in IVEnv.update. - IVEnv.hedge(points, { h, w, gaps: [[from, to]], seed, heightFn }) -> { group, colliders } - IVEnv.scatter(kind, areaTest, { heightFn, density, radius, seed }) -> { group, update(camera), info() } - kinds: wheat, maize (standing crop 2.3 m), reeds, ferns, brambles, nettles, dock, flowers, rocks, logs, stumps, litter, puddles. - areaTest(x, z) -> 0..1 (density multiplier). Plants stream around the camera in tiles like the grass; - rocks, logs, stumps, litter and puddles are placed once over opts.bounds [x0, z0, x1, z1]. - IVEnv.stream(points, { width, heightFn, waterY(x, z) | level, flow }) -> { group } - All foliage shares the wind (IVEnv.setWind) with the grass. Leaves are alpha-tested cards (alpha-to-coverage with - MSAA) with coverage-preserving mipmaps, canopy normals, darker interiors and translucency. */ -(function () { - 'use strict'; - const E = window.IVEnv; - const TAU = Math.PI * 2; - const V3 = THREE.Vector3; - - // ------------------------------------------------------------------ leaf atlas (made once, in code) - // 4 x 2 cells of 256 px: 0 oak, 1 ash/apple leaflets, 2 poplar, 3 maize (was pine needles; pines are not used), 4 hawthorn (hedge), 5 fern frond, - // 6 bramble / nettle / dock (big serrated), 7 reed / wheat blades. - let atlas = null; - function leafShape(g, x, y, len, wid, ang, lobed, serr) { - g.save(); g.translate(x, y); g.rotate(ang); g.beginPath(); g.moveTo(0, 0); - const n = 14; - for (let i = 0; i <= n; i++) { const t = i / n, w = Math.sin(Math.PI * Math.pow(t, 0.85)) * wid * (lobed ? 1 + 0.35 * Math.sin(t * 22) : 1) * (serr ? 1 + 0.12 * ((i % 2) ? 1 : -1) : 1); g.lineTo(t * len, -w); } - for (let i = n; i >= 0; i--) { const t = i / n, w = Math.sin(Math.PI * Math.pow(t, 0.85)) * wid * (lobed ? 1 + 0.35 * Math.sin(t * 22 + 1) : 1) * (serr ? 1 + 0.12 * ((i % 2) ? -1 : 1) : 1); g.lineTo(t * len, w); } - g.closePath(); g.fill(); g.restore(); - } - function makeAtlas() { - if (atlas) return atlas; - const W = 1024, H = 512, C = 256, c = document.createElement('canvas'); c.width = W; c.height = H; - const g = c.getContext('2d'), R = E.rng(31); - const col = (h, s, l) => `hsl(${h},${s}%,${l}%)`; - const cell = (i, fn) => { g.save(); g.translate((i % 4) * C, Math.floor(i / 4) * C); g.beginPath(); g.rect(0, 0, C, C); g.clip(); fn(); g.restore(); }; - const twig = (x0, y0, x1, y1, w) => { g.strokeStyle = '#3b3226'; g.lineWidth = w; g.beginPath(); g.moveTo(x0, y0); g.quadraticCurveTo((x0 + x1) / 2 + R.range(-10, 10), (y0 + y1) / 2, x1, y1); g.stroke(); }; - // 0 oak: lobed leaves round a twig - cell(0, () => { twig(128, 250, 128, 40, 4); for (let i = 0; i < 46; i++) { const a = R() * TAU, r = 20 + R() * 95; g.fillStyle = col(78 + R() * 22, 30 + R() * 18, 16 + R() * 14); leafShape(g, 128 + Math.cos(a) * r * 0.7, 140 + Math.sin(a) * r * 0.9, R.range(34, 52), R.range(9, 14), a + R.range(-0.6, 0.6), true, false); } }); - // 1 ash / apple: pinnate leaflets - cell(1, () => { for (let k = 0; k < 6; k++) { const ax = 128 + R.range(-70, 70), ay = 128 + R.range(-70, 70), a = R() * TAU; twig(ax, ay, ax + Math.cos(a) * 90, ay + Math.sin(a) * 90, 2); for (let i = 0; i < 9; i++) { const t = i / 9; g.fillStyle = col(82 + R() * 18, 30 + R() * 20, 18 + R() * 14); for (const s of [-1, 1]) leafShape(g, ax + Math.cos(a) * 90 * t, ay + Math.sin(a) * 90 * t, R.range(18, 26), R.range(5, 7), a + s * 1.0, false, true); } } }); - // 2 poplar: small rounded leaves, dense - cell(2, () => { twig(128, 255, 128, 10, 3); for (let i = 0; i < 90; i++) { const y = R.range(15, 245), x = 128 + R.range(-1, 1) * 70 * Math.sin(Math.PI * y / 255); g.fillStyle = col(75 + R() * 25, 28 + R() * 20, 17 + R() * 15); leafShape(g, x, y, R.range(16, 24), R.range(7, 10), R() * TAU, false, false); } }); - // 3 maize (late summer): three stalks, broad arching leaves yellowing at the tips, a tassel, a cob or two - cell(3, () => { for (let k = 0; k < 3; k++) { const x = 60 + k * 68 + R.range(-12, 12), lean = R.range(-10, 10); - g.strokeStyle = col(58 + R() * 8, 30 + R() * 12, 34 + R() * 8); g.lineWidth = 5; g.beginPath(); g.moveTo(x, 256); g.quadraticCurveTo(x + lean * 0.5, 130, x + lean, 22); g.stroke(); - for (let i = 0; i < 9; i++) { const t = 0.12 + i * 0.09, y = 256 - t * 234, s2 = i % 2 ? 1 : -1, len = R.range(70, 105) * (1 - t * 0.35), a = s2 > 0 ? R.range(-0.6, -0.2) : Math.PI + R.range(0.2, 0.6); - g.fillStyle = col(62 + R() * 18 - t * 20, 30 + R() * 14, 22 + R() * 12 + t * 10); g.save(); g.translate(x + lean * t, y); g.rotate(a); g.beginPath(); g.moveTo(0, 0); - for (let q = 0; q <= 10; q++) { const u = q / 10; g.lineTo(u * len, -Math.sin(Math.PI * Math.min(1, u * 1.15)) * 9 + u * u * 26); } for (let q = 10; q >= 0; q--) { const u = q / 10; g.lineTo(u * len, Math.sin(Math.PI * Math.min(1, u * 1.15)) * 5 + u * u * 26); } g.fill(); g.restore(); } - g.strokeStyle = col(44, 40, 56); g.lineWidth = 1.5; for (let q = 0; q < 7; q++) { g.beginPath(); g.moveTo(x + lean, 24); g.lineTo(x + lean + R.range(-16, 16), R.range(2, 12)); g.stroke(); } - if (R() < 0.8) { g.fillStyle = col(48, 30, 52); g.save(); g.translate(x + lean * 0.5 + 7, 140 + R.range(-15, 15)); g.rotate(0.35); g.beginPath(); g.ellipse(0, 0, 6, 20, 0, 0, 6.29); g.fill(); g.restore(); } } }); - // 4 hawthorn / hedge: small lobed leaves, thorny twigs, very dense - cell(4, () => { for (let k = 0; k < 9; k++) twig(R() * 256, R() * 256, R() * 256, R() * 256, 2); for (let i = 0; i < 140; i++) { const a = R() * TAU, r = Math.sqrt(R()) * 120; g.fillStyle = col(72 + R() * 30, 24 + R() * 20, 13 + R() * 15); leafShape(g, 128 + Math.cos(a) * r, 128 + Math.sin(a) * r, R.range(14, 22), R.range(6, 9), R() * TAU, true, false); } }); - // 5 fern frond - cell(5, () => { g.strokeStyle = '#3c4a26'; g.lineWidth = 3; g.beginPath(); g.moveTo(128, 252); g.quadraticCurveTo(140, 128, 120, 8); g.stroke(); for (let i = 0; i < 30; i++) { const t = i / 30, y = 250 - t * 240, x = 128 + Math.sin(t * 2) * 8, l = 95 * Math.sin(Math.PI * Math.min(1, (1 - t) * 1.1)) + 6; g.fillStyle = col(85 + R() * 15, 30 + R() * 15, 16 + R() * 10); for (const s of [-1, 1]) for (let j = 0; j < 7; j++) leafShape(g, x + s * l * j / 8, y - j * 1.5, l / 8 + 3, 3.5, s > 0 ? -0.3 : Math.PI + 0.3, false, false); } }); - // 6 big serrated leaves (bramble, nettle, dock) - cell(6, () => { for (let i = 0; i < 12; i++) { const a = R() * TAU, r = Math.sqrt(R()) * 80; g.fillStyle = col(85 + R() * 20, 24 + R() * 16, 22 + R() * 14); leafShape(g, 128 + Math.cos(a) * r, 128 + Math.sin(a) * r, R.range(50, 80), R.range(16, 26), R() * TAU, false, true); } }); - // 7 ripe wheat: stalks with ears and awns, a few leaves - cell(7, () => { for (let i = 0; i < 26; i++) { const x = R.range(16, 240), lean = R.range(-18, 18), top = R.range(8, 60), l = 42 + R() * 10; - g.strokeStyle = col(44 + R() * 8, 30 + R() * 15, 40 + R() * 14); g.lineWidth = R.range(2, 3); g.beginPath(); g.moveTo(x, 256); g.quadraticCurveTo(x + lean * 0.3, 150, x + lean, top + l); g.stroke(); - g.fillStyle = col(42 + R() * 8, 38 + R() * 15, 46 + R() * 12); g.save(); g.translate(x + lean, top + l / 2); g.rotate(lean * 0.004); g.beginPath(); g.ellipse(0, 0, 5.5, l / 2, 0, 0, 6.29); g.fill(); - g.strokeStyle = col(45, 35, 58); g.lineWidth = 0.8; for (let k = 0; k < 8; k++) { g.beginPath(); g.moveTo(0, -l / 2 + k * l / 8); g.lineTo((k % 2 ? 1 : -1) * 6, -l / 2 + k * l / 8 - 14); g.stroke(); } g.restore(); } }); - const img = g.getImageData(0, 0, W, H); - // coverage-preserving mipmaps: each level keeps the share of texels above the alpha cut of level 0 - const levels = [{ data: new Uint8Array(img.data.buffer.slice(0)), width: W, height: H }]; - const cover = (d) => { let n = 0; for (let i = 3; i < d.length; i += 4) if (d[i] >= 128) n++; return n / (d.length / 4); }; - const target = cover(levels[0].data); - let w = W, h = H, prev = levels[0].data; - while (w > 1 || h > 1) { - const nw = Math.max(1, w >> 1), nh = Math.max(1, h >> 1), d = new Uint8Array(nw * nh * 4); - for (let y = 0; y < nh; y++) for (let x = 0; x < nw; x++) { - let r = 0, gg = 0, b = 0, a = 0; - for (let j = 0; j < 2; j++) for (let i = 0; i < 2; i++) { const k = (Math.min(h - 1, y * 2 + j) * w + Math.min(w - 1, x * 2 + i)) * 4, al = prev[k + 3] / 255; r += prev[k] * al; gg += prev[k + 1] * al; b += prev[k + 2] * al; a += al; } - const q = (y * nw + x) * 4; d[q] = a ? r / a : 40; d[q + 1] = a ? gg / a : 50; d[q + 2] = a ? b / a : 30; d[q + 3] = a / 4 * 255; - } - // scale alpha so coverage at the 0.5 cut matches level 0 - let lo = 0.5, hi = 4; - for (let it = 0; it < 12; it++) { const m = (lo + hi) / 2; let n = 0; for (let i = 3; i < d.length; i += 4) if (d[i] * m >= 128) n++; if (n / (nw * nh) < target) lo = m; else hi = m; } - const sc = (lo + hi) / 2; for (let i = 3; i < d.length; i += 4) d[i] = Math.min(255, d[i] * sc); - levels.push({ data: d, width: nw, height: nh }); prev = d; w = nw; h = nh; - } - const t = new THREE.DataTexture(levels[0].data, W, H, THREE.RGBAFormat); - t.mipmaps = levels; t.generateMipmaps = false; t.minFilter = THREE.LinearMipmapLinearFilter; t.magFilter = THREE.LinearFilter; - t.flipY = false; t.encoding = THREE.sRGBEncoding; t.anisotropy = 4; t.needsUpdate = true; - E.extraTexBytes = (E.extraTexBytes || 0) + W * H * 4 * 1.33; - atlas = t; return t; - } - E.leafAtlas = makeAtlas; - const cellUV = (i) => [(i % 4) / 4, Math.floor(i / 4) / 2, 0.25, 0.5]; // u0, v0, du, dv (row 0 = v 0, image row 0) - - // ------------------------------------------------------------------ foliage materials (wind, translucency) - const FOL_VS = ` - attribute vec4 aWind; // x: branch phase, y: branch sway weight, z: flutter weight, w: height in the plant (m) - ${E.GLSL.wind} - vec3 ivSway(vec3 p) { - vec3 ip = vec3(0.0); vec3 ax = vec3(1.0, 0.0, 0.0), az = vec3(0.0, 0.0, 1.0); float sc = 1.0; - #ifdef USE_INSTANCING - ip = vec3(instanceMatrix[3][0], instanceMatrix[3][1], instanceMatrix[3][2]); - ax = vec3(instanceMatrix[0][0], instanceMatrix[0][1], instanceMatrix[0][2]); az = vec3(instanceMatrix[2][0], instanceMatrix[2][1], instanceMatrix[2][2]); - sc = length(ax); ax /= sc; az /= length(az); - #else - ip = vec3(modelMatrix[3][0], modelMatrix[3][1], modelMatrix[3][2]); - #endif - vec2 wv = ivWind(ip.xz + p.xz * 0.3); - float hh = max(aWind.w, 0.0) * sc; - vec2 bend = wv * 0.012 * hh * hh * uStiff; // trunk / whole plant - float ph = aWind.x + uTime * 1.6; - bend += wv * aWind.y * (0.06 + 0.05 * sin(ph)) ; // branch sway, own phase - vec3 fl = vec3(sin(uTime * 8.3 + aWind.x * 9.0), sin(uTime * 7.1 + aWind.x * 5.0) * 0.6, cos(uTime * 9.2 + aWind.x * 7.0)) * aWind.z * 0.02 * (0.4 + uWind.z); - // to object space (instance rotation and scale) - vec2 ob = vec2(dot(vec3(bend.x, 0.0, bend.y), ax), dot(vec3(bend.x, 0.0, bend.y), az)) / sc; - return p + vec3(ob.x, -dot(ob, ob) * 0.3, ob.y) + fl / sc; - } - `; - function foliagePatch(m, opts) { - const uni = { uTime: E.U.uTime, uWind: E.U.uWind, uNight: E.U.uNight, uStiff: { value: opts.stiff == null ? 1 : opts.stiff }, uTrans: { value: opts.trans == null ? 1 : opts.trans } }; - m.userData.uniforms = uni; - const leaf = !!opts.leaf; - m.onBeforeCompile = function (sh) { - Object.assign(sh.uniforms, uni); - const P = (stage, a, b) => E.patch(sh, stage, a, b, 'env/nature ' + (leaf ? 'leaves ' : 'foliage ') + (opts.key || '')); - P('vertex', '#include ', 'vec3 transformed = ivSway(position);'); - sh.vertexShader = 'uniform float uStiff;\n' + FOL_VS + sh.vertexShader; - if (leaf) { - // r187: the light's colour already carries r128's factor PI (lib/three's compat layer), so the light through - // the leaf is not multiplied by PI again here; geometry.normal / geometry.viewDir are geometryNormal / ...ViewDir - P('fragment', '#include ', THREE.ShaderChunk.lights_physical_pars_fragment); - P('fragment', 'vec3 irradiance = dotNL * directLight.color;', `vec3 irradiance = dotNL * directLight.color; - { float back = saturate(dot(-geometryNormal, directLight.direction)); float scat = pow(saturate(dot(-geometryViewDir, directLight.direction)), 4.0); - vec3 tr = ivTransCol * directLight.color * (back * 0.2 + scat * 0.25) * ivTransAmt; - reflectedLight.directDiffuse += tr * RECIPROCAL_PI; }`); - P('fragment', '#include ', 'float faceDirection = gl_FrontFacing ? 1.0 : -1.0; vec3 normal = normalize(vNormal); vec3 nonPerturbedNormal = normal;'); - P('fragment', '#include ', '#include \n { float lm = dot(diffuseColor.rgb, vec3(0.3, 0.59, 0.11)), cap = mix(0.3, 0.15, uNight); if (lm > cap) diffuseColor.rgb *= cap / lm; } ivTransCol = diffuseColor.rgb * vec3(1.1, 1.2, 0.7); ivTransAmt = uTrans;'); - P('fragment', '#include ', 'reflectedLight.directSpecular = vec3(0.0); reflectedLight.indirectSpecular = vec3(0.0);'); - // alpha to coverage as r128 did it: cut at alphaTest, the texture's alpha gives the coverage. r187 sharpens the - // alpha over fwidth instead, which thinned distant hedges and crowns where the mip alpha varies pixel to pixel - P('fragment', '#include ', '#ifdef USE_ALPHATEST\n if (diffuseColor.a < alphaTest) discard;\n#endif'); - P('fragment', 'float dotNL = saturate( dot( geometryNormal, directLight.direction ) );', 'float dotNL = saturate( (dot( geometryNormal, directLight.direction ) + 0.45) / 1.45 ) * 0.85;'); - sh.fragmentShader = 'uniform float uTrans, uNight;\nvec3 ivTransCol; float ivTransAmt;\n' + sh.fragmentShader; - } - }; - m.customProgramCacheKey = () => 'ivfol' + (leaf ? 'L' : 'B') + (opts.key || ''); - return m; - } - const leafMats = {}, barkMats = {}; - E.leafMaterial = function (key, o) { - if (leafMats[key]) return leafMats[key]; - const m = new THREE.MeshStandardMaterial({ map: makeAtlas(), alphaTest: 0.5, side: THREE.DoubleSide, vertexColors: true, roughness: 0.95, metalness: 0, envMapIntensity: 0.12 }); - m.alphaToCoverage = !!(E.renderer && E.renderer.capabilities.isWebGL2 && E.Q.post); - m.userData.linear = true; - foliagePatch(m, Object.assign({ leaf: true, key }, o || {})); - // shadows of the cards follow their alpha - m.userData.depth = new THREE.MeshDepthMaterial({ depthPacking: THREE.RGBADepthPacking, map: m.map, alphaTest: 0.5, side: THREE.DoubleSide }); - leafMats[key] = m; return m; - }; - E.barkMaterial = function (name, stiff) { - const key = name + ':' + (stiff || 1); if (barkMats[key]) return barkMats[key]; - const base = E.mat(name), m = base.clone(); - m.userData = Object.assign({}, base.userData); - const prev = base.onBeforeCompile; - const uni = { uTime: E.U.uTime, uWind: E.U.uWind, uStiff: { value: stiff || 1 } }; - m.onBeforeCompile = function (sh) { - prev.call(this, sh); Object.assign(sh.uniforms, uni); - E.patch(sh, 'vertex', '#include ', 'vec3 transformed = ivSway(position);', 'env/nature bark ' + name); - sh.vertexShader = 'uniform float uStiff;\n' + FOL_VS + sh.vertexShader; - }; - m.customProgramCacheKey = () => 'ivbark' + name; - barkMats[key] = m; return m; - }; - - // ------------------------------------------------------------------ tree generator - const KIND = { - oak: { h: [7, 10], trunkR: 0.32, trunkH: 0.32, limbs: [5, 7], limbAng: [0.75, 1.15], limbLen: 0.55, depth: 3, child: 4, cards: 0.95, cell: 0, bark: 'bark_oak', crown: [0.5, 0.42], spread: 1.0, tint: 0xffffff, droop: 0.15 }, - ash: { h: [10, 14], trunkR: 0.24, trunkH: 0.45, limbs: [5, 6], limbAng: [0.45, 0.75], limbLen: 0.45, depth: 3, child: 3, cards: 0.85, cell: 1, bark: 'bark_oak', crown: [0.62, 0.32], spread: 0.8, tint: 0xc8c6c0, droop: 0.05 }, - poplar: { h: [16, 22], trunkR: 0.26, trunkH: 0.12, limbs: [16, 22], limbAng: [0.18, 0.35], limbLen: 0.16, depth: 2, child: 3, cards: 0.7, cell: 2, bark: 'bark_oak', crown: [0.55, 0.12], spread: 0.3, tint: 0xd0ccc4, droop: 0 }, - apple: { h: [3.5, 5], trunkR: 0.14, trunkH: 0.32, limbs: [4, 5], limbAng: [0.8, 1.2], limbLen: 0.6, depth: 3, child: 3, cards: 0.6, cell: 1, bark: 'bark_oak', crown: [0.6, 0.55], spread: 1.0, tint: 0x9a9088, droop: 0.25 }, - pine: { h: [12, 18], trunkR: 0.25, trunkH: 0.35, limbs: [44, 54], limbAng: [1.5, 1.85], limbLen: 0.28, depth: 2, child: 3, cards: 0.9, cell: 3, bark: 'bark_pine', crown: [0.6, 0.25], spread: 0.5, tint: 0xffffff, droop: 0.2, whorl: true }, - dead: { h: [7, 10], trunkR: 0.3, trunkH: 0.35, limbs: [4, 6], limbAng: [0.7, 1.1], limbLen: 0.5, depth: 3, child: 3, cards: 0, cell: 0, bark: 'bark_oak', crown: [0.5, 0.4], spread: 0.9, tint: 0x8a8580, droop: 0.1, broken: true }, - burnt: { h: [5, 8], trunkR: 0.28, trunkH: 0.4, limbs: [2, 4], limbAng: [0.6, 1.0], limbLen: 0.4, depth: 2, child: 2, cards: 0, cell: 0, bark: 'bark_oak', crown: [0.5, 0.4], spread: 0.7, tint: 0x2c2826, droop: 0.05, broken: true }, - sapling: { h: [2.2, 3.2], trunkR: 0.04, trunkH: 0.25, limbs: [4, 6], limbAng: [0.5, 0.9], limbLen: 0.35, depth: 2, child: 2, cards: 0.45, cell: 1, bark: 'bark_oak', crown: [0.6, 0.3], spread: 0.6, tint: 0xb0a898, droop: 0.05 } - }; - E.TREE_KINDS = KIND; - // Build one tree. lod 0 (full), 1 (reduced). Returns { bark: BufferGeometry, leaves: BufferGeometry|null, height, crown } - function genTree(kind, seed, lod) { - const K = KIND[kind], R = E.rng(seed * 131 + 7), H = R.range(K.h[0], K.h[1]); - const bark = { p: [], n: [], u: [], w: [], i: [] }, leaves = { p: [], n: [], u: [], c: [], w: [], i: [] }; - const crownC = new V3(0, H * K.crown[0] + H * 0.12, 0), crownR = new V3(H * K.crown[1] * K.spread + 1.0, H * (1 - K.crown[0]) * 0.75, H * K.crown[1] * K.spread + 1.0); - const sides = (r) => lod ? (r > 0.15 ? 6 : 4) : (r > 0.15 ? 10 : r > 0.05 ? 6 : 4); - // tube along a list of points with radii - function tube(pts, rad, phase) { - const s = sides(rad[0]), base = bark.p.length / 3; let vlen = 0; - for (let k = 0; k < pts.length; k++) { - const p = pts[k], q = pts[Math.min(pts.length - 1, k + 1)], o = pts[Math.max(0, k - 1)], dir = new V3().subVectors(q, o).normalize(); - if (k > 0) vlen += p.distanceTo(pts[k - 1]); - const up = Math.abs(dir.y) < 0.95 ? new V3(0, 1, 0) : new V3(1, 0, 0), a = new V3().crossVectors(dir, up).normalize(), b = new V3().crossVectors(dir, a).normalize(); - for (let j = 0; j <= s; j++) { - const t = j / s * TAU, nrm = a.clone().multiplyScalar(Math.cos(t)).addScaledVector(b, Math.sin(t)), r = rad[k] * (1 + (k === 0 && pts === trunkPts ? 0 : 0)); - bark.p.push(p.x + nrm.x * r, p.y + nrm.y * r, p.z + nrm.z * r); bark.n.push(nrm.x, nrm.y, nrm.z); - bark.u.push(j / s * TAU * Math.max(0.15, rad[k]) * 1.0, vlen); bark.w.push(phase, Math.min(1, p.distanceTo(new V3(0, p.y, 0)) / 4), 0, p.y); - } - } - for (let k = 0; k < pts.length - 1; k++) for (let j = 0; j < s; j++) { const a = base + k * (s + 1) + j, b = a + s + 1; bark.i.push(a, b, a + 1, a + 1, b, b + 1); } - } - const tips = []; - function quad(c, ax, ay, w, h, cell, cn, shade, phase) { - const base = leaves.p.length / 3, [u0, v0, du, dv] = cellUV(cell), hue = R.range(0.92, 1.06); - for (const [i, j] of [[-1, -1], [1, -1], [1, 1], [-1, 1]]) { - const v = c.clone().addScaledVector(ax, i * w / 2).addScaledVector(ay, j * h / 2); - leaves.p.push(v.x, v.y, v.z); leaves.n.push(cn.x, cn.y, cn.z); leaves.u.push(u0 + (i * 0.5 + 0.5) * du, v0 + (j * 0.5 + 0.5) * dv); - leaves.c.push(shade * hue * (kind === 'pine' ? 0.75 : 1), shade * (kind === 'pine' ? 0.92 : 1), shade * (2 - hue) * (kind === 'pine' ? 1.05 : 1)); leaves.w.push(phase, 1, 1, v.y); - } - leaves.i.push(base, base + 1, base + 2, base, base + 2, base + 3); - } - function card(p, size, cell, phase, sway, rotRand, along) { - // a leaf-cluster card facing a random direction, normal pointing out of the crown - const base = leaves.p.length / 3, rel = new V3().subVectors(p, crownC), out = rel.clone().normalize(); - let nrm = new V3(R.range(-1, 1), R.range(-0.4, 1), R.range(-1, 1)).normalize().lerp(out, 0.4).normalize(); - if (along) { const side = new V3().crossVectors(along, new V3(0, 1, 0)).normalize(); nrm = side.multiplyScalar(R() < 0.5 ? 1 : -1).add(new V3(0, R.range(0.2, 0.6), 0)).normalize(); } - const up = Math.abs(nrm.y) > 0.9 ? new V3(1, 0, 0) : new V3(0, 1, 0), tx = new V3().crossVectors(up, nrm).normalize(), ty = new V3().crossVectors(nrm, tx).normalize(); - const ang = rotRand ? R() * TAU : R.range(-0.5, 0.5), ca = Math.cos(ang), sa = Math.sin(ang), ax = tx.clone().multiplyScalar(ca).addScaledVector(ty, sa), ay = ty.clone().multiplyScalar(ca).addScaledVector(tx, -sa); - const [u0, v0, du, dv] = cellUV(cell); - // interior darkening: cards near the crown centre are in the shade of the others - const e = Math.sqrt((rel.x / crownR.x) ** 2 + (rel.y / crownR.y) ** 2 + (rel.z / crownR.z) ** 2), shade = E.clamp(0.35 + 0.7 * e, 0.35, 1.05); - const hue = R.range(0.9, 1.08); - const cn = out.clone().lerp(nrm, 0.25).normalize(); // canopy normal - for (const [i, j] of [[-1, -1], [1, -1], [1, 1], [-1, 1]]) { - const v = p.clone().addScaledVector(ax, i * size / 2).addScaledVector(ay, j * size / 2); - leaves.p.push(v.x, v.y, v.z); leaves.n.push(cn.x, cn.y, cn.z); leaves.u.push(u0 + (i * 0.5 + 0.5) * du, v0 + (j * 0.5 + 0.5) * dv); - leaves.c.push(shade * hue, shade, shade * (2 - hue)); leaves.w.push(phase, sway, 1, v.y); - } - leaves.i.push(base, base + 1, base + 2, base, base + 2, base + 3); - } - // the trunk: a slightly wandering line with a flared base - const trunkTop = H * K.trunkH + (K.whorl || kind === 'poplar' ? H * 0.6 : 0); - const trunkPts = [], trunkRad = [], tn = lod ? 4 : 7, lean = kind === 'pine' || kind === 'poplar' ? new V3(R.range(-0.03, 0.03), 0, R.range(-0.03, 0.03)) : new V3(R.range(-0.15, 0.15), 0, R.range(-0.15, 0.15)); - const fullH = K.whorl || kind === 'poplar' ? H * 0.95 : trunkTop; - for (let k = 0; k <= tn; k++) { const t = k / tn; const wob = kind === 'pine' ? 0.01 : 0.04; trunkPts.push(new V3(lean.x * t * t * H * 0.3 + R.range(-wob, wob) * (k > 0), t * fullH, lean.z * t * t * H * 0.3 + R.range(-wob, wob) * (k > 0))); trunkRad.push(K.trunkR * (1 - t * 0.55) * (k === 0 ? 1.45 : k === 1 ? 1.1 : 1)); } - trunkPts[0].y = -0.15; - tube(trunkPts, trunkRad, 0); - // roots: three or four short flares at the base (full LOD only) - if (!lod && K.trunkR > 0.1) for (let r = 0; r < 4; r++) { const a = r / 4 * TAU + R() * 0.8, d = new V3(Math.cos(a), 0, Math.sin(a)); tube([new V3(0, 0.25, 0).addScaledVector(d, K.trunkR * 0.6), new V3(0, 0.02, 0).addScaledVector(d, K.trunkR * 1.6), new V3(0, -0.12, 0).addScaledVector(d, K.trunkR * 2.6)], [K.trunkR * 0.45, K.trunkR * 0.28, K.trunkR * 0.1], 0); } - // branches, recursively - function branch(start, dir, len, rad, depth, phase) { - const n = lod ? 2 : 4, pts = [start.clone()], rads = [rad]; - const d = dir.clone(); - for (let k = 1; k <= n; k++) { - d.y -= K.droop * 0.25 * (depth + 1) / n; d.x += R.range(-0.18, 0.18); d.z += R.range(-0.18, 0.18); d.normalize(); - const p = pts[k - 1].clone().addScaledVector(d, len / n); pts.push(p); rads.push(rad * (1 - k / n * 0.65)); - } - if (K.broken && depth === 1 && R() < 0.4) { pts.length = 2; rads.length = 2; } - tube(pts, rads, phase); - const tip = pts[pts.length - 1]; - if (kind === 'pine' && K.cards > 0) { - // drooping bough: crossed needle fans along the branch, flat fan + a hanging fan - const segs = pts.length - 1; - for (let k = 0; k < segs; k++) { - const p0 = pts[k], p1 = pts[k + 1], c = p0.clone().lerp(p1, 0.5), ax = p1.clone().sub(p0); const L = ax.length(); ax.normalize(); - const side = new V3().crossVectors(ax, new V3(0, 1, 0)).normalize(), hang = new V3().crossVectors(side, ax).normalize(); - const wdt = (1.25 - 0.45 * k / segs) * (lod ? 1.3 : 1), shade = 0.42 + 0.3 * (k / segs); - // two fans hanging in a V under the bough (never a flat disc seen edge-on), plus a top fan - const w2 = wdt * 1.5, cA = Math.cos(0.75), sA = Math.sin(0.75); - for (const sg of [1, -1]) { const fd = side.clone().multiplyScalar(sg * cA).addScaledVector(hang, -sA).normalize(); quad(c.clone().addScaledVector(fd, w2 * 0.45), ax, fd, L + 0.4, w2, 3, side.clone().multiplyScalar(sg).add(new V3(0, 0.9, 0)).normalize(), shade * (0.8 + 0.2 * sg), phase); } - if (!lod) quad(c.clone().addScaledVector(hang, 0.06), ax, side, L + 0.3, wdt, 3, new V3(0, 1, 0).add(side.clone().multiplyScalar(0.3)).normalize(), shade, phase); - } - } - if (depth >= K.depth || rad < 0.02) { if (kind !== 'pine') tips.push(tip.clone()); return; } - const nch = K.child + (lod ? -1 : 0); - for (let c = 0; c < nch; c++) { - const t = R.range(0.35, 1), sp = pts[Math.min(pts.length - 1, Math.round(t * (pts.length - 1)))]; - const nd = d.clone().add(new V3(R.range(-1, 1), R.range(-0.2, 0.7), R.range(-1, 1)).multiplyScalar(0.9)).normalize(); - branch(sp, nd, len * R.range(0.45, 0.7), rad * 0.6, depth + 1, phase + R() * 2); - } - } - const nl = Math.round(R.range(K.limbs[0], K.limbs[1]) * (lod ? 0.75 : 1)); - for (let l = 0; l < nl; l++) { - const t = kind === 'pine' ? 0.22 + 0.76 * Math.pow((l + R() * 0.6) / nl, 0.9) : K.whorl || kind === 'poplar' ? 0.18 + 0.8 * (l + R()) / nl : 0.85 + R() * 0.15; - const sy = (K.whorl || kind === 'poplar') ? fullH * t : trunkTop * t; - const a = l / nl * TAU * 2.4 + R.range(-0.4, 0.4), el = R.range(K.limbAng[0], K.limbAng[1]); - const dir = new V3(Math.cos(a) * Math.sin(el), Math.cos(el), Math.sin(a) * Math.sin(el)).normalize(); - const lenK = (kind === 'pine' ? Math.pow(1 - t, 0.9) * 1.25 + 0.06 : K.whorl ? (1 - t) * 1.2 + 0.15 : 1) * K.limbLen * H * R.range(0.85, 1.1); - branch(new V3(lean.x * t * t * H * 0.3, sy, lean.z * t * t * H * 0.3), dir, lenK, K.trunkR * (K.whorl || kind === 'poplar' ? 0.25 : 0.6) * (1 - t * 0.3), 1, R() * 6); - } - // ---- crown mass: rounded sub-crowns of overlapping leaf clusters around the branch ends (poplar: a column) - if (K.cards > 0 && kind !== 'pine') { - let centres = []; - if (kind === 'poplar') { for (let y = H * 0.14; y < H * 0.98; y += 0.9) centres.push(new V3(R.range(-0.3, 0.3), y, R.range(-0.3, 0.3))); } - else { const mergeD = kind === 'sapling' ? 0.4 : 1.3; for (const t of tips) { if (!centres.some(c => c.distanceTo(t) < mergeD)) centres.push(t.clone().add(new V3(0, 0.35, 0))); } } - const rs0 = { oak: 1.9, ash: 1.6, apple: 1.2, sapling: 0.55, poplar: 1.55, dead: 0, burnt: 0 }[kind] || 1.4; - const per = Math.round((lod ? 10 : 30) * (kind === 'poplar' ? 1.4 : K.cards)), size0 = { sapling: 0.55, apple: 0.95, poplar: 1.3 }[kind] || 1.35; - for (const cc of centres) { - const rs = rs0 * R.range(0.8, 1.2) * (kind === 'poplar' ? (1 - 0.45 * Math.pow(cc.y / H, 3)) : 1); - for (let k = 0; k < per; k++) { - const dir = new V3(R.range(-1, 1), R.range(-0.7, 1), R.range(-1, 1)).normalize(), rr = rs * (0.3 + 0.7 * Math.cbrt(R())); - const p = cc.clone().addScaledVector(dir, rr); if (kind === 'poplar') { p.x = cc.x + (p.x - cc.x) * 0.75; p.z = cc.z + (p.z - cc.z) * 0.75; } - // spherical normals: mostly from the sub-crown centre, a little from the whole crown - const sub = p.clone().sub(cc).normalize(), whole = p.clone().sub(crownC).normalize(), cn = sub.multiplyScalar(0.6).add(whole.multiplyScalar(0.4)).normalize(); - const inner = rr / rs, shade = E.clamp(0.32 + 0.62 * inner + 0.12 * cn.y, 0.3, 0.98); - const fwd = cn.clone().lerp(new V3(R.range(-1, 1), R.range(-1, 1), R.range(-1, 1)).normalize(), 0.55).normalize(); - const up = Math.abs(fwd.y) > 0.9 ? new V3(1, 0, 0) : new V3(0, 1, 0), ax = new V3().crossVectors(up, fwd).normalize(), ay = new V3().crossVectors(fwd, ax).normalize(); - const sz = size0 * (lod ? 1.45 : 1) * R.range(0.8, 1.25); - quad(p, ax, ay, sz, sz, K.cell, cn, shade, R() * 6 + cc.x); - } - } - } - // a few cards hugging the upper trunk of columnar trees - const mk = (A, attrs) => { const g = new THREE.BufferGeometry(); for (const [k, n] of attrs) g.setAttribute(k, new THREE.Float32BufferAttribute(A[n.name], n.size)); g.setIndex(A.i); g.computeBoundingSphere(); return g; }; - const bg = new THREE.BufferGeometry(); - bg.setAttribute('position', new THREE.Float32BufferAttribute(bark.p, 3)); bg.setAttribute('normal', new THREE.Float32BufferAttribute(bark.n, 3)); - bg.setAttribute('uv', new THREE.Float32BufferAttribute(bark.u, 2)); bg.setAttribute('aWind', new THREE.Float32BufferAttribute(bark.w, 4)); - const ae = new Float32Array(bark.p.length / 3 * 4); const tc = new THREE.Color(K.tint); for (let i = 0; i < ae.length / 4; i++) { ae[i * 4] = tc.r; ae[i * 4 + 1] = tc.g; ae[i * 4 + 2] = tc.b; ae[i * 4 + 3] = 1 + Math.max(0, bark.p[i * 3 + 1]); } - bg.setAttribute('aEnv', new THREE.BufferAttribute(ae, 4)); bg.setIndex(bark.i); bg.computeBoundingSphere(); - let lg = null; - if (leaves.i.length) { - lg = new THREE.BufferGeometry(); - lg.setAttribute('position', new THREE.Float32BufferAttribute(leaves.p, 3)); lg.setAttribute('normal', new THREE.Float32BufferAttribute(leaves.n, 3)); - lg.setAttribute('uv', new THREE.Float32BufferAttribute(leaves.u, 2)); lg.setAttribute('color', new THREE.Float32BufferAttribute(leaves.c, 3)); - lg.setAttribute('aWind', new THREE.Float32BufferAttribute(leaves.w, 4)); lg.setIndex(leaves.i); lg.computeBoundingSphere(); - } - return { bark: bg, leaves: lg, height: H, radius: crownR.x, kind }; - } - const treeCache = {}; - function treeGeo(kind, variant, lod) { const k = kind + ':' + variant + ':' + lod; return treeCache[k] || (treeCache[k] = genTree(kind, 1000 + variant * 37 + kind.length * 101, lod)); } - E.tree = function (kind, seed) { - if (!KIND[kind]) throw new Error('IVEnv.tree: unknown kind ' + kind); - const t = genTree(kind, seed || 1, 0), g = new THREE.Group(); g.name = 'IVEnv.tree:' + kind; - const b = new THREE.Mesh(t.bark, E.barkMaterial(KIND[kind].bark)); b.castShadow = true; b.receiveShadow = true; g.add(b); - if (t.leaves) { const lm = E.leafMaterial(kind); const l = new THREE.Mesh(t.leaves, lm); l.castShadow = true; l.receiveShadow = true; l.customDepthMaterial = lm.userData.depth; g.add(l); } - g.userData.height = t.height; return g; - }; - - // impostor: the full tree drawn once from the side into a small texture, shown on two crossed quads - const impCache = {}; - function impostor(kind, variant) { - const k = kind + ':' + variant; if (impCache[k]) return impCache[k]; - const t = treeGeo(kind, variant, 0), r = E.renderer, S = 256; - const rt = new THREE.WebGLRenderTarget(S, S, { minFilter: THREE.LinearMipmapLinearFilter, generateMipmaps: true }); - const sc = new THREE.Scene(); sc.add(new THREE.AmbientLight(0xffffff, 0.55)); - const b = new THREE.Mesh(t.bark, new THREE.MeshLambertMaterial({ color: new THREE.Color(0x4a4038) })); sc.add(b); - if (t.leaves) { const lm = new THREE.MeshLambertMaterial({ map: makeAtlas(), alphaTest: 0.5, side: THREE.DoubleSide, vertexColors: true }); sc.add(new THREE.Mesh(t.leaves, lm)); } - const w = Math.max(t.radius * 1.15, t.height * 0.32) + 0.5, h = t.height * 1.08 + 0.5; - const cam = new THREE.OrthographicCamera(-w, w, h, 0 - 0.2, 0.1, 100); cam.position.set(0, 0, 50); cam.lookAt(0, 0, 0); - const prevT = r.getRenderTarget(), tm = r.toneMapping, cc = r.getClearColor(new THREE.Color()), ca = r.getClearAlpha(); - r.toneMapping = THREE.NoToneMapping; r.setRenderTarget(rt); r.setClearColor(0x2a3020, 0); r.clear(); r.render(sc, cam); - r.setRenderTarget(prevT); r.toneMapping = tm; r.setClearColor(cc, ca); - rt.texture.encoding = THREE.LinearEncoding; - const g = new THREE.BufferGeometry(), P = [], N = [], U = [], I = [], Wd = []; - for (let q = 0; q < 2; q++) { - const a = q * Math.PI / 2, c = Math.cos(a), s = Math.sin(a), base = P.length / 3; - for (const [i, j] of [[-1, 0], [1, 0], [1, 1], [-1, 1]]) { P.push(i * w * c, j * (h + 0.2) - 0.2, i * w * s); N.push(-s * 0.4, 0.9, c * 0.4); U.push(i * 0.5 + 0.5, j); Wd.push(0, 0, 0, j * h); } - I.push(base, base + 1, base + 2, base, base + 2, base + 3); - } - g.setAttribute('position', new THREE.Float32BufferAttribute(P, 3)); g.setAttribute('normal', new THREE.Float32BufferAttribute(N, 3)); g.setAttribute('uv', new THREE.Float32BufferAttribute(U, 2)); g.setAttribute('aWind', new THREE.Float32BufferAttribute(Wd, 4)); g.setIndex(I); - const m = new THREE.MeshStandardMaterial({ map: rt.texture, alphaTest: 0.5, side: THREE.DoubleSide, roughness: 0.9 }); m.userData.linear = true; - foliagePatch(m, { leaf: true, key: 'imp', stiff: 0.6, trans: 0.6 }); - m.alphaToCoverage = !!(r.capabilities.isWebGL2 && E.Q.post); - E.extraTexBytes = (E.extraTexBytes || 0) + S * S * 4 * 1.33; - return impCache[k] = { geo: g, mat: m, depth: new THREE.MeshDepthMaterial({ depthPacking: THREE.RGBADepthPacking, map: rt.texture, alphaTest: 0.5, side: THREE.DoubleSide }) }; - } - - // ------------------------------------------------------------------ instanced forests with LOD swaps - E.trees = function (list) { - const Q = E.Q, group = new THREE.Group(); group.name = 'IVEnv.trees'; - const sets = {}; // kind:variant -> { lod0: [bark, leaves], lod1: [...], imp, items } - const dummy = new THREE.Object3D(); - for (const it of list) { - const kind = KIND[it.kind] ? it.kind : 'oak', variant = (it.seed != null ? it.seed : Math.round(it.x * 7 + it.z * 13)) & 1, key = kind + ':' + variant; - let s = sets[key]; - if (!s) { - s = sets[key] = { kind, variant, items: [], meshes: [] }; - const cap = list.length; - const mkI = (geo, mat, lod, part, depth) => { const m = new THREE.InstancedMesh(geo, mat, cap); m.count = 0; m.castShadow = true; m.receiveShadow = true; m.frustumCulled = false; if (depth) m.customDepthMaterial = depth; m.userData = { lod, part }; group.add(m); s.meshes.push(m); return m; }; - for (const lod of [0, 1]) { - const t = treeGeo(kind, variant, lod); - const bm = mkI(t.bark, E.barkMaterial(KIND[kind].bark), lod, 'bark'); if (lod > 0) bm.castShadow = false; - if (t.leaves) { const lm = E.leafMaterial(kind); const lm2 = mkI(t.leaves, lm, lod, 'leaves', lm.userData.depth); if (E.Q.name === 'low' || lod > 0) lm2.castShadow = false; } - } - const imp = impostor(kind, variant); mkI(imp.geo, imp.mat, 2, 'imp', imp.depth).castShadow = false; - } - s.items.push({ x: it.x, y: it.y || 0, z: it.z, rot: it.rot != null ? it.rot : (it.x * 12.9898 + it.z * 78.233) % TAU, scale: it.scale || 1, lod: -1 }); - } - const T = { group, sets, last: -1, near: Q.treeLod, mid: Q.treeLod * (Q.name === 'low' ? 2 : 3) }; - T.update = function (camera, force) { - const now = performance.now(); if (!force && now - T.last < 250) return; T.last = now; - const cx = camera.position.x, cz = camera.position.z; - for (const k in sets) { - const s = sets[k], counts = [0, 0, 0]; - for (const m of s.meshes) m.count = 0; - for (const it of s.items) { - const d = Math.hypot(it.x - cx, it.z - cz), lod = d < T.near ? 0 : d < T.mid ? 1 : 2; - dummy.position.set(it.x, it.y, it.z); dummy.rotation.set(0, lod === 2 ? Math.atan2(cx - it.x, cz - it.z) : it.rot, 0); dummy.scale.setScalar(it.scale); dummy.updateMatrix(); - for (const m of s.meshes) if (m.userData.lod === lod) m.setMatrixAt(m.count++, dummy.matrix); - counts[lod]++; - } - for (const m of s.meshes) { m.instanceMatrix.needsUpdate = true; m.visible = m.count > 0; } - } - }; - T.info = function () { let tris = 0, calls = 0; for (const k in sets) for (const m of sets[k].meshes) if (m.count) { calls++; tris += m.count * m.geometry.index.count / 3; } return { drawCalls: calls, triangles: tris }; }; - T.colliders = list.map(it => ({ x: it.x, z: it.z, hx: (KIND[it.kind] || KIND.oak).trunkR * (it.scale || 1), hz: (KIND[it.kind] || KIND.oak).trunkR * (it.scale || 1), y0: it.y || 0, y1: (it.y || 0) + 4, rot: 0, surf: 'wood', kind: 'trunk' })); - (E._updaters = E._updaters || []).push((dt, cam) => T.update(cam)); - return T; - }; - - // ------------------------------------------------------------------ hedgerows - E.hedge = function (points, opts) { - opts = Object.assign({ h: 2.4, w: 1.8, gaps: [], seed: 21 }, opts || {}); - const R = E.rng(opts.seed), hf = opts.heightFn || (() => 0), group = new THREE.Group(); group.name = 'IVEnv.hedge'; - const colliders = []; - let total = 0; const segs = []; - for (let i = 0; i < points.length - 1; i++) { const a = points[i], b = points[i + 1], L = Math.hypot(b[0] - a[0], b[1] - a[1]); segs.push({ a, b, L, s0: total }); total += L; } - const inGap = (s) => opts.gaps.some(g => s > g[0] && s < g[1]); - const CH = 16, perM = E.Q.name === 'low' ? 7 : E.Q.name === 'medium' ? 17 : 30, cardK = E.Q.name === 'medium' ? 1.25 : E.Q.name === 'high' ? 1.06 : 1.12; // fewer, larger cards on Medium - const lm = E.leafMaterial('hedge', { stiff: 0.4 }), bm = E.barkMaterial('bark_oak', 0.3); - for (let c0 = 0; c0 < total; c0 += CH) { - const L = { p: [], n: [], u: [], c: [], w: [], i: [] }, Bk = E.builder(opts.seed + c0); - const at = (s) => { for (const sg of segs) if (s <= sg.s0 + sg.L + 1e-6) { const t = (s - sg.s0) / sg.L; return [sg.a[0] + (sg.b[0] - sg.a[0]) * t, sg.a[1] + (sg.b[1] - sg.a[1]) * t, (sg.b[0] - sg.a[0]) / sg.L, (sg.b[1] - sg.a[1]) / sg.L]; } const sg = segs[segs.length - 1]; return [sg.b[0], sg.b[1], (sg.b[0] - sg.a[0]) / sg.L, (sg.b[1] - sg.a[1]) / sg.L]; }; - const c1 = Math.min(total, c0 + CH), n = Math.round((c1 - c0) * perM * (E.Q.name === 'low' ? 1 : 1.08)); // +8%, and a third of all cards go to the lower 2 m (a dense foot) - const ctr = at((c0 + c1) / 2); - for (let k = 0; k < n; k++) { - const s = R.range(c0, c1); if (inGap(s)) continue; - // ragged profile: height and width wander, thinner near gap edges - const gapD = Math.min(...opts.gaps.map(g => s < g[0] ? g[0] - s : s > g[1] ? s - g[1] : 0), 99); - const hk = (0.82 + 0.3 * E.fbm2(s * 0.18, opts.seed, 77, 3)) * Math.min(1, 0.55 + gapD / 1.5), H = opts.h * hk; - const [px, pz, dx, dz] = at(s), side = R.range(-1, 1), y0 = hf(px, pz); - const low = R() < 0.32, u = low ? Math.pow(R(), 1.3) * Math.min(1, 2.0 / Math.max(H, 0.5)) : R(), y = y0 + (low ? u * H : Math.pow(u, 0.8) * H), wk = opts.w * 0.5 * (low ? 0.75 + 0.35 * R() : 0.6 + 0.6 * Math.sin(Math.PI * Math.min(1, u * 1.1 + 0.1))) * (0.8 + 0.4 * E.vnoise(s * 0.5, 3, opts.seed)); - const p = new V3(px - dz * side * wk, y, pz + dx * side * wk), cc = new V3(px, y0 + H * 0.5, pz); - const out = p.clone().sub(cc).normalize(), size = R.range(0.55, 0.95) * cardK; - const nrm = new V3(R.range(-1, 1), R.range(-0.5, 1), R.range(-1, 1)).normalize().lerp(out, 0.4).normalize(); - const up = Math.abs(nrm.y) > 0.9 ? new V3(1, 0, 0) : new V3(0, 1, 0), tx = new V3().crossVectors(up, nrm).normalize(), ty = new V3().crossVectors(nrm, tx).normalize(); - const ang = R() * TAU, ca = Math.cos(ang), sa = Math.sin(ang), ax = tx.clone().multiplyScalar(ca).addScaledVector(ty, sa), ay = ty.clone().multiplyScalar(ca).addScaledVector(tx, -sa); - const cell = R() < 0.75 ? 4 : R() < 0.5 ? 6 : 0, [u0, v0, du, dv] = cellUV(cell); - const shade = E.clamp(0.3 + 0.75 * Math.abs(side) + 0.25 * u, 0.3, 1.05), hue = R.range(0.88, 1.1), base = L.p.length / 3; - const cn = out.clone().lerp(nrm, 0.3).normalize(); - for (const [i, j] of [[-1, -1], [1, -1], [1, 1], [-1, 1]]) { const v = p.clone().addScaledVector(ax, i * size / 2).addScaledVector(ay, j * size / 2); L.p.push(v.x, v.y, v.z); L.n.push(cn.x, cn.y, cn.z); L.u.push(u0 + (i * 0.5 + 0.5) * du, v0 + (j * 0.5 + 0.5) * dv); L.c.push(shade * hue * (1 + 0.1 * u), shade * (1 - 0.1 * u), shade * (2 - hue) * (1 + 0.08 * u)); L.w.push(R() * 6, 0.4, 1, v.y - y0); } - L.i.push(base, base + 1, base + 2, base, base + 2, base + 3); - } - // stems and a few thicker hazel/hawthorn trunks seen in the gaps and at the foot - for (let k = 0; k < Math.round((c1 - c0) * 1.2); k++) { - const s = R.range(c0, c1); if (inGap(s)) continue; const [px, pz] = at(s), y0 = hf(px, pz); - const sx = R.range(-0.4, 0.4); Bk.det(1, () => Bk.box('bark_oak', px + sx, y0 - 0.1, pz + R.range(-0.4, 0.4), 0.05, opts.h * R.range(0.4, 0.8), 0.05, R() * TAU, { rx: R.range(-0.35, 0.35), rz: R.range(-0.35, 0.35), noFoot: true, tint: new THREE.Color(0.75, 0.72, 0.68) })); - } - // leaf litter and dead leaves at the foot of the hedge - for (let k = 0; k < Math.round((c1 - c0) / 2); k++) { const s = R.range(c0, c1), [px, pz, dx, dz] = at(s), sd = R.range(-1, 1) * opts.w * 0.7; Bk.decal(R() < 0.8 ? 'grime' : 'leaves', [px - dz * sd, hf(px - dz * sd, pz + dx * sd) + 0.03, pz + dx * sd], [0, 1, 0], R.range(1, 2), R.range(1, 2), R() * 6); } // mostly brown earth, a little litter - if (L.i.length) { - const g = new THREE.BufferGeometry(); - g.setAttribute('position', new THREE.Float32BufferAttribute(L.p, 3)); g.setAttribute('normal', new THREE.Float32BufferAttribute(L.n, 3)); g.setAttribute('uv', new THREE.Float32BufferAttribute(L.u, 2)); - g.setAttribute('color', new THREE.Float32BufferAttribute(L.c, 3)); g.setAttribute('aWind', new THREE.Float32BufferAttribute(L.w, 4)); g.setIndex(L.i); g.computeBoundingSphere(); - const m = new THREE.Mesh(g, lm); m.castShadow = E.Q.name !== 'low'; m.userData.shadowNear = 22; m.receiveShadow = true; m.customDepthMaterial = lm.userData.depth; m.name = 'hedge-leaves'; group.add(m); - } - const st = Bk.finish(); st.traverse(o => { if (o.isMesh && o.material === E.mat('bark_oak')) o.material = bm; }); group.add(st); - // colliders: sight-blocking boxes along the hedge (the game decides flags) - for (let s = c0; s < c1; s += 2) { if (inGap(s + 1)) continue; const [px, pz, dx, dz] = at(Math.min(c1, s + 1)), y0 = hf(px, pz); colliders.push({ x: px, z: pz, hx: 1.0, hz: opts.w * 0.45, y0, y1: y0 + opts.h * 0.9, rot: Math.atan2(-dz, dx), surf: 'foliage', kind: 'hedge' }); } - } - return { group, colliders }; - }; - - // ------------------------------------------------------------------ scatter: plants stream like grass, objects are placed once - function plantGeo(kind) { - // small meshes; aWind.w = height above the root - const P = [], N = [], U = [], C = [], W = [], I = [], R = E.rng(kind.length * 31 + 5); - const card = (cx, cy, cz, w, h, ang, cell, tilt, shade) => { - const [u0, v0, du, dv] = cellUV(cell), base = P.length / 3, ca = Math.cos(ang), sa = Math.sin(ang), tx = Math.sin(tilt || 0); - for (const [i, j] of [[-1, 0], [1, 0], [1, 1], [-1, 1]]) { const x = cx + ca * i * w / 2 + (j ? -sa * tx * h : 0), y = cy + j * h * Math.cos(tilt || 0), z = cz + sa * i * w / 2 + (j ? ca * tx * h : 0); P.push(x, y, z); N.push(-sa * 0.3, 0.9, ca * 0.3); U.push(u0 + (i * 0.5 + 0.5) * du, v0 + j * dv); C.push(shade, shade, shade); W.push(R() * 6, 0, j, y); } - I.push(base, base + 1, base + 2, base, base + 2, base + 3); - }; - const blade = (x, z, h, w, lean, ang, col) => { // a geometric stalk: tapered strip of 3 segments - const base = P.length / 3, ca = Math.cos(ang), sa = Math.sin(ang); - for (let k = 0; k <= 3; k++) { const t = k / 3, ww = w * (1 - t * 0.7), off = lean * t * t * h; for (const s of [-1, 1]) { const px = x + ca * off + -sa * s * ww / 2, pz = z + sa * off + ca * s * ww / 2; P.push(px, t * h, pz); N.push(ca * 0.3, 0.9, sa * 0.3); U.push(0.125 + s * 0.01, 0.95); C.push(col[0], col[1], col[2]); W.push(R() * 6, 0, t, t * h); } } - for (let k = 0; k < 3; k++) { const a = base + k * 2; I.push(a, a + 1, a + 2, a + 1, a + 3, a + 2); } - return [x + ca * lean * h, h, z + sa * lean * h]; - }; - if (kind === 'maize') { - // three crossed cards of standing maize, 2.3 m (6 triangles a clump) - for (let k = 0; k < 3; k++) card(0, 0, 0, 1.1, 2.3, k / 3 * Math.PI + R() * 0.3, 3, 0, 1.0); - } else if (kind === 'wheat') { - // three crossed cards of ripe stalks (6 triangles): cheap enough for a whole field - for (let k = 0; k < 3; k++) card(0, 0, 0, 0.55, 1.0, k / 3 * Math.PI + R() * 0.3, 7, 0, 1.0); - } else if (kind === 'reeds') { for (let k = 0; k < 9; k++) blade(R.range(-0.15, 0.15), R.range(-0.15, 0.15), R.range(1.1, 1.8), 0.02, R.range(0.05, 0.35), R() * TAU, [0.9, 1.0, 0.75]); } - else if (kind === 'ferns') { for (let k = 0; k < 6; k++) { const a = k / 6 * TAU + R() * 0.4; card(Math.cos(a) * 0.12, 0, Math.sin(a) * 0.12, 0.45, 0.75, a + Math.PI / 2, 5, 0.7, 0.9); } } - else if (kind === 'brambles') { for (let k = 0; k < 7; k++) { const a = R() * TAU; card(R.range(-0.3, 0.3), R.range(0, 0.3), R.range(-0.3, 0.3), 0.7, 0.55, a, 6, R.range(0.2, 0.8), R.range(0.6, 1.0)); } for (let k = 0; k < 4; k++) blade(R.range(-0.3, 0.3), R.range(-0.3, 0.3), R.range(0.8, 1.2), 0.012, R.range(0.6, 1.1), R() * TAU, [0.6, 0.45, 0.4]); } - else if (kind === 'nettles') { for (let k = 0; k < 5; k++) { const x = R.range(-0.15, 0.15), z = R.range(-0.15, 0.15), h = R.range(0.6, 1.0); blade(x, z, h, 0.012, 0.05, R() * TAU, [0.7, 0.8, 0.6]); for (let j = 0; j < 3; j++) card(x, h * (0.35 + j * 0.22), z, 0.28 - j * 0.05, 0.22, R() * TAU, 6, 1.2, 0.9); } } - else if (kind === 'dock') { for (let k = 0; k < 6; k++) { const a = k / 6 * TAU; card(0, 0.02, 0, 0.35, 0.55, a, 6, 1.1, 0.85); } blade(0, 0, 0.9, 0.015, 0.05, 0, [0.7, 0.5, 0.4]); } - else if (kind === 'flowers') { for (let k = 0; k < 4; k++) { const tip = blade(R.range(-0.1, 0.1), R.range(-0.1, 0.1), R.range(0.3, 0.55), 0.006, 0.1, R() * TAU, [0.8, 0.9, 0.7]); const base = P.length / 3; for (let s = 0; s < 5; s++) { const a = s / 5 * TAU; P.push(tip[0] + Math.cos(a) * 0.022, tip[1], tip[2] + Math.sin(a) * 0.022); N.push(0, 1, 0); U.push(0.13, 0.96); C.push(3.2, 3.1, 2.6); W.push(0, 0, 1, tip[1]); } P.push(tip[0], tip[1] + 0.005, tip[2]); N.push(0, 1, 0); U.push(0.13, 0.96); C.push(3, 2.6, 0.8); W.push(0, 0, 1, tip[1]); for (let s = 0; s < 5; s++) I.push(base + s, base + 5, base + (s + 1) % 5); } } - const g = new THREE.BufferGeometry(); - g.setAttribute('position', new THREE.Float32BufferAttribute(P, 3)); g.setAttribute('normal', new THREE.Float32BufferAttribute(N, 3)); g.setAttribute('uv', new THREE.Float32BufferAttribute(U, 2)); - g.setAttribute('color', new THREE.Float32BufferAttribute(C, 3)); g.setAttribute('aWind', new THREE.Float32BufferAttribute(W, 4)); g.setIndex(I); g.computeBoundingSphere(); - return g; - } - const PLANTS = { - wheat: { dens: 7, r: [25, 35, 45], scale: [0.7, 1.15], tint: 0xa09070, cell: 7, stiff: 1.4 }, - maize: { dens: 2.2, r: [35, 45, 60], scale: [0.85, 1.15], tint: 0x767c56, cell: 3, stiff: 1.0 }, - reeds: { dens: 3, r: [20, 30, 40], scale: [0.8, 1.2], tint: 0x8a9a5a, stiff: 1.2 }, - ferns: { dens: 1.2, r: [18, 25, 35], scale: [0.7, 1.3], tint: 0x6a8040, stiff: 0.6 }, - brambles: { dens: 0.8, r: [18, 25, 35], scale: [0.8, 1.4], tint: 0x5a6a38, stiff: 0.5 }, - nettles: { dens: 1.5, r: [15, 22, 30], scale: [0.7, 1.2], tint: 0x5f7040, stiff: 0.8 }, - dock: { dens: 0.6, r: [15, 22, 30], scale: [0.7, 1.2], tint: 0x5a6a34, stiff: 0.6 }, - flowers: { dens: 1.5, r: [12, 18, 25], scale: [0.8, 1.2], tint: 0x6a7a48, stiff: 1.2 } - }; - E.scatter = function (kind, areaTest, opts) { - opts = Object.assign({ density: 1, seed: 7 }, opts || {}); - const hf = opts.heightFn || (() => 0), Q = E.Q, qi = Q.name === 'low' ? 0 : Q.name === 'medium' ? 1 : 2; - if (PLANTS[kind]) { - if (Q.plantKinds && Q.plantKinds.indexOf(kind) < 0) { const g = new THREE.Group(); g.name = 'IVEnv.scatter:' + kind + ' (off on ' + Q.name + ')'; return { group: g, update() { }, info() { return { drawCalls: 0, triangles: 0 }; } }; } - return plantField(kind, areaTest, hf, opts, qi); - } - return objectField(kind, areaTest, hf, opts); - }; - const _pm = new THREE.Matrix4(), _fr = new THREE.Frustum(), _bx = new THREE.Box3(); - function plantField(kind, areaTest, hf, opts, qi) { - const P = PLANTS[kind], radius = opts.radius || P.r[qi], dens = P.dens * opts.density * (qi === 0 ? 0.5 : qi === 1 ? 0.75 : 1), TS = 8; - const geo = plantGeo(kind), lm = E.leafMaterial('plant-' + kind, { stiff: P.stiff, trans: 1 }); - const cap = Math.ceil(Math.PI * (radius + 10) ** 2 * dens * 0.9); - const mesh = new THREE.InstancedMesh(geo, lm, cap); mesh.count = 0; mesh.frustumCulled = false; - // The per-instance tint buffer must be made at full capacity here: InstancedMesh.setColorAt sizes it from the - // current count, which is 0 at this point, and every tint then reads as black (the old black cut-out plants). - mesh.instanceColor = new THREE.InstancedBufferAttribute(new Float32Array(cap * 3).fill(1), 3); mesh.receiveShadow = true; mesh.castShadow = kind === 'wheat' || kind === 'maize' ? false : qi === 2; mesh.customDepthMaterial = lm.userData.depth; mesh.name = 'scatter-' + kind; - const tint = new THREE.Color(P.tint).convertSRGBToLinear(); if (kind !== 'wheat' && kind !== 'maize') tint.multiplyScalar(0.6 / Math.max(tint.r, tint.g, tint.b)); // a hue shift, not a darkening (the atlas already carries the colour) - const tiles = new Map(), group = new THREE.Group(); group.add(mesh); group.name = 'IVEnv.scatter:' + kind; - const dummy = new THREE.Object3D(), col = new THREE.Color(); - const gen = (tx, tz) => { - const out = [], n = Math.ceil(Math.sqrt(dens * TS * TS)), cell = TS / n; - for (let j = 0; j < n; j++) for (let i = 0; i < n; i++) { - const gi = tx * n + i, gj = tz * n + j, x = tx * TS + (i + E.hash(gi, gj, 61 + opts.seed)) * cell, z = tz * TS + (j + E.hash(gi, gj, 62 + opts.seed)) * cell; - const a = areaTest(x, z); if (!a || E.hash(gi, gj, 63 + opts.seed) > a) continue; - const patch = E.fbm2(x / 9, z / 9, 66 + opts.seed, 2), s = (P.scale[0] + (P.scale[1] - P.scale[0]) * E.hash(gi, gj, 64)) * (0.85 + 0.3 * E.fbm2(x / 3.5, z / 3.5, 67 + opts.seed, 2)); - out.push(x, hf(x, z) - 0.02, z, E.hash(gi, gj, 65) * TAU, s * (0.85 + 0.3 * patch), patch); - } - return new Float32Array(out); - }; - let key = ''; - const F = { - group, update(camera) { - const cx = camera.position.x, cz = camera.position.z, i0 = Math.floor((cx - radius) / TS), i1 = Math.floor((cx + radius) / TS), j0 = Math.floor((cz - radius) / TS), j1 = Math.floor((cz + radius) / TS); - const fwd = new V3(); camera.getWorldDirection(fwd); const yaw = Math.round(Math.atan2(fwd.x, fwd.z) / 0.26); - const k = i0 + ',' + j0 + ',' + i1 + ',' + j1 + ',' + yaw + ',' + Math.round(camera.position.x / 4) + ',' + Math.round(camera.position.z / 4); if (k === key) return; key = k; - camera.updateMatrixWorld(); _pm.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse); _fr.setFromProjectionMatrix(_pm); - let n = 0; - for (let tz = j0; tz <= j1; tz++) for (let tx = i0; tx <= i1; tx++) { - const dxT = Math.max(tx * TS - cx, 0, cx - (tx + 1) * TS), dzT = Math.max(tz * TS - cz, 0, cz - (tz + 1) * TS); - _bx.min.set(tx * TS - 2, camera.position.y - 60, tz * TS - 2); _bx.max.set((tx + 1) * TS + 2, camera.position.y + 60, (tz + 1) * TS + 2); - if (Math.hypot(dxT, dzT) > 4 && !_fr.intersectsBox(_bx)) continue; - const tk = tx + ',' + tz; let t = tiles.get(tk); if (!t) { t = gen(tx, tz); tiles.set(tk, t); } - for (let q = 0; q < t.length && n < mesh.instanceMatrix.count; q += 6) { - const d = Math.hypot(t[q] - cx, t[q + 2] - cz); if (d > radius) continue; - const fade = E.clamp((radius - d) / 6, 0, 1); - dummy.position.set(t[q], t[q + 1], t[q + 2]); dummy.rotation.set(0, t[q + 3], 0); dummy.scale.setScalar(t[q + 4] * (0.3 + 0.7 * fade)); dummy.updateMatrix(); - mesh.setMatrixAt(n, dummy.matrix); - col.copy(tint).multiplyScalar(0.8 + 0.4 * t[q + 5]); mesh.setColorAt(n, col); n++; - } - } - mesh.count = n; mesh.instanceMatrix.needsUpdate = true; if (mesh.instanceColor) mesh.instanceColor.needsUpdate = true; - if (tiles.size > 400) tiles.clear(); - }, - info() { return { drawCalls: mesh.count ? 1 : 0, triangles: mesh.count * geo.index.count / 3, instances: mesh.count }; } - }; - (E._systems = E._systems || []).push(F); - return F; - } - // objects placed once over bounds (rocks, logs, stumps, leaf litter, puddles): merged, not streamed - function objectField(kind, areaTest, hf, opts) { - if (E.Q.name === 'low' && (kind === 'logs' || kind === 'stumps' || kind === 'rocks')) { const g = new THREE.Group(); g.name = 'IVEnv.scatter:' + kind + ' (off on low)'; return { group: g, colliders: [], update() { }, info() { return {}; } }; } - const b = opts.bounds || [-50, -50, 50, 50], R = E.rng(opts.seed * 17 + kind.length), B = E.builder(opts.seed), group = new THREE.Group(); - const area = (b[2] - b[0]) * (b[3] - b[1]), dens = { rocks: 0.006, logs: 0.004, stumps: 0.004, litter: 0.02, puddles: 0.006 }[kind] || 0.01; - const n = Math.round(area * dens * opts.density * (E.Q.name === 'low' && kind !== 'puddles' ? 0.45 : 1)), colliders = []; - const puddles = []; - let placed = 0; - for (let k = 0; k < n * 6 && placed < n; k++) { - const x = R.range(b[0], b[2]), z = R.range(b[1], b[3]), a = areaTest(x, z); if (!a || R() > a) continue; placed++; - const y = hf(x, z); - if (kind === 'rocks') { const s = R.range(0.12, 0.6) * (R() < 0.1 ? 2 : 1); E.placeRock(B, 'fieldstone', x, y - s * 0.35, z, s, (R() * 999) | 0, [R() * 0.4, R() * 6, R() * 0.4], E.tintJ(R, 0.15, 0x8a8680)); if (R() < 0.6) B.decal('moss', [x, y + s * 0.42, z], [0, 1, 0], s * 1.3, s * 1.3, R() * 6); if (s > 0.4) colliders.push({ x, z, hx: s * 0.8, hz: s * 0.8, y0: y, y1: y + s * 0.5, rot: 0, surf: 'stone', kind: 'rock' }); } - else if (kind === 'logs') { const L = R.range(1.5, 4), r = R.range(0.12, 0.3), rot = R() * TAU, g = new THREE.CylinderGeometry(r, r * 1.08, L, 9, 3); g.rotateZ(Math.PI / 2); B.geo('bark_oak', g, new THREE.Matrix4().compose(new V3(x, y + r * 0.8, z), new THREE.Quaternion().setFromEuler(new THREE.Euler(0, rot, R.range(-0.05, 0.05))), new V3(1, 1, 1)), { tint: new THREE.Color(0.7, 0.66, 0.6), foot: y }); for (const s of [-1, 1]) B.geo('timber', new THREE.CircleGeometry(r * 0.96, 9), new THREE.Matrix4().compose(new V3(x + Math.cos(rot) * s * L / 2, y + r * 0.8, z - Math.sin(rot) * s * L / 2), new THREE.Quaternion().setFromEuler(new THREE.Euler(0, rot + s * Math.PI / 2, 0)), new V3(1, 1, 1)), { noFoot: true, tint: new THREE.Color(0.9, 0.75, 0.6) }); B.decal('moss', [x, y + r * 1.75, z], [0, 1, 0], L * 0.6, r * 1.5, rot); colliders.push({ x, z, hx: L / 2, hz: r, y0: y, y1: y + r * 1.6, rot, surf: 'wood', kind: 'log' }); } - else if (kind === 'stumps') { const r = R.range(0.18, 0.45), h = R.range(0.25, 0.6); B.geo('bark_oak', new THREE.CylinderGeometry(r * 0.9, r * 1.25, h, 10, 2), new THREE.Matrix4().compose(new V3(x, y + h / 2 - 0.05, z), new THREE.Quaternion(), new V3(1, 1, 1)), { tint: new THREE.Color(0.7, 0.66, 0.6), foot: y }); B.geo('timber', new THREE.CircleGeometry(r * 0.88, 10).rotateX(-Math.PI / 2), new THREE.Matrix4().makeTranslation(x, y + h - 0.049, z), { noFoot: true, tint: new THREE.Color(0.85, 0.72, 0.6) }); B.decal('moss', [x, y + h - 0.04, z], [0, 1, 0], r * 1.6, r * 1.6, R() * 6); colliders.push({ x, z, hx: r, hz: r, y0: y, y1: y + h, rot: 0, surf: 'wood', kind: 'stump' }); } - else if (kind === 'litter') B.decal('leaves', [x, y + 0.02, z], [0, 1, 0], R.range(1, 2.5), R.range(1, 2.5), R() * 6); - else if (kind === 'puddles') puddles.push([x, y, z, R.range(0.6, 2.2), R.range(0.4, 1.4), R() * TAU]); - } - const g = B.finish({ castShadow: kind === 'logs' }); group.add(g); group.name = 'IVEnv.scatter:' + kind; - if (puddles.length) group.add(E.puddleMesh(puddles)); - return { group, colliders, update() { }, info() { return {}; } }; - } - // standing water discs (ruts, yard): dark mirror with soft edges, rippling when it rains - let pudMat = null; - E.puddleMaterial = function () { - if (pudMat) return pudMat; - const m = new THREE.MeshStandardMaterial({ color: 0x07080a, roughness: 0.06, metalness: 0, transparent: true, depthWrite: false, polygonOffset: true, polygonOffsetFactor: -1, polygonOffsetUnits: -2, envMapIntensity: 0.55 }); m.defines = { USE_UV: '' }; - const uni = { uTime: E.U.uTime, uWet: E.U.uWet }; m.customProgramCacheKey = () => 'ivpuddle'; - m.onBeforeCompile = (sh) => { - Object.assign(sh.uniforms, uni); - E.patch(sh, 'fragment', '#include ', `{ vec2 p = vUv * 6.0; float rn = uWet; vec2 g = vec2(ivN(p * 3.0 + uTime * 0.7) - ivN(p * 3.0 + vec2(0.37, 0.0) + uTime * 0.7), ivN(p * 3.0 + vec2(0.0, 0.37) - uTime * 0.5) - ivN(p * 3.0 - uTime * 0.5)); normal = normalize(normal + (vec3(g.x, g.y, 0.0)) * (0.05 + 0.3 * rn)); }`, 'env/nature puddle'); - E.patch(sh, 'fragment', '#include ', '{ float r = length(vUv - 0.5) * 2.0; diffuseColor.a = smoothstep(1.0, 0.55, r + (ivN(vUv * 9.0) - 0.5) * 0.4); }', 'env/nature puddle'); - sh.fragmentShader = 'uniform float uTime, uWet;\n' + E.GLSL.noise + sh.fragmentShader; - }; - m.userData.linear = true; pudMat = m; return m; - }; - // opaque brown water (shell holes, ruts in clay): the same ripples, a muddy colour, little reflection - let pudMatB = null; - E.puddleMaterialBrown = function () { - if (pudMatB) return pudMatB; - const m = E.puddleMaterial().clone(); m.defines = { USE_UV: '' }; m.color.setHex(0x2a2012); m.roughness = 0.16; m.envMapIntensity = 0.3; m.onBeforeCompile = E.puddleMaterial().onBeforeCompile; m.customProgramCacheKey = () => 'ivpuddle'; - m.userData.linear = true; pudMatB = m; return m; - }; - E.puddleMesh = function (list, opts) { - const B = { p: [], n: [], u: [], i: [] }; - for (const [x, y, z, a, b, r] of list) { - const base = B.p.length / 3, c = Math.cos(r), s = Math.sin(r); - for (const [i, j] of [[-1, -1], [1, -1], [1, 1], [-1, 1]]) { B.p.push(x + c * i * a - s * j * b, y + 0.015, z + s * i * a + c * j * b); B.n.push(0, 1, 0); B.u.push(i * 0.5 + 0.5, j * 0.5 + 0.5); } - B.i.push(base, base + 2, base + 1, base, base + 3, base + 2); - } - const g = new THREE.BufferGeometry(); g.setAttribute('position', new THREE.Float32BufferAttribute(B.p, 3)); g.setAttribute('normal', new THREE.Float32BufferAttribute(B.n, 3)); g.setAttribute('uv', new THREE.Float32BufferAttribute(B.u, 2)); g.setIndex(B.i); - g.computeBoundingSphere(); - const m = new THREE.Mesh(g, opts && opts.brown ? E.puddleMaterialBrown() : E.puddleMaterial()); m.receiveShadow = true; m.renderOrder = 1; m.name = 'puddles'; return m; - }; - - // ------------------------------------------------------------------ the stream - E.stream = function (points, opts) { - opts = Object.assign({ width: 3, flow: 0.35 }, opts || {}); - const hf = opts.heightFn || (() => 0), wy = opts.waterY || ((x, z) => opts.level != null ? opts.level : 0); - const P = [], N = [], U = [], D = [], I = []; - let along = 0; const step = 1.0, across = 6; - const pts = []; - for (let i = 0; i < points.length - 1; i++) { const a = points[i], b = points[i + 1], L = Math.hypot(b[0] - a[0], b[1] - a[1]), n = Math.max(1, Math.round(L / step)); for (let k = 0; k < n; k++) pts.push([a[0] + (b[0] - a[0]) * k / n, a[1] + (b[1] - a[1]) * k / n]); } - pts.push(points[points.length - 1]); - for (let i = 0; i < pts.length; i++) { - const p = pts[i], q = pts[Math.min(pts.length - 1, i + 1)], o = pts[Math.max(0, i - 1)], dx = q[0] - o[0], dz = q[1] - o[1], l = Math.hypot(dx, dz) || 1, nx = -dz / l, nz = dx / l; - if (i > 0) along += Math.hypot(p[0] - pts[i - 1][0], p[1] - pts[i - 1][1]); - const w = opts.width * (0.85 + 0.3 * E.vnoise(along * 0.2, 1, 9)); - for (let k = 0; k <= across; k++) { - const t = k / across - 0.5, x = p[0] + nx * t * w * 1.6, z = p[1] + nz * t * w * 1.6, y = wy(p[0], p[1]); - P.push(x, y, z); N.push(0, 1, 0); U.push(t * w * 1.6, along); D.push(Math.max(0, y - hf(x, z))); - } - } - for (let i = 0; i < pts.length - 1; i++) for (let k = 0; k < across; k++) { const a = i * (across + 1) + k, b = a + across + 1; I.push(a, b, a + 1, a + 1, b, b + 1); } - const g = new THREE.BufferGeometry(); - g.setAttribute('position', new THREE.Float32BufferAttribute(P, 3)); g.setAttribute('normal', new THREE.Float32BufferAttribute(N, 3)); g.setAttribute('uv', new THREE.Float32BufferAttribute(U, 2)); g.setAttribute('aDepth', new THREE.Float32BufferAttribute(D, 1)); - g.setIndex(I); g.computeBoundingSphere(); - // water: Fresnel reflection of the sky (environment map) and lamps, two ripple normals scrolling along the flow, - // body colour from depth (clear at the edge, dark peat-brown green in the middle), lapping foam at the banks - const m = new THREE.MeshStandardMaterial({ color: 0x0b1210, roughness: 0.05, metalness: 0, transparent: true, depthWrite: false, envMapIntensity: 1.2 }); m.defines = { USE_UV: '' }; - const uni = { uTime: E.U.uTime, uWet: E.U.uWet, uFlow: { value: opts.flow }, uMacro: E.U.uMacro }; m.customProgramCacheKey = () => 'ivwater'; - m.onBeforeCompile = (sh) => { - Object.assign(sh.uniforms, uni); - const P = (stage, a, b) => E.patch(sh, stage, a, b, 'env/nature stream'); - P('vertex', '#include ', '#include \n vDepth = aDepth;'); - sh.vertexShader = 'attribute float aDepth; varying float vDepth;\n' + sh.vertexShader; - P('fragment', '#include ', ` - float dep = vDepth; - vec3 shallow = vec3(0.045, 0.05, 0.035), deep = vec3(0.006, 0.012, 0.011); - diffuseColor.rgb = mix(deep, shallow, exp(-dep * 3.0)); - vec2 fuv1 = vUv * vec2(0.35, 0.18) + vec2(0.0, -uTime * uFlow * 0.18), fuv2 = vUv * vec2(0.7, 0.3) + vec2(0.31, -uTime * uFlow * 0.31); - float f1 = texture2D(uMacro, fuv1).b, f2 = texture2D(uMacro, fuv2).g; - float foam = smoothstep(0.12, 0.0, dep + (f1 - 0.5) * 0.12 + sin(uTime * 0.8 + vUv.y * 0.7) * 0.02) * smoothstep(0.35, 0.7, f2); - diffuseColor.rgb = mix(diffuseColor.rgb, vec3(0.38, 0.38, 0.34), foam * 0.7); - diffuseColor.a = smoothstep(0.0, 0.12, dep) * (0.86 + 0.14 * foam);`); - P('fragment', '#include ', 'float roughnessFactor = mix(0.04, 0.6, foam);'); - P('fragment', '#include ', `{ - float e = 0.02; - float a1 = texture2D(uMacro, fuv1).b, b1 = texture2D(uMacro, fuv1 + vec2(e, 0.0)).b, c1 = texture2D(uMacro, fuv1 + vec2(0.0, e)).b; - float a2 = texture2D(uMacro, fuv2).g, b2 = texture2D(uMacro, fuv2 + vec2(e, 0.0)).g, c2 = texture2D(uMacro, fuv2 + vec2(0.0, e)).g; - vec2 g = vec2(a1 - b1, a1 - c1) * 1.2 + vec2(a2 - b2, a2 - c2) * 0.7; - normal = normalize(normal + (viewMatrix * vec4(g.x, 0.0, g.y, 0.0)).xyz * (0.6 + uWet * 0.6)); - }`); - sh.fragmentShader = 'uniform float uTime, uWet, uFlow; uniform sampler2D uMacro; varying float vDepth;\n' + sh.fragmentShader; - }; - m.userData.linear = true; - const mesh = new THREE.Mesh(g, m); mesh.receiveShadow = true; mesh.renderOrder = 1; mesh.name = 'stream'; - const group = new THREE.Group(); group.name = 'IVEnv.stream'; group.add(mesh); - return { group, mesh }; - }; -})(); diff --git a/e63334287a3deaa3/ironveil/env/props.js b/e63334287a3deaa3/ironveil/env/props.js deleted file mode 100644 index ac77f7ac..00000000 --- a/e63334287a3deaa3/ironveil/env/props.js +++ /dev/null @@ -1,367 +0,0 @@ -/* Midnight Ops environment: props. - IVEnv.prop(kind, seed, opts) -> { group, colliders, lights } (local space, feet on y = 0) - kinds: crate, crates (stack), barrel, barrels, sandbags (a wall, opts.length), cart, haybale, haystack, well, trough, - telegraph (pole; wires via IVEnv.wireMesh between poles: group.userData.wireTop gives the insulator positions), - lamppost (lights[0] is the lamp), gate, ladder, drums (fuel drums), ammo (ammunition boxes), truck (period lorry, - no markings), logpile, tarp (tarpaulin over a stack), bottles; camp dressing: noticeboard, flagpole (bare mast), - duckboards (opts.length), tent (ridge tent), washline (opts.length), watertower, targetframe, car (staff car), - guardtower, shelter (firing-point lean-to), aframe (assault-course frame). - Wear sits where wear happens: scuffed crate corners and bases, rust runs under rivets, chipped paint on drum rims, - worn handles, mud on wheels and the truck's lower panels. */ -(function () { - 'use strict'; - const E = window.IVEnv; - const TAU = Math.PI * 2, V3 = THREE.Vector3; - const M4 = (x, y, z, rx, ry, rz, s) => new THREE.Matrix4().compose(new V3(x, y, z), new THREE.Quaternion().setFromEuler(new THREE.Euler(rx || 0, ry || 0, rz || 0)), s ? (s.isVector3 ? s : new V3(s, s, s)) : new V3(1, 1, 1)); - const cyl = (rt, rb, h, seg, open) => new THREE.CylinderGeometry(rt, rb, h, seg || 12, 1, !!open); - // stencilled text on crates, drums and ammunition boxes (env/labels.js atlas). The words follow IVEnv.labelLang - // ('en' Boot Camp, 'fr' Night Drop), set by the mission. Own random stream, so the props' layout is unchanged. - const STEN = { - en: { crate: ['RATIONS\nLOT 14', 'FRAGILE', 'TINNED STORES', 'THIS SIDE UP', 'No 7', 'KEEP DRY', 'SPARES\nBOX 3', 'MESS TINS'], drum: ['PETROL', 'OIL', 'WATER\nONLY', 'PETROL 40 GAL'], ammo: ['AMMUNITION\nLOT 22', 'SMALL ARMS', 'LOT 9'] }, - fr: { crate: ['VIVRES\nLOT 14', 'FRAGILE', 'CONSERVES', 'HAUT', 'No 7', 'CRAINT L\'HUMIDITE', 'PIECES\nCAISSE 3', 'GAMELLES'], drum: ['ESSENCE', 'HUILE', 'EAU', 'ESSENCE 200 L'], ammo: ['MUNITIONS\nLOT 22', 'CARTOUCHES', 'LOT 9'] } - }; - const stencil = (B, kind, x, y, z, nx, nz, w, col, curve) => { - if (!B.label) return; const L = STEN[E.labelLang] || STEN.en, list = L[kind], r = E.rng(((x * 97 + z * 61 + y * 13) * 100 + (B.seed || 1) * 7) | 0); - if (r() < 0.15) return; // the odd one blank - B.label(list[(r() * list.length) | 0], { kind: 'stencil', color: col || 'rgba(28,24,18,0.9)', distress: 0.35 + r() * 0.35, size: 64 }, [x, y, z], [nx, 0, nz], w, { rot: curve ? 0 : (r() - 0.5) * 0.06, curve }); - }; - - function crate(B, R, x, y, z, rot, s, worn) { - s = s || 1; const w = 0.8 * s, h = 0.6 * s, d = 0.5 * s; - B.box('planks', x, y, z, w, h, d, rot, { tint: E.tintJ(R, 0.06, 0x8a7e6c), uvOff: [R() * 9, R() * 9], grain: 'long' }); // straight weathered boards - // corner battens and lid boards, slightly proud - const c = Math.cos(rot), sn = Math.sin(rot); - for (const [i, k] of [[-1, -1], [1, -1], [-1, 1], [1, 1]]) B.box('timber', x + c * i * (w / 2 - 0.03) + sn * k * (d / 2 - 0.01), y, z - sn * i * (w / 2 - 0.03) + c * k * (d / 2 - 0.01), 0.06, h, 0.03, rot, { grain: 'long', tint: new THREE.Color(0.75, 0.68, 0.6) }); - for (const k of [-1, 1]) B.box('timber', x + sn * k * (d / 2 + 0.005), y + h * 0.45, z + c * k * (d / 2 + 0.005), w - 0.1, 0.07, 0.02, rot, { grain: 'long' }); - B.decal('scratches', [x + sn * (d / 2 + 0.02), y + h * 0.3, z + c * (d / 2 + 0.02)], [sn, 0, c], w * 0.9, h * 0.6, R() * 3); - B.decal(worn ? 'mud' : 'grime', [x + sn * (d / 2 + 0.02), y + 0.1, z + c * (d / 2 + 0.02)], [sn, 0, c], w, 0.25, 0); - if (R() < 0.5) B.decal('chalk', [x - sn * (d / 2 + 0.02), y + h * 0.55, z - c * (d / 2 + 0.02)], [-sn, 0, -c], 0.3, 0.25, 0); - stencil(B, 'crate', x + sn * (d / 2 + 0.006), y + h * 0.62, z + c * (d / 2 + 0.006), sn, c, w * 0.62); - B.col(x, z, w, d, y, y + h, rot, 'wood', 'crate'); - return h; - } - function barrel(B, R, x, y, z, s, metal) { - s = s || 1; const r = 0.29 * s, h = 0.88 * s; - if (metal) { - B.geo('metal_painted', cyl(r, r, h, 16), M4(x, y + h / 2, z, 0, R() * TAU, 0), { tint: E.tintJ(R, 0.1, metal === 2 ? 0x8a5a4a : 0x9aa090), keepUv: true, uvW: TAU * r, uvH: h }); - for (const yy of [0.02, 0.33, 0.66, 0.98]) B.geo('metal_rust', new THREE.TorusGeometry(r + 0.005, 0.012, 4, 18).rotateX(Math.PI / 2), M4(x, y + h * yy, z), { noFoot: true }); - B.geo('metal_painted', new THREE.CircleGeometry(r, 16).rotateX(-Math.PI / 2), M4(x, y + h - 0.01, z), { noFoot: true, tint: E.tintJ(R, 0.1, metal === 2 ? 0x8a5a4a : 0x9aa090) }); - B.decal('rust', [x + r * 0.71 + 0.005, y + h * 0.75, z + r * 0.71 + 0.005], [0.71, 0, 0.71], 0.2, 0.45, 0); - B.decal('chipped', [x - r * 0.71 - 0.005, y + h * 0.93, z + r * 0.71], [-0.71, 0, 0.71], 0.3, 0.15, 0); - stencil(B, 'drum', x, y + h * 0.5, z + r + 0.004, 0, 1, r * 1.6, 'rgba(226,218,196,0.92)', r + 0.004); - } else { - const g = cyl(r, r, h, 14), p = g.attributes.position; for (let i = 0; i < p.count; i++) { const yy = p.getY(i) / (h / 2), k = 1 + 0.12 * (1 - yy * yy); p.setX(i, p.getX(i) * k); p.setZ(i, p.getZ(i) * k); } g.computeVertexNormals(); - B.geo('planks', g, M4(x, y + h / 2, z, 0, R() * TAU, 0), { keepUv: true, uvW: TAU * r * 1.1, uvH: h, tint: E.tintJ(R, 0.1, 0xd0b8a0) }); - for (const yy of [0.1, 0.3, 0.7, 0.9]) { const k = 1 + 0.12 * (1 - ((yy - 0.5) * 2) ** 2); B.geo('metal_rust', new THREE.TorusGeometry(r * k + 0.004, 0.01, 4, 18).rotateX(Math.PI / 2), M4(x, y + h * yy, z), { noFoot: true }); } - B.geo('timber', new THREE.CircleGeometry(r * 0.98, 14).rotateX(-Math.PI / 2), M4(x, y + h - 0.02, z), { noFoot: true }); - } - B.col(x, z, r * 2, r * 2, y, y + h, 0, metal ? 'metal' : 'wood', 'barrel'); - return h; - } - function wheel(B, R, x, y, z, rot, r, spokes) { - // a cart wheel: rim, hub, spokes; the iron tyre is rusty and muddy at the bottom - const c = Math.cos(rot), s = Math.sin(rot); - B.geo('timber', new THREE.TorusGeometry(r - 0.03, 0.04, 6, 24), M4(x, y, z, 0, rot, 0), { noFoot: true }); - B.geo('metal_rust', new THREE.TorusGeometry(r, 0.018, 4, 28), M4(x, y, z, 0, rot, 0), { noFoot: true }); - B.geo('timber', cyl(0.08, 0.08, 0.22, 10).rotateX(Math.PI / 2), M4(x, y, z, 0, rot, 0), { noFoot: true }); - for (let k = 0; k < (spokes || 12); k++) { const a = k / (spokes || 12) * TAU; B.box('timber', x + c * Math.cos(a) * r * 0.48, y + Math.sin(a) * r * 0.48 - 0.02, z - s * Math.cos(a) * r * 0.48, r * 0.9, 0.035, 0.035, rot, { rz: a, noFoot: true }); } - B.decal('mud', [x + s * 0.06, y - r * 0.7, z + c * 0.06], [s, 0, c], r * 1.2, r * 0.7, 0); - } - const KINDS = {}; - KINDS.crate = (B, R) => { crate(B, R, 0, 0, 0, 0, 1, R() < 0.5); }; - KINDS.crates = (B, R) => { let h = crate(B, R, 0, 0, 0, 0.05, 1, true); crate(B, R, 0.85, 0, 0.1, -0.08, 1, true); crate(B, R, 0.35, h, 0.02, 0.2, 0.9); if (R() < 0.6) crate(B, R, -0.2, 0, 0.75, 1.6, 0.8); }; - KINDS.barrel = (B, R) => barrel(B, R, 0, 0, 0, 1, 0); - KINDS.barrels = (B, R) => { barrel(B, R, 0, 0, 0); barrel(B, R, 0.62, 0, 0.1); barrel(B, R, 0.3, 0, 0.55); }; - KINDS.drums = (B, R) => { barrel(B, R, 0, 0, 0, 1, 1); barrel(B, R, 0.63, 0, 0.05, 1, 1); barrel(B, R, 0.3, 0, 0.6, 1, 2); B.geo('metal_painted', cyl(0.29, 0.29, 0.88, 16).rotateZ(Math.PI / 2), M4(-0.75, 0.29, 0.3, 0, 0.4, 0), { tint: new THREE.Color(1.1, 1.1, 1.0) }); B.decal('waterstain', [0.3, 0.01, 0.2], [0, 1, 0], 1.8, 1.4, 0); }; - KINDS.sandbags = (B, R, o) => { const L = o.length || 3, rows = o.rows || 4; for (let r = 0; r < rows; r++) for (let i = 0; i < Math.round(L / 0.5); i++) E.sandbag(B, -L / 2 + (i + 0.5 + (r % 2) * 0.5) * 0.5 - 0.25 * (r % 2), r * 0.16, R.range(-0.02, 0.02) + (r % 2) * 0.04, R.range(-0.05, 0.05), R); }; - KINDS.haybale = (B, R) => E.hayBale(B, 0, 0, 0, 0, R); - KINDS.haystack = (B, R) => { for (let l = 0; l < 4; l++) for (let i = 0; i < 4 - l; i++) for (let j = 0; j < 2; j++) E.hayBale(B, -0.9 + i * 0.92 + l * 0.46, l * 0.4, j * 0.5 - 0.25, (l % 2) * 0.03, R); for (let k = 0; k < 6; k++) B.box('straw', R.range(-1, 1.5), 0, R.range(-0.8, 0.8), R.range(0.2, 0.5), 0.03, R.range(0.2, 0.4), R() * 3, { noFoot: true }); }; - KINDS.cart = (B, R) => { - const rot = 0; B.box('planks', 0, 0.75, 0, 2.4, 0.06, 1.3, 0, { tint: new THREE.Color(0.85, 0.78, 0.7) }); - for (const s of [-1, 1]) { B.box('planks', 0, 0.81, s * 0.63, 2.4, 0.38, 0.04, 0, {}); B.box('planks', s * 1.18, 0.81, 0, 0.04, 0.38, 1.26, 0, {}); } - for (const s of [-1, 1]) wheel(B, R, -0.25, 0.62, s * 0.78, Math.PI / 2, 0.62, 12); - B.box('timber', -0.25, 0.58, 0, 0.1, 0.1, 1.7, 0, { grain: 'long' }); - for (const s of [-0.35, 0.35]) B.box('timber', 1.9, 0.35, s, 2.0, 0.08, 0.08, 0.0, { rz: -0.32, grain: 'long' }); - B.decal('scratches', [0, 1.0, 0.655], [0, 0, 1], 2, 0.3, 0); B.decal('mud', [0, 0.9, 0.655], [0, 0, 1], 2.2, 0.3, 0); - E.hayBale(B, 0.4, 0.81, 0.1, 0.1, R); - B.col(0, 0, 2.4, 1.6, 0, 1.2, 0, 'wood', 'cart'); - }; - KINDS.well = (B, R) => { - const r = 0.8; for (let k = 0; k < 14; k++) { const a = k / 14 * TAU; B.box('fieldstone', Math.cos(a) * r, 0, Math.sin(a) * r, 0.42, 0.75 + R.range(-0.04, 0.04), 0.3, -a + Math.PI / 2, { tint: E.tintJ(R, 0.12) }); B.box('ashlar', Math.cos(a) * r, 0.75, Math.sin(a) * r, 0.44, 0.08, 0.36, -a + Math.PI / 2, { tint: E.tintJ(R, 0.08) }); } - B.geo('mud', new THREE.CircleGeometry(r - 0.1, 16).rotateX(-Math.PI / 2), M4(0, 0.3, 0), { tint: new THREE.Color(0.1, 0.1, 0.1), noFoot: true }); - for (const s of [-1, 1]) B.box('timber', s * (r + 0.05), 0, 0, 0.12, 2.0, 0.12, 0, { grain: 'long' }); - B.box('timber', 0, 1.9, 0, 2 * r + 0.3, 0.1, 0.1, 0, { grain: 'long' }); - B.geo('timber', cyl(0.08, 0.08, 1.3, 10).rotateZ(Math.PI / 2), M4(0, 1.55, 0), { noFoot: true }); - B.geo('metal_rust', cyl(0.004, 0.004, 1.1, 3), M4(0, 1.0, 0), { noFoot: true }); - B.geo('planks', cyl(0.13, 0.11, 0.25, 10), M4(0, 0.4, 0), { noFoot: true }); - B.decal('moss', [0, 0.2, r + 0.16], [0, 0, 1], 0.9, 0.4, 0); - B.col(0, 0, 2 * r + 0.3, 2 * r + 0.3, 0, 0.8, 0, 'stone', 'well'); - }; - KINDS.trough = (B, R) => { - B.box('ashlar', 0, 0, 0, 1.8, 0.55, 0.65, 0, { tint: new THREE.Color(0.75, 0.73, 0.7) }); - B.box('mud', 0, 0.42, 0, 1.6, 0.04, 0.45, 0, { tint: new THREE.Color(0.1, 0.11, 0.1), noFoot: true }); - B.decal('moss', [0, 0.15, 0.33], [0, 0, 1], 1.6, 0.35, 0); B.decal('waterstain', [0, 0.01, 0.6], [0, 1, 0], 2, 0.8, 0); - B.col(0, 0, 1.8, 0.65, 0, 0.55, 0, 'stone', 'trough'); - }; - KINDS.telegraph = (B, R, o) => { - const h = 7; B.geo('timber', cyl(0.1, 0.14, h, 9), M4(0, h / 2 - 0.3, 0, R.range(-0.03, 0.03), 0, R.range(-0.03, 0.03)), { grain: 'long', tint: new THREE.Color(0.55, 0.5, 0.45) }); - B.box('timber', 0, h - 0.8, 0, 1.4, 0.1, 0.1, 0, { grain: 'long' }); - const tops = []; - for (const x of [-0.6, -0.3, 0.3, 0.6]) { B.geo('glass', cyl(0.035, 0.05, 0.1, 8), M4(x, h - 0.65, 0), { noFoot: true }); tops.push([x, h - 0.55, 0]); } - B.decal('scratches', [0, 1.4, 0.12], [0, 0, 1], 0.2, 1.0, Math.PI / 2); - B.col(0, 0, 0.3, 0.3, 0, h, 0, 'wood', 'pole'); - return { wireTop: tops }; - }; - KINDS.lamppost = (B, R) => { - const h = 3.4; - B.geo('metal_painted', cyl(0.05, 0.08, h, 10), M4(0, h / 2, 0), { tint: new THREE.Color(0.35, 0.35, 0.33) }); - B.geo('metal_painted', cyl(0.12, 0.14, 0.3, 10), M4(0, 0.15, 0), { tint: new THREE.Color(0.35, 0.35, 0.33) }); - B.box('metal_painted', 0.3, h - 0.05, 0, 0.6, 0.05, 0.05, 0, { noFoot: true, tint: new THREE.Color(0.35, 0.35, 0.33) }); - B.geo('metal_painted', cyl(0.06, 0.22, 0.16, 12, true), M4(0.55, h - 0.2, 0), { noFoot: true, tint: new THREE.Color(0.3, 0.3, 0.28) }); - B.geo('glass_lit', new THREE.SphereGeometry(0.075, 10, 8), M4(0.55, h - 0.28, 0), { noFoot: true }); - B.decal('rust', [0.051, h * 0.7, 0], [1, 0, 0], 0.08, 0.5, 0); B.decal('chipped', [0, 0.25, 0.141], [0, 0, 1], 0.25, 0.25, 0); - B.col(0, 0, 0.25, 0.25, 0, h, 0, 'metal', 'lamp'); - return { light: { x: 0.55, y: h - 0.35, z: 0, color: 0xffb060, r: 16, power: 2.2, flicker: true } }; - }; - KINDS.gate = (B, R, o) => { - const w = o.width || 3.2, open = o.open || 0; - for (const s of [-1, 1]) { B.box('timber', s * (w / 2 + 0.1), -0.4, 0, 0.18, 1.8, 0.18, 0, { grain: 'long' }); B.decal('moss', [s * (w / 2 + 0.1), 0.2, 0.091], [0, 0, 1], 0.15, 0.4, 0); B.col(s * (w / 2 + 0.1), 0, 0.2, 0.2, 0, 1.4, 0, 'wood', 'gatepost'); } - const G = E.builder(R() * 1e4 | 0); - for (const yy of [0.15, 0.55, 0.95, 1.3]) G.box('timber', w / 2, yy, 0, w - 0.1, 0.09, 0.05, 0, { grain: 'long', tint: new THREE.Color(0.8, 0.76, 0.7) }); - G.box('timber', 0.06, 0, 0, 0.1, 1.42, 0.07, 0, { grain: 'long' }); G.box('timber', w - 0.12, 0, 0, 0.1, 1.42, 0.07, 0, { grain: 'long' }); - G.box('timber', w / 2, 0.15, 0.04, Math.hypot(w - 0.2, 1.2), 0.08, 0.04, 0, { rz: Math.atan2(1.15, w - 0.2), grain: 'long' }); - G.box('metal_rust', w - 0.25, 1.0, 0.05, 0.2, 0.04, 0.04, 0, { noFoot: true }); - G.decal('mud', [w / 2, 0.2, 0.03], [0, 0, 1], w * 0.8, 0.3, 0); - const leaf = G.finish(), pv = new THREE.Group(); pv.add(leaf); pv.position.set(-w / 2, 0.1, 0); pv.rotation.y = -open; pv.userData.dynamic = true; B._extra.push(pv); - return { door: { pivot: pv, width: w, open(a) { pv.rotation.y = -a; } } }; - }; - KINDS.ladder = (B, R) => { for (const s of [-0.22, 0.22]) B.box('timber', s, 0, 0.5, 0.06, 3.2, 0.06, 0, { rx: -0.3, grain: 'long' }); for (let k = 1; k < 11; k++) B.box('timber', 0, k * 0.28, 0.5 - Math.sin(0.3) * k * 0.29, 0.5, 0.035, 0.05, 0, { noFoot: true }); }; - KINDS.ammo = (B, R) => { - const box = (x, y, z, rot) => { B.box('metal_painted', x, y, z, 0.3, 0.19, 0.11, rot, { tint: new THREE.Color(0.8, 0.85, 0.7) }); B.box('metal_painted', x, y + 0.19, z, 0.31, 0.03, 0.12, rot, { noFoot: true, tint: new THREE.Color(0.75, 0.8, 0.65) }); B.box('metal_rust', x, y + 0.22, z, 0.12, 0.02, 0.025, rot, { noFoot: true }); B.decal('scratches', [x + Math.sin(rot) * 0.058, y + 0.1, z + Math.cos(rot) * 0.058], [Math.sin(rot), 0, Math.cos(rot)], 0.28, 0.16, R() * 3); stencil(B, 'ammo', x + Math.sin(rot) * 0.059, y + 0.1, z + Math.cos(rot) * 0.059, Math.sin(rot), Math.cos(rot), 0.22, 'rgba(236,228,200,0.9)'); }; - box(0, 0, 0, 0); box(0.04, 0.22, 0.02, 0.1); box(0.35, 0, 0.05, -0.05); box(-0.05, 0, 0.3, 1.57); B.col(0.15, 0.1, 0.7, 0.5, 0, 0.45, 0, 'metal', 'ammo'); - }; - KINDS.logpile = (B, R) => { for (let l = 0; l < 4; l++) for (let i = 0; i < 6 - l; i++) { const r = R.range(0.09, 0.14), x = -0.7 + i * 0.27 + l * 0.135, y = 0.12 + l * 0.22; B.geo('bark_oak', cyl(r, r, 1.6, 8).rotateX(Math.PI / 2), M4(x, y, R.range(-0.08, 0.08)), { tint: new THREE.Color(0.75, 0.7, 0.62) }); for (const s of [-1, 1]) B.geo('timber', new THREE.CircleGeometry(r * 0.95, 8), M4(x, y, s * 0.801 + R.range(-0.08, 0.08) * 0, 0, s > 0 ? 0 : Math.PI, 0), { noFoot: true, tint: new THREE.Color(1.0, 0.85, 0.65) }); } B.col(0, 0, 1.7, 1.7, 0, 0.9, 0, 'wood', 'logs'); }; - KINDS.tarp = (B, R) => { - crate(B, R, -0.45, 0, 0, 0, 1); crate(B, R, 0.45, 0, 0, 0.05, 1); crate(B, R, 0, 0.6, 0, 0.1, 0.9); - // a draped tarpaulin: a grid sagging over the stack, tied down at the corners - const g = new THREE.PlaneGeometry(2.4, 1.9, 16, 12); g.rotateX(-Math.PI / 2); const p = g.attributes.position; - for (let i = 0; i < p.count; i++) { const x = p.getX(i), z = p.getZ(i), ax = Math.abs(x), az = Math.abs(z), top = ax < 0.4 && az < 0.25 ? 1.15 : ax < 0.85 && az < 0.3 ? 0.62 : 0; let y = Math.max(top, 0) ; if (ax >= 0.85 || az >= 0.3) y = Math.max(0.02, (ax < 0.9 ? 0.62 : 0.6) - Math.max(ax - 0.85, az - 0.3) * 1.6); p.setY(i, Math.max(0.03, y) + 0.03 * Math.sin(x * 9 + z * 7) + 0.02); } - g.computeVertexNormals(); B.geo('canvas', g, M4(0, 0, 0), { keepUv: true, uvW: 2.4, uvH: 1.9 }); - B.col(0, 0, 1.8, 0.6, 0, 1.2, 0, 'cloth', 'tarp'); - }; - KINDS.bottles = (B, R) => { for (let k = 0; k < 5; k++) { const x = R.range(-0.2, 0.2), z = R.range(-0.15, 0.15), lie = R() < 0.4; B.geo('glass', cyl(0.035, 0.035, 0.24, 10), M4(x, lie ? 0.035 : 0.12, z, lie ? Math.PI / 2 : 0, R() * 3, 0), { noFoot: true }); } }; - // a burnt-out lorry: what is left after the fire. Chassis rails and cross members, four wheels on bare burnt rims - // (tyres gone, one wheel off), the cab as an empty frame with no glass or doors, the bonnet buckled, bare tilt hoops - // over a bed with only a few charred boards, the tailgate dropped on its chain; rust, soot and white ash. - KINDS.wreck = (B, R) => { - const burnt = new THREE.Color(0.32, 0.27, 0.23), rust = new THREE.Color(0.75, 0.55, 0.42), black = new THREE.Color(0.12, 0.11, 0.1); - for (const s of [-1, 1]) B.box('metal_rust', 0, 0.5, s * 0.45, 6.2, 0.2, 0.09, 0, { tint: rust }); // chassis rails - for (const x of [-2.6, -1.2, 0.4, 1.9]) B.box('metal_rust', x, 0.52, 0, 0.09, 0.14, 0.9, 0, { tint: rust }); // cross members - for (const [x, sz] of [[2.4, 1], [2.4, -1], [-1.6, 1], [-1.6, -1]]) { - if (x < 0 && sz < 0 && R() < 0.8) { B.geo('metal_rust', new THREE.TorusGeometry(0.36, 0.05, 6, 16), M4(-2.9, 0.12, -1.5, Math.PI / 2 + 0.1, 0, 0.2), { tint: black }); continue; } // a wheel off, lying in the mud - B.geo('metal_rust', new THREE.TorusGeometry(0.36, 0.055, 6, 16), M4(x, 0.42, sz * 0.92, 0, 0, 0), { tint: black }); // bare rim - B.geo('metal_rust', cyl(0.24, 0.24, 0.16, 10).rotateX(Math.PI / 2), M4(x, 0.42, sz * 0.9), { tint: burnt }); // hub and disc - for (let k = 0; k < 6; k++) { const a = k / 6 * Math.PI * 2; B.box('metal_rust', x + Math.cos(a) * 0.2, 0.42 + Math.sin(a) * 0.2 - 0.02, sz * 0.92, 0.05, 0.04, 0.04, 0, { noFoot: true, tint: black }); } - } - for (const s of [-1, 1]) B.box('metal_rust', 0.7, 0.62, s * 0.55, 6.6, 0.06, 0.06, 0, { tint: burnt }); // axle beams' springs - // bonnet buckled up in the middle, grille hanging - B.box('metal_rust', 2.35, 0.75, 0, 1.4, 0.05, 1.45, 0, { rz: 0.12, rx: 0.06, tint: burnt }); - for (const s of [-1, 1]) B.box('metal_rust', 2.35, 0.7, s * 0.72, 1.4, 0.55, 0.04, 0, { rz: 0.05 * s, tint: rust }); - B.box('metal_rust', 3.1, 0.55, 0.05, 0.05, 0.62, 0.95, 0, { rz: -0.35, noFoot: true, tint: black }); - B.box('metal_rust', 2.3, 0.62, 0, 0.9, 0.45, 0.7, 0, { tint: black }); // the engine block - // cab: floor, scuttle, four pillars, roof frame, no glass, no doors; a steering column and wheel ring - B.box('metal_rust', 1.1, 0.68, 0, 1.25, 0.05, 1.9, 0, { tint: burnt }); - B.box('metal_rust', 1.7, 0.7, 0, 0.06, 0.75, 1.9, 0, { tint: rust }); - for (const [x, z] of [[1.7, 0.92], [1.7, -0.92], [0.5, 0.92], [0.5, -0.92]]) B.box('metal_rust', x, 0.7, z, 0.07, 1.5, 0.07, 0, { rz: R.range(-0.06, 0.06), tint: burnt }); - for (const s of [-1, 1]) B.box('metal_rust', 1.1, 2.18, s * 0.92, 1.3, 0.06, 0.06, 0, { tint: burnt }); - for (const x of [0.5, 1.7]) B.box('metal_rust', x, 2.18, 0, 0.06, 0.06, 1.9, 0, { tint: burnt }); - B.box('metal_rust', 1.1, 2.2, 0.2, 1.1, 0.03, 1.2, 0, { rz: 0.15, rx: -0.1, tint: black }); // a sagging piece of roof skin - B.box('metal_rust', 0.55, 0.7, 0, 0.06, 1.0, 1.9, 0, { tint: rust }); // cab back - B.box('metal_rust', 1.45, 1.1, 0.4, 0.04, 0.5, 0.04, 0, { rz: -0.6, noFoot: true, tint: black }); - B.geo('metal_rust', new THREE.TorusGeometry(0.2, 0.02, 4, 12), M4(1.32, 1.35, 0.4, 0, Math.PI / 2, 0.6), { noFoot: true, tint: black }); - // bed: two side rails, a few charred boards left, bare tilt hoops (one bent), the tailgate dropped - for (const s of [-1, 1]) B.box('metal_rust', -1.45, 0.72, s * 1.08, 3.9, 0.12, 0.05, 0, { tint: rust }); - for (let k = 0; k < 7; k++) if (R() < 0.55) B.box('planks', -1.45 + R.range(-0.2, 0.2), 0.7, -0.9 + k * 0.3, R.range(1.2, 3.6), 0.04, 0.18, R.range(-0.05, 0.05), { tint: black }); - for (let k = 0; k < 4; k++) { const g = new THREE.TorusGeometry(1.08, 0.025, 4, 16, Math.PI); B.geo('metal_rust', g, M4(-3.1 + k * 1.1, 0.8, 0, 0, Math.PI / 2, k === 2 ? 0.25 : 0, k === 2 ? new V3(1, 0.8, 1) : null), { noFoot: true, tint: burnt }); } - B.box('metal_rust', -3.55, 0.25, 0, 0.05, 0.55, 2.1, 0, { rz: 1.2, tint: rust }); // tailgate down on its chains - for (const s of [-1, 1]) B.box('metal_rust', -3.42, 0.5, s * 1.0, 0.02, 0.45, 0.02, 0, { rz: -0.5, noFoot: true, tint: black }); - // soot, ash, rust runs - B.decal('soot', [1.1, 1.2, 0.97], [0, 0, 1], 1.8, 1.6, 0); B.decal('soot', [1.1, 1.2, -0.97], [0, 0, -1], 1.8, 1.6, 0); - B.decal('rust', [2.35, 0.6, 0.75], [0, 0, 1], 1.2, 0.5, 0); B.decal('rust', [-1.45, 0.6, 1.11], [0, 0, 1], 3, 0.4, 0); - B.col(0, 0, 6.6, 2.3, 0, 2.2, 0, 'metal', 'vehicle'); - }; - KINDS.truck = (B, R) => { - // a period 3-ton lorry in plain drab, no markings: cab, bonnet, wheels with mud, a canvas tilt over the bed - const drab = new THREE.Color(0.75, 0.78, 0.62); - B.box('metal_painted', 0, 0.55, 0, 6.2, 0.18, 1.1, 0, { tint: new THREE.Color(0.45, 0.45, 0.4) }); // chassis rails - B.box('metal_painted', 2.35, 0.75, 0, 1.4, 0.75, 1.5, 0, { tint: drab }); // bonnet - B.box('metal_rust', 3.08, 0.75, 0, 0.05, 0.7, 1.1, 0, { noFoot: true }); // grille - B.box('metal_painted', 1.1, 0.75, 0, 1.2, 1.55, 2.0, 0, { tint: drab }); // cab - B.box('glass', 1.71, 1.55, 0, 0.02, 0.5, 1.7, 0, { noFoot: true }); - for (const s of [-1, 1]) B.box('glass', 1.1, 1.6, s * 1.005, 0.8, 0.45, 0.02, 0, { noFoot: true }); - for (const s of [-1, 1]) { B.geo('metal_painted', cyl(0.5, 0.5, 0.1, 14, true).rotateX(Math.PI / 2), M4(2.4, 0.95, s * 0.92), { tint: drab, noFoot: true }); B.geo('glass_lit', new THREE.CircleGeometry(0.11, 12), M4(3.11, 1.2, s * 0.6, 0, Math.PI / 2, 0), { noFoot: true }); } - B.box('planks', -1.45, 0.75, 0, 3.9, 0.08, 2.2, 0, { tint: new THREE.Color(0.7, 0.68, 0.6) }); // bed - for (const s of [-1, 1]) B.box('planks', -1.45, 0.83, s * 1.08, 3.9, 0.5, 0.04, 0, { tint: drab }); - B.box('planks', -3.38, 0.83, 0, 0.04, 0.5, 2.2, 0, { tint: drab }); - const tilt = new THREE.CylinderGeometry(1.12, 1.12, 3.9, 14, 1, true, 0, Math.PI); tilt.rotateZ(Math.PI / 2); tilt.rotateX(-Math.PI / 2 * 0); - B.geo('canvas', tilt, M4(-1.45, 1.3, 0, -Math.PI / 2, 0, 0, new V3(1, 1, 0.75)), { keepUv: true, uvW: 3.9, uvH: 3.5, tint: new THREE.Color(0.85, 0.85, 0.75) }); - for (const x of [2.4, -0.9, -2.2]) for (const s of [-1, 1]) { const r = 0.48; B.geo('metal_rust', cyl(r, r, 0.26, 18).rotateX(Math.PI / 2), M4(x, r, s * 0.95), { tint: new THREE.Color(0.25, 0.25, 0.25) }); B.geo('metal_painted', cyl(r * 0.5, r * 0.5, 0.28, 12).rotateX(Math.PI / 2), M4(x, r, s * 0.95), { noFoot: true, tint: drab }); B.decal('mud', [x, r * 0.8, s * 1.09], [0, 0, s], 1.0, 0.8, 0); } - for (const s of [-1, 1]) { B.decal('mud', [0, 0.75, s * 1.11], [0, 0, s], 6, 0.6, 0); B.decal('scratches', [1.1, 1.0, s * 1.006], [0, 0, s], 1.0, 0.8, R() * 3); B.decal('chipped', [1.6, 1.4, s * 1.006], [0, 0, s], 0.5, 0.4, 0); } - B.col(0, 0, 6.6, 2.3, 0, 2.4, 0, 'metal', 'truck'); - return { light: { x: 3.2, y: 1.2, z: 0, color: 0xffd8a0, r: 14, power: 0 } }; - }; - - // ---- camp dressing: notice board, bare flag mast, duckboards, ridge tent, wash line, water tower, target frame - const C = (r, g, b) => new THREE.Color(r, g, b); - KINDS.noticeboard = (B, R) => { - for (const s of [-1, 1]) B.box('timber', s * 0.8, 0, 0, 0.1, 2.1, 0.1, 0, { grain: 'long' }); - B.box('planks', 0, 0.9, 0, 1.5, 0.95, 0.04, 0, { tint: C(0.72, 0.7, 0.62) }); - B.box('timber', 0, 2.0, 0.04, 1.8, 0.04, 0.42, 0, { rx: 0.35, noFoot: true, tint: C(0.6, 0.58, 0.55) }); - // pinned notices: pale cards, a few curling, one rain-stained - for (let k = 0; k < 6; k++) { const w = R.range(0.2, 0.32), h = R.range(0.25, 0.38); B.box('canvas', -0.55 + (k % 3) * 0.48 + R.range(-0.04, 0.04), 0.98 + (k > 2 ? 0 : 0.42) + R.range(-0.03, 0.03), 0.025, w, h, 0.004, R.range(-0.04, 0.04), { noFoot: true, tint: C(1.25, 1.22, 1.08).multiplyScalar(R.range(0.75, 1)) }); } - B.decal('waterstain', [0, 1.3, 0.03], [0, 0, 1], 1.4, 0.8, 0); B.decal('moss', [0.8, 0.15, 0.055], [0, 0, 1], 0.12, 0.3, 0); - B.col(0, 0, 1.7, 0.2, 0, 2.1, 0, 'wood', 'board'); - }; - KINDS.flagpole = (B, R) => { - // a bare white mast with a halyard and cleat; no flag is flown on the training ground - const h = 9; - B.geo('metal_painted', cyl(0.045, 0.09, h, 10), M4(0, h / 2, 0), { tint: C(1.5, 1.5, 1.45) }); - B.geo('metal_painted', new THREE.SphereGeometry(0.1, 8, 6), M4(0, h + 0.05, 0), { noFoot: true, tint: C(1.5, 1.5, 1.45) }); - B.geo('canvas', cyl(0.006, 0.006, h - 1.2, 3), M4(0.06, h / 2 + 0.5, 0), { noFoot: true, tint: C(0.8, 0.78, 0.7) }); - B.box('metal_rust', 0.09, 1.2, 0, 0.04, 0.16, 0.04, 0, { noFoot: true }); - // whitewashed kerb stones round the foot - for (let k = 0; k < 10; k++) { const a = k / 10 * TAU; B.box('ashlar', Math.cos(a) * 1.1, 0, Math.sin(a) * 1.1, 0.34, 0.14, 0.18, -a + Math.PI / 2, { tint: C(1.3, 1.3, 1.25) }); } - B.decal('chipped', [0, 0.5, 0.06], [0, 0, 1], 0.12, 0.4, 0); - B.col(0, 0, 0.2, 0.2, 0, h, 0, 'wood', 'pole'); - }; - KINDS.duckboards = (B, R, o) => { - // slatted walkway sections on two bearers, slightly askew, sunk in at the ends - const L = o.length || 6, n = Math.max(1, Math.round(L / 2)); - for (let i = 0; i < n; i++) { - const x0 = -L / 2 + (i + 0.5) * (L / n), tw = R.range(-0.04, 0.04), dy = R.range(-0.03, 0.01); - for (const s of [-1, 1]) B.box('timber', x0, dy, s * 0.22, L / n - 0.06, 0.07, 0.07, tw, { grain: 'long', tint: C(0.55, 0.52, 0.48) }); - for (let k = 0; k < Math.round((L / n) / 0.16); k++) B.box('planks', x0 - (L / n) / 2 + 0.08 + k * 0.16, dy + 0.07, 0, 0.1, 0.03, 0.62, tw, { tint: E.tintJ(R, 0.1, 0x8a8070), noFoot: true }); - } - B.decal('mud', [0, 0.11, 0], [0, 1, 0], L * 0.8, 0.5, 0); - }; - KINDS.tent = (B, R) => { - // a ridge tent: canvas sheet over a ridge pole, walls guyed out, flaps half tied - const L = 3.6, W2 = 1.35, H = 2.0, wall = 0.45; - const g = new THREE.BufferGeometry(), P = [], I = [], UV = []; - const nx = 10, ny = 6; - for (let side of [-1, 1]) { - const b0 = P.length / 3; - for (let j = 0; j <= ny; j++) for (let i = 0; i <= nx; i++) { - const u = i / nx, v = j / ny, x = -L / 2 + u * L, sag = 0.06 * Math.sin(u * Math.PI * 3) ** 2 * Math.sin(v * Math.PI); - const z = side * (W2 * (1 - v)), y = wall + (H - wall) * v - sag + (j === 0 ? 0 : 0); - P.push(x, y, z + side * sag * 0.5); UV.push(u * L, v * 1.6); - } - for (let j = 0; j < ny; j++) for (let i = 0; i < nx; i++) { const a = b0 + j * (nx + 1) + i, b = a + 1, c = a + nx + 1, d = c + 1; if (side > 0) I.push(a, b, d, a, d, c); else I.push(a, d, b, a, c, d); } - // the short wall - const w0 = P.length / 3; for (let i = 0; i <= nx; i++) { const x = -L / 2 + i / nx * L; P.push(x, 0, side * W2, x, wall, side * W2); UV.push(i / nx * L, 0, i / nx * L, 0.45); } - for (let i = 0; i < nx; i++) { const a = w0 + i * 2; if (side > 0) I.push(a, a + 2, a + 3, a, a + 3, a + 1); else I.push(a, a + 3, a + 2, a, a + 1, a + 3); } - } - g.setAttribute('position', new THREE.Float32BufferAttribute(P, 3)); g.setAttribute('uv', new THREE.Float32BufferAttribute(UV, 2)); g.setIndex(I); g.computeVertexNormals(); - B.geo('canvas', g, M4(0, 0, 0), { keepUv: true, tint: E.tintJ(R, 0.08, 0xb8b090) }); - // gable ends: back closed, front a dark opening with a tied flap - for (const e of [-1, 1]) { const t = new THREE.BufferGeometry(); t.setAttribute('position', new THREE.Float32BufferAttribute([e * L / 2, 0, -W2, e * L / 2, 0, W2, e * L / 2, H, 0, e * L / 2, wall, -W2, e * L / 2, wall, W2], 3)); t.setIndex(e > 0 ? [0, 2, 1] : [0, 1, 2]); t.computeVertexNormals(); B.geo('canvas', t, M4(0, 0, 0), { tint: e > 0 ? C(0.25, 0.24, 0.2) : E.tintJ(R, 0.08, 0xb0a888) }); } - B.box('canvas', L / 2 + 0.02, 0.2, -0.55, 0.05, 1.5, 0.5, 0, { rz: 0.1, tint: C(0.7, 0.68, 0.56) }); - for (const e of [-1, 1]) { B.box('timber', e * (L / 2 - 0.05), 0, 0, 0.05, H + 0.15, 0.05, 0, { grain: 'long' }); for (const s of [-1, 1]) B.geo('canvas', cyl(0.006, 0.006, 1.5, 3), M4(e * (L / 2 + 0.55), H * 0.5, s * (W2 * 0.6), 0, 0, e * 0.9), { noFoot: true, tint: C(0.7, 0.68, 0.6) }); } - B.decal('mud', [0, 0.02, W2 + 0.2], [0, 1, 0], L, 0.6, 0); B.decal('mud', [L / 2 + 0.5, 0.02, 0], [0, 1, 0], 1.2, 1.4, 0); - B.col(0, 0, L, W2 * 2, 0, H, 0, 'cloth', 'tent'); - }; - KINDS.washline = (B, R, o) => { - const L = o.length || 6; - for (const s of [-1, 1]) B.box('timber', s * L / 2, 0, 0, 0.09, 2.0, 0.09, 0, { grain: 'long', rz: s * 0.04 }); - B.geo('canvas', cyl(0.006, 0.006, L, 3).rotateZ(Math.PI / 2), M4(0, 1.88, 0), { noFoot: true, tint: C(0.75, 0.72, 0.65) }); - // shirts, socks and a towel: greys, khakis, one faded white - let x = -L / 2 + 0.5; - while (x < L / 2 - 0.5) { const w = R.range(0.25, 0.7), h = R.range(0.3, 0.75), sag = 0.05 * (1 - (2 * x / L) ** 2); B.box('canvas', x + w / 2, 1.88 - sag - h, 0, w, h, 0.01, R.range(-0.08, 0.08), { noFoot: true, tint: [C(0.6, 0.6, 0.5), C(0.75, 0.7, 0.55), C(1.1, 1.08, 1.0), C(0.45, 0.47, 0.42)][(R() * 4) | 0] }); x += w + R.range(0.12, 0.4); } - }; - KINDS.watertower = (B, R) => { - // a timber trestle with cross-bracing carrying a riveted steel tank, a ladder up one leg - const h = 7.5, s = 1.6; - for (const a of [-1, 1]) for (const b of [-1, 1]) B.box('timber', a * s, 0, b * s, 0.26, h, 0.26, 0, { grain: 'long', tint: C(0.65, 0.6, 0.55), rx: -b * 0.03, rz: a * 0.03 }); - for (const y of [2.4, 5.0]) for (const side of [0, 1]) for (const k of [-1, 1]) { - const len = Math.hypot(2 * s, 2.4); if (side) B.box('timber', k * s, y - 2.25, 0, 0.1, 0.12, len, 0, { rx: Math.atan2(2.4, 2 * s) * (y > 3 ? 1 : -1), noFoot: true, grain: 'long' }); else B.box('timber', 0, y - 2.25, k * s, len, 0.12, 0.1, 0, { rz: Math.atan2(2.4, 2 * s) * (y > 3 ? -1 : 1), noFoot: true, grain: 'long' }); } - for (const y of [0.4, h - 0.2]) for (const k of [-1, 1]) { B.box('timber', 0, y, k * s, 2 * s + 0.3, 0.16, 0.14, 0, { grain: 'long', noFoot: true }); B.box('timber', k * s, y, 0, 0.14, 0.16, 2 * s + 0.3, 0, { grain: 'long', noFoot: true }); } - B.box('planks', 0, h, 0, 2 * s + 0.6, 0.12, 2 * s + 0.6, 0, { noFoot: true }); - B.geo('metal_painted', cyl(2.0, 2.0, 2.7, 20), M4(0, h + 0.12 + 1.35, 0), { tint: C(0.5, 0.52, 0.48), keepUv: true, uvW: 12.6, uvH: 2.7 }); - B.geo('metal_painted', new THREE.ConeGeometry(2.1, 0.5, 20), M4(0, h + 0.12 + 2.95, 0), { noFoot: true, tint: C(0.45, 0.46, 0.43) }); - for (const yy of [0.05, 0.95, 1.85, 2.65]) B.geo('metal_rust', new THREE.TorusGeometry(2.01, 0.025, 4, 28).rotateX(Math.PI / 2), M4(0, h + 0.12 + yy, 0), { noFoot: true }); - B.geo('metal_rust', cyl(0.09, 0.09, h + 0.2, 8), M4(0.4, (h + 0.2) / 2, 0.3), { noFoot: true }); - for (let k = 0; k < 24; k++) B.box('metal_rust', s + 0.2, 0.3 + k * 0.3, s + 0.05, 0.4, 0.03, 0.03, 0.785, { noFoot: true }); - B.decal('rust', [1.42, h + 1.4, 1.42], [0.71, 0, 0.71], 0.6, 2.2, 0); B.decal('rust', [-2.01, h + 1.0, 0], [-1, 0, 0], 1.2, 1.8, 0); - B.decal('waterstain', [0, 0.02, 0], [0, 1, 0], 3.6, 3.6, 0); - for (const a of [-1, 1]) for (const b of [-1, 1]) B.col(a * s, b * s, 0.3, 0.3, 0, h, 0, 'wood', 'tower'); - }; - KINDS.targetframe = (B, R, o) => { - // a range target frame: two uprights, a paper-faced board, patched; spare frames lean on the butts - const w = 1.2, h = 1.6; - for (const s of [-1, 1]) B.box('timber', s * (w / 2 + 0.04), 0, 0, 0.08, h + 0.6, 0.08, 0, { grain: 'long' }); - B.box('canvas', 0, 0.6, 0, w, h, 0.02, 0, { tint: C(1.05, 1.0, 0.85) }); - B.box('timber', 0, 0.6, -0.03, w + 0.1, 0.06, 0.04, 0, { noFoot: true }); B.box('timber', 0, 0.6 + h - 0.06, -0.03, w + 0.1, 0.06, 0.04, 0, { noFoot: true }); - for (let k = 0; k < 7; k++) B.box('canvas', R.range(-0.45, 0.45), 0.8 + R.range(0, h - 0.4), 0.012, 0.06, 0.06, 0.004, R() * 0.8, { noFoot: true, tint: C(0.55, 0.5, 0.4) }); - B.decal('mud', [0, 0.7, 0.02], [0, 0, 1], w, 0.3, 0); - B.col(0, 0, w + 0.2, 0.15, 0, h + 0.6, 0, 'wood', 'target'); - }; - KINDS.car = (B, R) => { - // a plain staff car of the period: long bonnet, upright cab, separate wings and running boards, no markings - const paint = new THREE.Color(0.32, 0.34, 0.27); - B.box('metal_painted', 0.2, 0.42, 0, 4.1, 0.55, 1.5, 0, { tint: paint }); - B.box('metal_painted', -0.55, 0.97, 0, 2.0, 0.62, 1.42, 0, { tint: paint }); - B.box('glass', 0.47, 1.0, 0, 0.04, 0.5, 1.28, 0, { rz: 0.35, noFoot: true }); - for (const sz of [-1, 1]) { B.box('glass', -0.55, 1.05, sz * 0.715, 1.6, 0.42, 0.02, 0, { noFoot: true }); B.box('metal_painted', 0.15, 0.32, sz * 0.83, 3.4, 0.05, 0.22, 0, { tint: paint, noFoot: true }); } - for (const [x, sz] of [[1.45, -1], [1.45, 1], [-1.3, -1], [-1.3, 1]]) { B.geo('metal_rust', new THREE.CylinderGeometry(0.36, 0.36, 0.2, 14).rotateX(Math.PI / 2), M4(x, 0.36, sz * 0.72), { tint: new THREE.Color(0.12, 0.12, 0.12) }); B.box('metal_painted', x, 0.62, sz * 0.72, 0.9, 0.12, 0.34, 0, { tint: paint, noFoot: true }); } - for (const sz of [-0.45, 0.45]) B.geo('glass_lit', new THREE.SphereGeometry(0.11, 8, 6), M4(2.22, 0.78, sz), { noFoot: true }); - B.decal('mud', [0, 0.35, 0.76], [0, 0, 1], 3.6, 0.5, 0); B.decal('mud', [0, 0.35, -0.76], [0, 0, -1], 3.6, 0.5, 0); - B.col(0.1, 0, 4.4, 1.7, 0, 1.6, 0, 'metal', 'car'); - }; - KINDS.guardtower = (B, R) => { - // a timber sentry tower: four braced legs, a boarded box with a roof, a ladder - const h = 5.2, s = 1.4; - for (const a of [-1, 1]) for (const b of [-1, 1]) B.box('timber', a * s, 0, b * s, 0.2, h + 2.2, 0.2, 0, { grain: 'long', rx: -b * 0.04, rz: a * 0.04 }); - for (const k of [-1, 1]) { B.box('timber', 0, 2.2, k * s, 2 * s, 0.1, 0.1, 0, { rz: 0.9, noFoot: true }); B.box('timber', k * s, 2.2, 0, 0.1, 0.1, 2 * s, 0, { rx: 0.9, noFoot: true }); } - B.box('planks', 0, h, 0, 2 * s + 0.6, 0.12, 2 * s + 0.6, 0, { noFoot: true }); - for (const k of [-1, 1]) { B.box('planks', 0, h + 0.12, k * (s + 0.3), 2 * s + 0.6, 1.0, 0.05, 0, { noFoot: true }); B.box('planks', k * (s + 0.3), h + 0.12, 0, 0.05, 1.0, 2 * s + 0.6, 0, { noFoot: true }); } - B.box('slate', 0, h + 2.2, 0, 2 * s + 1.2, 0.08, 2 * s + 1.2, 0, { noFoot: true, rx: 0.12 }); - for (let k = 0; k < 17; k++) B.box('timber', 0, 0.3 + k * 0.3, s + 0.55, 0.5, 0.04, 0.05, 0, { noFoot: true }); - for (const a of [-0.25, 0.25]) B.box('timber', a, 0, s + 0.55, 0.06, h + 0.2, 0.06, 0, { noFoot: true }); - B.decal('mud', [0, 0.02, 0], [0, 1, 0], 4, 4, 0); - for (const a of [-1, 1]) for (const b of [-1, 1]) B.col(a * s, b * s, 0.3, 0.3, 0, h, 0, 'wood', 'tower'); - }; - KINDS.shelter = (B, R) => { - // an open firing-point shelter: posts and a lean-to roof, a bench and an ammunition table - const w = 6, d = 3; - for (const a of [-1, 1]) for (const b of [-1, 1]) B.box('timber', a * (w / 2 - 0.1), 0, b * (d / 2 - 0.1), 0.14, b > 0 ? 2.5 : 2.2, 0.14, 0, { grain: 'long' }); - B.box('slate', 0, 2.3, 0, w + 0.5, 0.06, d + 0.6, 0, { rx: -0.1, noFoot: true }); - B.box('planks', 0, 0.42, -d / 2 + 0.4, w - 0.6, 0.06, 0.35, 0, {}); B.box('planks', 0, 0.75, 0.4, 2.2, 0.06, 0.8, 0, {}); - B.col(0, 0, w, d, 0, 2.4, 0, 'wood', 'shelter'); - }; - KINDS.aframe = (B, R) => { - // an assault-course climbing frame: two A legs, rungs, a scramble net strung on poles - for (const a of [-1.6, 1.6]) for (const b of [-1, 1]) B.box('timber', a, 0, b * 0.9, 0.16, 3.6, 0.16, 0, { grain: 'long', rx: -b * 0.26 }); - for (let k = 0; k < 6; k++) B.box('timber', 0, 0.5 + k * 0.5, 0.75 - k * 0.12, 3.6, 0.08, 0.08, 0, { noFoot: true }); - B.box('canvas', 0, 1.0, -0.6, 3.2, 2.2, 0.02, 0, { rx: 0.26, noFoot: true, tint: new THREE.Color(0.45, 0.42, 0.34) }); - }; - E.prop = function (kind, seed, opts) { - opts = opts || {}; - const fn = KINDS[kind] || KINDS[({ 'sandbag wall': 'sandbags', 'hay bale': 'haybale', 'hay stack': 'haystack', 'water trough': 'trough', 'telegraph pole': 'telegraph', 'lamp post': 'lamppost', 'fuel drums': 'drums', 'ammunition boxes': 'ammo', 'log pile': 'logpile', 'tarpaulin stack': 'tarp' })[kind]]; - if (!fn) throw new Error('IVEnv.prop: unknown kind ' + kind); - const B = E.builder(seed || 1), R = E.rng((seed || 1) * 13 + 5); B._extra = []; if (E.Q.name !== 'low' && !E.noBevel) B.bevelAuto = true; // props are seen close: every box gets a bevel - const extra = fn(B, R, opts) || {}; - const group = B.finish(); group.name = 'IVEnv.prop:' + kind; - for (const x of B._extra) group.add(x); - const lights = extra.light ? [extra.light] : []; - if (extra.light && kind === 'lamppost') group.add(E.glowSprite(extra.light)); - if (extra.wireTop) group.userData.wireTop = extra.wireTop; - return { group, colliders: B.colliders, lights, door: extra.door }; - }; - // a soft halo around a lamp (moist night air), additive, never above the threshold that would strobe - let glowTex = null; - E.glowSprite = function (l) { - if (!glowTex) { const c = document.createElement('canvas'); c.width = c.height = 64; const g = c.getContext('2d'), gr = g.createRadialGradient(32, 32, 0, 32, 32, 32); gr.addColorStop(0, 'rgba(255,255,255,1)'); gr.addColorStop(0.2, 'rgba(255,255,255,0.35)'); gr.addColorStop(1, 'rgba(255,255,255,0)'); g.fillStyle = gr; g.fillRect(0, 0, 64, 64); glowTex = new THREE.CanvasTexture(c); } - const m = new THREE.SpriteMaterial({ map: glowTex, color: new THREE.Color(l.color).multiplyScalar(0.18), blending: THREE.AdditiveBlending, depthWrite: false, transparent: true }); - const s = new THREE.Sprite(m); s.position.set(l.x, l.y + 0.05, l.z); s.scale.set(1.2, 1.2, 1); s.userData.dynamic = true; s.name = 'lamp-glow'; return s; - }; -})(); diff --git a/e63334287a3deaa3/ironveil/env/rooms.js b/e63334287a3deaa3/ironveil/env/rooms.js deleted file mode 100644 index 32e74f8b..00000000 --- a/e63334287a3deaa3/ironveil/env/rooms.js +++ /dev/null @@ -1,96 +0,0 @@ -/* Midnight Ops environment: room light, soldier rim light and the wear-layer recipe flags. Midnight Ops only (loaded - after env/core.js by its pages; Ironwing shares env/core.js but not this file, and never makes these materials). - Adds to IVEnv.U the uniforms the materials in env/core.js read (openings, room fill, probe, rim), IVEnv.setPortals, - IVEnv.GLSL.interior / interiorUniforms, IVEnv.interiorPatch (kit materials) and IVEnv.rimPatch (characters). */ -(function () { - 'use strict'; - const E = window.IVEnv, U = E.U; - // openings (windows, doors) of the rooms near the camera: the light that comes in through them (IVEnv.setPortals) - Object.assign(U, { uWin: { value: [] }, uWinN: { value: [] }, uWinNum: { value: 0 }, uWinC: { value: new THREE.Color(0.3, 0.32, 0.36) }, uProbeK: { value: 0 }, uRoomAmb: { value: new THREE.Color(0.036, 0.038, 0.043) }, - uRim: { value: new THREE.Color(0, 0, 0) } }); // uRim: the edge light on soldiers (IVEnv.rimPatch), set by the atmosphere - for (let i = 0; i < 8; i++) { U.uWin.value.push(new THREE.Vector4()); U.uWinN.value.push(new THREE.Vector4()); } - - // IVEnv.setPortals([{ x, y, z, nx, nz, w, h }]): the openings of roofed rooms (centre, normal pointing INTO the room, - // width, height, metres). The 8 nearest the camera light the inside of their room (E.GLSL.interior). - let portals = [], portT = 0; - E.setPortals = function (list) { portals = (list || []).slice(); portT = 1e9; }; - E._updaters.push(function (dt, cam) { - portT += dt; if (portT < 0.25 || !cam) return; portT = 0; - const px = cam.position.x, py = cam.position.y, pz = cam.position.z; - const l = portals.filter(p => (p.x - px) ** 2 + (p.z - pz) ** 2 < 30 * 30).sort((a, b) => ((a.x - px) ** 2 + (a.y - py) ** 2 + (a.z - pz) ** 2) - ((b.x - px) ** 2 + (b.y - py) ** 2 + (b.z - pz) ** 2)); - const n = Math.min(8, l.length); U.uWinNum.value = n; - for (let i = 0; i < n; i++) { const p = l[i], k = Math.hypot(p.nx, p.nz) || 1; U.uWin.value[i].set(p.x, p.y, p.z, p.w / 2); U.uWinN.value[i].set(p.nx / k, 0, p.nz / k, p.h / 2); } - }); - // Inside a roofed room the outdoor sky fill and sky reflections fall away and the room is lit by its openings: each - // one is a small area light of the sky's colour (form factor of the opening seen from the point), so light comes in - // at the windows and door and falls off across the floor and up the far wall; lamps add their own pools. Without a - // shadow map (Low) the sun and moon are also mostly kept out under the roof. vec3 wp: world position, nW: world normal. - E.GLSL.interior = ` - float ivInside(vec3 wp){ float d = 0.0; - for (int i = 0; i < 16; i++) { if (i >= uRoofN) break; vec4 r = uRoof[i]; - vec2 inb = smoothstep(vec2(0.05), vec2(0.5), min(wp.xz - r.xy, r.zw - wp.xz)); - d = max(d, inb.x * inb.y * step(wp.y, uRoofY[i] + 0.6)); } - return d; } - vec3 ivWindows(vec3 wp, vec3 nW){ vec3 s = vec3(0.0); - for (int i = 0; i < 8; i++) { if (i >= uWinNum) break; - vec3 wn = uWinN[i].xyz; float A = 4.0 * uWin[i].w * uWinN[i].w; - vec3 L = uWin[i].xyz - wp; float d2 = max(dot(L, L), 0.04); L *= inversesqrt(d2); - float cw = max(dot(-L, wn), 0.0), cn = clamp(dot(nW, L) * 0.7 + 0.3, 0.0, 1.0); - s += A * cw * cn / (3.14159 * d2 + A); } - return s * uWinC; } - void ivInteriorLight(inout ReflectedLight rl, vec3 albedo, vec3 wp, vec3 nV){ - float inside = ivInside(wp); if (inside <= 0.0) return; - vec3 nW = inverseTransformDirection(nV, viewMatrix); - rl.indirectDiffuse *= mix(1.0, 0.2, inside); rl.indirectSpecular *= mix(1.0, 0.6, inside); - #ifdef USE_SHADOWMAP - rl.indirectDiffuse += inside * albedo * (ivWindows(wp, nW) * 10.0 + uRoomAmb); - #else - rl.indirectDiffuse += inside * albedo * (uWinC * 0.45 + uRoomAmb); // Low: one flat fill, not a loop over the openings (cost) - #endif - // bounce: the room's own light probe (js/world.js renders one when the camera walks into a room), its most - // blurred level along the normal - #if defined( USE_ENVMAP ) && defined( STANDARD ) - rl.indirectDiffuse += inside * albedo * getIBLRadiance(vec3(0.0, 0.0, 1.0), nV, 1.0) * uProbeK; - #endif - #ifndef USE_SHADOWMAP - rl.directDiffuse *= mix(1.0, 0.15, inside); rl.directSpecular *= mix(1.0, 0.15, inside); - #endif - }`; - E.GLSL.interiorUniforms = 'uniform vec4 uWin[8]; uniform vec4 uWinN[8]; uniform int uWinNum; uniform vec3 uWinC; uniform float uProbeK; uniform vec3 uRoomAmb;\n'; - // the same for a material that is not an IVEnv one (the kit's, js/world.js): adds the world position and uniforms - E.interiorPatch = function (sh, tag) { - Object.assign(sh.uniforms, { uRoof: U.uRoof, uRoofY: U.uRoofY, uRoofN: U.uRoofN, uWin: U.uWin, uWinN: U.uWinN, uWinNum: U.uWinNum, uWinC: U.uWinC, uProbeK: U.uProbeK, uRoomAmb: U.uRoomAmb }); - E.patch(sh, 'vertex', '#include ', `#include - { vec4 ivp = vec4(transformed, 1.0); - #ifdef USE_INSTANCING - ivp = instanceMatrix * ivp; - #endif - vIvW = (modelMatrix * ivp).xyz; }`, tag); - sh.vertexShader = 'varying vec3 vIvW;\n' + sh.vertexShader; - E.patch(sh, 'fragment', '#include ', '#include \n ivInteriorLight(reflectedLight, diffuseColor.rgb, vIvW, normal);', tag); - sh.fragmentShader = 'varying vec3 vIvW; uniform vec4 uRoof[16]; uniform float uRoofY[16]; uniform int uRoofN;\n' + E.GLSL.interiorUniforms + sh.fragmentShader.replace('void main() {', E.GLSL.interior + '\nvoid main() {'); - }; - - // IVEnv.rimPatch(material): a soft cool edge light on a character's body (the sky and moon catching the rim), so a - // figure separates from a dark field at 30 to 40 m by its outline. Faded with distance by the fog like the rest. - E.rimPatch = function (m) { - if (!m || m.userData.ivRim || Object.prototype.hasOwnProperty.call(m, 'onBeforeCompile')) return; - m.userData.ivRim = true; - m.onBeforeCompile = function (sh) { - sh.uniforms.uRim = U.uRim; - E.patch(sh, 'fragment', '#include ', `{ float ivF = 1.0 - clamp(dot(normalize(normal), normalize(vViewPosition)), 0.0, 1.0); - outgoingLight += uRim * ivF * ivF * ivF * (0.4 + 0.6 * clamp(normal.y * 0.5 + 0.6, 0.0, 1.0)); } - #include `, 'env/core rim'); - sh.fragmentShader = 'uniform vec3 uRim;\n' + sh.fragmentShader; - }; - m.customProgramCacheKey = () => 'ivrim'; - }; - - - // wear layers by recipe (drawn in env/core.js's material, Medium and High): chipped paint and what shows under it, - // rust, weathered timber, scuffed floors, stained plaster, mottled sandbags - const RC = E.RECIPES; - RC.wood_painted.paintUnder = 'vec3(0.16, 0.135, 0.11)'; RC.metal_painted.paintUnder = 'vec3(0.16, 0.075, 0.035)'; - RC.metal_painted.rust = 1; RC.metal_rust.rust = 1; RC.planks.timber = 1; RC.timber.timber = 1; - RC.floorboards.floor = 1; RC.plaster_interior.stain = 1; RC.plaster.stain = 1; RC.sandbag.bag = 1; RC.canvas.bag = 1; -})(); diff --git a/e63334287a3deaa3/ironveil/es.js b/e63334287a3deaa3/ironveil/es.js index 18752fbc..828b107a 100644 --- a/e63334287a3deaa3/ironveil/es.js +++ b/e63334287a3deaa3/ironveil/es.js @@ -1,162 +1,61 @@ /* Midnight Ops (folder ironveil/) in Spanish (lang.js; see README). English -> Spanish, in our own words. Loaded right - after lang.js, before the game's scripts. The game name itself comes from IV.GAME_NAME and is not translated. */ + after lang.js, before the game's scripts. The game name itself comes from MO.GAME_NAME and is not translated. */ (function () { if (!window.BackRoomLang) return; BackRoomLang.add({ - // ---- content note, title, menus - 'Before you play': 'Antes de jugar', '{n} contains war violence and blood.': '{n} tiene violencia bélica y sangre.', - 'Realistic Second World War weapons': 'Armas realistas de la Segunda Guerra Mundial', 'Enemy soldiers are shot and killed': 'Se dispara y se abate a soldados enemigos', - 'Blood effects (they can be turned off in Settings)': 'Efectos de sangre (se pueden quitar en Ajustes)', 'I understand, continue': 'Entiendo, continuar', 'Back': 'Volver', - 'Behind the lines, Normandy country, 1944.': 'Detrás de las líneas, campiña de Normandía, 1944.', - 'Continue': 'Continuar', 'Campaign': 'Campaña', 'Settings': 'Ajustes', 'Controls': 'Controles', 'checkpoint': 'punto de control', - 'Single player · progress saves in this browser': 'Un jugador · el progreso se guarda en este navegador', 'Back Room': 'Back Room', - 'The Farmhouse': 'La granja', 'Map table. Pick an operation. Each one can be replayed for a better rating.': 'Mesa de mapas. Elige una operación. Puedes repetirlas para mejorar la nota.', - 'Difficulty': 'Dificultad', 'Recruit': 'Recluta', 'Regular': 'Soldado', 'Veteran': 'Veterano', - 'Strong aim assist. Enemies slow to notice and miss more.': 'Mucha ayuda de puntería. Los enemigos tardan en verte y fallan más.', - 'Mild aim assist. A fair fight.': 'Ayuda de puntería suave. Una pelea pareja.', 'No aim assist. Sharp eyes, hard hits.': 'Sin ayuda de puntería. Ven bien y pegan fuerte.', - 'Done': 'Hecha', 'Locked': 'Bloqueada', 'New': 'Nueva', 'Coming soon': 'Muy pronto', 'gold': 'oro', 'silver': 'plata', 'bronze': 'bronce', - 'Secret': 'Secreto', 'Training': 'Entrenamiento', 'Objectives': 'Objetivos', 'Begin': 'Empezar', 'Skip tutorial': 'Saltar el tutorial', 'optional': 'opcional', - 'Sketch map of the area': 'Croquis de la zona', 'Game view': 'Vista del juego', - 'PAUSED': 'PAUSA', 'Resume': 'Seguir', 'Restart from checkpoint': 'Volver al punto de control', 'Restart mission': 'Reiniciar la misión', 'Quit to map table': 'Salir a la mesa de mapas', - 'Game': 'Juego', 'Video': 'Video', 'Audio': 'Audio', 'Look sensitivity': 'Sensibilidad de la vista', 'Aim sensitivity': 'Sensibilidad al apuntar', 'While aiming or scoped': 'Al apuntar o con la mira', - // ---- shooting (aim assist only on touch screens, debrief rating, hit and ammo cues) - 'Enemies slow to notice and miss more. Strong aim assist on touch screens.': 'Los enemigos tardan en verte y fallan más. Mucha ayuda de puntería en pantallas táctiles.', - 'A fair fight. Light aim assist on touch screens.': 'Una pelea pareja. Poca ayuda de puntería en pantallas táctiles.', - 'Sharp eyes, hard hits. Faint aim assist on touch screens.': 'Ven bien y pegan fuerte. Una pizca de ayuda de puntería en pantallas táctiles.', - 'Touch screens only (never with a mouse). 0 turns it off.': 'Solo en pantallas táctiles (nunca con ratón). 0 la apaga.', - 'Skill rating': 'Nota de habilidad', 'Skill rating of {n} or better': 'Nota de habilidad de {n} o más', 'Head shots': 'Tiros a la cabeza', 'Deaths': 'Muertes', - 'new best': 'nuevo récord', 'best {n}': 'récord {n}', 'par {t}': 'referencia {t}', - 'Invert look up and down': 'Invertir la vista arriba y abajo', 'Aim assist strength': 'Fuerza de la ayuda de puntería', "Multiplies the difficulty's assist. 0 turns it off.": 'Multiplica la ayuda de la dificultad. 0 la apaga.', - 'Auto-fire on target': 'Disparo automático sobre el blanco', 'Touch screens: fires when the reticle is on an enemy': 'Pantallas táctiles: dispara cuando la mira está sobre un enemigo', - 'Subtitle size': 'Tamaño de subtítulos', 'Small': 'Chico', 'Medium': 'Mediano', 'Large': 'Grande', 'Blood effects': 'Efectos de sangre', 'Off: hits show dust puffs instead': 'Apagado: los impactos muestran polvo', - 'Reduced motion': 'Menos movimiento', 'View': 'Vista', 'First person, or the camera over your shoulder': 'Primera persona, o la cámara sobre el hombro', 'First person': 'Primera persona', 'Over the shoulder': 'Sobre el hombro', 'Lean left': 'Asomarse a la izquierda', 'Lean L': 'Asom. I', 'Lean R': 'Asom. D', 'Lean right': 'Asomarse a la derecha', 'Swap shoulder (over-the-shoulder view)': 'Cambiar de hombro (vista sobre el hombro)', 'Camera bob': 'Balanceo de cámara', 'A small step bob and a dip when you land': 'Un leve balanceo al caminar y al caer', 'Less camera shake and sway, no lightning flashes': 'Menos sacudidas y balanceo de cámara, sin relámpagos', - 'Quality': 'Calidad', 'Low is best for school laptops and phones': 'Baja es mejor para laptops de la escuela y celulares', 'Low': 'Baja', 'High': 'Alta', 'Field of view': 'Campo de visión', 'Brightness': 'Brillo', - 'Master volume': 'Volumen general', 'Effects': 'Efectos', 'Music': 'Música', 'Mute (M)': 'Silencio (M)', 'Change keys': 'Cambiar teclas', - 'Quality changes apply when the page reloads': 'Los cambios de calidad se aplican al recargar la página', - 'Mission complete': 'Misión cumplida', 'Training complete': 'Entrenamiento completo', 'Mission failed': 'Misión fallida', 'Map table': 'Mesa de mapas', 'Replay': 'Repetir', 'Next: {t}': 'Siguiente: {t}', - 'Retry': 'Reintentar', 'Retry from checkpoint': 'Reintentar desde el punto de control', 'Gold': 'Oro', 'Silver': 'Plata', 'Bronze': 'Bronce', - 'Time': 'Tiempo', 'Accuracy': 'Puntería', 'Times spotted': 'Veces que te vieron', 'Enemies down': 'Enemigos abatidos', 'Takedowns': 'Derribos', 'Optional objectives': 'Objetivos opcionales', - 'You were killed.': 'Te mataron.', 'Killed. Back to the last checkpoint.': 'Caíste. Vuelves al último punto de control.', "Farm's north-east, past the orchard. Keep moving.": 'La granja está al noreste, pasando el huerto. Sigue.', 'Down the lane! Go!': '¡Camino abajo! ¡Vamos!', '{n} is down.': '{n} cayó.', 'Turn your phone sideways to play {n}.': 'Pon el celular de costado para jugar a {n}.', 'Loading…': 'Cargando…', - 'Loading soldiers…': 'Cargando soldados…', 'Laying out the country…': 'Trazando el campo…', 'Planting hedgerows…': 'Plantando setos…', 'Walking the lanes…': 'Recorriendo los caminos…', 'Briefing the squad…': 'Informando al pelotón…', - // ---- HUD - 'Standing': 'De pie', 'Crouched': 'Agachado', 'Prone': 'Cuerpo a tierra', 'Following': 'Te sigue', 'Holding': 'Espera', 'Fire at will': 'Fuego a discreción', 'Down': 'Caído', - 'Scoped rifle': 'Fusil con mira', 'Submachine gun': 'Subfusil', 'Pistol': 'Pistola', 'Binoculars': 'Binoculares', 'Grenade': 'Granada', 'Rock': 'Piedra', 's fuse': ' s de mecha', - 'Grenades': 'Granadas', 'Rocks': 'Piedras', 'Reloading': 'Recargando', '{k} Reload': '{k} Recargar', 'Empty': 'Vacío', 'Low ammo': 'Poca munición', 'Low ammo · {k} Reload': 'Poca munición · {k} Recargar', 'Reload': 'Recargar', 'Takedown': 'Derribar', 'Use': 'Usar', 'Range': 'Distancia', 'Wind {s} m/s': 'Viento {s} m/s', - 'Checkpoint reached': 'Punto de control', 'Soldier marked': 'Soldado marcado', 'Bombing run: your noise is masked': 'Bombardeo: tapa tu ruido', - 'Tap Fire to mark the soldier in the middle': 'Toca Disparar para marcar al soldado del centro', '{k} marks the soldier in the middle': '{k} marca al soldado del centro', - 'N': 'N', 'NW': 'NO', 'W': 'O', 'SW': 'SO', 'S': 'S', 'SE': 'SE', 'E': 'E', 'NE': 'NE', - 'On you.': 'Detrás de ti.', 'Holding here.': 'Me quedo acá.', 'Weapons free. Say the word, I shoot.': 'Armas libres. Si hace falta, disparo.', - // keybinds actions - 'Sprint': 'Correr', 'Crouch': 'Agacharse', 'Go prone': 'Tirarse al suelo', 'Vault over / stand up': 'Saltar el obstáculo / pararse', 'Hold breath (scoped)': 'Contener la respiración (con mira)', - 'Grenade ': 'Granada', 'Throw a rock': 'Tirar una piedra', 'Knife takedown': 'Derribo con cuchillo', 'Use / interact': 'Usar / interactuar', 'Squad order': 'Orden al compañero', 'Swap shoulder': 'Cambiar de hombro', 'Mute': 'Silencio', - 'Hold. The rifle goes to its scope': 'Mantener. El fusil usa la mira', 'Hold to cook and aim, let go to throw': 'Mantén para quitar el seguro y apuntar, suelta para tirar', - 'Hold to aim, let go to throw. Guards go to look': 'Mantén para apuntar, suelta para tirar. Los guardias van a mirar', 'From behind, close up': 'Desde atrás, de cerca', - 'Hold. Fire tags the soldier in the middle': 'Mantener. Disparar marca al soldado del centro', 'Hold for longer jobs': 'Mantén para tareas largas', 'Follow, hold, fire at will': 'Seguir, esperar, fuego a discreción', 'Fight': 'Combate', - // ---- enemy barks - 'Hm? Who is there?': '¿Mm? ¿Quién anda ahí?', 'Did you hear that?': '¿Oíste eso?', 'Something moved.': 'Algo se movió.', 'I will take a look.': 'Voy a mirar.', 'Stay here. I am checking it.': 'Quédate acá. Voy a revisar.', - 'Nothing. Just the wind.': 'Nada. Solo el viento.', 'Probably a fox.': 'Seguro era un zorro.', 'Back to it.': 'A lo nuestro.', 'There! Enemy!': '¡Ahí! ¡Enemigo!', 'Alarm! Over there!': '¡Alarma! ¡Por allá!', 'Contact!': '¡Contacto!', - 'Man down! Over here!': '¡Hombre caído! ¡Acá!', 'He is dead! Search the area!': '¡Está muerto! ¡Revisen la zona!', 'Grenade!': '¡Granada!', 'Reloading!': '¡Recargando!', 'I have him!': '¡Lo tengo!', 'Steady... now!': 'Quieto... ¡ahora!', 'In my sights!': '¡En la mira!', 'Take him!': '¡A él!', 'Gun up!': '¡Arma lista!', 'Feeding a belt!': '¡Cargando cinta!', 'Go round the side!': '¡Rodéalo por el costado!', 'Falling back!': '¡Me repliego!', - // ---- campaign list - 'Boot Camp': 'Instrucción', 'A morning on the training range: moving, shooting, sneaking. About five minutes.': 'Una mañana en el campo de prácticas: moverse, disparar, escabullirse. Unos cinco minutos.', - 'Night Drop': 'Salto nocturno', 'Behind the lines at night. Find your corporal, then the flak gun at Mauvenant Farm.': 'Detrás de las líneas, de noche. Encuentra a tu cabo y luego el antiaéreo de la granja Mauvenant.', - 'The Radio Mast': 'La antena', 'A signals compound with three ways in. Silence the transmitter before it calls in the guns.': 'Un recinto de transmisiones con tres entradas. Calla el transmisor antes de que pida artillería.', - 'Bridge at Dawn': 'Puente al amanecer', 'Take the river bridge with the platoon, then hold it through three counter-attacks.': 'Toma el puente con el pelotón y resiste tres contraataques.', - 'The Clocktower': 'El campanario', 'Sniper overwatch over an occupied town while a courier crosses the square.': 'Cubres como francotirador un pueblo ocupado mientras un mensajero cruza la plaza.', - 'Rail Yard': 'La estación de carga', 'Charges on a fuel train, a fuse already burning, and a truck out of the yard.': 'Cargas en un tren de combustible, una mecha encendida y un camión para salir.', - 'The Chateau': 'El castillo', "Lift the plans from an officers' dinner. If the alarm goes, out through the cellars.": 'Roba los planos durante una cena de oficiales. Si suena la alarma, sales por los sótanos.', - 'The Bunker Line': 'La línea de búnkeres', 'Trenches, pillboxes and machine-gun nests, with the whole company behind you.': 'Trincheras, fortines y nidos de ametralladora, con toda la compañía detrás.', - 'Last Light': 'Última luz', 'A mountain research site, a prototype to wreck and a long shot at a fleeing convoy.': 'Un laboratorio en la montaña, un prototipo que destruir y un tiro largo a un convoy que huye.', - // ---- boot camp - 'Training range, England, the week before the jump. Sergeant Okafor runs the course.': 'Campo de prácticas en Inglaterra, la semana antes del salto. El sargento Okafor dirige el circuito.', - 'One thing at a time. Each station waits until you have done it, and the prompts show your own keys.': 'Una cosa por vez. Cada puesto espera a que lo hagas, y las ayudas muestran tus propias teclas.', - 'Move, sprint, crouch, crawl and vault': 'Moverse, correr, agacharse, arrastrarse y saltar', 'Pop-up targets with the aim assist': 'Blancos emergentes con ayuda de puntería', 'The scoped rifle at 100, 200 and 300 m': 'El fusil con mira a 100, 200 y 300 m', - 'Distract a guard and take him down': 'Distraer a un guardia y derribarlo', 'Binoculars and grenades': 'Binoculares y granadas', - 'Walk to the first post': 'Camina hasta el primer poste', 'Sprint to the next post': 'Corre hasta el siguiente poste', 'Crouch under the log': 'Pasa agachado bajo el tronco', 'Crawl under the wire': 'Arrástrate bajo el alambre', - 'Vault the wall': 'Salta el muro', 'Hit the three pop-up targets': 'Acierta a los tres blancos', 'Go to the rifle bench': 'Ve al puesto de tiro', 'Hit the 100, 200 and 300 m plates': 'Acierta a las placas de 100, 200 y 300 m', - 'Throw a rock to distract the guard': 'Tira una piedra para distraer al guardia', 'Sneak up behind him and take him down': 'Acércate por detrás y derríbalo', 'Mark the three dummies with the binoculars': 'Marca los tres muñecos con los binoculares', 'Throw a grenade into the pit': 'Tira una granada al pozo', - 'Morning. One thing at a time. Walk up to the first post.': 'Buen día. Una cosa por vez. Camina hasta el primer poste.', 'Now run. Hold sprint all the way to the flag.': 'Ahora corre. Mantén correr hasta la bandera.', - 'Under the log. Crouch and go through.': 'Bajo el tronco. Agáchate y pasa.', "Wire's low. On your belly and crawl.": 'El alambre está bajo. Al suelo y arrástrate.', "Wall. Over it, don't walk round it.": 'El muro. Por encima, no lo rodees.', - 'Pop-ups to your left. Aim, and the sights settle on the nearest one. Then squeeze.': 'Blancos a tu izquierda. Apunta y la mira se va al más cercano. Después aprieta.', - 'Rifle. Plates at one, two and three hundred yards. Well, metres. Close enough.': 'Fusil. Placas a cien, doscientos y trescientos metros.', - "Middle of the scope hits at one hundred. The marks under it are for two and three hundred. Wind's from the west, so lean into it.": 'El centro de la mira pega a cien. Las marcas de abajo son para doscientos y trescientos. El viento viene del oeste, corrígelo.', - "Corporal Hale is playing the guard in the pen. He's watching the gate. Draw him off with a stone, get behind him, and put him down. Gently.": 'El cabo Hale hace de guardia en el corral y vigila la tranquera. Atráelo con una piedra, ponte detrás y derríbalo. Con cuidado.', - 'Dummies downrange, dressed like the other side. Binoculars up and mark all three.': 'Hay muñecos en el campo, vestidos como el enemigo. Binoculares arriba y márcalos a los tres.', - "Last one. Grenade into the pit. The fuse starts when you pull the pin, so don't hang on to it.": 'El último. Granada al pozo. La mecha arranca al quitar el seguro, así que no la retengas.', - 'Missed. Have another.': 'Fallaste. Toma otra.', 'Seen you! Back out and try again.': '¡Te vi! Sal y prueba de nuevo.', "Ow. Alright, that'll do.": 'Ay. Bueno, alcanza.', - "That's the course. You'll do. Get some sleep, you jump tomorrow night.": 'Ese es el circuito. Sirves. Duerme un poco: saltas mañana a la noche.', - 'Move with {k}. Look with the mouse.': 'Muévete con {k}. Mira con el mouse.', 'the mouse': 'el mouse', 'a finger on the right side': 'un dedo en el lado derecho', 'the left stick': 'el joystick izquierdo', - 'Hold {k} to sprint': 'Mantén {k} para correr', '{k} crouches (and stands up again)': '{k} te agacha (y te vuelve a parar)', - '{k} goes prone. Crouched or prone, you are quieter and harder to see.': '{k} te tira al suelo. Agachado o en el suelo haces menos ruido y cuesta más verte.', - 'Run at it and press {k} to vault': 'Corre hacia él y pulsa {k} para saltarlo', 'Hold {a} to aim, {f} to fire. The aim pulls onto targets: that is the aim assist.': 'Mantén {a} para apuntar y {f} para disparar. La mira se va sola al blanco: esa es la ayuda de puntería.', - 'Good. Now get your head round cover without stepping out. Lean left, then right.': 'Bien. Ahora asoma la cabeza por la cobertura sin salir. Inclínate a la izquierda y luego a la derecha.', - 'Lean out to the left and to the right': 'Asómate a la izquierda y a la derecha', - 'Hold {l} to lean left and {r} to lean right. You can aim and fire while leaning.': 'Mantén {l} para asomarte a la izquierda y {r} a la derecha. Puedes apuntar y disparar asomado.', - 'Pop-ups to your left. Bring the gun up, look down the sights, then squeeze.': 'Blancos a tu izquierda. Sube el arma, mira por el alza y después aprieta.', - 'Hold {a} to look down the sights, {f} to fire. From the hip the crosshair opens up while you move. Your aim slows over a target: that is the aim assist.': 'Mantén {a} para mirar por el alza y {f} para disparar. Desde la cadera la cruz se abre al moverte. La puntería se frena sobre un blanco: esa es la ayuda de puntería.', - 'Hold {a} to put your eye to the scope. Hold {b} to steady your breath. Lie down for the steadiest shot.': 'Mantén {a} para llevar el ojo a la mira. Mantén {b} para contener la respiración. Acostado es el tiro más firme.', - 'Behind him and close: {k} for the knife': 'Por detrás y de cerca: {k} para el cuchillo', - 'Move, sprint, crouch, crawl, vault and lean': 'Moverse, correr, agacharse, arrastrarse, saltar y asomarse', 'Pop-up targets down the sights': 'Blancos emergentes con el alza', - 'Play upright anyway': 'Jugar en vertical igualmente', - 'In progress': 'En preparación', - 'Press {k} for the rifle': 'Pulsa {k} para el fusil', 'Hold {a} for the scope. Hold {b} to steady your breath. Lie down for the steadiest shot.': 'Mantén {a} para la mira. Mantén {b} para contener la respiración. Acostado es el tiro más firme.', - 'Hold {k} to aim a rock, let go to throw. Land it away from where you want to go.': 'Mantén {k} para apuntar una piedra y suelta para tirarla. Que caiga lejos de donde quieres ir.', - 'Behind him and close: {k}': 'Detrás y cerca: {k}', 'Hold {b} for binoculars, then {f} marks the one in the middle. Marked soldiers stay on your compass.': 'Mantén {b} para los binoculares; {f} marca al del centro. Los marcados quedan en tu brújula.', - 'Hold {g} to pull the pin and aim (the line shows where it lands), let go to throw.': 'Mantén {g} para quitar el seguro y apuntar (la línea muestra dónde cae), suelta para tirar.', - 'Finish in under 6:00': 'Terminar en menos de 6:00', 'Three plates in six rifle shots or fewer': 'Las tres placas en seis tiros o menos', 'Accuracy of 50% or better': 'Puntería del 50 % o más', - // ---- night drop - 'June 1944. Your stick of pathfinders jumps ahead of the main drop. A flak gun at Mauvenant Farm covers the drop zone, and it has to be gone before the transports come over.': 'Junio de 1944. Tu grupo de exploradores salta antes que el resto. Un antiaéreo en la granja Mauvenant cubre la zona de salto y hay que eliminarlo antes de que lleguen los aviones de transporte.', - "You will land wide. Find Cpl. Dunning, keep off the lanes the patrols walk, and cut the farm's field-telephone line on the way.": 'Vas a caer lejos. Encuentra al cabo Dunning, evita los caminos de las patrullas y corta la línea de teléfono de campaña de la granja.', - "Set the charge on the gun. When it goes up the whole farm will be on you: get clear and down the sunken lane to the east, where Rook's men are waiting.": 'Pon la carga en el cañón. Cuando explote, toda la granja irá por ti: sal y baja por el camino hundido del este, donde esperan los hombres de Rook.', - 'Find Cpl. Dunning': 'Encuentra al cabo Dunning', 'Cut the field-telephone line': 'Corta la línea de teléfono de campaña', 'Destroy the flak gun': 'Destruye el antiaéreo', 'Reach the extraction lane': 'Llega al camino de extracción', - 'Take the map from the farm office': 'Llévate el mapa de la oficina de la granja', 'Take out the sniper in the barn loft': 'Elimina al francotirador del altillo del granero', - 'Cut yourself free of the harness': 'Libérate del arnés', 'Cut the harness': 'Cortar el arnés', 'Get to the orchard west of the farm': 'Llega al huerto al oeste de la granja', 'Cut the telephone line': 'Cortar la línea', - 'Plant the charge on the flak gun': 'Pon la carga en el antiaéreo', 'Plant the charge': 'Poner la carga', 'Charge set on the flak gun': 'Carga puesta en el antiaéreo', "The house! Clear it, or we'll never hold this yard.": '¡La casa! Límpiala o no vamos a aguantar en el patio.', 'Clear the farmhouse': 'Limpia la casa', 'Take the map from the office desk': 'Llévate el mapa del escritorio', - 'Take the map': 'Tomar el mapa', 'Breach the door': 'Abrir la puerta', 'Hold the yard until the charge blows: {s}': 'Resiste en el patio hasta que explote la carga: {s}', - 'Pathfinder Two, Rook. You came down short. The stick is scattered east of the river.': 'Explorador Dos, aquí Rook. Caíste corto. El grupo está disperso al este del río.', - 'The flak gun at the farm is still yours. Find your corporal and get it done.': 'El antiaéreo de la granja sigue siendo tuyo. Encuentra a tu cabo y cúmplelo.', - '(low whistle from the hedge to the north-east)': '(un silbido bajo desde el seto, al noreste)', 'Crouch to move quietly': 'Agáchate para moverte en silencio', - "Easy, it's me. Dunning. Thought you were hung up for the night.": 'Tranquilo, soy yo, Dunning. Pensé que te quedabas colgado toda la noche.', - "Rest of the stick landed past the river. So it's you and me for the gun.": 'El resto cayó pasando el río. Así que el cañón es cosa tuya y mía.', - "Farm's north-east. There's a lane patrol and a post at the crossroads. We go quiet.": 'La granja está al noreste. Hay una patrulla en el camino y un puesto en el cruce. Vamos en silencio.', - 'Patrol in the lane. Keep low and stay in the dark under the bank.': 'Patrulla en el camino. Agachado y en la sombra del talud.', 'Freeze. He heard something. Let him settle.': 'Quieto. Oyó algo. Deja que se calme.', - "Good. Down in the wheat they'll walk right past us.": 'Bien. Agachados en el trigo nos pasan al lado.', "Throw a stone past him. He'll go and look, and we slip by.": 'Tira una piedra más allá. Va a ir a mirar y pasamos.', - "Stream bed's low, but the water is noisy. Slow and steady.": 'El arroyo está bajo, pero el agua hace ruido. Despacio.', "Crossroads post, two of them. Wheat field's east of the road, it takes us right past.": 'Puesto del cruce, son dos. El trigal al este del camino nos deja pasar.', - 'Rook to all units: bombers on the rail junction east of you in thirty seconds.': 'Rook a todas las unidades: bombarderos sobre el empalme ferroviario al este en treinta segundos.', - 'When they hit, move. Nobody will hear us over that.': 'Cuando caigan las bombas, nos movemos. Nadie nos va a oír.', - "Line's dead. Now all they've got is the bell.": 'La línea está muerta. Ahora solo les queda la campana.', "Line's cut. Orchard next, then the farm.": 'Línea cortada. Ahora el huerto y después la granja.', - "Hold. Barn loft, the hay door. There's a sniper up there.": 'Espera. Altillo del granero, la puerta del heno. Hay un francotirador.', - "Rifle's yours. Mind the drop and the wind. Or we go round below his window.": 'El fusil es tuyo. Ojo con la caída y el viento. O lo rodeamos por debajo de su ventana.', - "Good shot. Loft's clear.": 'Buen tiro. Altillo limpio.', 'Hold aim with the rifle to use the scope': 'Mantén apuntar con el fusil para usar la mira', - "Charge is set. Pencil fuse, a few minutes. Now let's get clear of—": 'Carga puesta. Mecha de lápiz, unos minutos. Ahora salgamos de—', - "That's torn it! They're in the house, shooting from the windows!": '¡Se arruinó todo! ¡Están en la casa, disparando por las ventanas!', - "On the back door. Get on the other side, I'll go in first.": 'En la puerta de atrás. Ponte del otro lado, entro yo primero.', 'Going in!': '¡Entro!', - 'Their gun plan for the whole sector. Rook will want that.': 'Su plan de baterías de todo el sector. Rook lo va a querer.', 'House clear!': '¡Casa limpia!', - 'Charge is still burning. Hold the yard!': 'La carga sigue encendida. ¡Resistan en el patio!', 'Truck on the east road! Get to the wall and hold them off!': '¡Camión por el camino del este! ¡Al muro y aguántenlos!', - "They're off the truck! Four of them!": '¡Bajaron del camión! ¡Son cuatro!', "Gun's gone! Out the gap by the barn and down the lane! Go, go!": '¡Cañón destruido! ¡Por el hueco del granero y camino abajo! ¡Vamos, vamos!', - 'Contact in the lane! Down the side, use the bank!': '¡Contacto en el camino! ¡Por el costado, usa el talud!', 'Pathfinder Two, Rook. We see you. Come on in.': 'Explorador Dos, aquí Rook. Te vemos. Vengan.', - "That's the bell. Every soldier on the farm is awake now.": 'Es la campana. Ahora toda la granja está despierta.', - 'Finish in under 15:00': 'Terminar en menos de 15:00', 'Spotted no more than once before the farm': 'Que te vean como mucho una vez antes de la granja', - // sketch labels - 'FLAK': 'ANTIAÉREO', 'MG': 'AMETR.', 'post': 'puesto', 'sniper?': '¿francotirador?', 'Mauvenant Farm': 'Granja Mauvenant', 'orchard': 'huerto', 'wheat': 'trigo', 'the Lirette': 'el Lirette', 'telephone line': 'línea telefónica', - 'you are here (roughly)': 'estás acá (más o menos)', 'out': 'salida', 'start': 'inicio', 'run': 'correr', 'crouch': 'agacharse', 'crawl': 'arrastrarse', 'vault': 'saltar', 'pop-ups': 'blancos', 'rifle': 'fusil', 'pen': 'corral', 'binoculars': 'binoculares', 'pit': 'pozo', - 'Camp Hollowmere': 'Campamento Hollowmere', - // ---- handling round (movement, jump, crouch setting, crosshair, throws) - 'Hold: sprint while the key is down. Toggle: press once, it stops when you stop or aim': 'Mantener: corres mientras tengas la tecla apretada. Alternar: aprieta una vez, se para cuando te detienes o apuntas', - 'Toggle: press to crouch, again to stand. Hold: crouched while the key is down': 'Alternar: aprieta para agacharte y otra vez para pararte. Mantener: agachado mientras tengas la tecla apretada', - 'Toggle': 'Alternar', 'Hold': 'Mantener', - 'Hold to cook and aim (the arc shows where it lands), let go to throw. Tap throws at once': 'Mantén para quitar el seguro y apuntar (el arco muestra dónde cae), suelta para tirar. Un toque la tira enseguida', - 'Hold to aim (the arc shows where it lands), let go to throw. Guards go to look': 'Mantén para apuntar (el arco muestra dónde cae), suelta para tirar. Los guardias van a mirar', - 'Jump': 'Saltar', - 'Jump / vault / stand up': 'Saltar / pasar por encima / pararse', - // ---- enemy calls (js/ai.js): what they are about to do - 'Loading!': '¡Cargando!', 'Changing magazine!': '¡Cambio de cargador!', - 'I am working round him!': '¡Lo rodeo por el costado!', 'Moving to flank!': '¡Voy por el flanco!', - 'Pull back! Pull back!': '¡Atrás! ¡Atrás!', 'Too many of them, back!': '¡Son demasiados, atrás!', - 'Grenade out!': '¡Granada va!', 'Throwing one in!': '¡Le tiro una!', 'Smoke him out!': '¡Hay que sacarlo de ahí!', - 'Keep his head down!': '¡Que no asome la cabeza!', 'Covering fire!': '¡Fuego de cobertura!', 'Pin him there!': '¡Déjenlo clavado ahí!', - 'I am hit!': '¡Me dieron!', 'Ah! Hit!': '¡Ah! ¡Herido!', 'My leg!': '¡Mi pierna!', 'I am hit in the leg!': '¡Me dieron en la pierna!', - 'Where did he go?': '¿Adónde se fue?', 'Lost him!': '¡Lo perdí!', 'I cannot see him!': '¡No lo veo!', - 'Move up on him! Slowly!': '¡Avancen hacia él! ¡Despacio!', 'You two, check where he was!': '¡Ustedes dos, revisen donde estaba!', - 'Man down!': '¡Hombre caído!', 'He is down!': '¡Cayó!', 'Hold still...': 'Quieto...', 'Got you now...': 'Ya te tengo...' + // ---- title and content note + 'Night Drop': 'Salto nocturno', 'Normandy, 6 June 1944': 'Normandía, 6 de junio de 1944', + 'You came down three miles off the drop zone. The flak battery in this hamlet is tearing up the second wave. Spike its three guns, then reach the rally point.': 'Caíste a cinco kilómetros de la zona de salto. La batería antiaérea de esta aldea está destrozando a la segunda oleada. Inutiliza sus tres cañones y llega al punto de reunión.', + 'Deploy': 'Desplegar', 'Settings': 'Ajustes', 'Controls': 'Controles', 'Back': 'Volver', + 'Every stone, weapon and sound is made in your browser as the game starts. More missions are on the way.': 'Cada piedra, arma y sonido se crea en tu navegador al empezar el juego. Vienen más misiones en camino.', + 'Before you play': 'Antes de jugar', + 'Midnight Ops is a war game set in 1944. It shows soldiers shooting at each other, and some blood. You can turn the blood off in Settings.': 'Midnight Ops es un juego de guerra ambientado en 1944. Muestra soldados disparándose y algo de sangre. Puedes quitar la sangre en Ajustes.', + 'I understand, continue': 'Entiendo, continuar', + 'Building the hamlet': 'Construyendo la aldea', 'Raising the storm': 'Levantando la tormenta', 'Checking the weapon': 'Revisando el arma', + // ---- key hints + 'Move': 'Moverse', 'Look': 'Mirar', 'Fire': 'Disparar', 'Aim': 'Apuntar', 'Reload': 'Recargar', 'Plant charge': 'Poner carga', 'Sprint': 'Correr', 'Crouch': 'Agacharse', 'Jump': 'Saltar', 'Pause': 'Pausa', + 'Mouse': 'Ratón', 'Left': 'Izq.', 'Right': 'Der.', 'Left click': 'Clic izquierdo', 'Right click': 'Clic derecho', + 'Look (arrow keys also work)': 'Mirar (las flechas también sirven)', 'Aim down the sights': 'Apuntar con la mira', 'Hold to plant a charge on a gun': 'Mantén para poner una carga en un cañón', 'Crouch (harder to see and to hit)': 'Agacharse (más difícil que te vean y te den)', + 'On a phone or tablet: drag the left side of the screen to move, drag the right side to look, and use the buttons on the right. Push the move stick far forward to sprint.': 'En teléfono o tableta: arrastra el lado izquierdo de la pantalla para moverte, el derecho para mirar, y usa los botones de la derecha. Empuja la palanca bien hacia delante para correr.', + 'Done': 'Listo', 'Load': 'Carga', 'Duck': 'Agachar', 'Hold': 'Mantén', + // ---- pause, death, debrief + 'Paused': 'En pausa', 'Resume': 'Seguir', 'Restart mission': 'Reiniciar misión', 'Quit': 'Salir', 'Guns destroyed: {n} of 3': 'Cañones destruidos: {n} de 3', + 'Killed in action': 'Caído en combate', 'Try again': 'Reintentar', 'You go back in from the last gun you destroyed.': 'Vuelves a entrar desde el último cañón que destruiste.', 'You go back in from the drop zone.': 'Vuelves a entrar desde la zona de salto.', + 'Mission complete': 'Misión cumplida', 'The battery is silent. The second wave is coming in clean.': 'La batería calló. La segunda oleada entra sin problemas.', 'Play again': 'Jugar otra vez', 'Title': 'Inicio', + 'Time': 'Tiempo', 'Accuracy': 'Puntería', 'Enemies down': 'Enemigos abatidos', 'Retries': 'Reintentos', + 'Ragged': 'A duras penas', 'Loud': 'Ruidoso', 'Steady': 'Firme', 'Clean': 'Limpio', 'Sharp': 'Afilado', 'Textbook': 'De manual', + // ---- settings + 'Graphics': 'Gráficos', 'Auto': 'Automático', 'Low': 'Bajos', 'Medium': 'Medios', 'High': 'Altos', 'Look speed': 'Velocidad de la mira', 'Field of view': 'Campo de visión', 'Volume': 'Volumen', + 'Invert look up and down': 'Invertir mirar arriba y abajo', 'Blood effects': 'Efectos de sangre', 'Language': 'Idioma', 'A change to Graphics takes effect when the page is opened again.': 'El cambio de Gráficos se aplica al volver a abrir la página.', + // ---- campaign + 'Missions': 'Misiones', 'Ready': 'Lista', 'Play': 'Jugar', 'Locked': 'Bloqueada', 'Coming soon': 'Muy pronto', 'Done': 'Hecha', 'Next mission': 'Siguiente misión', 'Next: {t}': 'Siguiente: {t}', 'Building the map': 'Construyendo el mapa', + 'Bridge at Dawn': 'El puente al amanecer', 'Take the river bridge, then hold it through three counter-attacks.': 'Toma el puente del río y aguanta tres contraataques.', + 'The Clocktower': 'La torre del reloj', 'Sniper overwatch over an occupied town while a courier crosses the square.': 'Cubre con el fusil de precisión a un mensajero que cruza la plaza de un pueblo ocupado.', + 'Rail Yard': 'La playa de vías', 'Charges on a fuel train, a fuse already burning, and a truck out of the yard.': 'Cargas en un tren de combustible, una mecha ya encendida y un camión para salir de la estación.', + 'Exit': 'Salida', 'Treeline': 'Arboleda', 'Radio': 'Radio', 'Mast': 'Mástil', 'Power': 'Corriente', 'Charges': 'Cargas', + // ---- mission 2, The Radio Mast + 'The Radio Mast': 'El mástil de radio', 'Normandy, France. 6 June 1944, 04:10': 'Normandía, Francia. 6 de junio de 1944, 04:10', + 'A signals compound with three ways in. Silence the transmitter before it calls in the guns, then bring down the mast.': 'Un recinto de transmisiones con tres entradas. Calla el transmisor antes de que llame a la artillería y luego derriba el mástil.', + 'Silence the transmitter': 'Calla el transmisor', 'Bring down the mast': 'Derriba el mástil', 'Get to the treeline': 'Llega a la arboleda', + 'That mast is how they call the guns down on the beaches. Kill the transmitter in the bunker, then drop the mast.': 'Con ese mástil dirigen los cañones contra las playas. Destruye el transmisor del búnker y luego tira el mástil.', + 'Three ways in: the main gate, the drainage ditch on the west side, or the broken fence behind the generator.': 'Tres entradas: la puerta principal, la zanja de desagüe del lado oeste o la cerca rota detrás del generador.', + 'If they see you, that radio starts calling for artillery. Keep out of the searchlight.': 'Si te ven, esa radio empezará a pedir artillería. No te metas en el reflector.', + 'Radio is dead. That is both. Get to the treeline, north-west. Go!': 'La radio está muerta. Ya están los dos. Ve a la arboleda, al noroeste. ¡Vamos!', + 'Transmitter is scrap. Now the mast, or they will have a spare set talking by morning.': 'El transmisor es chatarra. Ahora el mástil, o por la mañana tendrán otro equipo hablando.', + 'Down she comes! Get to the treeline, north-west. Go!': '¡Ahí cae! Ve a la arboleda, al noroeste. ¡Vamos!', + 'The mast is down, but that radio can still talk on a short aerial. Finish it.': 'El mástil cayó, pero esa radio aún puede hablar con una antena corta. Acaba con ella.', + 'Lights out. That will make them jumpy, and half blind.': 'Sin luces. Eso los pondrá nerviosos y medio ciegos.', + 'They are on the set. Calling the guns. You have two and a half minutes.': 'Están en la radio. Llaman a los cañones. Tienes dos minutos y medio.', + 'Guns called: {t}': 'Cañones pedidos: {t}', 'Incoming!': '¡Obuses!', 'Spotted by the searchlight!': '¡Te vio el reflector!', 'The guns found you.': 'Los cañones te encontraron.', + 'You go back in from your last charge.': 'Vuelves a entrar desde tu última carga.', 'You go back in from the woods.': 'Vuelves a entrar desde el bosque.', + 'The mast is down and the radio is silent. The guns stay blind until dawn.': 'El mástil cayó y la radio calla. Los cañones siguen ciegos hasta el amanecer.', + // ---- HUD and radio + 'Objective': 'Objetivo', 'Spike the three flak guns': 'Inutiliza los tres cañones antiaéreos', 'Reach the rally point': 'Llega al punto de reunión', 'Guns': 'Cañones', 'Rally': 'Reunión', + 'Hold to plant the charge': 'Mantén para poner la carga', 'Charge set. Get clear!': '¡Carga puesta. Aléjate!', 'Reinforcements': 'Refuerzos', 'Reloading': 'Recargando', 'Health': 'Salud', 'Seen': 'Te ven', 'Under fire': 'Bajo fuego', '+20 rounds': '+20 balas', + 'Normandy, France. 6 June 1944, 01:42': 'Normandía, Francia. 6 de junio de 1944, 01:42', + 'You are down and in one piece. Good. The battery in that hamlet is cutting the second wave to bits.': 'Aterrizaste entero. Bien. La batería de esa aldea está haciendo pedazos a la segunda oleada.', + 'Three guns: the farmyard, the orchard, and one by the church. Put a charge on each. Go quiet if you can.': 'Tres cañones: el corral, el huerto y uno junto a la iglesia. Pon una carga en cada uno. Ve en silencio si puedes.', + 'That is all three. Rally at the wayside cross, north end of the lane. Move!': 'Ya son los tres. Reúnete en la cruz del camino, al norte del sendero. ¡Muévete!', + 'One gun down. They know you are here now. Keep moving.': 'Un cañón menos. Ya saben que estás aquí. No te detengas.', 'Two down. One more and the sky is ours.': 'Van dos. Uno más y el cielo es nuestro.' }); })(); diff --git a/e63334287a3deaa3/ironveil/index.html b/e63334287a3deaa3/ironveil/index.html index 99736e7d..aa582277 100644 --- a/e63334287a3deaa3/ironveil/index.html +++ b/e63334287a3deaa3/ironveil/index.html @@ -5,9 +5,9 @@ - - + + Midnight Ops
- - -
-
-
- -
+
-