<?phpnamespace App\Revisited\Render;use App\Revisited\Land\Creature;use App\Revisited\Land\Npc;use App\Revisited\Land\Thing;use App\Revisited\Land\Zone;use JumPHP\Gl\Mat4;use JumPHP\Gl\WebGl;/** * The 3D of "Experience - Rob revisited" (docs/reborn.md "Render"): textured terrain splatted by biome and slope, * water, sky with a day / night cycle and clouds, weather, vegetation and things, animated creatures and humans, * caves lit by the torch and fires, the item in hand, a light post-processing. * * $g = new Graphics($this->engine->gl(), 'high'); // in enter(); 'low' for phones * $g->loadZone($zone); // each time the zone changes (builds its meshes once) * // render(): clear the 2D with Graphics::KEY where the 3D must show, draw the HUD over it, then * $g->render($view); * $g->dispose(); // in exit() * * The layer is drawn at the window's resolution ('native', behind the 2D: the 2D shows the 3D where it is * Graphics::KEY). Meshes are built once per zone; render() only sends draw commands with uniforms. Zone things * that change (picked, cut, moved) are noticed every few frames and only their chunk is rebuilt. */final class Graphics{ /** the 2D colour through which the 3D shows */ public const KEY = [255, 0, 255]; /** quality level => the shaders' QUALITY (ultra: -1, cheaper than low everywhere) */ private const Q = ['ultra' => -1, 'low' => 0, 'medium' => 1, 'high' => 2]; /** * per quality: view distance, static props, small props, grass, grass density / m², outer reach, precipitation * quads, the levels of detail of the props near / far and where far begins, flames of a big fire */ private const SETTINGS = [ -1 => ['far' => 70.0, 'props' => 55.0, 'small' => 18.0, 'grass' => 0.0, 'density' => 0.0, 'outer' => 110.0, 'precip' => 300, 'lodNear' => 2, 'lodFar' => 2, 'lodDist' => 0.0, 'flames' => 5], 0 => ['far' => 110.0, 'props' => 85.0, 'small' => 35.0, 'grass' => 0.0, 'density' => 0.0, 'outer' => 260.0, 'precip' => 900, 'lodNear' => 1, 'lodFar' => 2, 'lodDist' => 30.0, 'flames' => 10], 1 => ['far' => 170.0, 'props' => 130.0, 'small' => 50.0, 'grass' => 30.0, 'density' => 0.5, 'outer' => 420.0, 'precip' => 2200, 'lodNear' => 0, 'lodFar' => 1, 'lodDist' => 40.0, 'flames' => 18], 2 => ['far' => 240.0, 'props' => 190.0, 'small' => 70.0, 'grass' => 45.0, 'density' => 0.95, 'outer' => 600.0, 'precip' => 4200, 'lodNear' => 0, 'lodFar' => 1, 'lodDist' => 55.0, 'flames' => 28], ]; private int $q; /** the level's name (Quality::LEVELS) */ private string $level; /** supersampling of the layer now (high: 2 while the window stays under Quality::MAX_PIXELS) */ private int $ss = 1; /** @var array{far: float, props: float, small: float, grass: float, density: float, outer: float, precip: int, lodNear: int, lodFar: int, lodDist: float, flames: int} */ private array $set; private bool $ok; private int $pTerrain = 0; private int $pProps = 0; private int $pBody = 0; private int $pSky = 0; private int $pWater = 0; private int $pFlame = 0; /** ground cover tufts coloured by the ground under them (PROPS_VS + GRASS, Shaders::GRASS_FS) */ private int $pGrass = 0; private int $pPrecip = 0; private int $pFall = 0; private int $pBolt = 0; /** @var array{key: string, vb: int, n: int}|null the lightning bolt being drawn */ private ?array $bolt = null; /** @var list<array{x: float, y: float, z: float, kind: string, id: int, r: float}> steam vents, geysers of the zone */ private array $emitters = []; /** @var list<array{0: float, 1: float, 2: float, 3: float}> burning patches of the zone: x, y, z, radius */ private array $patches = []; /** @var list<Thing> things drawn one by one (they bob on the water) */ private array $floating = []; /** zone look: water colours, far ridges, grass hue, outcrops @var array<string, mixed> */ private array $look = []; /** @var list<array{vb: int, n: int, x: float, z: float, top: float, bottom: float, w: float, yaw: float, reach: float, layer: int}> */ private array $falls = []; /** @var array<string, int> */ private array $tex = []; private int $skyVb = 0; private int $skyIb = 0; private int $skyN = 0; private int $flameVb = 0; /** puffs of smoke and steam: a quad turned to the eye (Shaders::PUFF_VS), drawn last, sorted (Graphics::drawPuffs()) */ private int $pPuff = 0; private int $puffVb = 0; /** @var list<array{0: float, 1: float, 2: float, 3: float, 4: float, 5: float, 6: float, 7: float, 8: float, 9: list<float>}> this frame's puffs: x y z, width, height, flow, seed, alpha, mode (2 steam, 3 smoke), colour */ private array $puffs = []; private int $precipVb = 0; private int $precipIb = 0; private int $precipN = 0; private ?Zone $zone = null; /** @var list<array<string, mixed>> */ private array $chunks = []; private int $chunkCells = 16; /** @var array{vb: int, ib: int, n: int}|null */ private ?array $outer = null; /** @var array{vb: int, n: int}|null */ private ?array $water = null; /** @var array<string, array{vb: int, ib: int, n: int}> */ private array $models = []; /** @var array<string, array<string, mixed>> */ private array $bodies = []; /** @var list<array{0: float, 1: float, 2: float}> lit campfires of the zone */ private array $campfires = []; /** @var list<int> resources of the zone (deleted on the next loadZone) */ private array $zoneRes = []; private int $frame = 0; private float $clock = 0.0; private float $lastTime = -1.0; /** @var array<string, mixed>|null the environment drawn last frame (smoothed toward the target one) */ private ?array $envShown = null; private float $envAt = -1.0; /** @var list<int> chunks waiting for a rebuild of their props */ private array $dirty = []; /** @var array<string, mixed> statistics of the last frame */ private array $stats = []; public function __construct(private WebGl $gl, string $quality = 'medium') { $this->level = isset(self::Q[$quality]) ? $quality : 'medium'; $this->q = self::Q[$this->level]; $this->set = self::SETTINGS[$this->q]; $this->ok = $gl->isAvailable(); if (!$this->ok) { return; } // ultra: the game's view resolution (320 x 240: ~20x fewer pixels than a window), else the window's $gl->setLayer('below', $this->q < 0 ? 'view' : 'native', self::KEY); $gl->setSupersample(1); $this->ss = 1; $q = Shaders::quality($this->q); $f = Shaders::FRAG_HEAD . $q; $this->pTerrain = $gl->program($q . Shaders::TERRAIN_VS, $f . Shaders::LIGHT . ($this->q < 0 ? Shaders::TERRAIN_FS : self::triplanar(Shaders::TERRAIN_FS))); $this->pProps = $gl->program($q . Shaders::PROPS_VS, $f . Shaders::LIGHT . Shaders::DITHER . Shaders::PROPS_FS); $skin = Shaders::quality($this->q, "#define SKIN 1\n"); $grass = Shaders::quality($this->q, "#define GRASS 1\n"); $this->pGrass = $gl->program($grass . Shaders::PROPS_VS, Shaders::FRAG_HEAD . $grass . Shaders::LIGHT . Shaders::DITHER . Shaders::GRASS_FS); $this->pBody = $gl->program($skin . Shaders::PROPS_VS, Shaders::FRAG_HEAD . $skin . Shaders::LIGHT . Shaders::DITHER . Shaders::PROPS_FS); $this->pBolt = $gl->program(Shaders::FLAME_VS, Shaders::FRAG_HEAD . Shaders::DITHER . Shaders::BOLT_FS); $this->pSky = $gl->program($q . Shaders::SKY_VS, $f . Shaders::LIGHT . Shaders::SKY_FS); $this->pWater = $gl->program($q . Shaders::WATER_VS, $f . Shaders::LIGHT . Shaders::DITHER . Shaders::WATER_FS); $this->pFlame = $gl->program(Shaders::FLAME_VS, Shaders::FRAG_HEAD . Shaders::DITHER . Shaders::FLAME_FS); $this->pPuff = $gl->program(Shaders::PUFF_VS, Shaders::FRAG_HEAD . Shaders::DITHER . Shaders::FLAME_FS); $this->pPrecip = $gl->program(Shaders::PRECIP_VS, Shaders::FRAG_HEAD . Shaders::DITHER . Shaders::PRECIP_FS); $this->pFall = $gl->program(Shaders::FLAME_VS, $f . Shaders::LIGHT . Shaders::DITHER . Shaders::FALL_FS); foreach (['grass', 'jungle', 'mud', 'sand', 'rock', 'snow'] as $name) { $this->tex[$name] = $this->loadTexture("ground_$name.png", true); } $this->tex['atlas'] = $this->loadTexture('props.png', true); $this->tex['noise'] = $this->loadTexture('noise.png', true); $this->tex['detail'] = $this->loadTexture('detail.png', true); $this->buildShared(); $gl->setPostShader(Shaders::POST, ['u_hurt' => 0.0, 'u_vignette' => 0.55, 'u_flashP' => 0.0]); } /** kinds whose colour varies per instance (a forest is never one green) */ private const TINTED = ['tree_broad' => 1, 'tree_palm' => 1, 'tree_conifer' => 1, 'bush_berry' => 1, 'giant_tree' => 1, 'mangrove' => 1, 'palm_coast' => 1, 'reeds_tall' => 1, 'reed' => 1, 'vine' => 1]; /** Rock on cliffs and cave walls: sampled on the vertical plane instead of the ground's (no smearing). */ private static function triplanar(string $fs): string { return str_replace( 'if (rockW > 0.01) { sr = layer(t_rock, a * 0.5, b * 0.6, fd); hr = rockW + hgt(sr) * 0.6; }', "if (rockW > 0.01) {\n" . " vec3 an = abs(normalize(v_nrm));\n" . " vec2 side = an.x > an.z ? vec2(v_uv.y, v_pos.y) : vec2(v_uv.x, v_pos.y);\n" . " float vert = smoothstep(0.75, 0.45, an.y);\n" . " vec2 ra = mix(a * 0.5, side * u_scale.x * 0.5, vert);\n" . " vec2 rb = mix(b * 0.6, side * u_scale.y * 0.6, vert);\n" . " sr = layer(t_rock, ra, rb, fd); hr = rockW + hgt(sr) * 0.6; }", $fs ); } public function isAvailable(): bool { return $this->ok; } /** The quality level it draws at (Quality::LEVELS). */ public function level(): string { return $this->level; } /** @return array<string, mixed> draws, triangles, chunks... of the last frame */ public function stats(): array { return $this->stats; } // ---- textures --------------------------------------------------------------------------------- /** * A PNG of assets/revisited, uploaded without a per-pixel PHP loop (GD's raw format, shifted by one byte: * see Shaders), with mipmaps. */ private function loadTexture(string $file, bool $mip): int { $path = (\defined('JUMPHP_ROOT') ? JUMPHP_ROOT . '/' : '') . 'assets/revisited/' . $file; $data = @file_get_contents($path); $img = $data === false ? false : @imagecreatefromstring($data); if ($img === false) { \JumPHP\Kernel\Application::stderr("[revisited] missing texture $file\n"); return $this->gl->textureFromRgba(1, 1, "\x80\x80\x80\x00", true); } if (!imageistruecolor($img)) { imagepalettetotruecolor($img); } imagesavealpha($img, true); $w = imagesx($img); $h = imagesy($img); ob_start(); imagegd($img); $raw = (string) ob_get_clean(); $rgba = substr($raw, 12) . "\x00"; if (strlen($rgba) !== $w * $h * 4) { return $this->gl->texture('assets/revisited/' . $file, true, true); } $id = $this->gl->textureFromRgba($w, $h, $rgba, true); if ($mip && $id > 0 && function_exists('glGenerateMipmap')) { $name = $this->glName($id); $ogl = $this->gl->openGl(); $ogl->save(); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, $name); glGenerateMipmap(GL_TEXTURE_2D); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); $ogl->restore(); } return $id; } /** The GL name behind a WebGl texture id (WebGl keeps it private; mipmaps need it). */ private function glName(int $id): int { $get = \Closure::bind(fn (int $i): int => (int) ($this->res[$i][1] ?? 0), $this->gl, WebGl::class); return $get($id); } // ---- shared meshes ---------------------------------------------------------------------------- private function buildShared(): void { $gl = $this->gl; // sky: a sphere around the eye $v = []; $idx = []; $lat = 14; $lon = 28; for ($a = 0; $a <= $lat; $a++) { $phi = M_PI * $a / $lat - M_PI / 2; for ($b = 0; $b <= $lon; $b++) { $th = 2 * M_PI * $b / $lon; array_push($v, cos($phi) * cos($th), sin($phi), cos($phi) * sin($th)); } } for ($a = 0; $a < $lat; $a++) { for ($b = 0; $b < $lon; $b++) { $p = $a * ($lon + 1) + $b; array_push($idx, $p, $p + 1, $p + $lon + 2, $p, $p + $lon + 2, $p + $lon + 1); } } $this->skyVb = $gl->buffer($v); $this->skyIb = $gl->indexBuffer($idx); $this->skyN = count($idx); // flames: three crossed quads, 1 m high (x y z u v) $f = []; for ($k = 0; $k < 3; $k++) { $a = $k * M_PI / 3; $c = cos($a) * 0.5; $s = sin($a) * 0.5; foreach ([[-1, 0, 0, 0], [1, 0, 1, 0], [1, 1, 1, 1], [-1, 0, 0, 0], [1, 1, 1, 1], [-1, 1, 0, 1]] as [$e, $y, $u, $vv]) { array_push($f, $c * $e, $y, $s * $e, $u, $vv); } } $this->flameVb = $gl->buffer($f); $this->puffVb = $gl->buffer([-0.5, -0.5, 0, 0, 0, 0.5, -0.5, 0, 1, 0, 0.5, 0.5, 0, 1, 1, -0.5, -0.5, 0, 0, 0, 0.5, 0.5, 0, 1, 1, -0.5, 0.5, 0, 0, 1]); // precipitation: quads of seeds in a unit box $n = $this->set['precip']; $pv = []; $pi = []; for ($k = 0; $k < $n; $k++) { $x = Mesh::hash($k, 1); $y = Mesh::hash($k, 2); $z = Mesh::hash($k, 3); for ($c = 0; $c < 4; $c++) { array_push($pv, $x, $y, $z, (float) $c); } $o = $k * 4; array_push($pi, $o, $o + 1, $o + 2, $o, $o + 2, $o + 3); } $this->precipVb = $gl->buffer($pv); $this->precipIb = $gl->indexBuffer($pi); $this->precipN = count($pi); } // ---- the zone --------------------------------------------------------------------------------- public function loadZone(Zone $zone): void { $this->zone = $zone; $this->envShown = null; if (!$this->ok) { return; } foreach ($this->chunks as $c) { foreach (['static', 'far', 'small'] as $slot) { foreach ($c[$slot] ?? [] as $p) { $this->gl->delete($p['vb']); $this->gl->delete($p['ib']); } } } foreach ($this->zoneRes as $id) { $this->gl->delete($id); } $this->zoneRes = []; $this->chunks = []; $this->dirty = []; $this->outer = $this->water = null; $this->chunkCells = max(8, (int) round(36 / max(0.25, $zone->cell))); // the shade of trees and rocks on the ground $shadows = []; $this->campfires = []; foreach ($zone->things as $t) { if (isset(Models::SHADOW[$t->kind])) { [$r, $s] = Models::SHADOW[$t->kind]; $shadows[] = [$t->x, $t->z, $r * $t->scale, $s]; } } $terrain = new Terrain($zone, $shadows); $gl = $this->gl; foreach ($terrain->chunks($this->chunkCells) as $c) { $vb = $this->res($gl->buffer($c['verts'])); $ib = $this->res($gl->indexBuffer($c['idx'])); $roof = null; if ($c['roof'] !== null) { $roof = ['vb' => $this->res($gl->buffer($c['roof']['verts'])), 'ib' => $this->res($gl->indexBuffer($c['roof']['idx'])), 'n' => count($c['roof']['idx'])]; } $this->chunks[] = [ 'x0' => $c['x0'], 'z0' => $c['z0'], 'x1' => $c['x1'], 'z1' => $c['z1'], 'cx' => ($c['x0'] + $c['x1']) / 2, 'cz' => ($c['z0'] + $c['z1']) / 2, 'minY' => $c['minY'], 'maxY' => $c['maxY'], 'top' => $c['maxY'], 'vb' => $vb, 'ib' => $ib, 'n' => count($c['idx']), 'roof' => $roof, 'static' => [], 'far' => [], 'small' => [], 'grass' => null, 'tufts' => null, 'sigS' => -1.0, 'sigM' => -1.0, 'grassTried' => false, ]; } $outer = $terrain->outer($this->set['outer']); if ($outer !== null && $outer['idx'] !== []) { $this->outer = ['vb' => $this->res($gl->buffer($outer['verts'])), 'ib' => $this->res($gl->indexBuffer($outer['idx'])), 'n' => count($outer['idx'])]; } $this->look = $this->lookOf($zone); $flow = get_object_vars($zone)['flow'] ?? null; $down = is_array($flow) && isset($flow[0], $flow[1]) ? [(float) $flow[0], (float) $flow[1]] : null; $water = $terrain->water($down); if ($water !== []) { $this->water = ['vb' => $this->res($gl->buffer($water)), 'n' => intdiv(count($water), 6)]; } $this->collectSpecial(); // waterfalls: their sheets (two layers each), built once $this->falls = []; foreach ($zone->things as $t) { if ($t->kind === 'waterfall') { foreach ([0, 1] as $layer) { $verts = self::fallSheet($t, $layer); $this->falls[] = ['vb' => $this->res($gl->buffer($verts)), 'n' => intdiv(count($verts), 5), 'x' => $t->x, 'z' => $t->z, 'top' => (float) ($t->data['top'] ?? $t->y), 'bottom' => (float) ($t->data['bottom'] ?? $zone->water), 'w' => (float) ($t->data['w'] ?? 6.0), 'yaw' => $t->yaw, 'reach' => (float) ($t->data['reach'] ?? 5.4), 'layer' => $layer]; } } } // the props of every chunk $sigs = $this->signatures(); foreach ($this->chunks as $k => $c) { $this->buildProps($k, $sigs[$k] ?? [[], [], 0.0, 0.0]); } } private function res(int $id): int { $this->zoneRes[] = $id; return $id; } private function chunkOf(float $x, float $z): int { $zone = $this->zone; if ($zone === null) { return 0; } $per = (int) ceil($zone->grid / $this->chunkCells); $span = $this->chunkCells * $zone->cell; $cx = max(0, min($per - 1, (int) floor($x / $span))); $cz = max(0, min($per - 1, (int) floor($z / $span))); return $cz * $per + $cx; } /** * Things grouped by chunk, static and small apart, with a signature of each group (a change = a rebuild). * @return array<int, array{0: list<Thing>, 1: list<Thing>, 2: float, 3: float}> */ private function signatures(): array { $out = []; if ($this->zone === null) { return $out; } foreach ($this->zone->things as $t) { $k = $this->chunkOf($t->x, $t->z); $out[$k] ??= [[], [], 0.0, 0.0]; $sig = $t->id * 1.618 + $t->left * 0.37 + $t->x * 0.013 + $t->z * 0.029 + strlen($t->kind) * 0.7 + 1.0; if (in_array($t->kind, Models::STATIC, true)) { $out[$k][0][] = $t; $out[$k][2] += $sig; } else { $out[$k][1][] = $t; $out[$k][3] += $sig; } } return $out; } /** @param array{0: list<Thing>, 1: list<Thing>, 2: float, 3: float} $sig */ private function buildProps(int $k, array $sig, ?string $only = null): void { $zone = $this->zone; if ($zone === null) { return; } $c = &$this->chunks[$k]; $set = $this->set; foreach ([['static', 0, 2, 'sigS', $set['lodNear']], ['far', 0, 2, 'sigS', $set['lodFar']], ['small', 1, 3, 'sigM', 0]] as [$slot, $list, $sk, $sigName, $lod]) { if ($only !== null && $only !== $slot && !($only === 'static' && $slot === 'far')) { continue; } foreach ($c[$slot] ?? [] as $part) { $this->gl->delete($part['vb']); $this->gl->delete($part['ib']); } $c[$slot] = []; $c[$sigName] = $sig[$sk]; if ($slot === 'static' && $set['lodDist'] <= 0.0) { continue; // ultra: the far level of detail everywhere } $mesh = new Mesh(); foreach ($sig[$list] as $t) { if (in_array($t->kind, Models::DYNAMIC, true)) { continue; } $ground = $zone->heightAt($t->x, $t->z); $y = $t->y < $ground - 0.3 || $t->y > $ground + 3 ? $ground : $t->y; if ($slot !== 'small' && in_array($t->kind, ['tree_palm', 'tree_broad', 'tree_conifer', 'tree_dead', 'hut', 'relay_mast', 'giant_tree', 'palm_coast', 'burnt_tree', 'mangrove', 'totem', 'signpost'], true)) { $y -= 0.15; } if ($slot === 'static' && $t->kind === 'campfire' && ($t->data['lit'] ?? true)) { $this->campfires[] = [$t->x, $y, $t->z]; } $src = Models::get($t->kind, $t->id, $t->left, $lod, (float) ($t->data['len'] ?? 0.0)); if ($mesh->count() + $src->count() > 60000) { $c[$slot][] = $this->upload($mesh); $mesh = new Mesh(); } $h = Mesh::hash($t->id, 77); $tint = isset(self::TINTED[$t->kind]) ? [0.86 + 0.26 * $h, 0.92 + 0.16 * Mesh::hash($t->id, 78), 0.88 + 0.12 * $h] : [1.0, 1.0, 1.0]; $mesh->place($src, $t->x, $y, $t->z, $t->yaw, $t->scale, $tint); $c['top'] = max($c['top'], $y + ($t->kind === 'giant_tree' ? 45 : 26) * $t->scale); } if ($mesh->count() > 0) { $c[$slot][] = $this->upload($mesh); } } unset($c); } /** @return array{vb: int, ib: int, n: int, attr: array<string, array{0: int, 1: int, 2: int, 3: int}>} */ private function upload(Mesh $m): array { $vb = $this->gl->buffer($m->v); $ib = $this->gl->indexBuffer($m->i); return ['vb' => $vb, 'ib' => $ib, 'n' => count($m->i), 'attr' => self::propAttr($vb)]; } /** @return array<string, array{0: int, 1: int, 2: int, 3: int}> */ private static function propAttr(int $vb): array { $s = Mesh::STRIDE; return ['a_pos' => [$vb, 3, $s, 0], 'a_nrm' => [$vb, 3, $s, 3], 'a_uv' => [$vb, 2, $s, 6], 'a_col' => [$vb, 3, $s, 8], 'a_extra' => [$vb, 2, $s, 11], 'a_bone' => [$vb, 1, $s, 13]]; } /** @return array<string, array{0: int, 1: int, 2: int, 3: int}> */ private static function terrainAttr(int $vb): array { $s = Terrain::VERTEX; return ['a_pos' => [$vb, 3, $s, 0], 'a_nrm' => [$vb, 3, $s, 3], 'a_wa' => [$vb, 4, $s, 6], 'a_wb' => [$vb, 4, $s, 10], 'a_tint' => [$vb, 3, $s, 14], 'a_wc' => [$vb, 4, $s, 17]]; } /** * The ground cover of a chunk (near the eye only, built on demand, one chunk per frame at most). Grass: many small * tufts in irregular patches (a value noise of two scales sets the density), coloured by the ground under them * (Shaders::GRASS_FS), sinking into it toward the end of their reach; they bend in the wind and away from the walker. * Flowers in the meadows, ferns and broad leaves in the jungle, reeds in the marsh (the props program). */ private function buildGrass(int $k): void { $zone = $this->zone; $c = &$this->chunks[$k]; $c['grassTried'] = true; if ($zone === null || $zone->cave || $this->set['density'] <= 0) { unset($c); return; } $m = new Mesh(); $tm = new Mesh(); $area = ($c['x1'] - $c['x0']) * ($c['z1'] - $c['z0']); $count = (int) ($area * $this->set['density'] * 7.0); $seed = $k * 1013 + $zone->seed; $zs = $zone->seed; for ($i = 0; $i < $count; $i++) { $x = $c['x0'] + Mesh::hash($seed, $i * 3) * ($c['x1'] - $c['x0']); $z = $c['z0'] + Mesh::hash($seed, $i * 3 + 1) * ($c['z1'] - $c['z0']); $b = $zone->biomeAt($x, $z); $r = Mesh::hash($seed, $i * 3 + 2); $keep = match ($b) { 'grass' => 1.0, 'jungle' => 0.8, 'jungle_dense' => 1.0, 'marsh' => 0.9, 'mud' => 0.25, 'beach', 'sand' => 0.06, 'snow' => 0.0, 'rock' => 0.05, 'redrock' => 0.05, default => 0.0, }; // patches: thick here, thin there, bare in places (large and small noise) $patch = 0.65 * self::vnoise($x / 9.0, $z / 9.0, $zs) + 0.35 * self::vnoise($x / 2.6, $z / 2.6, $zs + 7); $dense = max(0.0, min(1.0, ($patch - 0.28) / 0.42)); if (Mesh::hash($seed, $i * 5 + 7) > $keep * (0.12 + 0.88 * $dense)) { continue; } $y = $zone->heightAt($x, $z); $wet = $zone->water > -999 && $y < $zone->water + 0.6; if (($zone->water > -999 && $y < $zone->water + 0.05 && $b !== 'marsh') || abs($zone->heightAt($x + 1, $z) - $y) > 0.7 || abs($zone->heightAt($x, $z + 1) - $y) > 0.7) { continue; } $kind = 'tuft'; if ($b === 'jungle' || $b === 'jungle_dense') { $kind = $r < 0.13 ? 'fern' : ($r < 0.18 ? 'leaves' : 'tuft'); } elseif ($b === 'marsh' || ($wet && $b === 'mud')) { $kind = $r < 0.25 ? 'reeds' : 'tuft'; } elseif ($b === 'grass' && $r < 0.03) { $kind = 'flowers'; } $big = Mesh::hash($seed, $i * 11 + 3); $hue = Mesh::hash($seed, $i * 7 + 5); $yaw = $hue * 6.283; if ($kind === 'tuft') { // a small clump: two crossed cards, the taller where the patch is thick $h = (0.12 + 0.3 * $big * $big) * (0.6 + 0.6 * $dense); $w = 0.18 + 0.22 * $big; $tm->cell = Atlas::TUFT; $tm->color = [$b === 'jungle' || $b === 'jungle_dense' ? 1.0 : 0.0, $b === 'mud' || $b === 'marsh' ? 0.6 : 0.0, 0.88 + 0.24 * $hue]; $tm->bone = $h; for ($q = 0; $q < 2; $q++) { $a = $yaw + $q * M_PI / 2; $cs = cos($a) * $w * 0.5; $sn = sin($a) * $w * 0.5; $tm->sway = 0.0; $tm->ao = 0.55; $i0 = $tm->vertexN($x - $cs, $y - 0.02, $z + $sn, 0.0, 1.0, 0.0, 0.0, 1.0); $i1 = $tm->vertexN($x + $cs, $y - 0.02, $z - $sn, 0.0, 1.0, 0.0, 1.0, 1.0); $tm->sway = 0.6; $tm->ao = 1.0; $i2 = $tm->vertexN($x + $cs, $y + $h, $z - $sn, 0.0, 1.0, 0.0, 1.0, 0.0); $i3 = $tm->vertexN($x - $cs, $y + $h, $z + $sn, 0.0, 1.0, 0.0, 0.0, 0.0); $tm->quad($i0, $i1, $i2, $i3); } if ($tm->count() > 60000) { break; } continue; } [$cell, $h, $w] = match ($kind) { 'fern' => [Atlas::FERN, 0.45 + 0.6 * $big, 0.6 + 0.6 * $big], 'leaves' => [Atlas::BIG_LEAVES, 0.5 + 0.8 * $big, 0.6 + 0.7 * $big], 'reeds' => [Atlas::REEDS, 1.0 + 1.0 * $big, 0.6 + 0.4 * $big], default => [Atlas::FLOWERS, 0.25 + 0.15 * $big, 0.38], }; $m->cell = $cell; $m->color = match ($kind) { 'fern', 'leaves' => [0.5 + 0.15 * $hue, 0.58 + 0.1 * $hue, 0.48], default => [0.95, 0.95, 0.9], }; $cards = $kind === 'fern' || $kind === 'leaves' ? 3 : 2; for ($q = 0; $q < $cards; $q++) { $a = $yaw + $q * M_PI / $cards; $cs = cos($a) * $w * 0.5; $sn = sin($a) * $w * 0.5; $lean = $kind === 'fern' || $kind === 'leaves' ? 0.35 * $h : 0.0; $lx = cos($a + 1.57) * $lean * ($q % 2 ? 1 : -1); $lz = sin($a + 1.57) * $lean * ($q % 2 ? 1 : -1); $m->sway = 0.0; $m->ao = 0.55; $i0 = $m->vertexN($x - $cs, $y - 0.03, $z + $sn, 0.0, 1.0, 0.0, 0.0, 1.0); $i1 = $m->vertexN($x + $cs, $y - 0.03, $z - $sn, 0.0, 1.0, 0.0, 1.0, 1.0); $m->sway = $kind === 'reeds' ? 0.9 : 0.6; $m->ao = 1.0; $i2 = $m->vertexN($x + $cs + $lx, $y + $h, $z - $sn + $lz, 0.0, 1.0, 0.0, 1.0, 0.0); $i3 = $m->vertexN($x - $cs + $lx, $y + $h, $z + $sn + $lz, 0.0, 1.0, 0.0, 0.0, 0.0); $m->quad($i0, $i1, $i2, $i3); } if ($m->count() > 60000) { break; } } foreach (['grass' => $m, 'tufts' => $tm] as $slot => $mesh) { if ($mesh->count() > 0) { $part = $this->upload($mesh); $this->zoneRes[] = $part['vb']; $this->zoneRes[] = $part['ib']; $c[$slot] = $part; } } unset($c); } /** Smooth value noise 0..1 (ground cover patches). */ private static function vnoise(float $x, float $z, int $seed): float { $ix = (int) floor($x); $iz = (int) floor($z); $fx = $x - $ix; $fz = $z - $iz; $fx = $fx * $fx * (3 - 2 * $fx); $fz = $fz * $fz * (3 - 2 * $fz); $a = Mesh::hash($ix + $seed * 131, $iz); $b = Mesh::hash($ix + 1 + $seed * 131, $iz); $c = Mesh::hash($ix + $seed * 131, $iz + 1); $d = Mesh::hash($ix + 1 + $seed * 131, $iz + 1); return $a + ($b - $a) * $fx + ($c - $a) * $fz + ($a - $b - $c + $d) * $fx * $fz; } /** * What low reflections on the water show: the dark wall of the forest on the banks of a jungle river or a marsh * (rgb, how much), open water shows the sky. @param array<string, mixed> $env @return list<float> */ private function banks(array $env): array { $amount = (float) ($this->look['banks'] ?? 0.0); $lit = self::add3(self::mul3(self::sq($env['skyAmb']), 0.5), self::mul3(self::sq($env['lightCol']), 0.06)); return [$lit[0] * 0.5, $lit[1] * 0.7, $lit[2] * 0.4, $amount]; } /** Burning patches, steam vents, geysers and floating things of the zone (looked for again when things change). */ private function collectSpecial(): void { $this->emitters = []; $this->patches = []; $this->floating = []; $zone = $this->zone; if ($zone === null) { return; } foreach ($zone->things as $t) { if ($t->kind === 'fire_patch' && ($t->data['lit'] ?? true)) { $this->patches[] = [$t->x, $zone->heightAt($t->x, $t->z), $t->z, (float) ($t->data['r'] ?? 2.4 * $t->scale)]; } elseif ($t->kind === 'fumarole' || $t->kind === 'geyser') { $this->emitters[] = ['x' => $t->x, 'y' => $zone->heightAt($t->x, $t->z), 'z' => $t->z, 'kind' => $t->kind, 'id' => $t->id, 'r' => $t->scale]; } elseif (in_array($t->kind, Models::DYNAMIC, true)) { $this->floating[] = $t; } } } /** * How the zone looks beyond its ground: the colour of its water (clear, murky, the sea), far mountain ranges on * the horizon, how dry its grass is, how much rock breaks through. From the zone's id and its biomes. * @return array<string, mixed> */ private function lookOf(Zone $zone): array { $count = []; foreach ($zone->biomes as $b) { $count[$b] = ($count[$b] ?? 0) + 1; } $total = max(1, count($zone->biomes)); $f = static fn (string ...$names): float => array_sum(array_map(static fn (string $n): int => $count[$n] ?? 0, $names)) / $total; $id = $zone->id; $jungle = $f('jungle', 'jungle_dense'); $marsh = $f('marsh', 'mud'); $coast = $f('basalt', 'beach', 'burnt') > 0.08 || str_contains($id, 'coast'); // water: [deep scatter colour, absorption per metre, bed colour] [$deep, $absorb, $bed] = match (true) { $zone->cave => [[0.01, 0.02, 0.025], [1.2, 0.8, 0.7], [0.3, 0.27, 0.24]], $coast => [[0.015, 0.075, 0.1], [0.55, 0.16, 0.11], [0.35, 0.33, 0.32]], str_contains($id, 'marsh') || $marsh > 0.3 => [[0.05, 0.065, 0.03], [1.4, 1.1, 1.6], [0.35, 0.3, 0.2]], str_contains($id, 'jungle') || $jungle > 0.35 => [[0.085, 0.075, 0.04], [1.0, 0.85, 1.2], [0.48, 0.38, 0.26]], default => [[0.03, 0.08, 0.085], [0.7, 0.3, 0.22], [0.5, 0.44, 0.33]], }; $ridge = match (true) { $zone->cave => 0.0, str_contains($id, 'plateau') => 0.035, $coast => 0.05, str_contains($id, 'canyon') => 0.06, default => 0.085, }; return [ 'deep' => $deep, 'absorb' => $absorb, 'bed' => $bed, 'ridge' => [$ridge, fmod($zone->seed * 0.137, 1.0), str_contains($id, 'plateau') || str_contains($id, 'valley') ? 1.0 : 0.3, 0.0], 'dry' => str_contains($id, 'canyon') || $coast ? 0.8 : ($jungle > 0.3 ? 0.0 : 0.3), 'banks' => $zone->cave ? 0.0 : (str_contains($id, 'jungle') || $jungle > 0.35 ? 0.85 : (str_contains($id, 'marsh') || $marsh > 0.3 ? 0.6 : ($coast ? 0.0 : 0.35))), 'outcrop' => $jungle > 0.4 || str_contains($id, 'marsh') ? 0.4 : 1.0, ]; } /** Things picked, cut, moved: rebuild the chunks whose signature changed (checked every 20 frames). */ private function watchThings(): void { if ($this->frame % 20 !== 0 || $this->zone === null) { if ($this->dirty !== []) { $k = array_shift($this->dirty); $sigs = $this->signatures(); $this->campfires = []; $this->buildProps($k, $sigs[$k] ?? [[], [], 0.0, 0.0]); $this->collectCampfires(); $this->collectSpecial(); } return; } $sigs = $this->signatures(); foreach ($this->chunks as $k => $c) { $s = $sigs[$k] ?? [[], [], 0.0, 0.0]; if (abs($s[2] - $c['sigS']) > 1e-6 || abs($s[3] - $c['sigM']) > 1e-6) { if (!in_array($k, $this->dirty, true)) { $this->dirty[] = $k; } } } } private function collectCampfires(): void { $this->campfires = []; if ($this->zone === null) { return; } foreach ($this->zone->things as $t) { if ($t->kind === 'campfire' && ($t->data['lit'] ?? true)) { $this->campfires[] = [$t->x, $this->zone->heightAt($t->x, $t->z), $t->z]; } } } private function modelBuffer(string $kind, int $variant, int $left): array { $key = $kind . ':' . ($variant % Models::VARIANTS) . ':' . ($left > 0 ? 1 : 0); if (!isset($this->models[$key])) { $this->models[$key] = $this->upload(Models::get($kind, $variant, $left)); } return $this->models[$key]; } /** @return array<string, mixed> the uploaded body: buffers, attributes, skeleton */ private function bodyBuffer(string $key): array { if (!isset($this->bodies[$key])) { $b = Bodies::get($key); $this->bodies[$key] = $this->upload($b['mesh']) + ['parents' => $b['parents'], 'pivots' => $b['pivots'], 'rig' => $b['rig'], 'speed' => $b['speed'], 'drop' => $b['drop']]; } return $this->bodies[$key]; } // ---- environment ------------------------------------------------------------------------------ /** @return array<string, mixed> sun, sky, fog, light colours for this time and weather */ private function environment(View $v): array { $cave = $this->zone !== null && $this->zone->cave; $tod = fmod(fmod($v->minutes, 1440.0) + 1440.0, 1440.0) / 60.0; $a = ($tod - 6.0) / 12.0 * M_PI; $sun = self::norm([cos($a) * 0.8, sin($a) * 0.95, 0.42]); $moon = self::norm([-cos($a) * 0.7, -sin($a) * 0.8 + 0.12, -0.35]); $e = $sun[1]; $day = self::smooth(-0.1, 0.3, $e); $dusk = 1.0 - self::smooth(0.0, 0.3, abs($e + 0.03)); $night = 1.0 - self::smooth(-0.22, 0.02, $e); $kind = (string) ($v->weather['kind'] ?? 'clear'); $amt = max(0.0, min(1.0, (float) ($v->weather['amount'] ?? ($kind === 'clear' ? 0.0 : 0.7)))); $cover = match ($kind) { 'rain' => 0.55 + 0.4 * $amt, 'storm' => 0.85 + 0.15 * $amt, 'snow' => 0.6 + 0.35 * $amt, 'fog' => 0.45, default => 0.32 + 0.15 * $amt }; $gloom = match ($kind) { 'rain' => 0.45 * $amt, 'storm' => 0.75 * $amt, 'snow' => 0.35 * $amt, 'fog' => 0.3 * $amt, default => 0.0 }; $zenith = self::mix3([0.010, 0.016, 0.045], [0.16, 0.36, 0.78], $day); $zenith = self::add3($zenith, self::mul3([0.12, 0.06, 0.14], $dusk)); $horizon = self::mix3([0.045, 0.058, 0.1], [0.62, 0.74, 0.88], $day); $horizon = self::mix3($horizon, [0.78, 0.6, 0.58], $dusk * 0.6); $sunCol = self::mix3([1.0, 0.45, 0.18], [1.0, 0.95, 0.86], self::smooth(0.0, 0.35, $e)); $sunI = self::smooth(-0.04, 0.1, $e) * 2.3 * (1.0 - 0.8 * $gloom); $glow = self::add3(self::mul3([1.0, 0.48, 0.18], $dusk * 1.5), self::mul3([1.0, 0.9, 0.7], 0.25 * $day)); // weather: everything greyer and darker $grey = [0.5, 0.52, 0.55]; $zenith = self::mix3($zenith, self::mul3($grey, 0.25 + 0.6 * $day), $gloom * 0.8); $horizon = self::mix3($horizon, self::mul3($grey, 0.25 + 0.8 * $day), $gloom * 0.8); $glow = self::mul3($glow, 1.0 - $gloom); // moonlight and starlight at night: the ground and the shapes stay faintly readable (less under clouds; the // moon waxes and wanes over 8 days) $phase = 0.55 + 0.45 * cos(floor($v->minutes / 1440.0) * 6.2832 / 8.0); $clear = 1.0 - min(1.0, $gloom * 1.4); $moonlit = $night * (0.35 + 0.65 * $phase) * (0.3 + 0.7 * $clear); $skyAmb = self::mix3(self::add3([0.025, 0.035, 0.06], self::mul3([0.06, 0.075, 0.12], $moonlit)), [0.4, 0.5, 0.62], $day); $skyAmb = self::mix3($skyAmb, [0.5, 0.36, 0.3], $dusk * 0.3 * $day); $skyAmb = self::mul3($skyAmb, 1.0 - 0.35 * $gloom); $lightDir = $sun; $lightCol = self::mul3($sunCol, $sunI); if ($night > 0) { // moonlight once the sun is down $lightDir = $e > 0.02 ? $sun : $moon; $lightCol = self::add3($lightCol, self::mul3([0.24, 0.29, 0.42], $night * (0.4 + 0.6 * $phase) * (1.0 - $gloom))); } $fogDensity = match ($kind) { 'fog' => 0.012 + 0.05 * $amt, 'rain' => 0.007 + 0.01 * $amt, 'storm' => 0.012 + 0.014 * $amt, 'snow' => 0.009 + 0.02 * $amt, default => 0.0035 }; $fogCol = $horizon; $fogSun = self::add3($horizon, self::mul3($glow, 0.45)); $env = [ 'sun' => $sun, 'moon' => $moon, 'lightDir' => $lightDir, 'lightCol' => $lightCol, 'skyAmb' => $skyAmb, 'gndAmb' => self::mul3($skyAmb, 0.42), 'zenith' => $zenith, 'horizon' => $horizon, 'glow' => $glow, 'sunDisc' => self::mul3($sunCol, self::smooth(-0.03, 0.02, $e) * (1.0 - $gloom)), 'fogCol' => $fogCol, 'fogSun' => $fogSun, 'fog' => [$fogDensity, 0.035, $this->fogBase(), $this->set['far'] + $this->set['outer']], 'stars' => $night * (1.0 - $cover * 0.8), 'cover' => $cover, 'dark' => min(1.0, $gloom * 1.3), 'cloudCol' => self::mix3(self::mul3([0.6, 0.62, 0.7], 0.06 + 0.94 * $day), [1.0, 0.7, 0.55], $dusk * 0.5), 'haze' => $kind === 'fog' ? 0.5 * $amt : ($kind === 'snow' || $kind === 'rain' || $kind === 'storm' ? 0.35 * $amt : 0.0), 'wet' => in_array($kind, ['rain', 'storm'], true) ? $amt : 0.0, 'wind' => match ($kind) { 'storm' => 2.6, 'rain' => 1.5, 'snow' => 1.2, default => 0.8 }, 'rain' => in_array($kind, ['rain', 'storm'], true) ? $amt : 0.0, 'snow' => $kind === 'snow' ? $amt : 0.0, 'storm' => $kind === 'storm' ? $amt : 0.0, 'exposure' => 0.72 + 0.3 * (1 - $day) + 0.3 * $night, 'cave' => false, ]; if ($cave) { $dim = 0.6 + 0.4 * max(0.0, min(1.0, $v->light * 4)); $env['lightCol'] = [0.0, 0.0, 0.0]; $env['skyAmb'] = self::mul3([0.028, 0.026, 0.026], $dim); $env['gndAmb'] = self::mul3([0.012, 0.011, 0.01], $dim); $env['fogCol'] = [0.004, 0.004, 0.005]; $env['fogSun'] = $env['fogCol']; $env['fog'] = [0.035, 0.0, 0.0, min(80.0, $this->set['far'])]; $env['wet'] = 0.25; $env['rain'] = $env['snow'] = $env['storm'] = 0.0; $env['exposure'] = 1.15; $env['cave'] = true; $env['wind'] = 0.0; } return $env; } /** Environment values that are directions or switches: taken as they are, never blended. */ private const ENV_SNAP = ['sun' => true, 'moon' => true, 'lightDir' => true, 'cave' => true]; /** * The environment eased toward the target computed for this frame (sky, clouds, fog, light, wind, rain and snow * density...): an exponential approach with a time constant of ~2 s, independent of the frame rate, so a change * of weather or of light never jumps. A new zone (or a cave) starts from its own values. * * @param array<string, mixed> $target * @return array<string, mixed> */ private function smoothed(array $target, float $t): array { $prev = $this->envShown; $dt = $t - $this->envAt; $this->envAt = $t; if ($prev === null || $dt < 0 || $dt > 5 || ($prev['cave'] ?? false) !== ($target['cave'] ?? false)) { return $this->envShown = $target; } $k = 1.0 - exp(-$dt / 1.8); $out = $target; foreach ($target as $key => $value) { if (isset(self::ENV_SNAP[$key]) || !isset($prev[$key])) { continue; } $from = $prev[$key]; if (is_float($value) || is_int($value)) { $out[$key] = (float) $from + ((float) $value - (float) $from) * $k; } elseif (is_array($value) && is_array($from) && count($value) === count($from)) { $mixed = []; foreach ($value as $i => $c) { $mixed[$i] = (float) ($from[$i] ?? $c) + ((float) $c - (float) ($from[$i] ?? $c)) * $k; } $out[$key] = $mixed; } } return $this->envShown = $out; } // ---- frame ------------------------------------------------------------------------------------ public function render(View $v): void { if (!$this->ok || $this->zone === null) { return; } $this->frame++; if ($v->time > 0) { $this->clock = $v->time; } else { $now = microtime(true); $this->clock += $this->lastTime < 0 ? 0.0 : min(0.1, $now - $this->lastTime); $this->lastTime = $now; } $t = $this->clock; $this->watchThings(); $gl = $this->gl; $zone = $this->zone; $env = $this->smoothed($this->environment($v), $t); $set = $this->set; $draws = 0; $tris = 0; // the camera $cp = cos($v->pitch); $fwd = [sin($v->yaw) * $cp, sin($v->pitch), cos($v->yaw) * $cp]; $right = self::norm([-cos($v->yaw), 0.0, sin($v->yaw)]); $up = self::cross($right, $fwd); $eye = [$v->x, $v->y, $v->z]; [, , $lw, $lh] = $gl->openGl()->renderer()->letterbox(); $ss = Quality::supersample($this->level, (int) $lw, (int) $lh); if ($ss !== $this->ss) { $gl->setSupersample($ss); $this->ss = $ss; } $aspect = $lh > 0 ? $lw / $lh : 4 / 3; $fovY = rad2deg(2 * atan(tan(deg2rad($v->fov) / 2) / max(1.0, $aspect))); $farTerrain = $set['far'] + $set['outer']; $proj = Mat4::perspective($fovY, $aspect, 0.08, $farTerrain + 50); $view = Mat4::lookAt($eye, [$eye[0] + $fwd[0], $eye[1] + $fwd[1], $eye[2] + $fwd[2]]); $vp = Mat4::multiply($proj, $view); $planes = self::planes($vp); // lightning: the bolt lives ~0.6 s, the world flashes at its start $flash = 0.0; $boltAge = -1.0; if ($v->lightning !== null && isset($v->lightning['x'], $v->lightning['z'])) { $boltAge = $t - (float) ($v->lightning['t'] ?? $t); if ($boltAge >= 0.0 && $boltAge < 0.7) { $flash = max($flash, ($boltAge < 0.12 ? 1.0 : (sin($boltAge * 55.0) > 0.2 ? 0.7 : 0.25)) * (1.0 - $boltAge / 0.7)); } } if ($env['storm'] > 0) { $slot = (int) floor($t / 6.0); $ph = $t - $slot * 6.0; if (Mesh::hash($slot, 5) < 0.45 * $env['storm'] && $ph < 0.35) { $flash = max($flash, (sin($ph * 40) > 0 ? 1.0 : 0.4) * (1 - $ph / 0.35)); } } // point lights: the torch, a strike, the nearest fires (big fires reach farther) $lights = []; $lightCount = 0; $flick = 0.85 + 0.1 * sin($t * 13.0) + 0.05 * sin($t * 31.0 + 1.3); $leftLit = $v->heldLeft !== null && Models::held($v->heldLeft)[1] !== null; $torch = $v->torch || $leftLit || ($v->held !== null && Models::held($v->held)[1] !== null); if ($torch) { $side = $leftLit ? -0.35 : 0.35; array_push($lights, $eye[0] + $fwd[0] * 0.3 + $right[0] * $side, $eye[1] + 0.05, $eye[2] + $fwd[2] * 0.3 + $right[2] * $side, 11.0 * $flick); $lightCount++; } if ($boltAge >= 0.0 && $boltAge < 0.4 && $v->lightning !== null) { $bx = (float) $v->lightning['x']; $bz = (float) $v->lightning['z']; array_push($lights, $bx, $zone->heightAt($bx, $bz) + 6.0, $bz, 70.0 * (1.0 - $boltAge / 0.4)); $lightCount++; } $fires = []; foreach ($v->fires as $f) { $fx = (float) $f['x']; $fz = (float) $f['z']; $fires[] = [$fx, $zone->heightAt($fx, $fz), $fz, (float) ($f['r'] ?? 0.0)]; } foreach ($this->campfires as $f) { $fires[] = [$f[0], $f[1], $f[2], 0.0]; } foreach ($this->patches as $f) { $fires[] = $f; } $near = []; foreach ($fires as $i => $f) { $d = sqrt(($f[0] - $eye[0]) ** 2 + ($f[2] - $eye[2]) ** 2) - $f[3] * 3.0; if ($d < 60 + $f[3] * 6) { $near[$i] = $d; } } asort($near); foreach (array_keys($near) as $i) { if ($lightCount >= 4) { break; } $f = $fires[$i]; $reach = min(48.0, 15.0 * (1.0 + $f[3] * 0.35)); array_push($lights, $f[0], $f[1] + 0.8 + $f[3] * 0.3, $f[2], $reach * (0.85 + 0.1 * sin($t * 11.0 + $i * 2.1) + 0.05 * sin($t * 23.0 + $i))); $lightCount++; } while (count($lights) < 16) { $lights[] = 0.0; } $lightColour = $env['cave'] ? [1.0, 0.6, 0.3] : [1.0, 0.62, 0.32]; $tw = fmod($t, 20 * M_PI); $windDir = [cos($t * 0.05) * $env['wind'], $env['wind'] * 0.15, sin($t * 0.05 + 1.0) * $env['wind']]; $common = [ 'u_vp' => $vp, 'u_eye' => $eye, 'u_sunDir' => $env['lightDir'], 'u_sunCol' => self::sq($env['lightCol']), 'u_skyCol' => self::sq(self::add3($env['skyAmb'], [$flash * 0.5, $flash * 0.52, $flash * 0.6])), 'u_gndCol' => self::sq($env['gndAmb']), 'u_lights' => $lights, 'u_lightCol' => $lightColour, 'u_fogCol' => self::sq($env['fogCol']), 'u_fogSun' => self::sq($env['fogSun']), 'u_fog' => $env['fog'], 'u_wet' => $env['wet'], 'u_exposure' => $env['exposure'], 'u_time' => $tw, 'u_wind' => $windDir, 'u_tint' => [1.0, 1.0, 1.0], 'u_model' => Mat4::identity(), 'u_push' => [$eye[0], $eye[1] - 1.0, $eye[2]], 'u_dfr' => (float) ($this->frame % 64), ]; $this->puffs = []; // sky (or the dark of a cave) if ($env['cave']) { $gl->clear([1, 1, 2, 255]); } else { $gl->clear([0, 0, 0, 255]); $gl->draw($this->pSky, [ 'attributes' => ['a_pos' => [$this->skyVb, 3, 3, 0]], 'indices' => $this->skyIb, 'count' => $this->skyN, 'depth' => false, 'textures' => ['t_noise' => $this->tex['noise']], 'uniforms' => [ 'u_zenith' => self::sq($env['zenith']), 'u_horizon' => self::sq($env['horizon']), 'u_glow' => self::sq($env['glow']), 'u_sunDisc' => $env['sunDisc'], 'u_moonDir' => $env['moon'], 'u_stars' => $env['stars'], 'u_cloud' => [$env['cover'], $env['dark'], fmod($t * 0.0035, 1.0), fmod($t * 0.0021, 1.0)], 'u_cloudCol' => self::sq($env['cloudCol']), 'u_haze' => $env['haze'], 'u_flash' => $flash * 0.5, 'u_sunDir' => $env['sun'], 'u_ridge' => $this->look['ridge'] ?? [0.0, 0.0, 0.0, 0.0], ] + $common, ]); $draws++; } // visible chunks, near first $vis = []; foreach ($this->chunks as $k => $c) { $dx = max($c['x0'] - $eye[0], 0.0, $eye[0] - $c['x1']); $dz = max($c['z0'] - $eye[2], 0.0, $eye[2] - $c['z1']); $d = sqrt($dx * $dx + $dz * $dz); if ($d > $farTerrain) { continue; } $hx = ($c['x1'] - $c['x0']) / 2; $hz = ($c['z1'] - $c['z0']) / 2; $cy = ($c['minY'] + $c['top']) / 2; $r = sqrt($hx * $hx + $hz * $hz + (($c['top'] - $c['minY']) / 2) ** 2); if (!self::sphereVisible($planes, $c['cx'], $cy, $c['cz'], $r)) { continue; } $vis[$k] = $d; } asort($vis); // burnt ground: the nearest eight areas $burnt = []; foreach ($v->burnt as $b) { $bx = (float) ($b['x'] ?? 0.0); $bz = (float) ($b['z'] ?? 0.0); $br = (float) ($b['r'] ?? 0.0); if ($br > 0) { $burnt[] = [($bx - $eye[0]) ** 2 + ($bz - $eye[2]) ** 2 - $br * $br, $bx, $bz, $br]; } } usort($burnt, static fn (array $a, array $b): int => $a[0] <=> $b[0]); $burntU = []; for ($i = 0; $i < 8; $i++) { $b = $burnt[$i] ?? null; array_push($burntU, $b[1] ?? 0.0, $b[2] ?? 0.0, $b[3] ?? 0.0); } // terrain $first = true; $terrainU = $common + ['u_origin' => [0.0, 0.0], 'u_scale' => [1 / 2.6, 1 / 11.0, 1 / 95.0, $this->q >= 2 ? 34.0 : 24.0], 'u_ground' => [$this->q >= 2 ? 0.75 : 0.55, (float) ($this->look['outcrop'] ?? 1.0), (float) ($this->look['dry'] ?? 0.3), 0.0], 'u_burnt' => $burntU]; $terrainT = ['t_grass' => $this->tex['grass'], 't_jungle' => $this->tex['jungle'], 't_mud' => $this->tex['mud'], 't_sand' => $this->tex['sand'], 't_rock' => $this->tex['rock'], 't_snow' => $this->tex['snow'], 't_noise' => $this->tex['noise'], 't_detail' => $this->tex['detail']]; foreach ($vis as $k => $d) { $c = $this->chunks[$k]; $o = ['attributes' => self::terrainAttr($c['vb']), 'indices' => $c['ib'], 'count' => $c['n']]; if ($first) { $o['uniforms'] = $terrainU; $o['textures'] = $terrainT; $first = false; } $gl->draw($this->pTerrain, $o); $draws++; $tris += intdiv($c['n'], 3); if ($c['roof'] !== null) { $gl->draw($this->pTerrain, ['attributes' => self::terrainAttr($c['roof']['vb']), 'indices' => $c['roof']['ib'], 'count' => $c['roof']['n']]); $draws++; } } if ($this->outer !== null) { $o = ['attributes' => self::terrainAttr($this->outer['vb']), 'indices' => $this->outer['ib'], 'count' => $this->outer['n']]; if ($first) { $o['uniforms'] = $terrainU; $o['textures'] = $terrainT; } $gl->draw($this->pTerrain, $o); $draws++; } // props baked in the chunks (near: detailed, far: their far level of detail) $first = true; $propsU = $common; $grassBuilt = false; $tufts = []; foreach ($vis as $k => $d) { $c = $this->chunks[$k]; $parts = []; if ($d < $set['props']) { $parts = $d < $set['lodDist'] ? $c['static'] : $c['far']; } if ($d < $set['small']) { $parts = array_merge($parts, $c['small']); } if ($set['grass'] > 0 && $d < $set['grass']) { if ($c['grass'] === null && !$c['grassTried'] && !$grassBuilt) { $this->buildGrass($k); $grassBuilt = true; $c = $this->chunks[$k]; } if ($c['grass'] !== null) { $parts[] = $c['grass']; } if ($c['tufts'] !== null) { $tufts[] = $c['tufts']; } } foreach ($parts as $p) { $o = ['attributes' => $p['attr'], 'indices' => $p['ib'], 'count' => $p['n']]; if ($first) { $o['uniforms'] = $propsU; $o['textures'] = ['t_atlas' => $this->tex['atlas']]; $first = false; } $gl->draw($this->pProps, $o); $draws++; $tris += intdiv($p['n'], 3); } } // ground cover tufts: their own program (the ground's colour under them), sunk away toward the end of their reach $firstTuft = true; foreach ($tufts as $p) { $o = ['attributes' => $p['attr'], 'indices' => $p['ib'], 'count' => $p['n']]; if ($firstTuft) { $o['uniforms'] = $common + ['u_scale' => [1 / 2.6, 1 / 11.0, 1 / 95.0, 24.0], 'u_ground' => [0.0, 0.0, (float) ($this->look['dry'] ?? 0.3), 0.0], 'u_grassFar' => [$set['grass'] * 0.5, $set['grass'] * 0.92]]; $o['textures'] = ['t_atlas' => $this->tex['atlas'], 't_grass' => $this->tex['grass'], 't_jungle' => $this->tex['jungle'], 't_mud' => $this->tex['mud'], 't_noise' => $this->tex['noise']]; $firstTuft = false; } $gl->draw($this->pGrass, $o); $draws++; $tris += intdiv($p['n'], 3); } // floating things (a raft bobbing) and Rob's own raft $waterY = $zone->water > -999 ? $zone->water : null; $rafts = []; foreach ($this->floating as $ft) { $rafts[] = [$ft->kind, $ft->id, $ft->x, $ft->z, $ft->yaw, $ft->scale, $ft->y]; } if ($v->raft !== null && isset($v->raft['x'], $v->raft['z'])) { $rafts[] = ['raft', 7, (float) $v->raft['x'], (float) $v->raft['z'], (float) ($v->raft['yaw'] ?? $v->yaw), 1.0, null]; } foreach ($rafts as [$kind, $id, $rx, $rz, $ryaw, $rs, $ry]) { if (($rx - $eye[0]) ** 2 + ($rz - $eye[2]) ** 2 > $set['props'] ** 2 || !self::sphereVisible($planes, $rx, $eye[1], $rz, 4.0 * $rs)) { continue; } $base = $waterY ?? ($ry ?? $zone->heightAt($rx, $rz)); $by = $base - 0.05 + sin($t * 1.3 + $id) * 0.045; $p = $this->modelBuffer($kind, $id, 1); $m = Mat4::multiply(self::model($rx, $by, $rz, $ryaw, $rs), Mat4::rotateZ(sin($t * 0.9 + $id) * 0.035), Mat4::rotateX(sin($t * 1.1 + $id * 2) * 0.03)); $o = ['attributes' => $p['attr'], 'indices' => $p['ib'], 'count' => $p['n'], 'uniforms' => ['u_model' => $m]]; if ($first) { $o['uniforms'] += $propsU; $o['textures'] = ['t_atlas' => $this->tex['atlas']]; $first = false; } $gl->draw($this->pProps, $o); $draws++; } // entities: things (props program), creatures and humans (skinned bodies) $firstBody = true; foreach ($v->entities as $en) { $dx = $en->x - $eye[0]; $dz = $en->z - $eye[2]; $d2 = $dx * $dx + $dz * $dz; if ($en instanceof Thing) { if ($d2 > $set['props'] * $set['props'] || !self::sphereVisible($planes, $en->x, $en->y + 1, $en->z, 4 * $en->scale)) { continue; } $p = $this->modelBuffer($en->kind, $en->id, $en->left); $o = ['attributes' => $p['attr'], 'indices' => $p['ib'], 'count' => $p['n'], 'uniforms' => ['u_model' => self::model($en->x, $en->y, $en->z, $en->yaw, $en->scale)]]; if ($first) { $o['uniforms'] += $propsU; $o['textures'] = ['t_atlas' => $this->tex['atlas']]; $first = false; } $gl->draw($this->pProps, $o); $draws++; continue; } $bodyFar = $this->q < 0 ? 65.0 : 110.0; if ($d2 > $bodyFar * $bodyFar || !self::sphereVisible($planes, $en->x, $en->y + 1, $en->z, 4.5)) { continue; } $key = Bodies::keyOf($en); if ($en instanceof Creature) { $scale = (float) ($en->data['scale'] ?? 1.0); } else { $child = (bool) ($en->data['child'] ?? false); $scale = $child ? 0.62 : (float) ($en->data['scale'] ?? (0.95 + 0.1 * Mesh::hash($en->id, 3))); } $b = $this->bodyBuffer($key); [$angles, $lift, $roll, $pitch] = Bodies::pose((string) $b['rig'], $en->state, $en->anim, (float) $b['speed']); $m = self::model($en->x, $en->y + $lift * $scale, $en->z, $en->yaw, $scale); if ($roll !== 0.0 || $pitch !== 0.0) { $drop = (float) $b['drop']; $m = Mat4::multiply($m, Mat4::translate(0, $drop, 0), Mat4::rotateZ($roll), Mat4::rotateX($pitch), Mat4::translate(0, -$drop, 0)); } $o = ['attributes' => $b['attr'], 'indices' => $b['ib'], 'count' => $b['n'], 'uniforms' => ['u_model' => $m, 'u_bones' => Bodies::matrices($b['parents'], $b['pivots'], $angles), 'u_tint' => $en instanceof Creature && $en->health <= 0 && $en->state !== 'dead' ? [0.8, 0.8, 0.8] : [1.0, 1.0, 1.0]]]; if ($firstBody) { $o['uniforms'] += $common; $o['textures'] = ['t_atlas' => $this->tex['atlas']]; $firstBody = false; } $gl->draw($this->pBody, $o); $draws++; $tris += intdiv($b['n'], 3); } // water if ($this->water !== null) { $wv = $this->water['vb']; $gl->draw($this->pWater, [ 'attributes' => ['a_pos' => [$wv, 3, 6, 0], 'a_depth' => [$wv, 1, 6, 3], 'a_flow' => [$wv, 2, 6, 4]], 'count' => $this->water['n'], 'textures' => ['t_noise' => $this->tex['noise']], 'uniforms' => [ 'u_zenith' => self::sq($env['zenith']), 'u_horizon' => self::sq($env['horizon']), 'u_flow' => [fmod($t * 0.011, 1.0), fmod($t * 0.007, 1.0), fmod(-$t * 0.009, 1.0), fmod($t * 0.013, 1.0)], 'u_phase' => [fmod($t * 0.25, 1.0), fmod($t * 0.25 + 0.5, 1.0), fmod($t, 40 * M_PI), $env['rain']], 'u_deep' => $this->look['deep'] ?? [0.03, 0.08, 0.085], 'u_absorb' => $this->look['absorb'] ?? [0.7, 0.3, 0.22], 'u_origin' => [0.0, 0.0], 'u_bed' => $this->look['bed'] ?? [0.5, 0.44, 0.33], 'u_rough' => 0.35 + 0.5 * $env['wind'] / 2.6 + 0.3 * $env['rain'], 'u_banks' => $this->banks($env), ] + $common, ]); $draws++; } // waterfalls: the sheets, then the spray at their foot foreach ($this->falls as $k => $f) { $mid = ($f['top'] + $f['bottom']) / 2; if (($f['x'] - $eye[0]) ** 2 + ($f['z'] - $eye[2]) ** 2 > ($set['props'] + 40) ** 2 || !self::sphereVisible($planes, $f['x'], $mid, $f['z'], ($f['top'] - $f['bottom']) / 2 + $f['w'] + $f['reach'])) { continue; } $gl->draw($this->pFall, [ 'attributes' => ['a_pos' => [$f['vb'], 3, 5, 0], 'a_uv' => [$f['vb'], 2, 5, 3]], 'count' => $f['n'], 'textures' => ['t_noise' => $this->tex['noise']], 'uniforms' => ['u_fall' => [fmod($t * ($f['layer'] === 0 ? 0.42 : 0.6), 1.0), $f['layer'] === 0 ? 0.9 : 0.5, $f['layer'] * 0.37 + $k * 0.11, 0.0], 'u_nrm' => [sin($f['yaw']), 0.25, cos($f['yaw'])]] + $common, ]); $draws++; if ($f['layer'] === 1) { $this->fallSpray($f, $t, $vp, $env); } } // steam vents and geysers $draws += $this->emitters($t, $vp, $env, $eye, $planes); // fires: a campfire's flames, or a spreading blaze (many flames over its radius, a column of smoke) $shown = 0; foreach (array_keys($near) as $i) { if ($shown >= 6) { break; } $f = $fires[$i]; if (!self::sphereVisible($planes, $f[0], $f[1] + 2.5 + $f[3], $f[2], 4.5 + $f[3] * 2.5)) { // flames and smoke continue; } $shown++; $draws += $this->blaze($f[0], $f[1], $f[2], $f[3], $t + $i * 3.7, $vp, $env); } // the lightning bolt if ($boltAge >= 0.0 && $boltAge < 0.7 && $v->lightning !== null) { $draws += $this->drawBolt((float) $v->lightning['x'], (float) $v->lightning['z'], (float) ($v->lightning['t'] ?? 0.0), $boltAge, $vp); } // rain and snow if (($env['rain'] > 0 || $env['snow'] > 0) && !$env['cave']) { $snow = $env['snow'] > 0; $amount = max($env['rain'], $env['snow']); $n = (int) ($this->precipN * min(1.0, 0.25 + 0.75 * $amount) / 6) * 6; $speed = $snow ? 1.4 : 11.0; $size = $snow ? 18.0 : 22.0; $gl->draw($this->pPrecip, [ 'attributes' => ['a_seed' => [$this->precipVb, 4, 4, 0]], 'indices' => $this->precipIb, 'count' => $n, 'uniforms' => [ 'u_vp' => $vp, 'u_eye' => $eye, 'u_box' => [$size, fmod($t * $speed, $size), $snow ? 0.0 : 0.38, $snow ? 0.045 : 0.01], 'u_drift' => [$windDir[0] * ($snow ? 0.25 : 0.06), 0.0, $windDir[2] * ($snow ? 0.25 : 0.06)], 'u_snow' => $snow ? 1.0 : 0.0, 'u_right' => $right, 'u_up' => $up, 'u_dfr' => (float) ($this->frame % 64), 'u_color' => $snow ? [0.95, 0.96, 1.0, 0.9] : [0.66, 0.7, 0.76, 0.5 + 0.2 * $env['storm']], ], ]); $draws++; } // smoke and steam: last, so that the smoke blends over everything behind it (and steam is sorted with it) $draws += $this->drawPuffs($vp, $eye, $right, $up, $env); // the items in hand (over everything: no depth test): the left one, then the right one, each with its pose $basis = [$right, $up, $fwd]; if ($v->heldLeft !== null && $v->heldLeft !== '') { if (str_starts_with(Models::itemKind($v->heldLeft), 'shield')) { $draws += $this->drawHeld($v->heldLeft, HeldPose::LEFT, HeldPose::shield($v->guard), $eye, $basis, $t, $v->bob, $vp, $common, null); } else { $pose = $v->brandish > 0 ? HeldPose::brandish($v->brandish) : ($v->attackSide === 'left' ? HeldPose::attack($v->attackKind, $v->attackPhase, $v->attackStrike) : [0.0, 0.0, 0.0, 0.0, 0.0, 0.0]); $draws += $this->drawHeld($v->heldLeft, HeldPose::LEFT, HeldPose::mirror($pose), $eye, $basis, $t, $v->bob, $vp, $common, $v->brandish > 0 ? $v->brandish : null); } } if ($v->held !== null && $v->held !== '') { $pose = $v->attackSide === 'right' ? HeldPose::attack($v->attackKind, $v->attackPhase, $v->attackStrike) : [0.0, 0.0, 0.0, 0.0, 0.0, 0.0]; if ($v->brandish > 0 && $v->heldLeft === null) { $pose = HeldPose::brandish($v->brandish); } $draws += $this->drawHeld($v->held, HeldPose::RIGHT, $pose, $eye, $basis, $t, $v->bob, $vp, $common, $v->brandish > 0 && $v->heldLeft === null ? $v->brandish : null); $muzzle = $v->attackSide === 'right' ? HeldPose::flash($v->attackKind, $v->attackPhase, $v->attackStrike) : 0.0; if ($muzzle > 0) { // the muzzle flash, at the end of the barrel $o = $this->heldOrigin(HeldPose::RIGHT, $pose, $eye, $basis, $t, $v->bob); $m = self::eyeVec($basis, [-0.04, 0.06, 0.5]); $this->flame($o[0] + $m[0], $o[1] + $m[1], $o[2] + $m[2], 0.09 + 0.1 * $muzzle, $t * 3.0, $vp); $draws++; } } $gl->setUniform('u_hurt', max(0.0, min(1.0, $v->hurt)) * 0.65); $gl->setUniform('u_flashP', $flash); $gl->setUniform('u_vignette', $env['cave'] ? 0.9 : 0.55); $this->stats = ['draws' => $draws, 'triangles' => $tris, 'chunks' => count($vis), 'lights' => $lightCount, 'level' => $this->level, 'ss' => $this->ss]; } /** * A fire of radius $r (0: a campfire): flames over the burning area, the bigger the fire the taller, and a * column of smoke rising and spreading with the wind. @param list<float> $vp @param array<string, mixed> $env * @return int draws */ private function blaze(float $x, float $y, float $z, float $r, float $t, array $vp, array $env): int { $lit = self::add3(self::mul3(self::sq($env['skyAmb']), 0.9), self::mul3(self::sq($env['lightCol']), 0.25)); $wind = $env['wind']; if ($r <= 0.8) { $this->flame($x, $y + 0.05, $z, 1.3, $t, $vp); // a campfire's thin column of pale smoke (blended, a few soft puffs) $pale = [min(1.0, sqrt($lit[0]) * 0.5 + 0.06), min(1.0, sqrt($lit[1]) * 0.5 + 0.06), min(1.0, sqrt($lit[2]) * 0.52 + 0.07)]; for ($k = 0; $k < 3; $k++) { $ph = fmod($t * 0.11 + $k / 3, 1.0); $h = 1.3 + $ph * 4.5; $sz = 0.7 + $ph * 2.0; $this->puffs[] = [$x + cos($t * 0.05) * $wind * $h * 0.4 + sin($k * 2.3 + $t * 0.3) * 0.15, $y + $h, $z + sin($t * 0.05 + 1.0) * $wind * $h * 0.4, $sz, $sz * 1.15, fmod($t * 0.06 + $k * 0.3, 1.0), fmod($k * 0.41, 1.0), 0.42 * (1.0 - $ph) * min(1.0, $ph * 5.0), 3.0, $pale]; } return 1; } $n = (int) min($this->set['flames'], round($r * $r * 1.1) + 3); $draws = 0; $zone = $this->zone; for ($k = 0; $k < $n; $k++) { $a = $k * 2.39996; $d = sqrt(($k + 0.5) / $n) * $r * 0.88; $fx = $x + cos($a) * $d; $fz = $z + sin($a) * $d; $fy = $zone !== null ? $zone->heightAt($fx, $fz) : $y; $edge = $d / max($r, 0.01); $size = (1.3 + 1.4 * Mesh::hash($k, 41)) * (1.0 + min(2.2, $r * 0.2)) * (1.0 - 0.5 * $edge); $this->flame($fx, $fy, $fz, $size, $t * (0.9 + 0.2 * Mesh::hash($k, 43)) + $k * 1.7, $vp); $draws++; } // smoke: a few big, soft, dark puffs rising, growing, leaning with the wind (blended: Graphics::drawPuffs()) $grey = [min(1.0, sqrt($lit[0]) * 0.3 + 0.04), min(1.0, sqrt($lit[1]) * 0.29 + 0.04), min(1.0, sqrt($lit[2]) * 0.28 + 0.04)]; $puffs = (int) min(6, 3 + $r / 2.5); for ($k = 0; $k < $puffs; $k++) { $ph = fmod($t * 0.06 + $k / $puffs, 1.0); $h = 2.5 + $ph * (11.0 + $r * 2.5); $sz = (3.0 + $ph * 8.0) * (0.6 + min(2.0, $r * 0.12)); $this->puffs[] = [$x + cos($t * 0.05) * $wind * $h * 0.35 + sin($k * 2.1) * $r * 0.25, $y + $h, $z + sin($t * 0.05 + 1.0) * $wind * $h * 0.35 + cos($k * 1.7) * $r * 0.25, $sz, $sz * 0.85, fmod($t * 0.04 + $k * 0.3, 1.0), fmod($k * 0.41, 1.0), 0.95 * (1.0 - $ph * 0.7) * min(1.0, $ph * 5.0), 3.0, $grey]; } return $draws; } /** * Steam from the vents (a slow, pale column) and the geysers (now and then a roaring column of water and steam). * @param list<float> $vp @param array<string, mixed> $env @param list<float> $eye @param list<array{0: float, 1: float, 2: float, 3: float}> $planes * @return int draws */ private function emitters(float $t, array $vp, array $env, array $eye, array $planes): int { $draws = 0; $lit = self::add3(self::mul3(self::sq($env['skyAmb']), 1.7), self::mul3(self::sq($env['lightCol']), 0.5)); $white = [min(1.0, sqrt($lit[0]) * 0.95), min(1.0, sqrt($lit[1]) * 0.96), min(1.0, sqrt($lit[2]))]; foreach ($this->emitters as $e) { if (($e['x'] - $eye[0]) ** 2 + ($e['z'] - $eye[2]) ** 2 > 110 * 110 || !self::sphereVisible($planes, $e['x'], $e['y'] + 6, $e['z'], 14)) { continue; } $geyser = $e['kind'] === 'geyser'; $cycle = fmod($t + $e['id'] * 7.3, 24.0); $erupt = $geyser && $cycle < 6.0 ? sin(min(1.0, $cycle / 0.6) * M_PI / 2) * (1.0 - max(0.0, $cycle - 4.5) / 1.5) : 0.0; $puffs = $geyser ? 3 + (int) ($erupt * 5) : 3; for ($k = 0; $k < $puffs; $k++) { $ph = fmod($t * ($geyser && $erupt > 0 ? 0.6 : 0.09) + $k / $puffs, 1.0); $h = $erupt > 0 ? 0.8 + $ph * 14.0 * $erupt : 1.0 + $ph * 5.5; $sz = $erupt > 0 ? (1.0 + $ph * 3.6) * $e['r'] : (1.0 + $ph * 3.0) * $e['r']; $this->puffs[] = [$e['x'] + cos($t * 0.05) * $env['wind'] * $h * 0.3, $e['y'] + $h + $sz * 0.2, $e['z'] + sin($t * 0.05 + 1.0) * $env['wind'] * $h * 0.3, $sz, $sz * ($erupt > 0 ? 1.4 : 1.0), fmod($t * 0.07 + $k * 0.3, 1.0), fmod($k * 0.37 + $e['id'] * 0.1, 1.0), ($erupt > 0 ? 0.75 : 0.45) * (1.0 - $ph * 0.85) * min(1.0, $ph * 5.0), 2.0, $white]; } } return $draws; } /** * A lightning bolt from the clouds to (x, z): a jagged main channel and a few branches, two crossed ribbons each * (seen from any side), built once per strike. @param list<float> $vp @return int draws */ private function drawBolt(float $x, float $z, float $t0, float $age, array $vp): int { $zone = $this->zone; if ($zone === null) { return 0; } $key = sprintf('%.2f:%.2f:%.2f', $x, $z, $t0); if ($this->bolt === null || $this->bolt['key'] !== $key) { if ($this->bolt !== null) { $this->gl->delete($this->bolt['vb']); } $seed = (int) (abs($x * 13.0 + $z * 7.0 + $t0 * 101.0)) % 100000; $gy = $zone->heightAt($x, $z); $v = []; $channel = function (array $from, array $dir, float $len, int $segs, float $w, int $s0) use (&$v, &$channel, $seed, $gy): void { $p = $from; for ($k = 0; $k < $segs; $k++) { $j = [(Mesh::hash($seed + $s0, $k * 3) - 0.5) * 0.9, (Mesh::hash($seed + $s0, $k * 3 + 1) - 0.5) * 0.9]; $q = [$p[0] + ($dir[0] + $j[0]) * $len / $segs, max($gy, $p[1] + $dir[1] * $len / $segs), $p[2] + ($dir[2] + $j[1]) * $len / $segs]; $ww = $w * (1.0 - 0.5 * $k / $segs); foreach ([[1.0, 0.0], [0.0, 1.0]] as [$ax, $az]) { $a0 = [$p[0] - $ax * $ww, $p[1], $p[2] - $az * $ww, 0.0, 1.0]; $a1 = [$p[0] + $ax * $ww, $p[1], $p[2] + $az * $ww, 1.0, 1.0]; $b0 = [$q[0] - $ax * $ww, $q[1], $q[2] - $az * $ww, 0.0, 1.0]; $b1 = [$q[0] + $ax * $ww, $q[1], $q[2] + $az * $ww, 1.0, 1.0]; foreach ([$a0, $a1, $b1, $a0, $b1, $b0] as $pt) { array_push($v, ...$pt); } } if ($s0 === 0 && $k > 2 && $k < $segs - 4 && Mesh::hash($seed, 900 + $k) < 0.22) { $channel($q, [(Mesh::hash($seed, 950 + $k) - 0.5) * 1.6, -0.8, (Mesh::hash($seed, 970 + $k) - 0.5) * 1.6], $len * 0.25, 6, $w * 0.45, 100 + $k); } $p = $q; if ($p[1] <= $gy) { break; } } }; $top = [$x + (Mesh::hash($seed, 1) - 0.5) * 40.0, $gy + 130.0, $z + (Mesh::hash($seed, 2) - 0.5) * 40.0]; $dir = [($x - $top[0]) / 130.0, -1.0, ($z - $top[2]) / 130.0]; $channel($top, $dir, 132.0, 28, 1.1, 0); $this->bolt = ['key' => $key, 'vb' => $this->gl->buffer($v), 'n' => intdiv(count($v), 5)]; } $this->gl->draw($this->pBolt, [ 'attributes' => ['a_pos' => [$this->bolt['vb'], 3, 5, 0], 'a_uv' => [$this->bolt['vb'], 2, 5, 3]], 'count' => $this->bolt['n'], 'depth' => true, 'uniforms' => ['u_vp' => $vp, 'u_model' => Mat4::identity(), 'u_bolt' => [max(0.0, 1.0 - $age / 0.7), sin($age * 60.0) > 0 ? 1.0 : 0.4, 0.0, 0.0], 'u_dfr' => (float) ($this->frame % 64)], ]); return 1; } /** Flames: three crossed quads with an animated flame shader (screen-door edges), $size metres wide. @param list<float> $vp */ /** * The grip's place in the world for a hand at $rest (eye frame) with a pose's offset and the walk's sway. * @param array{0: float, 1: float, 2: float} $rest @param array<int, float> $pose @param array{0: list<float>, 1: list<float>, 2: list<float>} $basis * @param list<float> $eye @return array{0: float, 1: float, 2: float} */ private function heldOrigin(array $rest, array $pose, array $eye, array $basis, float $t, float $bob): array { $side = $rest[0] < 0 ? -1.0 : 1.0; $sx = $rest[0] + $pose[0] + sin($t * 6.0 + ($side < 0 ? 1.4 : 0.0)) * 0.012 * $bob; $sy = $rest[1] + $pose[1] + abs(cos($t * 6.0 + ($side < 0 ? 1.4 : 0.0))) * 0.02 * $bob + sin($t * 1.3) * 0.004; $sz = $rest[2] + $pose[2]; $d = self::eyeVec($basis, [$sx, $sy, $sz]); return [$eye[0] + $d[0], $eye[1] + $d[1], $eye[2] + $d[2]]; } /** A vector of the eye's frame (right, up, forward) in the world. @param array{0: list<float>, 1: list<float>, 2: list<float>} $basis @param array<int, float> $v @return array{0: float, 1: float, 2: float} */ private static function eyeVec(array $basis, array $v): array { [$r, $u, $f] = $basis; return [$r[0] * $v[0] + $u[0] * $v[1] + $f[0] * $v[2], $r[1] * $v[0] + $u[1] * $v[1] + $f[1] * $v[2], $r[2] * $v[0] + $u[2] * $v[1] + $f[2] * $v[2]]; } /** * One item in first person at a hand's rest place with a pose (HeldPose), and its flame for a torch; a torch swept * ($sweep 0..1) leaves a trail of fading flames along its path. Returns the draw calls made. * @param array{0: float, 1: float, 2: float} $rest @param array<int, float> $pose @param list<float> $eye * @param array{0: list<float>, 1: list<float>, 2: list<float>} $basis @param list<float> $vp @param array<string, mixed> $common */ private function drawHeld(string $item, array $rest, array $pose, array $eye, array $basis, float $t, float $bob, array $vp, array $common, ?float $sweep): int { [$mesh, $tip] = Models::held($item); $key = 'held:' . Models::itemKind($item); if (!isset($this->models[$key])) { $this->models[$key] = $this->upload($mesh); } $p = $this->models[$key]; $o = $this->heldOrigin($rest, $pose, $eye, $basis, $t, $bob); $ax = HeldPose::axes($pose[3], $pose[4], $pose[5]); $wx = self::eyeVec($basis, $ax[0]); $wy = self::eyeVec($basis, $ax[1]); $wz = self::eyeVec($basis, $ax[2]); $hm = [$wx[0], $wx[1], $wx[2], 0.0, $wy[0], $wy[1], $wy[2], 0.0, $wz[0], $wz[1], $wz[2], 0.0, $o[0], $o[1], $o[2], 1.0]; $this->gl->draw($this->pProps, ['attributes' => $p['attr'], 'indices' => $p['ib'], 'count' => $p['n'], 'textures' => ['t_atlas' => $this->tex['atlas']], 'uniforms' => ['u_model' => $hm] + $common]); $draws = 1; if ($tip === null) { return $draws; } $up = $basis[1]; $tipAt = function (array $o, array $wx, array $wy, array $wz) use ($tip): array { return [$o[0] + $wx[0] * $tip[0] + $wy[0] * $tip[1] + $wz[0] * $tip[2], $o[1] + $wx[1] * $tip[0] + $wy[1] * $tip[1] + $wz[1] * $tip[2], $o[2] + $wx[2] * $tip[0] + $wy[2] * $tip[1] + $wz[2] * $tip[2]]; }; if ($sweep !== null) { // the trail: where the flame was a moment ago, smaller and smaller for ($k = 4; $k >= 1; $k--) { $q = $sweep - $k * 0.022; if ($q <= 0) { continue; } $pp = HeldPose::brandish($q); if ($rest[0] < 0) { $pp = HeldPose::mirror($pp); } $po = $this->heldOrigin($rest, $pp, $eye, $basis, $t, $bob); $pa = HeldPose::axes($pp[3], $pp[4], $pp[5]); $tp = $tipAt($po, self::eyeVec($basis, $pa[0]), self::eyeVec($basis, $pa[1]), self::eyeVec($basis, $pa[2])); $this->flame($tp[0], $tp[1] + 0.02, $tp[2], 0.13 * (1 - $k * 0.2), $t * 1.3 + $k * 0.4, $vp); $draws++; } } $tp = $tipAt($o, $wx, $wy, $wz); $this->flame($tp[0] + $up[0] * 0.015, $tp[1] + $up[1] * 0.015, $tp[2] + $up[2] * 0.015, $sweep !== null ? 0.18 : 0.15, $t * 1.3, $vp); return $draws + 1; } private function flame(float $x, float $y, float $z, float $size, float $t, array $vp): void { $s = $size * (0.9 + 0.1 * sin($t * 7.0)); $fm = [$s, 0.0, 0.0, 0.0, 0.0, $s * 1.25, 0.0, 0.0, 0.0, 0.0, $s, 0.0, $x, $y, $z, 1.0]; $this->gl->draw($this->pFlame, [ 'attributes' => ['a_pos' => [$this->flameVb, 3, 5, 0], 'a_uv' => [$this->flameVb, 2, 5, 3]], 'textures' => ['t_noise' => $this->tex['noise']], 'uniforms' => ['u_vp' => $vp, 'u_model' => $fm, 'u_flame' => [fmod($t * 0.9, 1.0), fmod($x * 0.37, 1.0), 1.0, 0.0], 'u_dfr' => (float) ($this->frame % 64)], ]); } /** * A waterfall's sheet (x y z u v, triangles): a short run of water over the lip, then the fall, arching out to * `reach` metres in front where it meets the pool. Layer 1 is a thinner veil a little in front. * @return list<float> */ private static function fallSheet(Thing $t, int $layer): array { $top = (float) ($t->data['top'] ?? $t->y); $bottom = (float) ($t->data['bottom'] ?? 0.0) - 0.15; $w = (float) ($t->data['w'] ?? 6.0) * ($layer === 0 ? 1.0 : 0.82); $reach = (float) ($t->data['reach'] ?? 5.4) + ($layer === 0 ? 0.0 : 0.3); $fx = sin($t->yaw); $fz = cos($t->yaw); $sx = $fz; $sz = -$fx; // the profile: (forward, height, length along the water) from the run over the lip to the pool $prof = [[-2.6, $top + 0.06], [-1.2, $top + 0.07], [0.15, $top + 0.02]]; $rows = 12; for ($k = 1; $k <= $rows; $k++) { $q = $k / $rows; $prof[] = [0.15 + ($reach - 0.15) * sqrt($q) + ($layer === 1 ? 0.25 * $q : 0.0), $top - ($top - $bottom) * $q]; } $len = [0.0]; for ($k = 1; $k < count($prof); $k++) { $len[$k] = $len[$k - 1] + hypot($prof[$k][0] - $prof[$k - 1][0], $prof[$k][1] - $prof[$k - 1][1]); } $cols = 6; $v = []; $pt = static function (int $r, int $c) use ($prof, $len, $cols, $w, $t, $fx, $fz, $sx, $sz, $rows): array { $u = $c / $cols; $spread = 1.0 + 0.15 * max(0, $r - 3) / $rows; // the water spreads a little as it falls $b = ($u - 0.5) * $w * $spread; $a = $prof[$r][0]; return [$t->x + $fx * $a + $sx * $b, $prof[$r][1], $t->z + $fz * $a + $sz * $b, $u, $len[$r] / 4.0]; }; for ($r = 0; $r < count($prof) - 1; $r++) { for ($c = 0; $c < $cols; $c++) { $p00 = $pt($r, $c); $p10 = $pt($r, $c + 1); $p01 = $pt($r + 1, $c); $p11 = $pt($r + 1, $c + 1); foreach ([$p00, $p10, $p11, $p00, $p11, $p01] as $p) { array_push($v, ...$p); } } } return $v; } /** * The spray where a waterfall meets its pool: soft puffs of mist (the flame program's smoke mode), lit by the sky. * @param array{x: float, z: float, top: float, bottom: float, w: float, yaw: float, reach: float} $f * @param list<float> $vp * @param array<string, mixed> $env */ private function fallSpray(array $f, float $t, array $vp, array $env): void { $fx = sin($f['yaw']); $fz = cos($f['yaw']); $lit = self::add3(self::mul3(self::sq($env['skyAmb']), 1.6), self::mul3(self::sq($env['lightCol']), 0.55)); $col = [min(1.0, sqrt($lit[0]) * 0.95), min(1.0, sqrt($lit[1])), min(1.0, sqrt($lit[2]) * 1.02)]; foreach ([-0.3, 0.0, 0.3] as $i => $side) { $s = $f['w'] * (0.34 + 0.06 * sin($t * 1.7 + $i * 2.0)); $x = $f['x'] + $fx * ($f['reach'] + 0.4) + $fz * $side * $f['w']; $z = $f['z'] + $fz * ($f['reach'] + 0.4) - $fx * $side * $f['w']; $this->puffs[] = [$x, $f['bottom'] - 0.3 + $s * 0.35, $z, $s, $s * 0.7, fmod($t * 0.35 + $i * 0.3, 1.0), fmod($i * 0.41 + $t * 0.05, 1.0), 0.4, 2.0, $col]; } } /** * The puffs of this frame: steam and spray first (dithered: they write like solid things), then the smoke far to * near, alpha blended. The layer's alpha would fall under a blended pixel (WebGl::draw blends it too) and the * composite multiplies by it: FLAME_FS picks the blend alpha and colour that give the transmittance asked anyway. * @param list<float> $vp @param list<float> $eye @param list<float> $right @param list<float> $up @param array<string, mixed> $env * @return int draws */ private function drawPuffs(array $vp, array $eye, array $right, array $up, array $env): int { if ($this->puffs === []) { return 0; } $dist = []; foreach ($this->puffs as $i => $p) { $dist[$i] = ($p[8] > 2.5 ? 1e6 : 0.0) + ($p[0] - $eye[0]) ** 2 + ($p[1] - $eye[1]) ** 2 + ($p[2] - $eye[2]) ** 2; } // steam (mode 2) in any order first, then the smoke from the farthest uksort($dist, fn (int $a, int $b): int => ($this->puffs[$a][8] <=> $this->puffs[$b][8]) ?: ($dist[$b] <=> $dist[$a])); $behind = $env['horizon'] ?? $env['fogCol']; $first = true; $draws = 0; foreach (array_keys($dist) as $i) { [$x, $y, $z, $w, $h, $flow, $seed, $alpha, $mode, $col] = $this->puffs[$i]; if ($alpha <= 0.005) { continue; } $u = ['u_centre' => [$x, $y, $z], 'u_size' => [$w, $h], 'u_flame' => [$flow, $seed, $alpha, $mode], 'u_glowCol' => $col]; if ($first) { $u += ['u_vp' => $vp, 'u_right' => $right, 'u_up' => $up, 'u_behind' => $behind, 'u_dfr' => (float) ($this->frame % 64)]; $first = false; } $this->gl->draw($this->pPuff, [ 'attributes' => ['a_pos' => [$this->puffVb, 3, 5, 0], 'a_uv' => [$this->puffVb, 2, 5, 3]], 'textures' => ['t_noise' => $this->tex['noise']], 'uniforms' => $u, 'blend' => $mode > 2.5, ]); $draws++; } return $draws; } private function fogBase(): float { $z = $this->zone; return $z !== null && $z->water > -999 ? $z->water : 0.0; } public function dispose(): void { if (!$this->ok) { return; } foreach ($this->chunks as $c) { foreach (['static', 'far', 'small'] as $slot) { foreach ($c[$slot] ?? [] as $p) { $this->gl->delete($p['vb']); $this->gl->delete($p['ib']); } } } foreach ($this->zoneRes as $id) { $this->gl->delete($id); } foreach ([$this->models, $this->bodies] as $list) { foreach ($list as $p) { $this->gl->delete($p['vb']); $this->gl->delete($p['ib']); } } foreach ($this->tex as $id) { $this->gl->delete($id); } foreach ([$this->skyVb, $this->skyIb, $this->flameVb, $this->precipVb, $this->precipIb, $this->pTerrain, $this->pProps, $this->pBody, $this->pSky, $this->pWater, $this->pFlame, $this->pPrecip, $this->pFall, $this->pBolt] as $id) { $this->gl->delete($id); } if ($this->bolt !== null) { $this->gl->delete($this->bolt['vb']); $this->bolt = null; } $this->chunks = $this->zoneRes = $this->models = $this->bodies = $this->tex = []; $this->zone = null; $this->gl->disable(); $this->ok = false; } // ---- small maths -------------------------------------------------------------------------------- /** @return list<float> translate × rotateY(yaw) × scale, directly */ private static function model(float $x, float $y, float $z, float $yaw, float $s): array { $c = cos($yaw) * $s; $n = sin($yaw) * $s; return [$c, 0.0, -$n, 0.0, 0.0, $s, 0.0, 0.0, $n, 0.0, $c, 0.0, $x, $y, $z, 1.0]; } /** @param list<float> $m @return list<array{0: float, 1: float, 2: float, 3: float}> left, right, bottom, top planes */ private static function planes(array $m): array { $out = []; foreach ([[0, 1], [0, -1], [1, 1], [1, -1]] as [$row, $sign]) { $a = $m[3] + $sign * $m[$row]; $b = $m[7] + $sign * $m[4 + $row]; $c = $m[11] + $sign * $m[8 + $row]; $d = $m[15] + $sign * $m[12 + $row]; $l = sqrt($a * $a + $b * $b + $c * $c) ?: 1.0; $out[] = [$a / $l, $b / $l, $c / $l, $d / $l]; } return $out; } /** @param list<array{0: float, 1: float, 2: float, 3: float}> $planes */ private static function sphereVisible(array $planes, float $x, float $y, float $z, float $r): bool { foreach ($planes as [$a, $b, $c, $d]) { if ($a * $x + $b * $y + $c * $z + $d < -$r) { return false; } } return true; } private static function smooth(float $e0, float $e1, float $x): float { $t = max(0.0, min(1.0, ($x - $e0) / ($e1 - $e0))); return $t * $t * (3 - 2 * $t); } /** @param list<float> $v @return list<float> */ private static function norm(array $v): array { $l = sqrt($v[0] ** 2 + $v[1] ** 2 + $v[2] ** 2) ?: 1.0; return [$v[0] / $l, $v[1] / $l, $v[2] / $l]; } /** @param list<float> $a @param list<float> $b @return list<float> */ private static function cross(array $a, array $b): array { return [$a[1] * $b[2] - $a[2] * $b[1], $a[2] * $b[0] - $a[0] * $b[2], $a[0] * $b[1] - $a[1] * $b[0]]; } /** @param list<float> $a @param list<float> $b @return list<float> */ private static function mix3(array $a, array $b, float $t): array { return [$a[0] + ($b[0] - $a[0]) * $t, $a[1] + ($b[1] - $a[1]) * $t, $a[2] + ($b[2] - $a[2]) * $t]; } /** @param list<float> $a @param list<float> $b @return list<float> */ private static function add3(array $a, array $b): array { return [$a[0] + $b[0], $a[1] + $b[1], $a[2] + $b[2]]; } /** @param list<float> $a @return list<float> */ private static function mul3(array $a, float $k): array { return [$a[0] * $k, $a[1] * $k, $a[2] * $k]; } /** display colour -> about linear @param list<float> $a @return list<float> */ private static function sq(array $a): array { return [$a[0] * $a[0], $a[1] * $a[1], $a[2] * $a[2]]; }}