NL
games/rob-revisited / src / Revisited / Land / Game.php · commit f9a1307
<?phpnamespace App\Revisited\Land;use App\Revisited\Sim\Body;use App\Revisited\Sim\Crafting;use App\Revisited\Sim\Environment;use App\Revisited\Sim\Inventory;use App\Revisited\Sim\Items;use App\Revisited\Sim\Talents;use App\Revisited\Sim\Weapons;/** * The whole state of a game of "Experience - Rob revisited" (docs/reborn.md "Land"): the zone Rob is in, his body * and his bag, time and weather, fires, animals and people, quests, dialogues. Pure logic: the scene calls * update() each frame with what the player wants (Intent), act() for the context action, and draws the rest. * * Conventions: positions in metres; $y = the height of Rob's FEET (eye: eyeY()); facing: forward = (sin yaw, cos yaw) * on (x, z), right = (-cos yaw, sin yaw) (a right-handed view, y up): Intent::$turn > 0 turns right (yaw decreases). * $minutes = game minutes since the crash, day 1 at 07:00; time runs at TIME_RATE game minutes per real second. */final class Game{    public const TIME_RATE = 1.0;    public const EYE = 1.7;    public const CROUCH_EYE = 1.05;    public const WALK = 3.2;    public const RUN = 5.8;    public const SNEAK = 1.4;    public const TURN = 2.4;          // radians per second    public const START_HOUR = 7;    public const JUMP_SPEED = 6.4;    // m/s up: about 1 m high (gravity 20), 0.64 s in the air    public const SPRINT = 8.2;        // m/s: running kept up (SPRINT_AFTER seconds), costs much more breath    public const SPRINT_AFTER = 1.2;    public const GRAVITY = 20.0;    public const FOG_CELLS = 64;      // the explored map: FOG_CELLS x FOG_CELLS cells per zone    public const SCAN_RANGE = 60.0;    /** climbing: metres of rise a second (stakes; the ice pick 35 % more), rest spent a second */    public const CLIMB = 0.6;    /** a dropped bundle lands this far in front of Rob (metres) */    public const DROP_AHEAD = 1.35;    /** seconds of a torch brandished (the sweep); crawlers within BRANDISH_REACH metres flee */    public const BRANDISH = 0.7;    public const BRANDISH_REACH = 8.0;    /**     * The shield (Game::guard()): raised in GUARD_UP seconds, lowered in GUARD_DOWN; a blow landing within PARRY seconds     * of the guard going up is a parry (no harm, the foe reels STAGGER_PARRY s); only blows from within GUARD_ARC of the     * gaze (cosine) are stopped; below GUARD_MIN rest the arm cannot hold it up; walking guarded: ×GUARD_SPEED.     */    public const GUARD_UP = 0.15;    public const GUARD_DOWN = 0.2;    public const PARRY = 0.3;    public const STAGGER_PARRY = 0.9;    public const GUARD_ARC = 0.26;    public const GUARD_MIN = 8.0;    public const GUARD_SPEED = 0.55;    /** radians from the crosshair within which Rob "looks at" a thing */    public const LOOK_AT = 0.16;    public const CLIMB_FATIGUE = 0.5;   // the scanner's reach outdoors (caves: half)    /** minutes for the weather to go from nothing to full (and back): it never changes at once */    public const WEATHER_RAMP = 8.0;    private const ADDED = 100000;    // ids of things added during the game    private const HOSTILE = ['stalker', 'crawler', 'burrower', 'glacier_brute', 'swarm', 'river_croc', 'lava_crab'];    private const PART_TEXT = ['head' => 'à la tête', 'torso' => 'au torse', 'larm' => 'au bras gauche', 'rarm' => 'au bras droit', 'lleg' => 'à la jambe gauche', 'rleg' => 'à la jambe droite'];    public const POD_LOG = 'Journal de bord, nacelle MR-7 du Meridian. Descente d\'urgence sur Ysor, balise hors service. Avant la panne, les capteurs ont relevé une émission très faible sous la vallée, au nord : la signature de la mission Halde, disparue il y a soixante ans. Une base enterrée ? Si quelque chose y fonctionne encore, c\'est ma seule chance de joindre la station.';    public const COLONY_LOG = 'Journal de la mission Halde, dernier enregistrement. Les secousses ont fermé la galerie principale. Nous évacuons les familles vers le canyon rouge par la galerie sud. La cellule de réserve reste ici : sans elle, le mât relais du plateau ne peut plus émettre. Celui qui trouvera ce message devra la porter au mât, régler l\'accordeur sur la fréquence de la station et émettre la nuit, quand elle passe au zénith.';    private const ZONE_TEXT = [        'jungle' => 'Des arbres géants, un fleuve large comme un lac qui coule vers le sud. De la fumée monte d\'un village sur pilotis.',        'marsh' => 'Une brume tiède colle à la peau. Des pilotis pourris, des roseaux, des essaims. Quelqu\'un chante, loin.',        'coast' => 'Le sable est noir, la mer grise. Des fumerolles sifflent entre les blocs de basalte. Et là-bas, couchée sur la roche : une navette.',        'caves3' => 'Des galeries humides où l\'air hésite : vase d\'un côté, sel de l\'autre, la rumeur du fleuve derrière.',        'valley' => 'La vallée du naufrage : jungle moite, lac tiède, et des montagnes tout autour.',        'caves1' => 'L\'obscurité t\'avale. L\'air est froid et humide ; quelque chose gratte au loin.',        'caves2' => 'Plus bas encore. Des câbles rouillés courent le long des parois : la colonie est passée par ici.',        'canyon' => 'La lumière ! Un canyon de roche rouge, écrasé de soleil. De la fumée monte au loin.',        'plateau' => 'Le vent glacé te gifle. Le plateau s\'étend, blanc et nu, jusqu\'au sommet où pointe un mât.',    ];    public Zone $zone;    public Body $body;    public Inventory $inv;    /** experience, level, talents (saved) */    public Talents $talents;    /** the combat mode: target, precision cursor, dodge, popups (not saved) */    public Combat $combat;    public float $x = 0.0;    public float $z = 0.0;    public float $y = 0.0;    public float $yaw = 0.0;    public float $pitch = 0.0;    public float $minutes = 0.0;    /** @var list<Creature> */    public array $creatures = [];    /** @var list<Npc> */    public array $npcs = [];    /** @var array{kind: string, amount: float}|null */    public ?array $weather = null;    /** @var array<int, array{x: float, z: float, minutes: float, permanent?: bool}> a list: x, z, minutes left (permanent: a village fire) */    public array $fires = [];    public int $seed;    public bool $crouching = false;    public bool $running = false;    /** running kept up for a while: the sprint (faster, tiring) */    public bool $sprinting = false;    /** seconds of running without a stop (the sprint starts at SPRINT_AFTER, ramps up over half a second) */    public float $runTime = 0.0;    public bool $swimming = false;    public bool $moving = false;    /** red flash 0..1 when Rob is hit (View::$hurt) */    public float $hurt = 0.0;    public float $vy = 0.0;    /** @var array<string, mixed> quest goals (q_*), visited zones, dead Rôdeurs, counters */    public array $flags = [];    /** @var list<string> */    private array $log = [];    /** @var list<string> news worth a toast (the fitness steps): the scene takes them (takeNotices()) */    private array $notices = [];    /** @var array<string, array<string, array<int, mixed>>> per zone: mod (id => kind/left/data), del (id => true), add (id => thing) */    private array $diffs = [];    /** @var array<string, array{at: float, list: list<array>}> fires of the zones Rob is not in */    private array $zoneFires = [];    /** @var array<string, Zone> */    private array $zones = [];    private Rng $rng;    private int $nextThing = self::ADDED;    private int $nextId = 1000;    private float $pending = 0.0;    private float $spawnTimer = 0.0;    private float $weatherLeft = 120.0;    /** @var array{id: int, node: string, say: ?string, pet?: bool}|null */    private ?array $talk = null;    private bool $won = false;    private bool $lastAttack = false;    private bool $lastLeft = false;    /**     * The blow under way (swing()): item (null: fists), side (right|left), kind (Weapons::anim), t (seconds since the     * press), at (the strike: the damage lands then), dur (until the next blow), counter, done (struck), hit (it     * touched someone), aim (combat mode: the precision cursor still sweeps, the strike waits for the next press), mult and     * grade (the cursor's verdict: crit ×1.5, good, weak ×0.7). Null: no blow. Render draws its anticipation, strike and     * recovery from it.     * @var array{item: ?string, side: string, kind: string, t: float, at: float, dur: float, counter: bool, done: bool, hit: bool, aim: bool, mult: float, grade: ?string}|null     */    public ?array $swing = null;    /** Game::$clock of the last torch brandished (-9: never) */    public float $brandishAt = -9.0;    /** Game::$clock when the shield went up (null: lowered) and when it last came down */    public ?float $guardAt = null;    public float $guardDownAt = -9.0;    /** Game::$clock of the last blow that touched someone (the view's nudge) */    public float $hitAt = -9.0;    private float $attackCool = 0.0;    private float $fight = 0.0;    private float $torchLeft = 0.0;    private ?array $village = null;    /** @var array{kind: string, amount: float}|null the weather the sky is turning into */    private ?array $weatherTarget = null;    /** @var array<string, string> per zone: the explored cells, one bit each (FOG_CELLS x FOG_CELLS) */    private array $explored = [];    /** grows each time a cell is revealed (the map rebuilds its fog then) */    public int $exploredVersion = 0;    private float $revealTimer = 0.0;    public bool $onGround = true;    private float $scanBat = 100.0;    /**     * GPS waypoints: id => [name, zone, x, z] (Rob's own marks and the coordinates of the logs inserted in the GPS)     * @var array<string, array{0: string, 1: string, 2: float, 3: float}>     */    public array $waypoints = [];    /** the waypoint the compass, the map and the scanner point at */    public ?string $activeWaypoint = null;    /**     * The sleep (or the rest) under way: the scene runs it fast (sleepStep()), Rob wakes up by himself or because of a     * danger. null: awake. Keys: mode, place, target (minutes to sleep, 0 = until a condition), slept, until, woken (why),     * rest (sitting, awake), fire (a fire was near at the start), dreams (lines), done.     * @var array<string, mixed>|null     */    public ?array $sleeping = null;    /** route of the zones, in a line (the door toward a zone further on is the next one) */    public const ROUTE = ['valley' => 0, 'caves1' => 1, 'caves2' => 2, 'canyon' => 3, 'plateau' => 4];    // ---- wave 2 (docs/reborn.md "Wave 2")    /** @var array<string, array> what the named people think of Rob (People) */    public array $people = [];    /** Rob aboard his raft: x, z, yaw, hp, vx, vz (Raft); null: on foot */    public ?array $raft = null;    /** @var list<array{x: float, z: float, r: float, fuel: float, age: float}> spreading fires of the zone (Wildfire) */    public array $blazes = [];    /** @var array<string, list<array{0: float, 1: float, 2: float}>> burnt ground per zone */    public array $burnt = [];    /** @var array{0: float, 1: float, 2: float} the wind: direction x, z, strength 0..1 */    public array $wind = [1.0, 0.0, 0.2];    /** the last lightning: x, z, t (Game::$clock seconds) */    public ?array $lightning = null;    public float $lightningTimer = 8.0;    /** seconds of play (real time) */    public float $clock = 0.0;    /** Rob climbs this frame (stakes / ice pick on a slope too steep to walk, or a cliff outdoors: Game::climbStep()) */    public bool $climbing = false;    /** metres risen while climbing, not yet worn into the tool */    private float $climbWear = 0.0;    /** the context action: the candidate chosen among the things within reach (cycleFocus()) and the list it indexes */    public int $focusPick = 0;    private string $focusKey = '';    /** the thing chosen with cycleFocus() (its id), kept while the same things are within reach */    private ?int $focusChosen = null;    /** @var list<array{0: string, 1: float, 2: float}> sounds for the scene: name, delay (s), volume */    public array $events = [];    public float $fireHurt = 0.0;    /** the human companion (People key), null: alone */    public ?string $companion = null;    public float $companionFed = 0.0;    /** the stalker cub: state wild|tame|gone|dead, health, hunger, tame, healed, mode follow|stay|hunt, zone, x, z */    public array $pet = [];    /** shots left in the energy cell in use */    public int $cellShots = 0;    /** the chest whose transfer screen is open (Chests::open(); the scene shows it), null: none */    public ?int $chestOpen = null;    /** @var array<string, array{at: float, list: list<array>}> blazes of the zones Rob left */    private array $blazeStore = [];    private ?Noise $riverNoise = null;    /** the last swing (Game::$clock) of a creature at Rob: a blow right after it is a counter */    private float $parryAt = -9.0;    /** the geographic point of the valley's (0, 0) corner on Ysor's grid (degrees) */    public const GRID_ORIGIN = [41.2120, 118.5490];    private function __construct(int $seed)    {        $this->seed = $seed;        $this->rng = new Rng($seed + 999);        $this->talents = new Talents();        $this->combat = new Combat();    }    public static function newGame(int $seed): self    {        $g = new self($seed);        $g->body = new Body();        $g->inv = new Inventory();        $g->inv->add('ration', 1);        $g->inv->add('bandage', 1);        $g->inv->add('scanner', 1);        $g->inv->dressForTheCrash();        $g->weather = ['kind' => 'clear', 'amount' => 0.0];        $g->enterZone('valley');        [$g->x, $g->z] = ZoneFactory::START;        $g->y = $g->zone->heightAt($g->x, $g->z);        $g->yaw = atan2(ZoneFactory::POD[0] - $g->x, ZoneFactory::POD[1] - $g->z);        Wildlife::spawn($g, true);        $g->reveal();        $g->say('Rob Calder reprend conscience dans la nacelle éventrée. Le Meridian est loin, très loin au-dessus.');        Quest::check($g);        return $g;    }    // ------------------------------------------------------------------------------------------ the frame    public function update(float $dt, Intent $in): void    {        if (!($dt > 0) || !is_finite($dt)) {            return;            // NaN / INF: never let them into the clock, the body or the loops        }        foreach (['forward', 'turn', 'strafe', 'look'] as $k) {            if (!is_finite($in->$k)) {                $in->$k = 0.0;            }        }        if (!is_finite($this->minutes)) {            $this->minutes = 0.0;        }        $dt = min($dt, 0.1);        $this->hurt = max(0.0, $this->hurt - $dt * 1.5);        if ($this->over() !== null || $this->won || $this->talk !== null || $this->sleeping !== null) {            return;        }        $mins = $dt * self::TIME_RATE;        $this->minutes += $mins;        $this->clock += $dt;        if ($this->raft !== null) {            Raft::move($this, $dt, $in);        } else {            $this->move($dt, $in);        }        if ($in->dodge !== null) {            $this->dodge($in->dodge);        }        if ($in->attack && !$this->lastAttack) {            if ($this->aiming()) {                $this->release();            } else {                $this->swing();            }        }        $this->lastAttack = $in->attack;        $this->guard($in->left);        if ($in->left && !$this->lastLeft && $this->inv->shield() === null) {            $this->leftHand();        }        $this->lastLeft = $in->left;        $this->attackCool = max(0.0, $this->attackCool - $dt);        $this->advanceSwing($dt);        $this->fight = max(0.0, $this->fight - $dt);        $this->burn($mins, false);        $this->pending += $mins;        if ($this->pending >= 0.5) {            $this->tickBody($this->pending, false);            $this->pending = 0.0;        }        Wildlife::update($this, $dt);        Folk::update($this, $dt);        Companions::update($this, $dt);        $this->combat->update($this, $dt, $in);        $this->unstick();        Wildfire::update($this, $dt);        $this->spawnTimer += $dt;        if ($this->spawnTimer >= 2.0) {            $this->spawnTimer = 0.0;            Wildlife::spawn($this);            $this->regrow();            $this->springTraps();            Chests::thieves($this, 2.0 * self::TIME_RATE);        }        $this->chargeScanner($dt);        $this->revealTimer -= $dt;        if ($this->revealTimer <= 0) {            $this->revealTimer = 0.4;            $this->reveal();        }        if ($this->zone->id === 'plateau' && hypot($this->x - ZoneFactory::MAST[0], $this->z - ZoneFactory::MAST[1]) < 16) {            $this->flags['q_reach_mast'] = true;        }        if ($this->zone->id === 'coast' && hypot($this->x - ZoneFactory::SHUTTLE[0], $this->z - ZoneFactory::SHUTTLE[1]) < 30) {            $this->flags['q_shuttle_found'] = true;        }        Quest::check($this);    }    private function move(float $dt, Intent $in): void    {        $z = $this->zone;        $this->crouching = $in->crouch;        $this->yaw -= $in->turn * self::TURN * $dt;        $this->yaw = fmod($this->yaw, 6.283185307);        $this->pitch = max(-1.3, min(1.3, $this->pitch + $in->look * 1.6 * $dt));        $fx = sin($this->yaw);        $fz = cos($this->yaw);        $mx = $fx * $in->forward - cos($this->yaw) * $in->strafe;        $mz = $fz * $in->forward + sin($this->yaw) * $in->strafe;        $len = hypot($mx, $mz);        if ($len > 1) {            $mx /= $len;            $mz /= $len;            $len = 1.0;        }        $ground = $z->heightAt($this->x, $this->z);        $this->swimming = $z->water - $ground > 1.1;        $this->running = $in->run && $this->guardAt === null && !$this->crouching && !$this->swimming && $in->forward > 0.1 && $this->body->vitals()['fatigue'] > 5;        $this->runTime = $this->running ? $this->runTime + $dt : 0.0;        $sprint = $this->running && $this->body->vitals()['fatigue'] > $this->body->sprintThreshold()            ? max(0.0, min(1.0, ($this->runTime - self::SPRINT_AFTER) / 0.5)) : 0.0;        $this->sprinting = $sprint > 0.0;        $speed = $this->crouching ? self::SNEAK : ($this->running ? self::RUN + (self::SPRINT - self::RUN) * $sprint : self::WALK);        $speed *= $this->body->speedFactor();        if ($this->swimming) {            $speed *= 0.45;        }        if ($this->combat->stagger > 0) {            $speed *= 0.5;      // shaken by a blow        }        if ($this->guardAt !== null) {            $speed *= self::GUARD_SPEED;      // behind the shield: short steps        }        $this->moving = $len > 0.05;        if ($z->solidHit($this->x, $this->z, Solids::ROB) !== null) {            [$this->x, $this->z] = Solids::pushOut($z, $this->x, $this->z, Solids::ROB);     // teleported / something built on Rob        }        $wasClimbing = $this->climbing;        $this->climbing = false;        if ($this->moving) {            $y0 = $z->heightAt($this->x, $this->z);            $sx = $mx * $speed * $dt;            $sz = $mz * $speed * $dt;            $ox = $this->x;            $oz = $this->z;            if (!$this->tryMove($this->x + $sx, $this->z) | !$this->tryMove($this->x, $this->z + $sz)) {                $hit = $z->solidHit($ox + $sx, $oz + $sz, Solids::ROB);                if ($hit !== null && hypot($this->x - $ox, $this->z - $oz) < 0.5 * hypot($sx, $sz)) {                    // a rock, a trunk: slide round it (the part of the step tangent to its circle)                    $nx = $ox - $hit[0];                    $nz = $oz - $hit[1];                    $nl = max(0.001, hypot($nx, $nz));                    $into = ($sx * $nx + $sz * $nz) / $nl;                    $tx = $sx - $into * $nx / $nl;                    $tz = $sz - $into * $nz / $nl;                    $tl = hypot($tx, $tz);                    if ($tl > 0.15 * hypot($sx, $sz)) {                        $k = hypot($sx, $sz) / $tl * 0.8;                        $this->tryMove($ox + $tx * $k, $oz + $tz * $k);                    }                } else {                    $this->climbStep($mx, $mz, $dt);                }            }            if ($this->climbing) {                $this->climbed($z->heightAt($this->x, $this->z) - $y0, $dt, $wasClimbing);            }        }        $ground = $z->heightAt($this->x, $this->z);        $this->swimming = $z->water - $ground > 1.1;        if ($in->jump && $this->onGround && !$this->swimming && !$this->crouching && $this->body->vitals()['fatigue'] > 3) {            $headroom = $z->cave ? ($z->ceilingAt($this->x, $this->z) ?? 99.0) - $ground : 99.0;            if ($headroom > 2.3) {                $this->vy = self::JUMP_SPEED * (0.75 + 0.25 * min(1.0, $this->body->speedFactor()));                $this->onGround = false;                $this->flags['jumps'] = (int) ($this->flags['jumps'] ?? 0) + 1;            }        }        if ($this->swimming) {            $this->y = $z->water - 1.35;            $this->vy = 0.0;            $this->onGround = false;        } elseif (!$this->onGround || $this->vy > 0 || $this->y > $ground + 0.6) {            // in the air (a jump, a ledge walked off): a whole arc down to the ground, never cut short            $this->onGround = false;            $this->vy -= self::GRAVITY * $dt;            $this->y += $this->vy * $dt;            if ($this->y <= $ground) {                $this->land($ground);            }        } else {            // walking: small steps down a slope follow the ground            $this->y = $ground;            $this->vy = 0.0;            $this->onGround = true;        }    }    /**     * Nobody stays inside a solid thing (Solids): an animal or a person standing still where one was spawned, a hut, a     * shelter built on them... pushed out to the nearest free side. One look in a grid square each: cheap every frame.     */    private function unstick(): void    {        $z = $this->zone;        foreach ($this->creatures as $c) {            if ($c->species === 'bird' || $c->species === 'swarm' || ($c->species === 'burrower' && $c->state === 'buried')) {                continue;            }            $r = Solids::body($c->species);            if ($z->solidHit($c->x, $c->z, $r) !== null) {                [$c->x, $c->z] = Solids::pushOut($z, $c->x, $c->z, $r);                if ($c->species !== 'fish') {                    $c->y = $z->heightAt($c->x, $c->z);                }            }        }        foreach ($this->npcs as $n) {            if ($z->solidHit($n->x, $n->z, Solids::PERSON) !== null) {                [$n->x, $n->z] = Solids::pushOut($z, $n->x, $n->z, Solids::PERSON);                $n->y = $z->heightAt($n->x, $n->z);            }        }    }    /** In the air (a jump, a fall)? */    public function airborne(): bool    {        return !$this->onGround && !$this->swimming;    }    private function land(float $ground): void    {        $impact = -$this->vy;        $this->y = $ground;        $this->vy = 0.0;        $this->onGround = true;        if ($impact > 9) {            $this->inv->wear(min(6.0, ($impact - 9) * 0.8), ['feet']);        }        if ($impact > 11) {            $this->inv->wear(2.0, ['worn', 'legs']);            $sev = min(1.0, 0.3 + ($impact - 11) / 10);            $leg = $this->rng->chance(0.5) ? 'lleg' : 'rleg';            $this->body->wound($leg, $sev > 0.55 ? 'fracture' : 'bruise', $sev);            $this->hurt = 1.0;            $this->say($sev > 0.55 ? 'Tu tombes lourdement : ta jambe craque !' : 'Tu tombes lourdement et te tords la jambe.');        }    }    /** The climbing tool in the bag (the ice pick first), null: none. */    public function climbTool(): ?string    {        foreach (['ice_pick', 'climbing_stakes'] as $id) {            if ($this->inv->has($id)) {                return $id;            }        }        return null;    }    /** A wall Rob may climb with a tool: the cliffs of the land (a solid cell outdoors, not the zone's edge); never a cave's rock. */    public function climbableAt(float $x, float $z): bool    {        $zone = $this->zone;        if ($zone->cave || $x < 2.5 * $zone->cell || $z < 2.5 * $zone->cell || $x > $zone->size - 2.5 * $zone->cell || $z > $zone->size - 2.5 * $zone->cell) {            return false;        }        return $zone->solidAt($x, $z);    }    /**     * Walking failed (too steep, a cliff): with a climbing tool Rob goes up anyway, slowly (CLIMB m/s of rise, the ice pick     * a bit faster), along the direction asked. Never through solid things or a cave's walls, never while swimming.     */    private function climbStep(float $mx, float $mz, float $dt): void    {        $tool = $this->climbTool();        if ($tool === null || $this->swimming || $this->raft !== null || $this->zone->cave || $this->body->vitals()['fatigue'] < 1) {            return;        }        $z = $this->zone;        $rise = ($tool === 'ice_pick' ? self::CLIMB * 1.35 : self::CLIMB) * min(1.0, $this->body->speedFactor() + 0.2) * $dt;        $h0 = $z->heightAt($this->x, $this->z);        // the horizontal step that rises $rise along this direction (the slope measured a short way ahead)        $probe = 0.25;        $ahead = ($z->heightAt($this->x + $mx * $probe, $this->z + $mz * $probe) - $h0) / $probe;        $r = Solids::ROB;        $onCliff = $this->climbableAt($this->x + $mx * 0.6, $this->z + $mz * 0.6) || $this->climbableAt($this->x, $this->z)            || $this->climbableAt($this->x + $r, $this->z) || $this->climbableAt($this->x - $r, $this->z)            || $this->climbableAt($this->x, $this->z + $r) || $this->climbableAt($this->x, $this->z - $r);        if ($ahead <= ZoneFactory::MAX_SLOPE * 0.8 && !$onCliff) {            return;      // not a slope that stops a walker (a rock, the river...): nothing to climb        }        $slope = max(0.3, $ahead);        $run = min(self::WALK * $dt, $rise / $slope);        $nx = $this->x + $mx * $run;        $nz = $this->z + $mz * $run;        foreach ([[$nx, $nz], [$nx + $r, $nz], [$nx - $r, $nz], [$nx, $nz + $r], [$nx, $nz - $r]] as [$px, $pz]) {            if ($z->solidAt($px, $pz) && !$this->climbableAt($px, $pz)) {                return;            }        }        if ($z->solidHit($nx, $nz, $r) !== null) {            return;        }        $this->x = $nx;        $this->z = $nz;        $this->climbing = true;    }    /** Rob rose $dh metres climbing: the tool wears, the breath goes, a tired or hurt climber may slip and fall. */    private function climbed(float $dh, float $dt, bool $wasClimbing): void    {        $tool = $this->climbTool();        if ($tool === null) {            return;        }        if (!$wasClimbing) {            $this->events[] = ['climb', 0.0, 0.8];            if (empty($this->flags['climb_told'])) {                $this->flags['climb_told'] = true;                $this->say('Tu plantes ' . ($tool === 'ice_pick' ? 'le piolet' : 'les pieux') . ' dans la pente et te hisses, prise après prise. C\'est épuisant : surveille ta fatigue, et ne grimpe pas les bras blessés.');            }        }        $this->body->exert(self::CLIMB_FATIGUE * $dt);        $this->climbWear += max(0.0, $dh);        if ($this->climbWear >= 1.0) {            $metres = floor($this->climbWear);            $this->climbWear -= $metres;            $c = $this->inv->condition($tool) - $metres * ($tool === 'ice_pick' ? 1.0 : 2.5);            $this->events[] = ['climb', 0.0, 0.5];            if ($c <= 0) {                $this->inv->remove($tool);                unset($this->inv->cond[$tool]);                $this->say($tool === 'ice_pick' ? 'Le manche du piolet casse net !' : 'Le dernier pieu se fend : il n\'en reste rien.');                $this->climbing = false;                return;            }            $this->inv->cond[$tool] = $c;        }        // a slip: exhausted, the arms hurt, the hands frozen        $v = $this->body->vitals();        $risk = ($v['fatigue'] < 12 ? 0.25 : 0.0) + (1.0 - $this->body->fightFactor()) * 0.35;        if ($risk > 0.0 && $this->rng->chance(min(0.6, $risk) * $dt)) {            $this->slip();        }    }    /** Rob loses his hold: he slides back down the slope a few metres and falls (Game::land() hurts him). */    private function slip(): void    {        $z = $this->zone;        $h = $z->heightAt($this->x, $this->z);        $best = null;        for ($a = 0; $a < 8; $a++) {            $dx = sin($a * 0.785);            $dz = cos($a * 0.785);            $px = $this->x + $dx * 3.0;            $pz = $this->z + $dz * 3.0;            if ($z->solidAt($px, $pz) || $z->solidHit($px, $pz, Solids::ROB) !== null) {                continue;            }            $ph = $z->heightAt($px, $pz);            if ($best === null || $ph < $best[2]) {                $best = [$px, $pz, $ph];            }        }        if ($best === null || $best[2] > $h - 0.5) {            return;        }        $this->x = $best[0];        $this->z = $best[1];        $this->y = $h;        $this->vy = 0.0;        $this->onGround = false;        $this->climbing = false;        $this->say('Ta prise lâche ! Tu glisses le long de la paroi...');    }    private function tryMove(float $nx, float $nz): bool    {        $z = $this->zone;        $r = Solids::ROB;        if ($z->solidAt($nx + $r, $nz) || $z->solidAt($nx - $r, $nz) || $z->solidAt($nx, $nz + $r) || $z->solidAt($nx, $nz - $r)) {            return false;        }        if ($z->solidHit($nx, $nz, $r) !== null) {            return false;        // a rock, a trunk, a hut: the other axis of the step slides along it        }        if (Raft::forbidden($this, $nx, $nz) && $z->waterDepth($nx, $nz) > $z->waterDepth($this->x, $this->z)) {            if (empty($this->flags['river_told']) || $this->minutes - (float) $this->flags['river_told'] > 30) {                $this->flags['river_told'] = $this->minutes;                $this->say('Le courant du fleuve est trop fort pour nager : il te faut un radeau (ou le passeur des Ouvi).');            }            return false;        }        $h0 = $z->heightAt($this->x, $this->z);        $h1 = $z->heightAt($nx, $nz);        $d = hypot($nx - $this->x, $nz - $this->z);        // too steep to walk up, unless a jump carries Rob over the edge        if (!$this->swimming && $h1 - $h0 > ZoneFactory::MAX_SLOPE * $d + 0.002 && !($this->vy !== 0.0 && $this->y >= $h1 - 0.05)) {            return false;        }        if ($z->cave) {            $ceil = $z->ceilingAt($nx, $nz);            if ($ceil !== null && $ceil - $h1 < ($this->crouching ? 1.25 : 1.8)) {                return false;            }        }        $this->x = $nx;        $this->z = $nz;        return true;    }    // ------------------------------------------------------------------------------------------ time, weather, body    public function hour(): float    {        return fmod(self::START_HOUR * 60 + $this->minutes, 1440.0) / 60;    }    public function day(): int    {        return 1 + (int) floor((self::START_HOUR * 60 + $this->minutes) / 1440);    }    /** "Jour 2, 21:45" */    public function clock(): string    {        $h = $this->hour();        return sprintf('Jour %d, %02d:%02d', $this->day(), (int) $h, (int) (($h - (int) $h) * 60));    }    public function isNight(): bool    {        $h = $this->hour();        return $h >= 20.5 || $h < 5.5;    }    /** 0 night / cave, 1 noon (without the torch: the renderer adds it). */    public function lightLevel(): float    {        if ($this->zone->cave) {            return 0.03;        }        $sun = sin(($this->hour() / 24 - 0.25) * 6.2832);        $l = max(0.04, min(1.0, 0.08 + $sun * 1.1));        $w = $this->weather;        if ($w !== null) {            $l *= match ($w['kind']) {                'storm' => 1 - 0.45 * $w['amount'],                'rain', 'snow' => 1 - 0.25 * $w['amount'],                'fog' => 1 - 0.15 * $w['amount'],                default => 1.0,            };        }        return max(0.03, $l);    }    public function torchLit(): bool    {        return $this->inv->holds('torch');    }    /**     * What Rob holds that can light a fire: a fire drill (any item of tool "fire") in a hand, or a lit torch; null: none.     * "Allumer un feu" is only offered with one in hand (taking the drill from the bag shows it). The flare gun does not     * count: a flare scatters the wood and is wasted.     */    public function fireInHand(): ?string    {        foreach ([$this->inv->hand, $this->inv->handLeft] as $h) {            if ($h !== null && $this->inv->has($h) && (Items::get($h)['tool'] ?? null) === 'fire') {                return $h;            }        }        return $this->torchLit() ? 'torch' : null;    }    public function eyeY(): float    {        return $this->y + ($this->crouching ? self::CROUCH_EYE : self::EYE);    }    /** °C of the air where Rob stands (zone, hour, altitude, weather). */    public function airTemp(): float    {        $z = $this->zone;        if ($z->cave) {            return $z->baseTemp;        }        $amp = ['valley' => 9.0, 'canyon' => 16.0, 'plateau' => 13.0][$z->id] ?? 10.0;        $ref = ['valley' => 5.0, 'canyon' => 6.0, 'plateau' => 100.0][$z->id] ?? 0.0;        $t = $z->baseTemp - $amp * (1 - cos(6.2832 * ($this->hour() - 14) / 24)) / 2;        $t -= max(0.0, $this->y - $ref) * 0.08;        if ($this->weather !== null) {            $t -= (['rain' => 3.0, 'storm' => 6.0, 'snow' => 5.0, 'fog' => 1.0][$this->weather['kind']] ?? 0.0) * min(1.0, 0.2 + (float) $this->weather['amount']);        }        return $t;    }    public function nearFire(float $r = 3.5): bool    {        if ($this->blazes !== [] && Wildfire::near($this, $r) !== null) {            return true;        }        foreach ($this->fires as $f) {            if ($f['minutes'] > 0 && hypot($f['x'] - $this->x, $f['z'] - $this->z) < $r) {                return true;            }        }        return false;    }    public function sheltered(): bool    {        if ($this->zone->cave) {            return true;        }        foreach ($this->zone->thingsNear($this->x, $this->z, 4.5) as $t) {            if ($t->kind === 'hut' || $t->kind === 'tent') {                return true;            }        }        return false;    }    public function environment(bool $sleeping = false): Environment    {        $e = new Environment();        $e->airTemp = $this->airTemp();        $e->nearFire = $this->nearFire();        $e->sheltered = $this->sheltered();        $raining = $this->weather !== null && in_array($this->weather['kind'], ['rain', 'storm'], true);        $e->wet = $this->swimming || ($raining && !$e->sheltered && (float) $this->weather['amount'] > 0.25) || $this->inv->wet > 0.6;        $e->effort = $sleeping ? 0.0 : ($this->climbing ? 2.0 : ($this->fight > 0 ? 1.0 : ($this->swimming ? 0.8 : ($this->sprinting ? 1.6 : ($this->running ? 1.0 : ($this->moving ? 0.3 : 0.05))))));        // the muscles: climbing, fighting, a heavy bag carried (more when walking with it)        $heavy = max(0.0, min(1.0, ($this->inv->load() - 0.5) * 2.0)) * ($this->moving ? 1.0 : 0.3);        $e->strain = $sleeping ? 0.0 : max($this->climbing ? 1.2 : 0.0, $this->fight > 0 ? 1.0 : 0.0, $heavy);        $e->sleeping = $sleeping;        $e->clothing = $this->inv->warmth();        foreach (Inventory::REGIONS as $r) {            $e->regions[$r] = $this->inv->regionWarmth($r);        }        $e->wetness = $this->inv->wet;        $e->resting = !empty($this->sleeping['rest']);        $e->hungerMul = $this->talents->hungerMul();        $e->thirstMul = $this->talents->thirstMul();        $e->coldResist = $this->talents->coldResist();        if ($sleeping) {            $e->comfort = $this->sleepComfort();        }        return $e;    }    private function tickBody(float $minutes, bool $sleeping): void    {        $pace = $this->zone->cave || $this->zone->id === 'plateau' ? 0.5 : ($this->airTemp() > 28 ? 1.3 : 1.0);        $rotten = $this->inv->spoil($minutes / 60, $pace);        if ($rotten !== []) {            $this->say('Ça sent mauvais dans ton sac : ' . Dialogues::list($rotten) . ' ' . (array_sum($rotten) > 1 ? 'se sont gâtés' : 's\'est gâté') . '. Fume ou sèche la viande pour la garder.');        }        $this->tickClothes($minutes);        $this->inv->carry = $this->body->carryFactor();        $this->body->loadRatio = $this->inv->load();        $this->body->tick($minutes, $this->environment($sleeping));        $this->inv->carry = $this->body->carryFactor();        foreach ($this->body->fitnessNews() as $news) {            $this->say($news);            $this->notices[] = $news;        }    }    /** The clothes get wet (rain, swimming, snow), dry (fire, sun) and wear out (time, water, walking in the snow). */    private function tickClothes(float $minutes): void    {        $inv = $this->inv;        $kind = $this->weather['kind'] ?? 'clear';        $amount = (float) ($this->weather['amount'] ?? 0);        $sheltered = $this->sheltered();        if ($this->swimming) {            $inv->wet = 1.0;        } elseif (!$sheltered && ($kind === 'rain' || $kind === 'storm')) {            $inv->wet = min(1.0, $inv->wet + 0.03 * $amount * $minutes);        } elseif (!$sheltered && $kind === 'snow') {            $inv->wet = min(1.0, $inv->wet + 0.008 * $amount * $minutes);        } elseif ($this->nearFire()) {            $inv->wet = max(0.0, $inv->wet - 0.06 * $minutes);        } else {            $inv->wet = max(0.0, $inv->wet - ($this->lightLevel() > 0.5 && !$this->zone->cave ? 0.012 : 0.005) * $minutes);        }        $wear = 0.004 * $minutes;        if ($this->swimming) {            $wear += 0.01 * $minutes;        }        $inv->wear($wear, ['worn', 'under', 'legs']);        $inv->wear($wear * 0.5, ['head', 'hands']);        if ($this->moving && $this->zone->biomeAt($this->x, $this->z) === 'jungle') {            $inv->wear(0.004 * $minutes, ['legs']);        }        // the spray of a waterfall soaks whoever stands under it        foreach ($this->zone->thingsNear($this->x, $this->z, 12.0) as $t) {            if ($t->kind === 'waterfall' && $this->underFall($t)) {                $inv->wet = min(1.0, $inv->wet + 0.25 * $minutes);            }        }        $feet = 0.003 * $minutes;        if ($this->moving && in_array($this->zone->biomeAt($this->x, $this->z), ['snow', 'ice', 'rock', 'redrock'], true)) {            $feet += 0.008 * $minutes;        }        $inv->wear($feet, ['feet']);    }    /** Fires burn down, the held torch too, the weather changes. */    private function burn(float $mins, bool $sleeping): void    {        $rain = $this->weather !== null ? (['rain' => 1.8, 'storm' => 3.0, 'snow' => 1.4][$this->weather['kind']] ?? 1.0) : 1.0;        if ($this->zone->cave) {            $rain = 1.0;        }        foreach ($this->fires as $k => $f) {            if (!empty($f['permanent'])) {                continue;            }            $this->fires[$k]['minutes'] = $f['minutes'] - $mins * $rain;            if ($this->fires[$k]['minutes'] <= 0) {                unset($this->fires[$k]);                if (hypot($f['x'] - $this->x, $f['z'] - $this->z) < 20) {                    $this->say('Le feu s\'éteint.');                }            }        }        $this->fires = array_values($this->fires);        if (!$sleeping && $this->torchLit()) {            if ($this->torchLeft <= 0) {                $this->torchLeft = (float) (Items::get('torch')['fuel'] ?? 40) * 4;            }            $this->torchLeft -= $mins * ($rain > 1.5 ? 2 : 1);            if ($this->torchLeft <= 0) {                $this->inv->remove('torch');                $this->torchLeft = 0.0;                $this->say($this->inv->has('torch') ? 'Ta torche s\'est consumée. Tu en allumes une autre.' : 'Ta torche s\'est consumée. Le noir revient.');            }        }        if ($this->zone->cave) {            $this->weather = null;            return;        }        if ($this->weather !== null && in_array($this->weather['kind'], ['rain', 'storm'], true) && (float) $this->weather['amount'] > 0.2) {            $this->flags['rain_at'] = $this->minutes;     // the soil stays wet a while: worms come up        }        $this->weatherLeft -= $mins;        if ($this->weather === null) {            $this->weather = ['kind' => 'clear', 'amount' => 0.0];        }        if ($this->weatherLeft <= 0) {            $this->weatherLeft = $this->rng->range(60, 240);            $table = match ($this->zone->id) {                'canyon' => ['clear' => 80, 'storm' => 8, 'fog' => 4, 'rain' => 8],                'plateau' => ['clear' => 40, 'snow' => 35, 'fog' => 15, 'storm' => 10],                'marsh' => ['fog' => 45, 'rain' => 30, 'clear' => 20, 'storm' => 5],                'jungle' => ['rain' => 40, 'clear' => 35, 'storm' => 15, 'fog' => 10],                'coast' => ['clear' => 45, 'fog' => 25, 'storm' => 15, 'rain' => 15],                default => ['clear' => 50, 'rain' => 25, 'storm' => 10, 'fog' => 15],            };            $r = $this->rng->next() * array_sum($table);            $kind = 'clear';            foreach ($table as $k => $w) {                $r -= $w;                if ($r < 0) {                    $kind = $k;                    break;                }            }            $this->weatherTarget = ['kind' => $kind, 'amount' => $kind === 'clear' ? 0.0 : round($this->rng->range(0.3, 1.0), 2)];        }        $this->rampWeather($mins);    }    /**     * The weather moves toward its target little by little: the old one fades out (its amount down to nothing), the     * new one comes in (its amount up), WEATHER_RAMP minutes for a whole change. The renderer smooths the rest.     */    private function rampWeather(float $mins): void    {        $target = $this->weatherTarget ?? $this->weather;        if ($target === null || $this->weather === null) {            return;        }        $step = $mins / self::WEATHER_RAMP;        $kind = $this->weather['kind'];        $amount = (float) $this->weather['amount'];        if ($kind !== $target['kind']) {            $amount -= $step;            if ($amount <= 0.0 || $kind === 'clear') {                $kind = $target['kind'];                $amount = 0.0;                $text = ['clear' => 'Le ciel se dégage.', 'rain' => 'Quelques gouttes : la pluie arrive.', 'storm' => 'Le ciel noircit : un orage approche.', 'fog' => 'Une brume monte lentement.', 'snow' => 'Les premiers flocons tombent.'][$kind] ?? null;                $this->say($text);            }        } else {            $amount += max(-$step, min($step, (float) $target['amount'] - $amount));        }        $this->weather = ['kind' => $kind, 'amount' => round(max(0.0, min(1.0, $amount)), 4)];    }    // ------------------------------------------------------------------------------------------ the scanner, the explored map    /** The sky starts turning into that weather (it ramps: WEATHER_RAMP minutes), for a while. */    public function setWeatherTarget(string $kind, float $amount, float $minutes = 120.0): void    {        $this->weather ??= ['kind' => 'clear', 'amount' => 0.0];        $this->weatherTarget = ['kind' => $kind, 'amount' => $kind === 'clear' ? 0.0 : max(0.0, min(1.0, $amount))];        $this->weatherLeft = $minutes;    }    /** 0..100: the scanner's battery. */    public function scanBattery(): float    {        return $this->scanBat;    }    /** The scanner is on for $dt seconds: the battery drains (about 3 minutes from full); false when it is flat. */    public function useScanner(float $dt): bool    {        $b = $this->scanBattery();        if ($b <= 0 || !$this->inv->has('scanner')) {            return false;        }        $this->scanBat = max(0.0, $b - 0.55 * $dt);        if (empty($this->flags['scan_revealed_' . (int) floor($this->minutes / 30)])) {            // a sweep maps the land around (a small area, once in a while)            $this->flags['scan_revealed_' . (int) floor($this->minutes / 30)] = true;            $this->revealAround($this->x, $this->z, $this->zone->cave ? 16.0 : 40.0);        }        return true;    }    /** The solar cell recharges by day outdoors, fast by the pod's panel, slowly from the colony's power cell. */    private function chargeScanner(float $dt): void    {        if (!$this->inv->has('scanner')) {            return;        }        $rate = 0.0;        if (!$this->zone->cave && $this->lightLevel() > 0.45) {            $rate += 0.12 * $this->lightLevel();        }        if ($this->zone->id === 'valley' && hypot($this->x - ZoneFactory::POD[0], $this->z - ZoneFactory::POD[1]) < 10) {            $rate += 3.0;        }        if ($this->inv->has('power_cell')) {            $rate += 0.25;        }        if ($rate > 0) {            $this->scanBat = min(100.0, $this->scanBat + $rate * $dt);        }        foreach (array_keys($this->flags) as $k) {            if (str_starts_with((string) $k, 'scan_revealed_') && (string) $k !== 'scan_revealed_' . (int) floor($this->minutes / 30)) {                unset($this->flags[$k]);            }        }    }    /** How far Rob sees the land around him for the map (metres): high ground and a clear day show more, caves little. */    public function sightRange(): float    {        if ($this->zone->cave) {            return $this->torchLit() ? 9.0 : 6.0;        }        $r = 34.0;        // high ground: compare with the land a little further around        $low = $this->y;        foreach ([[30, 0], [-30, 0], [0, 30], [0, -30]] as [$dx, $dz]) {            $low = min($low, $this->zone->heightAt($this->x + $dx, $this->z + $dz));        }        $r += max(0.0, min(40.0, ($this->y - $low) * 2.0));        $w = $this->weather;        if ($w !== null && $w['kind'] !== 'clear') {            $r *= 1 - ($w['kind'] === 'fog' ? 0.6 : 0.35) * (float) $w['amount'];        }        $r *= 0.55 + 0.45 * min(1.0, $this->lightLevel() * 2);        return max(12.0, $r);    }    /** Marks the cells around Rob as explored. */    public function reveal(): void    {        $this->revealAround($this->x, $this->z, $this->sightRange());    }    public function revealAround(float $x, float $z, float $r): void    {        $n = self::FOG_CELLS;        $id = $this->zone->id;        $bits = $this->explored[$id] ?? str_repeat("\0", intdiv($n * $n, 8));        $cell = $this->zone->size / $n;        $i0 = max(0, (int) floor(($x - $r) / $cell));        $i1 = min($n - 1, (int) floor(($x + $r) / $cell));        $j0 = max(0, (int) floor(($z - $r) / $cell));        $j1 = min($n - 1, (int) floor(($z + $r) / $cell));        $changed = false;        for ($j = $j0; $j <= $j1; $j++) {            for ($i = $i0; $i <= $i1; $i++) {                $cx = ($i + 0.5) * $cell - $x;                $cz = ($j + 0.5) * $cell - $z;                if ($cx * $cx + $cz * $cz > $r * $r + $cell * $cell * 0.5) {                    continue;                }                $k = $j * $n + $i;                $byte = ord($bits[$k >> 3]);                $bit = 1 << ($k & 7);                if (($byte & $bit) === 0) {                    $bits[$k >> 3] = chr($byte | $bit);                    $changed = true;                }            }        }        if ($changed || !isset($this->explored[$id])) {            $this->explored[$id] = $bits;            $this->exploredVersion++;        }    }    /** Has the map cell under (x, z) of the current zone been seen? */    public function isExplored(float $x, float $z): bool    {        $n = self::FOG_CELLS;        $bits = $this->explored[$this->zone->id] ?? null;        if ($bits === null) {            return false;        }        $cell = $this->zone->size / $n;        $i = (int) floor($x / $cell);        $j = (int) floor($z / $cell);        if ($i < 0 || $j < 0 || $i >= $n || $j >= $n) {            return false;        }        $k = $j * $n + $i;        return (ord($bits[$k >> 3]) & (1 << ($k & 7))) !== 0;    }    /** The explored bits of the current zone (FOG_CELLS² bits, row by row, z then x). */    public function exploredBits(): string    {        return $this->explored[$this->zone->id] ?? str_repeat("\0", intdiv(self::FOG_CELLS * self::FOG_CELLS, 8));    }    /** 0..1: how much of the zone has been seen. */    public function exploredShare(): float    {        $bits = $this->exploredBits();        $on = 0;        for ($k = 0, $n = strlen($bits); $k < $n; $k++) {            $on += substr_count(decbin(ord($bits[$k])), '1');        }        return $on / (self::FOG_CELLS * self::FOG_CELLS);    }    /** Takes off a garment / puts the item in hand back in the bag (clothes take a minute or two). */    public function unequip(string $slot): string    {        $id = $this->inv->$slot ?? null;        if ($id === null) {            return 'Rien à retirer.';        }        $hadLeft = $this->inv->handLeft;        $this->inv->unequip($slot);        if ($slot === 'hand' || $slot === 'handLeft') {            $back = $hadLeft === null && $this->inv->handLeft !== null ? ' Ta main gauche reprend : ' . mb_strtolower(Items::name($this->inv->handLeft)) . '.' : '';            return 'Tu ranges : ' . Items::name($id) . '.' . $back;        }        $this->passTime(['feet' => 2, 'head' => 0.5, 'hands' => 0.5, 'legs' => 3][$slot] ?? 3);        return 'Tu retires : ' . $this->inv->label($id) . '.';    }    /** A patch sewn on the most worn garment (needs the bone needle). */    private function mendClothes(): string    {        if (!$this->inv->hasTool('sew')) {            return 'Il te faut une aiguille d\'os pour rapiécer (artisanat : un os et ton couteau).';        }        $id = $this->inv->mend(35.0);        if ($id === null) {            return 'Tes vêtements n\'ont pas besoin d\'être rapiécés.';        }        $this->inv->remove('patch');        $this->passTime(15);        return 'Tu rapièces : ' . Items::name($id) . ' (état ' . (int) round($this->inv->condition($id)) . ' %).';    }    /** Time passes in one go (crafting, sleeping, fishing...): body, fires, weather. */    public function passTime(float $minutes, bool $sleeping = false): void    {        if (!($minutes > 0) || !is_finite($minutes)) {            return;        }        while ($minutes > 0 && !$this->body->dead()) {            $c = min(10.0, $minutes);            $minutes -= $c;            $this->minutes += $c;            $this->burn($c, $sleeping);            $this->tickBody($c, $sleeping);        }    }    private function regrow(): void    {        foreach ($this->zone->things as $t) {            if (isset($t->data['regrow']) && $t->data['regrow'] <= $this->minutes) {                unset($t->data['regrow']);                $t->left = ZoneFactory::leftOf($t->kind);                $this->touch($t);            }        }    }    // ------------------------------------------------------------------------------------------ messages, quests    public function say(?string $text): void    {        if ($text === null || $text === '') {            return;        }        if (end($this->log) === $text) {            return;        }        $this->log[] = $text;        if (count($this->log) > 80) {            array_splice($this->log, 0, count($this->log) - 80);        }    }    /** @return list<string> newest last */    public function messages(): array    {        return $this->log;    }    /** The news worth a toast since the last call (the scene shows them). @return list<string> */    public function takeNotices(): array    {        $n = $this->notices;        $this->notices = [];        return $n;    }    public function quest(): array    {        return Quest::state($this);    }    public function over(): ?string    {        return $this->body->dead() ? ($this->body->causeOfDeath() ?? 'Rob Calder est mort sur Ysor.') : null;    }    public function dead(): bool    {        return $this->body->dead();    }    public function won(): bool    {        return $this->won;    }    public function rng(): Rng    {        return $this->rng;    }    public function newId(): int    {        return ++$this->nextId;    }    public function villageCentre(): ?array    {        if ($this->zone->id !== 'canyon') {            return null;        }        return $this->village ??= ZoneFactory::villageCentre($this->seed);    }    /** Rob is hit: the body takes the wound, the screen flashes red. */    public function hitPlayer(string $part, string $kind, float $severity, string $who): void    {        // the clothes take a part of the blow, and suffer for it        $severity *= 1 - $this->inv->protection($part);        $severity *= $this->talents->woundMul();        $this->combat->stagger = max($this->combat->stagger, 0.45 * $this->talents->staggerMul());        $this->inv->wear(1.5 + 5 * $severity, match ($part) {            'lleg', 'rleg' => ['worn', 'legs', 'feet'], 'larm', 'rarm' => ['worn', 'under', 'hands'], 'head' => ['head'], default => ['worn', 'under'],        });        $this->body->wound($part, $kind, $severity);        $this->hurt = 1.0;        $this->fight = 2.0;        $where = self::PART_TEXT[$part] ?? '';        $this->say($severity > 0.5 ? $who . ' t\'atteint ' . $where . ' : blessure grave !' : $who . ' t\'atteint ' . $where . ' !');    }    /** Puts items in the bag; what does not fit is laid on the ground. Returns how many fitted. */    public function give(string $id, int $n = 1): int    {        $added = $this->inv->add($id, $n);        if ($added < $n) {            $this->drop($id, $n - $added);            $this->say('Ton sac est trop lourd : tu laisses ' . ($n - $added) . ' ' . Items::name($id) . ' par terre.');        }        return $added;    }    /**     * Lays items on the ground in a bundle (a crate that can be searched), a step in front of Rob (DROP_AHEAD metres, on a     * free spot: never inside a rock or a wall), joined to a bundle already there. The items are NOT taken from the bag:     * what did not fit in it (give(), a trade); dropBag() is the player's "Poser".     */    public function drop(string $id, int $n): void    {        if ($n <= 0) {            return;        }        $x = $this->x + sin($this->yaw) * self::DROP_AHEAD;        $z = $this->z + cos($this->yaw) * self::DROP_AHEAD;        if ($this->zone->solidAt($x, $z) || $this->zone->waterDepth($x, $z) > 0.4) {            $x = $this->x + sin($this->yaw) * 0.6;       // a wall or the water ahead: at Rob's feet, just in front            $z = $this->z + cos($this->yaw) * 0.6;        }        [$x, $z] = Solids::freeSpot($this->zone, $x, $z, 0.35);        foreach ($this->zone->thingsNear($x, $z, 1.5) as $t) {            if (!empty($t->data['bundle'])) {                $t->data['loot'][$id] = ($t->data['loot'][$id] ?? 0) + $n;                $t->data['dropped'] = $this->minutes;                $this->touch($t);                return;            }        }        $this->addThing('crate', $x, $z, ['label' => 'Affaires posées', 'bundle' => true, 'dropped' => $this->minutes, 'loot' => [$id => $n]], $this->yaw, 0.5);    }    /** "Poser": $n of an item taken out of the bag (its hand / worn slot freed when none is left) and laid in front of Rob. */    public function dropBag(string $id, int $n = 1): int    {        $n = min($n, $this->inv->count($id));        if ($n <= 0 || !$this->inv->remove($id, $n)) {            return 0;        }        $this->drop($id, $n);        return $n;    }    // ------------------------------------------------------------------------------------------ things and diffs    public function addThing(string $kind, float $x, float $z, array $data = [], float $yaw = 0.0, float $scale = 1.0): Thing    {        $t = new Thing($this->nextThing++, $kind, $x, $this->zone->heightAt($x, $z), $z, $yaw, $scale, ZoneFactory::leftOf($kind), $data);        $this->zone->addThing($t);        $this->diffs[$this->zone->id]['add'][$t->id] = self::thingArray($t);        return $t;    }    public function removeThing(Thing $t): void    {        $this->zone->removeThing($t);        $id = $this->zone->id;        if ($t->id >= self::ADDED) {            unset($this->diffs[$id]['add'][$t->id]);        } else {            unset($this->diffs[$id]['mod'][$t->id]);            $this->diffs[$id]['del'][$t->id] = true;        }    }    /** Records a change of a thing (left, data, kind) for the save. */    public function touch(Thing $t): void    {        $id = $this->zone->id;        $this->zone->version++;        if ($t->id >= self::ADDED) {            $this->diffs[$id]['add'][$t->id] = self::thingArray($t);        } else {            $this->diffs[$id]['mod'][$t->id] = ['kind' => $t->kind, 'left' => $t->left, 'data' => $t->data];        }    }    private static function thingArray(Thing $t): array    {        return ['id' => $t->id, 'kind' => $t->kind, 'x' => $t->x, 'z' => $t->z, 'yaw' => $t->yaw, 'scale' => $t->scale, 'left' => $t->left, 'data' => $t->data];    }    private function applyDiff(Zone $z): void    {        $d = $this->diffs[$z->id] ?? null;        if ($d === null) {            return;        }        foreach (array_keys($d['del'] ?? []) as $id) {            $t = $z->thing((int) $id);            if ($t !== null) {                $z->removeThing($t);            }        }        foreach ($d['mod'] ?? [] as $id => $m) {            $t = $z->thing((int) $id);            if ($t !== null) {                $t->kind = (string) $m['kind'];                $t->left = (int) $m['left'];                $t->data = (array) $m['data'];            }        }        foreach ($d['add'] ?? [] as $a) {            $z->addThing(new Thing((int) $a['id'], (string) $a['kind'], (float) $a['x'], $z->heightAt((float) $a['x'], (float) $a['z']), (float) $a['z'], (float) $a['yaw'], (float) $a['scale'], (int) $a['left'], (array) $a['data']));        }    }    // ------------------------------------------------------------------------------------------ zones    private function enterZone(string $id): void    {        $this->chestOpen = null;        if (isset($this->zone)) {            $keep = [];            foreach ($this->fires as $f) {                if (empty($f['permanent'])) {                    $keep[] = $f;                }            }            $this->zoneFires[$this->zone->id] = ['at' => $this->minutes, 'list' => $keep];            if ($this->blazes !== []) {                $this->blazeStore[$this->zone->id] = ['at' => $this->minutes, 'list' => $this->blazes];            }        }        if (!isset($this->zones[$id])) {            $z = ZoneFactory::make($id, $this->seed);            $this->applyDiff($z);            $this->zones[$id] = $z;        }        $this->zone = $this->zones[$id];        $this->fires = [];        foreach ($this->zone->things as $t) {            if ($t->kind === 'campfire' && !empty($t->data['permanent'])) {                $this->fires[] = ['x' => $t->x, 'z' => $t->z, 'minutes' => 999.0, 'permanent' => true];            }        }        $stored = $this->zoneFires[$id] ?? null;        if ($stored !== null) {            $elapsed = $this->minutes - $stored['at'];            foreach ($stored['list'] as $f) {                if ($f['minutes'] - $elapsed > 0) {                    $f['minutes'] -= $elapsed;                    $this->fires[] = $f;                }            }            unset($this->zoneFires[$id]);        }        $this->blazes = [];        $old = $this->blazeStore[$id] ?? null;        if ($old !== null) {            unset($this->blazeStore[$id]);            foreach ($old['list'] as $f) {                // the fire went on while Rob was away: what had fuel left still burns, the rest is ash                $f['fuel'] -= ($this->minutes - $old['at']) / self::TIME_RATE * 0.25;                if ($f['fuel'] > 0) {                    $this->blazes[] = $f;                } else {                    $this->burnt[$id][] = [round($f['x'], 1), round($f['z'], 1), round($f['r'] + 1, 1)];                }            }        }        $this->creatures = [];        $this->talk = null;        $first = empty($this->flags['visited_' . $id]) && $id !== 'valley';        $this->flags['visited_' . $id] = true;        $this->combat->disengage();        if ($first) {            $this->gainXp(Talents::FEAT_XP['zone'], true);        }        $this->revealTimer = 0.0;        $this->onGround = true;        $this->vy = 0.0;        $goal = ['caves1' => 'enter_caves', 'caves2' => 'reach_caves2', 'canyon' => 'reach_canyon', 'plateau' => 'reach_plateau',            'jungle' => 'reach_jungle', 'caves3' => 'reach_caves3', 'marsh' => 'reach_marsh', 'coast' => 'reach_coast'][$id] ?? null;        if ($goal !== null) {            $this->flags['q_' . $goal] = true;        }        if ($this->zone->cave) {            $this->weather = null;        } elseif ($this->weather === null) {            $this->weatherLeft = 0.0;        }        Folk::populate($this);        if ($id === 'jungle' && empty($this->flags['croc_dead'])) {            // the Old Jaw, queen of the river, downstream of the Ouvi village            $n = $this->riverNoise();            $v = 0.64;            $c = Wildlife::make($this, 'river_croc', ZoneFactory::riverX($v, $n) * 512 - 6, $v * 512);            $c->health = 320.0;            $c->data['boss'] = true;            $c->data['fixed'] = true;            $this->creatures[] = $c;        }    }    /** Goes through an exit to another zone. */    public function travel(array $exit): string    {        $this->enterZone((string) $exit['to']);        $this->x = (float) $exit['toX'];        $this->z = (float) $exit['toZ'];        $this->y = $this->zone->heightAt($this->x, $this->z);        $this->vy = 0.0;        // face away from the door Rob came through        $back = null;        foreach ($this->zone->exits as $e) {            if ($back === null || hypot($e['x'] - $this->x, $e['z'] - $this->z) < hypot($back['x'] - $this->x, $back['z'] - $this->z)) {                $back = $e;            }        }        if ($back !== null) {            $this->yaw = atan2($this->x - $back['x'], $this->z - $back['z']);        }        Wildlife::spawn($this, true);        Companions::arrive($this);        $this->burn(0.0, false);        $text = '— ' . $this->zone->name . ' — ' . (self::ZONE_TEXT[$this->zone->id] ?? '');        $this->say($text);        Quest::check($this);        return $text;    }    // ------------------------------------------------------------------------------------------ dialogues    public function talkingTo(): ?Npc    {        if ($this->talk === null) {            return null;        }        foreach ($this->npcs as $n) {            if ($n->id === $this->talk['id']) {                return $n;            }        }        return null;    }    /** Opens the orders of the tame cub (a small dialogue). */    public function talkToPet(): void    {        $this->talk = ['id' => -1, 'node' => 'root', 'say' => null, 'pet' => true];    }    public function talkTo(Npc $n): string    {        $this->talk = ['id' => $n->id, 'node' => 'root', 'say' => null];        $d = $this->dialogue();        return $d === null ? '' : $n->name . ' : « ' . $d['text'] . ' »';    }    /** @return array{npc: string, text: string, choices: list<string>, tones?: list<string>, attitude?: string, who?: string}|null */    public function dialogue(): ?array    {        if ($this->talk !== null && ($this->talk['pet'] ?? false) === true) {            $node = Companions::petNode($this);            if ($this->talk['say'] !== null) {                $node['text'] = $this->talk['say'];            }            return ['npc' => 'Le petit', 'text' => $node['text'], 'choices' => array_map(fn (array $c): string => $c[0], $node['choices']), 'tones' => [], 'attitude' => 'fidèle', 'who' => 'un petit rôdeur de nuit apprivoisé'];        }        $n = $this->talkingTo();        if ($n !== null && People::keyOf($n) !== null) {            $key = (string) People::keyOf($n);            $node = Talk::node($this, $n, $this->talk['node'], $this->talk['say']);            $tones = [];            $choices = [];            foreach ($node['choices'] as $c) {                $choices[] = $c[0];                $tones[] = $c[2] ?? 'neutral';            }            return ['npc' => $n->name, 'text' => $node['text'], 'choices' => $choices, 'tones' => $tones, 'attitude' => People::attitude($this, $key),                'who' => People::WHO[$key][5] . ' (' . People::PERSONALITY[People::personality($key)] . ')'];        }        if ($n === null) {            $this->talk = null;            return null;        }        $node = Dialogues::node($this, $n, $this->talk['node'], $this->talk['say']);        $choices = [];        foreach ($node['choices'] as $c) {            $choices[] = $c[0];        }        return ['npc' => $n->name, 'text' => $node['text'], 'choices' => $choices];    }    public function choose(int $i): void    {        if ($this->talk !== null && ($this->talk['pet'] ?? false) === true) {            $c = Companions::petNode($this)['choices'][$i] ?? null;            if ($c === null || $c[1] === 'end') {                $this->talk = null;                return;            }            $text = Companions::petDo($this, substr($c[1], 3));            $this->say($text);            $this->talk = null;            return;        }        $n = $this->talkingTo();        if ($n === null) {            $this->talk = null;            return;        }        $key = People::keyOf($n);        if ($key !== null) {            $node = Talk::node($this, $n, $this->talk['node'], $this->talk['say']);            $c = $node['choices'][$i] ?? null;            if ($c === null) {                return;            }            $tone = $c[2] ?? 'neutral';            $mood = $tone !== 'neutral' ? People::react($this, $key, $tone) : '';            $target = $c[1];            if ($target === 'end') {                $this->talk = null;                if ($mood !== '') {                    $this->say($n->name . ' ' . lcfirst(trim($mood, '()')));                }            } elseif (str_starts_with($target, 'node:')) {                $this->talk['node'] = substr($target, 5);                $this->talk['say'] = null;                if ($mood !== '') {                    $this->talk['say'] = $mood . ' ' . Talk::node($this, $n, $this->talk['node'], null)['text'];                }            } elseif (str_starts_with($target, 'do:')) {                [$text, $next] = Talk::run($this, $n, substr($target, 3));                if ($next === 'end' || $this->talk === null) {                    $this->talk = null;                    $this->say($n->name . ' : « ' . $text . ' »');                } else {                    $this->talk['node'] = $next;                    $this->talk['say'] = ($mood !== '' ? $mood . ' ' : '') . $text;                }            }            Quest::check($this);            return;        }        $node = Dialogues::node($this, $n, $this->talk['node'], $this->talk['say']);        $c = $node['choices'][$i] ?? null;        if ($c === null) {            return;        }        $target = $c[1];        if ($target === 'end') {            $this->talk = null;        } elseif (str_starts_with($target, 'node:')) {            $this->talk['node'] = substr($target, 5);            $this->talk['say'] = null;        } elseif (str_starts_with($target, 'do:')) {            [$text, $next] = Dialogues::run($this, $n, substr($target, 3));            if ($this->talk !== null) {                $this->talk['node'] = $next;                $this->talk['say'] = $text;            }        }        Quest::check($this);    }    public function closeDialogue(): void    {        $this->talk = null;    }    // ------------------------------------------------------------------------------------------ fighting    /**     * Uses the weapon in hand (Weapons::STATS) on what is in front: a melee blow (stronger as a counter, right after a beast     * lunged), or a shot at the crosshair (ammunition, energy cells, flares that set fire and scare). Weapons wear; worn out     * they break. Returns what happened, null if not ready.     */    public function attack(): ?string    {        if ($this->attackCool > 0 || $this->dead()) {            return null;        }        $hand = $this->inv->hand !== null && $this->inv->has($this->inv->hand) ? $this->inv->hand : null;        $this->attackCool = (float) Weapons::of($hand)['cool'];        return $this->blow($hand);    }    /**     * A blow begins (the attack key, the click, the pad's RT, the phone's button): the anticipation, then the strike     * Weapons::windup() seconds later (advanceSwing() lands it), then the recovery until Weapons::duration(). $side:     * right (the weapon) or left (a one-handed item in the left hand, weaker). False: not ready, or nothing to fire.     */    public function swing(string $side = 'right'): bool    {        if ($this->swing !== null || $this->attackCool > 0 || $this->dead() || $this->talk !== null || $this->sleeping !== null) {            return false;        }        $item = $side === 'left' ? $this->inv->handLeft : $this->inv->hand;        $item = $item !== null && $this->inv->has($item) ? $item : null;        $w = Weapons::of($item);        if ($w['type'] === 'ranged' && Weapons::ammo($this->inv, $item) === null && !((int) ($w['shots'] ?? 0) > 0 && $this->cellShots > 0)) {            $this->say('Plus de munitions : il te faut ' . Weapons::ammoLabel($item) . '.');            $this->attackCool = 0.5;            return false;        }        $this->attackCool = Weapons::duration($item);        $this->fight = 1.5;        // combat mode: a melee blow is aimed first (the precision cursor), the next press strikes        $aim = $this->combat->active && $w['type'] === 'melee';        $this->swing = ['item' => $item, 'side' => $side, 'kind' => Weapons::anim($item), 't' => 0.0, 'at' => $aim ? 99.0 : Weapons::windup($item),            'dur' => $aim ? 99.0 : $this->attackCool, 'counter' => !$aim && $this->counterNow(), 'done' => false, 'hit' => false, 'aim' => $aim, 'mult' => 1.0, 'grade' => null];        if ($aim) {            $this->aimPose();        }        if ($w['type'] === 'melee') {            Wildlife::provoke($this, 5.5);     // a blade swung near the crawlers held off by the flame (they keep 4.5 m): they feel threatened        }        return true;    }    /** A blow is being aimed (the precision cursor sweeps the bar). */    public function aiming(): bool    {        return $this->swing !== null && !empty($this->swing['aim']);    }    /** 0..1: where the precision cursor is on its bar (0: none). */    public function aimPos(): float    {        return $this->aiming() ? min(1.0, (float) $this->swing['t'] / Combat::AIM) : 0.0;    }    /** The aimed blow strikes now: its grade by the cursor's place (critical in the centre, weak at the edges). */    public function release(): void    {        if (!$this->aiming()) {            return;        }        [$grade, $mult] = Combat::grade($this->aimPos(), $this->talents->sweetWidth());        $item = $this->swing['item'];        $wind = Weapons::windup($item);        $this->swing['aim'] = false;        $this->swing['grade'] = $grade;        $this->swing['mult'] = $mult;        $this->swing['counter'] = $this->counterNow();        $this->swing['at'] = $this->swing['t'] + max(0.06, $wind * 0.5);        $this->swing['dur'] = $this->swing['at'] + max(0.25, Weapons::duration($item) - $wind);        $this->attackCool = $this->swing['dur'] - $this->swing['t'];        $this->combat->lastGrade = $grade;        $this->combat->lastGradeAt = $this->clock;    }    /** While aiming, the weapon stays drawn back (the view's anticipation, near its peak). */    private function aimPose(): void    {        $item = $this->swing['item'];        $this->swing['at'] = $this->swing['t'] + max(0.05, Weapons::windup($item) * 0.25);        $this->swing['dur'] = $this->swing['at'] + max(0.25, Weapons::duration($item) - Weapons::windup($item));    }    /**     * Is a blow pressed now a counter? Right after a beast lunged (0.6 s, + the timing talent), or while a foe within     * reach is at the end of its wind-up (its blow would land in the next 0.35 s, + the talent).     */    public function counterNow(): bool    {        $bonus = $this->talents->counterBonus();        $since = $this->clock - $this->parryAt;        if ($since >= 0 && $since < 0.6 + $bonus) {            return true;        }        foreach (array_merge($this->creatures, $this->npcs) as $t) {            $wu = (float) ($t->data['wu'] ?? 0);            if ($wu > 0 && $wu < 0.35 + $bonus && Combat::foe($t) && hypot($t->x - $this->x, $t->z - $this->z) < 4.0) {                return true;            }        }        return false;    }    /**     * The dodge (combat mode: the jump key): a quick step back, or aside ($side -1 left, 1 right), DODGE metres; the     * blows that land meanwhile miss. Costs a little rest; not in the water, on the raft, climbing or in the air.     */    public function dodge(float $side = 0.0): bool    {        $c = $this->combat;        if ($c->dodgeCool > 0 || $c->dodgeMove > 0 || $this->dead() || $this->swimming || $this->raft !== null || $this->climbing            || !$this->onGround || $this->body->vitals()['fatigue'] < 4) {            return false;        }        $fx = sin($this->yaw);        $fz = cos($this->yaw);        if ($side > 0.3 || $side < -0.3) {            $s = $side > 0 ? 1.0 : -1.0;            $c->dodgeDir = [-$fz * $s, $fx * $s];      // right = (-cos yaw, sin yaw)        } else {            $c->dodgeDir = [-$fx, -$fz];        }        $c->dodgeMove = Combat::DODGE_TIME;        $c->dodgeSafe = Combat::INVULNERABLE + $this->talents->dodgeBonus();        $c->dodgeCool = Combat::DODGE_COOL;        $this->body->exert(Combat::DODGE_COST * $this->talents->dodgeCostMul());        $this->fight = 1.5;        $this->events[] = ['dodge', 0.0, 0.8];        return true;    }    /** Rob pushed by ($dx, $dz) metres (the dodge), against walls and solid things like a step. */    public function shove(float $dx, float $dz): void    {        $this->tryMove($this->x + $dx, $this->z);        $this->tryMove($this->x, $this->z + $dz);    }    /** Experience: the level goes up (a toast, a sound, one talent point each). $tell: "+N XP" in the log. */    public function gainXp(float $xp, bool $tell = false): int    {        $levels = $this->talents->gain($xp);        if ($tell && $xp >= 1) {            $this->say('+' . (int) round($xp) . ' XP');        }        if ($levels > 0) {            $l = $this->talents->level();            $text = 'Niveau ' . $l . ' ! +' . $levels . ' point' . ($levels > 1 ? 's' : '') . ' de talent : ouvre l\'onglet Talents (L).';            $this->say($text);            $this->notices[] = $text;            $this->events[] = ['levelup', 0.0, 1.0];        }        return $levels;    }    /** The blow under way: aimed (the cursor), then the strike at its time (if the item is still in hand), then the recovery. */    private function advanceSwing(float $dt): void    {        if ($this->swing === null) {            return;        }        $this->swing['t'] += $dt;        if (!empty($this->swing['aim'])) {            if ($this->swing['t'] >= Combat::AIM) {                $this->release();       // held to the end of the bar: a weak blow            } else {                $this->aimPose();                return;            }        }        if (!$this->swing['done'] && $this->swing['t'] >= $this->swing['at']) {            $this->swing['done'] = true;            $item = $this->swing['item'];            if ($item === null || $this->inv->holds($item)) {                $before = $this->hitAt;                $this->blow($item, $this->swing['counter'], ($this->swing['side'] === 'left' ? 0.75 : 1.0) * (float) $this->swing['mult'], $this->swing['grade']);                $this->swing['hit'] = $this->hitAt !== $before;            }        }        if ($this->swing['t'] >= $this->swing['dur']) {            $this->swing = null;        }    }    /** 0..1 through the blow under way (0: none), for the view. */    public function swingPhase(): float    {        return $this->swing === null ? 0.0 : min(1.0, $this->swing['t'] / max(0.01, $this->swing['dur']));    }    /**     * The left hand's action (V, the right button clicked, the pad's LT, the phone's TORCHE): a torch is brandished     * (crawlers flee, night beasts back off), another item strikes; an empty left hand says how to fill it.     */    public function leftHand(): ?string    {        if ($this->dead() || $this->talk !== null || $this->sleeping !== null) {            return null;        }        $left = $this->inv->handLeft !== null && $this->inv->has($this->inv->handLeft) ? $this->inv->handLeft : null;        if (Inventory::isShield($left)) {            return null;        // a shield is held up (guard()), not swung        }        if ($left === 'torch' || ($left === null && $this->torchLit())) {            return $this->brandish();        }        if ($left !== null) {            return $this->swing('left') ? '' : null;        }        $text = 'Ta main gauche est vide : une torche s\'y tient (inventaire), elle éloigne les bêtes.';        $this->say($text);        return $text;    }    /**     * The shield held up while the left hand's action is held (V, the right button, the pad's LT, the phone's button):     * not while striking with the right hand, swimming, on the raft or too tired; true when it is up.     */    public function guard(bool $hold): bool    {        $up = $hold && $this->inv->shield() !== null && $this->swing === null && !$this->swimming && $this->raft === null            && !$this->dead() && $this->body->vitals()['fatigue'] > self::GUARD_MIN;        if ($up && $this->guardAt === null) {            $this->guardAt = $this->clock;            $this->events[] = ['guard', 0.0, 1.0];        } elseif (!$up && $this->guardAt !== null) {            $this->guardAt = null;            $this->guardDownAt = $this->clock;        }        if ($hold && !$up && !$this->lastLeft && $this->inv->shield() !== null && $this->body->vitals()['fatigue'] <= self::GUARD_MIN) {            $this->say('Trop épuisé pour lever le bouclier.');        }        return $up;    }    /** 0..1: how high the shield is (raised in GUARD_UP, lowered in GUARD_DOWN), for the view. */    public function guardPhase(): float    {        if ($this->guardAt !== null) {            return max(0.0, min(1.0, ($this->clock - $this->guardAt) / self::GUARD_UP));        }        return max(0.0, 1.0 - ($this->clock - $this->guardDownAt) / self::GUARD_DOWN);    }    /**     * What the shield does to a blow from $from (a beast, a person; $ranged: an arrow) of $severity: 'none' (no shield up,     * or the blow comes from the side or behind), 'parry' (the guard went up right as it landed: no harm) or 'block' (the     * share Weapons::SHIELDS stops; 'sev' is what is left). Pure: nothing changes.     * @return array{0: string, 1: float}     */    public function shieldCheck(Creature|Npc $from, float $severity, bool $ranged = false): array    {        $id = $this->inv->shield();        $s = Weapons::shield($id);        if ($s === null || $this->guardAt === null) {            return ['none', $severity];        }        $dx = $from->x - $this->x;        $dz = $from->z - $this->z;        $d = max(0.001, hypot($dx, $dz));        if (($dx * sin($this->yaw) + $dz * cos($this->yaw)) / $d < self::GUARD_ARC) {            return ['none', $severity];        }        if (!$ranged && $this->clock - $this->guardAt <= self::PARRY + $this->talents->counterBonus()) {            return ['parry', 0.0];        }        return ['block', $severity * (1.0 - $s['block'])];    }    /**     * A blow from $from meets the shield: parried (the foe reels, its blow broken), blocked (the rest of it bruises the     * shield arm; the shield wears, the arm tires) or not at all (false: the caller wounds Rob as usual). True when the     * shield dealt with it.     */    public function blockBlow(Creature|Npc $from, float $severity, string $who, bool $ranged = false): bool    {        [$res, $left] = $this->shieldCheck($from, $severity, $ranged);        if ($res === 'none') {            return false;        }        $id = (string) $this->inv->shield();        $s = (array) Weapons::shield($id);        $this->fight = 2.0;        $this->combat->engage($this, $from);        if ($res === 'parry') {            $from->data['stagger'] = self::STAGGER_PARRY;            unset($from->data['wu'], $from->data['wuT']);            if ($from instanceof Creature) {                $from->cooldown = max($from->cooldown, (float) (Wildlife::SPECIES[$from->species]['every'] ?? 1.5));            } else {                $from->data['cool'] = max((float) ($from->data['cool'] ?? 0), 1.6);            }            $this->body->exert((float) $s['tire'] * 0.5);            $this->wearShield($id, (float) $s['wear'] * 0.3);            $this->gainXp(Talents::FEAT_XP['counter']);            $this->parryAt = $this->clock;          // a blow right after a parry is a counter            $this->combat->popup('Parade !', [255, 226, 140]);            $this->events[] = ['parry', 0.0, 1.0];            $this->say('Parade ! ' . $who . ' rebondit sur ton bouclier et vacille.');            return true;        }        $this->body->exert((float) $s['tire'] * (0.6 + $severity));        $this->wearShield($id, (float) $s['wear'] * (0.5 + $severity));        $this->combat->popup('Bloqué −' . (int) round($s['block'] * 100) . ' %', [180, 214, 240]);        $this->events[] = ['block', 0.0, 1.0];        if ($left >= 0.06) {            $this->hitPlayer('larm', 'bruise', $left, $who);        } else {            $this->combat->stagger = max($this->combat->stagger, 0.15);            $this->say('Ton bouclier encaisse le coup : ' . mb_strtolower($who) . ' ne passe pas.');        }        return true;    }    /** Wears the shield on the arm; worn out, it falls apart (and the guard drops). */    private function wearShield(string $id, float $amount): void    {        $amount *= $this->talents->wearMul();        $c = $this->inv->condition($id) - $amount;        if ($c <= 0) {            $this->inv->remove($id);            unset($this->inv->cond[$id]);            $this->guardAt = null;            $this->guardDownAt = $this->clock;            $this->say('Ton bouclier vole en éclats : ' . mb_strtolower(Items::name($id)) . ' est hors d\'usage.');            return;        }        $this->inv->cond[$id] = $c;        if ($c < 25 && $c + $amount >= 25) {            $this->say(Items::name($id) . ' ne tient plus qu\'à un fil : répare-le.');        }    }    /** 0..1 through the torch's sweep (0: none). */    public function brandishPhase(): float    {        $t = $this->clock - $this->brandishAt;        return $t >= 0 && $t < self::BRANDISH ? max(0.001, $t / self::BRANDISH) : 0.0;    }    /**     * The lit torch swept before Rob: the crawlers within BRANDISH_REACH flee for a while, a night prowler or a brute     * close by backs off, one right in front is singed. It eats a little of the torch.     */    public function brandish(): ?string    {        if (!$this->torchLit() || $this->dead()) {            return null;        }        if ($this->clock - $this->brandishAt < self::BRANDISH) {            return null;        }        $this->brandishAt = $this->clock;        $this->fight = 1.5;        $this->events[] = ['brandish', 0.0, 1.0];        $this->torchLeft -= 2.0;        $fled = 0;        foreach ($this->creatures as $c) {            if (!empty($c->data['companion'])) {                continue;            }            $d = Wildlife::dist($this, $c);            $scare = match ($c->species) {                'crawler' => $d < self::BRANDISH_REACH ? $this->rng->range(5.0, 8.0) : 0.0,                'stalker', 'stalker_cub', 'climber', 'swarm' => $d < 7.0 && ($this->isNight() || $this->zone->cave) ? 4.0 : 0.0,                'glacier_brute', 'river_croc', 'burrower' => $d < 4.0 ? 1.5 : 0.0,                default => 0.0,            };            if ($scare > 0) {                $c->data['scared'] = max((float) ($c->data['scared'] ?? 0), $scare);                $c->data['starve'] = 0.0;                $c->data['cornered'] = 0.0;                $fled++;            }        }        $front = $this->targetAhead(2.4, 0.5);        if ($front !== null && $front[0] instanceof Creature) {            Wildlife::hurt($this, $front[0], 3.0);            $this->hitAt = $this->clock;        }        $text = $fled > 0 ? 'Tu balaies l\'air de ta torche : ' . ($fled > 1 ? 'les bêtes reculent' : 'la bête recule') . ' devant la flamme.' : 'Tu brandis ta torche.';        $this->say($text);        return $text;    }    /** Right and left hands exchanged (X). */    public function swapHands(): string    {        $err = $this->inv->swapHands();        if ($err !== null) {            $this->say($err);            return $err;        }        $r = $this->inv->hand !== null ? mb_strtolower(Items::name($this->inv->hand)) : 'rien';        $l = $this->inv->handLeft !== null ? mb_strtolower(Items::name($this->inv->handLeft)) : 'rien';        $text = 'Tu changes de main : ' . $r . ' à droite, ' . $l . ' à gauche.';        $this->say($text);        return $text;    }    /**     * The blow itself, now: melee on what is in front (stronger as a counter, right after a beast lunged; weaker from     * the left hand: $scale), or a shot at the crosshair.     */    private function blow(?string $hand, ?bool $counter = null, float $scale = 1.0, ?string $grade = null): string    {        $w = Weapons::of($hand);        $this->fight = 1.5;        $skill = $this->body->fightFactor() * $scale;        if ($w['type'] === 'ranged') {            return $this->shoot((string) $hand, $w, $skill);        }        $this->events[] = ['swing', 0.0, 1.0];        $this->body->train('force', 1.0);        $dmg = (float) $w['damage'] * $skill * $this->body->strengthFactor() * $this->talents->damageMul() * $this->rng->range(0.8, 1.2);        $target = $this->targetAhead((float) $w['range'], 0.55);        if ($target === null) {            if ($grade !== null) {                $this->combat->popup('Dans le vide', [200, 210, 220]);            }            return 'Tu frappes dans le vide.';        }        $counter ??= $this->counterNow();        if ($counter) {            $dmg *= 1.6;            $this->parryAt = -9.0;            $t = $target[0];            if ((float) ($t->data['wu'] ?? 0) > 0) {                // struck before its blow landed: it is broken off, the foe staggers                unset($t->data['wu'], $t->data['wuT']);                $t->data['stagger'] = 0.7;                if ($t instanceof Creature) {                    $t->cooldown = max($t->cooldown, (float) (Wildlife::SPECIES[$t->species]['every'] ?? 1.5) * 0.8);                } else {                    $t->data['cool'] = max((float) ($t->data['cool'] ?? 0), 1.2);                }            }            $this->gainXp(Talents::FEAT_XP['counter']);            $this->combat->popup('Contre !', [255, 214, 120]);            $this->events[] = ['counter', 0.0, 1.0];        }        if ($grade === 'crit') {            $this->combat->popup('CRITIQUE ×1,5', [255, 120, 90]);            $this->events[] = ['crit', 0.0, 1.0];        } elseif ($grade === 'weak') {            $this->combat->popup('Faible ×0,7', [170, 186, 200]);        }        if ($hand !== null) {            $this->wearWeapon($hand, (float) $w['wear']);        }        if (!empty($w['fire']) && $target[0] instanceof Creature) {            $target[0]->data['scared'] = 6.0;        }        return $this->strike($target[0], $dmg, $counter ? 'Contre parfait !' : ($grade === 'crit' ? 'Coup critique !' : ($hand !== null ? 'Tu frappes' : 'Tu cognes à mains nues')));    }    private function shoot(string $hand, array $w, float $skill): string    {        $ammo = Weapons::ammo($this->inv, $hand);        $shots = (int) ($w['shots'] ?? 0);        if ($shots > 0 && $this->cellShots > 0) {            $ammo = 'energy_cell';        }        if ($ammo === null) {            $text = 'Plus de munitions : il te faut ' . Weapons::ammoLabel($hand) . '.';            $this->say($text);            return $text;        }        if ($shots > 0) {            if ($this->cellShots <= 0) {                $this->inv->remove('energy_cell');                $this->cellShots = $shots;            }            $this->cellShots--;        } else {            $this->inv->remove($ammo);        }        $this->wearWeapon($hand, (float) $w['wear']);        $this->events[] = [$hand === 'pulse_rifle' || $hand === 'plasma_gun' ? 'zap' : ($hand === 'flare_gun' ? 'flare' : 'bow'), 0.0, 1.0];        $range = (float) $w['range'];        $target = $this->targetAhead($range, 0.985);        $fx = sin($this->yaw);        $fz = cos($this->yaw);        if (!empty($w['scare'])) {            foreach ($this->creatures as $c) {                if (empty($c->data['companion']) && Wildlife::dist($this, $c) < 40 && in_array($c->species, ['grazer', 'bird', 'climber', 'stalker'], true)) {                    $c->data['scared'] = 8.0;                }            }        }        $acc = (float) ($w['acc'] ?? 0.9);        if ($target === null || !$this->rng->chance($acc - $target[1] / ($range * 1.6))) {            if (!empty($w['fire'])) {                $d = $target[1] ?? $range * 0.6;                Wildfire::ignite($this, $this->x + $fx * $d, $this->z + $fz * $d, 0.8);            }            $text = $ammo === 'energy_cell' ? 'Le tir siffle et se perd au loin.' : 'Ton tir se perd au loin.';            $this->say($text);            return $text;        }        $dmg = ((float) $w['damage'] + (float) (Items::get($ammo)['damage'] ?? 0) * ($shots > 0 ? 0 : 1)) * $skill;        if (!empty($w['fire'])) {            Wildfire::ignite($this, $target[0]->x, $target[0]->z, 0.6);        }        if (in_array($ammo, ['arrow', 'arrow_bone', 'arrow_metal', 'bolt'], true) && $this->rng->chance(0.45)) {            $this->give($ammo);      // the arrow is pulled from the body        }        return $this->strike($target[0], $dmg, $ammo === 'energy_cell' ? 'Ton tir d\'énergie frappe' : 'Ton tir touche');    }    /** Wears the weapon in hand; worn out, it breaks. */    private function wearWeapon(string $id, float $amount): void    {        $amount *= $this->talents->wearMul();        if ($amount <= 0) {            return;        }        $c = $this->inv->condition($id) - $amount;        if ($c <= 0) {            $this->inv->remove($id);            unset($this->inv->cond[$id]);            $this->say('Ton arme se brise : ' . mb_strtolower(Items::name($id)) . ' est hors d\'usage.');            return;        }        $this->inv->cond[$id] = $c;        if ($c < 25 && $c + $amount >= 25) {            $this->say(Items::name($id) . ' est très usé : répare-le.');        }    }    /** Repairs the weapon in hand with its materials (Weapons::STATS 'repair'). */    public function repairWeapon(?string $id = null): string    {        $id ??= $this->inv->hand;        $need = $id !== null ? (Weapons::STATS[$id]['repair'] ?? (Weapons::shield($id) ?? [])['repair'] ?? null) : null;        if ($id === null || $need === null) {            return 'Rien à réparer en main.';        }        foreach ($need as $m => $n) {            if (!$this->inv->has($m, $n)) {                return 'Pour réparer : ' . Dialogues::list($need) . '.';            }        }        foreach ($need as $m => $n) {            $this->inv->remove($m, $n);        }        $this->inv->cond[$id] = min(100.0, $this->inv->condition($id) + 60 + $this->talents->repairBonus());        $this->passTime(20);        return 'Tu répares : ' . Items::name($id) . ' (' . (int) $this->inv->condition($id) . ' %).';    }    /** Ready for the next blow at once (tests, the context action). */    public function attackCoolReset(): void    {        $this->attackCool = 0.0;    }    /** A beast lunged at Rob: a blow in the next moment is a counter. */    public function lunged(): void    {        $this->parryAt = $this->clock;    }    private function strike(Creature|Npc $t, float $dmg, string $verb): string    {        $this->hitAt = $this->clock;        $this->events[] = ['hit', 0.0, 1.0];        $this->combat->engage($this, $t);        $this->combat->popup('−' . (int) max(1, round($dmg)), [255, 236, 200]);        if ($t instanceof Creature) {            $text = $verb . ' ' . Wildlife::the($t->species) . '.';            $this->say($text);            Wildlife::hurt($this, $t, $dmg);        } else {            $text = $verb . ' ' . Folk::the($t) . '.';            $this->say($text);            Folk::hurt($this, $t, $dmg);        }        return $text;    }    /** The nearest animal or hostile human in front within range: [target, distance]. */    private function targetAhead(float $range, float $cos): ?array    {        $fx = sin($this->yaw);        $fz = cos($this->yaw);        $best = null;        $eye = $this->eyeY();        $list = $this->creatures;        foreach ($this->npcs as $n) {            if (($n->hostile || $n->state === 'surrender') && empty($n->data['companion'])) {                $list[] = $n;            }        }        foreach ($list as $t) {            if ($t instanceof Creature && !empty($t->data['companion'])) {                continue;            }            $dx = $t->x - $this->x;            $dz = $t->z - $this->z;            $flat = hypot($dx, $dz);            $dy = $t->y + 0.8 - $eye;            $d = sqrt($flat * $flat + $dy * $dy);            if ($t instanceof Creature && $t->species === 'burrower' && $t->state === 'buried') {                continue;            }            if ($d > $range) {                continue;            }            $dot = $flat < 0.01 ? 1.0 : ($dx * $fx + $dz * $fz) / $flat;            if ($t instanceof Creature && $t->species === 'fish' && $range < 10 && $this->inv->hand !== 'harpoon') {                continue;            }            if ($range > 10) {                // the bow aims with the pitch too                $dot = min($dot, cos(atan2($dy, $flat) - $this->pitch * 0.5));            }            if ($dot < $cos && $flat > 0.9) {                continue;            }            if ($best === null || $d < $best[1]) {                $best = [$t, $d];            }        }        return $best;    }    private function dangerNear(): bool    {        foreach ($this->creatures as $c) {            if (in_array($c->species, self::HOSTILE, true) && $c->state !== 'buried' && $c->state !== 'flee' && Wildlife::dist($this, $c) < 22) {                return true;            }        }        foreach ($this->npcs as $n) {            if ($n->hostile && in_array($n->state, ['alert', 'attack'], true) && hypot($n->x - $this->x, $n->z - $this->z) < 45) {                return true;            }        }        return Wildfire::near($this, 6.0) !== null;    }    // ------------------------------------------------------------------------------------------ the context action    /** What act() would do here (French, for the HUD); null: nothing. */    public function prompt(): ?string    {        $o = $this->options();        return $o === [] ? null : $o[0]['label'];    }    /** @return list<array{id: string, label: string}> every action possible here, the first one is act()'s */    public function actions(): array    {        $out = [];        foreach ($this->options() as $o) {            $out[] = ['id' => $o['id'], 'label' => $o['label']];        }        return $out;    }    /** Does the context action (or the one named, from actions()); returns what happened (French), null: nothing. */    public function act(?string $id = null): ?string    {        if ($this->dead() || $this->won || $this->talk !== null || $this->sleeping !== null) {            return null;        }        foreach ($this->options() as $o) {            if ($id === null || $o['id'] === $id) {                $text = ($o['run'])();                $this->say($text);                Quest::check($this);                return $text;            }        }        return null;    }    /** @return list<array{id: string, label: string, run: \Closure}> */    private function options(): array    {        $o = [];        $fx = sin($this->yaw);        $fz = cos($this->yaw);        // people        if ($this->raft !== null) {            if (Raft::canLand($this)) {                $o[] = ['id' => 'land', 'label' => 'Débarquer sur la rive', 'run' => fn () => Raft::land($this)];            }            if ($this->raft['hp'] < 70) {                $o[] = ['id' => 'raft_repair', 'label' => 'Réparer le radeau (' . (int) $this->raft['hp'] . ' %)', 'run' => fn () => Raft::repair($this)];            }        }        foreach ($this->npcs as $n) {            $d = hypot($n->x - $this->x, $n->z - $this->z);            $friendly = !$n->hostile && empty($n->data['companion']) && $n->state !== 'dead' && ($n->faction !== 'rodeur' || People::keyOf($n) !== null);            if ($friendly && $d < 3.4 && ($d < 1.2 || (($n->x - $this->x) * $fx + ($n->z - $this->z) * $fz) / $d > 0.5)) {                if ($n->faction === 'rodeur' && $n->state === 'sleep') {                    continue;                }                $o[] = ['id' => 'talk', 'label' => 'Parler à ' . $n->name, 'run' => fn () => $this->talkTo($n)];                break;            }        }        // Vask asleep: his key        foreach ($this->npcs as $n) {            if (People::keyOf($n) === 'vask' && $n->state === 'sleep' && empty($this->flags['key_taken']) && hypot($n->x - $this->x, $n->z - $this->z) < 2.0) {                $o[] = ['id' => 'steal', 'label' => 'Voler la clé au cou de Vask' . ($this->crouching ? '' : ' (accroupis-toi)'), 'run' => function () use ($n): string {                    $p = $this->crouching ? 0.8 : 0.3;                    if ($this->rng->chance($p)) {                        return Talk::handKey($this, 'theft', '')[0] ?: 'Tes doigts glissent sous la chaîne... la clé est à toi. Vask ronfle toujours.';                    }                    $n->state = 'alert';                    $this->say('Vask ouvre les yeux : « Voleur ! »');                    return 'Vask se réveille en sursaut !';                }];            }        }        // Rôdeurs coming: hands up, ask for Vask        if (empty($this->flags['rodeur_truce']) && ($this->flags['parley_until'] ?? 0) <= $this->minutes && empty($this->flags['dead_vask'])) {            foreach ($this->npcs as $n) {                if ($n->faction === 'rodeur' && in_array($n->state, ['alert', 'attack'], true) && hypot($n->x - $this->x, $n->z - $this->z) < 40) {                    $o[] = ['id' => 'parley', 'label' => 'Lever les mains : « Je veux parler à Vask ! »', 'run' => function (): string {                        $this->flags['parley_until'] = $this->minutes + 4;                        People::change($this, 'vask', 3, false);                        return 'Tu lèves les mains bien haut. Les arcs se baissent à moitié. « Vask ! L\'homme du ciel veut te parler ! »';                    }];                    break;                }            }        }        Companions::options($this, $o);        // a foe within reach        $w = Weapons::of($this->inv->hand);        $ranged = $w['type'] === 'ranged';        $foe = $this->targetAhead((float) $w['range'], $ranged ? 0.985 : 0.55);        if ($foe !== null && ($foe[0] instanceof Npc || $foe[0]->species !== 'bird' || $ranged)) {            $name = $foe[0] instanceof Npc ? Folk::the($foe[0]) : Wildlife::the($foe[0]->species);            $o[] = ['id' => 'attack', 'label' => ($ranged ? 'Tirer sur ' : 'Attaquer ') . $name, 'run' => function () {                if ($this->aiming()) {                    $this->release();                } else {                    $this->swing();                }                return '';           // the strike tells what happened, Weapons::windup() later            }];        }        // a crawler or a night beast close while the torch burns: sweep it before them        if ($this->torchLit() && $this->clock - $this->brandishAt >= self::BRANDISH) {            foreach ($this->creatures as $c) {                if (empty($c->data['companion']) && in_array($c->species, ['crawler', 'stalker'], true) && in_array($c->state, ['keep', 'hunt', 'attack', 'stalk'], true)                    && Wildlife::dist($this, $c) < self::BRANDISH_REACH) {                    $o[] = ['id' => 'brandish', 'label' => 'Brandir la torche vers ' . Wildlife::the($c->species), 'run' => fn (): string => $this->brandish() ?? ''];                    break;                }            }        }        // the thing in front (a bundle Rob put down, not looked at: after everything else of the spot)        $t = $this->thingAhead();        $later = null;        if ($t !== null && !empty($t->data['bundle']) && $this->focusPick === 0 && !$this->lookingAt($t)) {            $later = $t;        } elseif ($t !== null) {            $this->thingOptions($t, $o);        }        // doors        foreach ($this->zone->exits as $e) {            if (hypot($e['x'] - $this->x, $e['z'] - $this->z) < $e['r'] + 1.5) {                $o[] = ['id' => 'exit', 'label' => $e['label'], 'run' => fn () => $this->travel($e)];            }        }        // water        $ax = $this->x + $fx * 1.4;        $az = $this->z + $fz * 1.4;        if ($this->swimming || $this->zone->waterDepth($ax, $az) > 0.05 || $this->zone->waterDepth($this->x, $this->z) > 0.05) {            $fall = $this->fallNear(14.0);            if ($fall !== null) {                $o[] = ['id' => 'drink', 'label' => 'Boire l\'eau vive de la cascade', 'run' => fn () => $this->drinkWater(true, 0.04)];            } else {                $o[] = $this->zone->id === 'coast'                    ? ['id' => 'drink', 'label' => 'Boire l\'eau de mer (salée)', 'run' => fn (): string => 'Tu craches aussitôt : l\'eau de mer est salée, elle t\'assoifferait plus encore. Il faut de l\'eau douce : une source, ou tes gourdes.']                    : ['id' => 'drink', 'label' => 'Boire l\'eau ' . ($this->zone->cave ? 'du bassin' : (['canyon' => 'du ruisseau', 'jungle' => 'du fleuve', 'marsh' => 'du marais'][$this->zone->id] ?? 'du lac')), 'run' => fn () => $this->drinkWater(false)];            }            if ($this->inv->has('gourd_empty') && $this->zone->id !== 'coast') {                $o[] = $fall !== null                    ? ['id' => 'fill', 'label' => 'Remplir une gourde à la cascade', 'run' => fn () => $this->fill(true)]                    : ['id' => 'fill', 'label' => 'Remplir une gourde d\'eau trouble', 'run' => fn () => $this->fill(false)];            }            $o[] = ['id' => 'fish', 'label' => $this->inv->hasTool('harpoon') ? 'Harponner un poisson' : ($this->inv->hasTool('fish') ? 'Pêcher' : 'Pêcher (il faut une ligne)'), 'run' => fn () => $this->fish()];        }        if ($this->raft === null && !$this->swimming && $this->inv->has('log') && Raft::launchSpot($this) !== null) {            $o[] = ['id' => 'raft', 'label' => 'Construire un radeau (' . Raft::NEEDS['log'] . ' rondins, ' . Raft::NEEDS['rope'] . ' cordes)', 'run' => fn () => Raft::build($this)];        }        if ($this->inv->hand !== null && isset(Weapons::STATS[$this->inv->hand]['repair']) && $this->inv->condition($this->inv->hand) < 60) {            $o[] = ['id' => 'repair_weapon', 'label' => 'Réparer : ' . mb_strtolower(Items::name($this->inv->hand)) . ' (' . (int) $this->inv->condition($this->inv->hand) . ' %)', 'run' => fn () => $this->repairWeapon()];        }        $sh = $this->inv->shield();        if ($sh !== null && $this->inv->condition($sh) < 60) {            $o[] = ['id' => 'repair_shield', 'label' => 'Réparer : ' . mb_strtolower(Items::name($sh)) . ' (' . (int) $this->inv->condition($sh) . ' %)', 'run' => fn () => $this->repairWeapon($sh)];        }        // fire        $fire = $this->fireNear(3.5);        if ($fire !== null) {            if (empty($this->fires[$fire]['permanent']) && ($this->inv->has('wood') || $this->inv->has('stick') || $this->inv->has('resin') || $this->inv->has('charcoal'))) {                $o[] = ['id' => 'fuel', 'label' => 'Remettre du bois dans le feu', 'run' => fn () => $this->feedFire($fire)];            }            if ($this->inv->has('gourd_dirty') || $this->inv->has('gourd_filtered')) {                $o[] = ['id' => 'boil', 'label' => 'Faire bouillir l\'eau' . ($this->inv->hasTool('pot') ? '' : ($this->inv->has('stone') ? ' (pierres chauffées)' : ' (il faut un pot ou une pierre)')),                    'run' => fn () => $this->boilWater()];            }            if (!$this->hasOption($o, 'sleep')) {                $o[] = ['id' => 'sleep', 'label' => 'Dormir près du feu', 'run' => fn () => $this->sleep()];            }        } elseif ($this->fireInHand() !== null && !$this->swimming && ($this->inv->has('wood') || $this->inv->has('stick', 3) || $this->inv->has('campfire_kit'))) {            $o[] = ['id' => 'fire', 'label' => 'Allumer un feu', 'run' => fn () => $this->lightFire()];        }        // the torch to dry grass: a fire that runs        if ($this->inv->hand === 'torch' && $this->raft === null && !$this->zone->cave && Wildfire::burnable($this, $this->x + $fx * 2, $this->z + $fz * 2) >= 0.5) {            $o[] = ['id' => 'burn', 'label' => 'Mettre le feu aux herbes (dangereux)', 'run' => function () use ($fx, $fz): string {                return Wildfire::ignite($this, $this->x + $fx * 3, $this->z + $fz * 3, 1.2) ? 'Les herbes sèches s\'embrasent d\'un coup. Recule !' : 'L\'herbe est trop humide pour brûler.';            }];        }        // the ground itself        if (!$this->swimming && $this->raft === null) {            $biome = $this->zone->biomeAt($this->x, $this->z);            if ($biome === 'jungle_dense' || $biome === 'marsh') {                $biome = $biome === 'marsh' ? 'mud' : 'jungle';            }            if (Wildfire::burntAt($this, $this->x, $this->z)) {                $o[] = ['id' => 'ash', 'label' => 'Ramasser du charbon dans les cendres', 'run' => fn () => $this->rng->chance(0.5) ? $this->gather('charcoal', 1, 5, 'Tu ramasses des morceaux de charbon de bois.') : 'Rien que de la cendre fine.'];                $biome = 'burnt';            }            if ($biome === 'beach') {                $o[] = ['id' => 'sand', 'label' => 'Ramasser du sable noir', 'run' => fn () => $this->gather('sand', 2, 3, 'Tu ramasses du sable noir, lourd et brillant.')];            }            if (($biome === 'grass' || $biome === 'jungle') && !$this->zone->cave) {                $o[] = ['id' => 'fiber', 'label' => 'Arracher des herbes (fibres)', 'run' => fn () => $this->gather('fiber', 2, 3, 'Tu arraches des herbes et en tires des fibres.')];            }            if ($biome === 'jungle') {                $o[] = ['id' => 'roots', 'label' => 'Creuser pour trouver des racines', 'run' => function () {                    $this->passTime(8);                    return $this->rng->chance(0.5) ? $this->gather('root', 1, 0, 'Tu déterres une racine amère.') : 'Tu creuses en vain : rien que de la terre.';                }];            }            if (in_array($biome, ['mud', 'jungle', 'grass'], true) && !$this->zone->cave) {                $o[] = ['id' => 'worms', 'label' => 'Fouiller la terre (vers)', 'run' => fn () => $this->digWorms()];            }            if ($biome === 'sand' && !$this->zone->cave) {                $o[] = ['id' => 'sand', 'label' => 'Ramasser du sable', 'run' => fn () => $this->gather('sand', 2, 3, 'Tu ramasses du sable fin dans un pan de feuille.')];            }            if ($biome === 'mud') {                $o[] = ['id' => 'clay', 'label' => 'Ramasser de l\'argile', 'run' => fn () => $this->gather('clay', 1, 5, 'Tu ramasses une motte d\'argile grasse.')];            }            if ($biome === 'snow' && $this->inv->has('gourd_empty') && $fire !== null) {                $o[] = ['id' => 'snow', 'label' => 'Faire fondre de la neige', 'run' => function () {                    $this->inv->remove('gourd_empty');                    $this->give('gourd_clean');                    $this->passTime(10);                    return 'La neige fond près du feu : une gourde d\'eau claire.';                }];            }        }        if ($later !== null) {            $this->thingOptions($later, $o);        }        // sleeping anywhere comes last: never the default action by mistake        if (!$this->hasOption($o, 'sleep') && !$this->swimming && $this->raft === null) {            $o[] = ['id' => 'sleep', 'label' => $this->sheltered() ? 'Dormir à l\'abri' : 'Dormir ici, à la belle étoile', 'run' => fn () => $this->sleep()];        }        return $o;    }    private function hasOption(array $o, string $id): bool    {        foreach ($o as $x) {            if ($x['id'] === $id) {                return true;            }        }        return false;    }    /** The thing Rob looks at, within reach. */    /** The thing the context action is about: the candidate picked (cycleFocus()) among thingsAhead(), null: none. */    public function thingAhead(): ?Thing    {        $list = $this->thingsAhead();        if ($list === []) {            return null;        }        return $list[$this->focusPick % count($list)];    }    /** The next thing within reach becomes the context action's (G / the pad's right stick / the prompt's arrows). */    public function cycleFocus(int $dir = 1): ?Thing    {        $list = $this->thingsAhead();        $n = count($list);        if ($n === 0) {            return null;        }        $this->focusPick = (($this->focusPick % $n) + $dir + $n) % $n;        $this->focusChosen = $list[$this->focusPick]->id;        return $list[$this->focusPick];    }    /**     * Every thing within reach, the one nearest the centre of the view (the crosshair: the angle between the gaze, pitch     * included, and the thing) first. Solid things are measured to their surface (a big boulder, the shuttle's hull).     * A bundle Rob put down comes after the rest unless he looks right at it: the action offers what was there before.     * When the list changes, the pick goes back to the first one.     * @return list<Thing>     */    public function thingsAhead(): array    {        $cp = cos($this->pitch);        $fx = sin($this->yaw) * $cp;        $fz = cos($this->yaw) * $cp;        $fy = sin($this->pitch);        $eye = $this->eyeY();        $found = [];        foreach ($this->zone->thingsNear($this->x, $this->z, 7.0) as $t) {            $found[$t->id] = $t;        }        foreach ($this->zone->bigThings() as $t) {            if (!isset($found[$t->id]) && hypot($t->x - $this->x, $t->z - $this->z) < 22.0) {                $found[$t->id] = $t;            }        }        $scored = [];        foreach ($found as $t) {            $reach = match ($t->kind) {                'relay_mast' => 6.5,                'shuttle' => 8.0,                'stilt_hut', 'giant_tree', 'boat_wreck' => 4.5,                'drone_wreck', 'totem', 'market_stall', 'forge', 'raft' => 3.5,                'terminal', 'weapon_rack', 'signpost', 'burnt_tree', 'mangrove', 'palm_coast', 'fumarole', 'geyser', 'reeds_tall' => 2.6,                'liana_bridge', 'ash' => 0.0,                'waterfall' => 9.0,                'hut', 'wreck_colony' => 5.0,                'wreck_pod', 'tent' => 4.0,                'campfire', 'crate', 'carcass', 'boulder', 'skin_rack', 'chest_wood', 'basket', 'chest_metal' => 2.8,                'tree_broad', 'tree_palm', 'tree_conifer', 'tree_dead' => 2.6,                'cave_entrance', 'ladder' => 0.0,                default => 2.2,            };            if ($reach <= 0) {                continue;            }            $cx = $t->x;            $cz = $t->z;            $d = hypot($cx - $this->x, $cz - $this->z);            $surface = Solids::surface($t, $this->x, $this->z);            if ($surface !== null) {                // a solid thing: how far its side is (Rob stands outside it now), toward its nearest part                [$gap, $cx, $cz] = $surface;                $d = min($d, max(0.0, $gap) + 0.6);            }            if ($d > $reach) {                continue;            }            $dx = $cx - $this->x;            $dz = $cz - $this->z;            $flat = hypot($dx, $dz);            $dot = $flat < 0.01 ? 1.0 : ($dx * sin($this->yaw) + $dz * cos($this->yaw)) / $flat;            if ($dot < 0.4 && $d > 1.2) {                continue;            }            // the angle from the crosshair: to the thing's middle height (its foot for what lies on the ground)            $ty = $t->y + match (true) {                $surface !== null => min(1.2, 0.8 * $t->scale),                default => 0.2,            };            $dy = $ty - $eye;            $len = sqrt($dx * $dx + $dz * $dz + $dy * $dy);            $cos = $len < 0.01 ? 1.0 : ($dx * $fx + $dz * $fz + $dy * $fy) / $len;            $angle = acos(max(-1.0, min(1.0, $cos)));            $score = $angle + 0.04 * $d;            if (!empty($t->data['bundle']) && $angle > self::LOOK_AT) {                $score += 10.0;      // what Rob put down: only when looked at, or when nothing else is here            }            $scored[] = [$score, $t];        }        usort($scored, static fn (array $a, array $b): int => $a[0] <=> $b[0]);        $list = array_map(static fn (array $x): Thing => $x[1], $scored);        $ids = array_map(static fn (Thing $t): int => $t->id, $list);        $set = $ids;        sort($set);        $key = implode(',', $set);        if ($key !== $this->focusKey) {            // other things within reach: the crosshair decides again            $this->focusKey = $key;            $this->focusChosen = null;        }        $at = $this->focusChosen === null ? false : array_search($this->focusChosen, $ids, true);        $this->focusPick = $at === false ? 0 : (int) $at;        return $list;    }    /** Is the thing (a dropped bundle) right in the crosshair? */    public function lookingAt(Thing $t): bool    {        $dx = $t->x - $this->x;        $dz = $t->z - $this->z;        $dy = $t->y + 0.2 - $this->eyeY();        $len = sqrt($dx * $dx + $dz * $dz + $dy * $dy);        if ($len < 0.01) {            return true;        }        $cp = cos($this->pitch);        $cos = ($dx * sin($this->yaw) * $cp + $dz * cos($this->yaw) * $cp + $dy * sin($this->pitch)) / $len;        return acos(max(-1.0, min(1.0, $cos))) <= self::LOOK_AT;    }    private function thingOptions(Thing $t, array &$o): void    {        $label = (string) ($t->data['label'] ?? '');        $axe = $this->inv->hasTool('chop');        $knife = $this->inv->hasTool('cut');        switch ($t->kind) {            case 'tree_broad':            case 'tree_palm':            case 'tree_conifer':                $name = ['tree_broad' => 'l\'arbre', 'tree_palm' => 'le palmier', 'tree_conifer' => 'le conifère'][$t->kind];                if ($t->kind === 'tree_palm' && (int) ($t->data['fruit'] ?? 2) > 0) {                    $o[] = ['id' => 'fruit', 'label' => 'Cueillir des fruits', 'run' => fn () => $this->harvest($t, 'fruit', 2, 'fruit', 1, 'Tu cueilles un fruit juteux.')];                }                if ($t->kind === 'tree_broad' && (int) ($t->data['leaves'] ?? 3) > 0) {                    $o[] = ['id' => 'leaves', 'label' => 'Cueillir de grandes feuilles', 'run' => fn () => $this->harvest($t, 'leaves', 3, 'leaves', 3, 'Tu cueilles de grandes feuilles souples.')];                }                if ($t->kind === 'tree_conifer' && (int) ($t->data['resin'] ?? 2) > 0) {                    $o[] = ['id' => 'resin', 'label' => 'Récolter de la résine', 'run' => fn () => $this->harvest($t, 'resin', 2, 'resin', 1, 'Tu grattes l\'écorce : de la résine collante.')];                }                $o[] = ['id' => 'chop', 'label' => 'Abattre ' . $name . ($axe ? '' : ' (il faut une hache)'), 'run' => fn () => $this->chop($t)];                break;            case 'tree_dead':                if ((int) ($t->data['sticks'] ?? 2) > 0) {                    $o[] = ['id' => 'sticks', 'label' => 'Ramasser du bois mort', 'run' => fn () => $this->harvest($t, 'sticks', 2, 'stick', 2, 'Tu casses des branches mortes.')];                }                $o[] = ['id' => 'chop', 'label' => 'Abattre l\'arbre mort' . ($axe ? '' : ' (il faut une hache)'), 'run' => fn () => $this->chop($t)];                break;            case 'bush_berry':            case 'bush_red':                $item = $t->kind === 'bush_berry' ? 'berries_blue' : 'berries_red';                if ($t->left > 0) {                    $o[] = ['id' => 'pick', 'label' => 'Cueillir des ' . lcfirst(Items::name($item)), 'run' => fn () => $this->pickBush($t, $item)];                } else {                    $o[] = ['id' => 'look', 'label' => 'Buisson dépouillé', 'run' => fn () => 'Il n\'y a plus de baies. Elles repousseront dans quelques jours.'];                }                break;            case 'mushroom':                $item = (string) ($t->data['item'] ?? ($t->id % 3 === 0 ? 'mushroom_pale' : 'mushroom_brown'));                $o[] = ['id' => 'pick', 'label' => 'Cueillir : ' . Items::name($item), 'run' => fn () => $this->pickUp($t, $item, 1)];                break;            case 'herb_heal':            case 'herb_fever':                $item = (string) ($t->data['item'] ?? $t->kind);                $o[] = ['id' => 'pick', 'label' => 'Cueillir : ' . Items::name($item), 'run' => fn () => $this->pickUp($t, $item, 2)];                break;            case 'reed':                $o[] = ['id' => 'pick', 'label' => 'Couper des roseaux', 'run' => fn () => $this->useUp($t, ['reed' => 1, 'fiber' => 1], 2, 'Tu coupes des roseaux et en tires des fibres.')];                break;            case 'vine':                $o[] = ['id' => 'pick', 'label' => 'Arracher des lianes', 'run' => fn () => $this->useUp($t, ['vine' => 2], 3, 'Tu arraches de longues lianes.')];                break;            case 'stick':            case 'stone_small':            case 'flint':            case 'wood':                $item = ['stick' => 'stick', 'stone_small' => 'stone', 'flint' => 'flint', 'wood' => 'wood'][$t->kind];                $o[] = ['id' => 'pick', 'label' => 'Ramasser : ' . Items::name($item), 'run' => fn () => $this->pickUp($t, $item, 1)];                break;            case 'rock':                $o[] = ['id' => 'mine', 'label' => 'Casser des pierres', 'run' => fn () => $this->mine($t, false)];                break;            case 'boulder':                $o[] = ['id' => 'mine', 'label' => 'Débiter le rocher' . ($axe ? '' : ' (il faut une hache)'), 'run' => fn () => $this->mine($t, true)];                break;            case 'waterfall':                if (!$this->hasOption($o, 'drink')) {                    $o[] = ['id' => 'drink', 'label' => 'Boire l\'eau vive de la cascade', 'run' => fn () => $this->drinkWater(true, 0.04)];                    if ($this->inv->has('gourd_empty')) {                        $o[] = ['id' => 'fill', 'label' => 'Remplir une gourde à la cascade', 'run' => fn () => $this->fill(true)];                    }                }                $o[] = ['id' => 'look', 'label' => 'Regarder : ' . ($label ?: 'la cascade'), 'run' => fn () => (string) ($t->data['note']                    ?? 'L\'eau tombe de la falaise dans un grondement continu. Derrière le rideau d\'eau, la roche semble creusée.')];                break;            case 'water_spring':                $o[] = ['id' => 'drink', 'label' => 'Boire à la source', 'run' => fn () => $this->drinkWater(true)];                if ($this->inv->has('gourd_empty')) {                    $o[] = ['id' => 'fill', 'label' => 'Remplir une gourde d\'eau claire', 'run' => fn () => $this->fill(true)];                }                break;            case 'carcass':                $o[] = ['id' => 'skin', 'label' => 'Dépecer : ' . ($label ?: 'carcasse') . ($knife ? '' : ' (il faut un couteau)'), 'run' => fn () => $this->skin($t)];                break;            case 'wreck_pod':                if (empty($this->flags['q_pod_log'])) {                    $o[] = ['id' => 'read', 'label' => 'Lire le journal de bord', 'run' => fn () => $this->readPodLog()];                }                $this->searchOption($t, $o, 'Fouiller la nacelle');                break;            case 'wreck_colony':                if (!empty($t->data['locked'])) {                    $o[] = ['id' => 'open', 'label' => 'Ouvrir le sas de la base', 'run' => fn () => $this->openBase($t)];                } else {                    $this->searchOption($t, $o, 'Fouiller la base');                }                break;            case 'crate':            case 'bones':                if (!empty($t->data['bundle'])) {                    $this->searchOption($t, $o, 'Reprendre tes affaires posées');                    break;                }                $this->searchOption($t, $o, 'Fouiller : ' . ($label ?: ($t->kind === 'crate' ? 'caisse' : 'ossements')));                break;            case 'tent':            case 'hut':                $this->searchOption($t, $o, 'Fouiller : ' . ($label ?: 'tente'), false);                $o[] = ['id' => 'sleep', 'label' => 'Dormir à l\'abri', 'run' => fn () => $this->sleep()];                break;            case 'relay_mast':                $this->mastOptions($o);                break;            case 'chest_wood':            case 'basket':            case 'chest_metal':                Chests::options($this, $t, $o);                break;            case 'snare':                $o[] = ['id' => 'snare', 'label' => 'Relever le collet', 'run' => fn () => $this->checkSnare($t)];                break;            case 'skin_rack':                $o[] = ['id' => 'look', 'label' => 'Regarder : ' . ($label ?: 'les peaux'), 'run' => fn () => $this->zone->id === 'jungle' ? 'Des poissons fendus sèchent au-dessus d\'un feu de feuilles : c\'est ainsi que les Ouvi les gardent des semaines.' : 'Des peaux de brouteur sèchent, tendues sur des perches. Les Haldi les échangent contre presque tout.'];                break;            case 'shuttle':                Escape::options($this, $t, $o);                break;            case 'giant_tree':                if ((int) ($t->data['sticks'] ?? 3) > 0) {                    $o[] = ['id' => 'sticks', 'label' => 'Ramasser des branches tombées', 'run' => fn () => $this->harvest($t, 'sticks', 3, 'stick', 2, 'Le géant laisse tomber des branches grosses comme ton bras.')];                }                $o[] = ['id' => 'look', 'label' => 'Regarder : ' . ($label ?: 'l\'arbre géant'), 'run' => fn () => 'Un tronc large comme une maison, des racines en contreforts. Trop dur pour une hache de pierre. Des grimpeurs crient dans les hauteurs.'];                break;            case 'burnt_tree':                if ((int) ($t->data['sticks'] ?? 1) > 0) {                    $o[] = ['id' => 'charcoal', 'label' => 'Prendre du charbon sur l\'arbre calciné', 'run' => fn () => $this->harvest($t, 'sticks', 1, 'charcoal', 2, 'Tu détaches des morceaux de charbon du tronc noirci.')];                }                $o[] = ['id' => 'chop', 'label' => 'Abattre l\'arbre calciné' . ($axe ? '' : ' (il faut une hache)'), 'run' => fn () => $this->chop($t)];                break;            case 'reeds_tall':                $o[] = ['id' => 'pick', 'label' => 'Couper des cannes', 'run' => fn () => $this->useUp($t, ['cane' => 2, 'fiber' => 1], 4, 'Tu coupes des cannes juteuses : de quoi faire du fermenté, ou mâcher.')];                break;            case 'mangrove':            case 'palm_coast':                $o[] = ['id' => 'pick', 'label' => $t->kind === 'mangrove' ? 'Couper du bois de palétuvier' : 'Cueillir des noix de la côte', 'run' => fn () => $t->kind === 'mangrove'                    ? $this->useUp($t, ['wood' => 1, 'stick' => 1], 15, 'Le bois du palétuvier est dur et lourd.') : $this->useUp($t, ['fruit' => 1, 'fiber' => 2], 6, 'Une noix pleine d\'eau sucrée, et des fibres de sa bourre.')];                break;            case 'fumarole':            case 'geyser':                $o[] = ['id' => 'look', 'label' => 'Regarder : ' . ($t->kind === 'geyser' ? 'le geyser' : 'la fumerolle'), 'run' => function () use ($t): string {                    if ($this->inv->has('meat_raw') && $t->kind === 'fumarole') {                        $this->inv->remove('meat_raw');                        $this->give('meat_cooked');                        $this->passTime(20);                        return 'Tu cuis ta viande dans la vapeur soufrée de la fumerolle. Elle sent l\'œuf pourri, mais elle est cuite.';                    }                    return 'La terre siffle et crache une vapeur jaune qui pique les yeux. Une cuisson naturelle, pour qui a de la viande crue.';                }];                break;            case 'stilt_hut':                $this->searchOption($t, $o, 'Fouiller : ' . ($label ?: 'la case'), false);                $o[] = ['id' => 'sleep', 'label' => 'Dormir à l\'abri', 'run' => fn () => $this->sleep()];                break;            case 'drone_wreck':            case 'boat_wreck':            case 'weapon_rack':                $this->searchOption($t, $o, 'Fouiller : ' . ($label ?: 'l\'épave'));                break;            case 'terminal':                $this->searchOption($t, $o, 'Fouiller : ' . ($label ?: 'la console'), false);                $o[] = ['id' => 'look', 'label' => 'Examiner : ' . ($label ?: 'la console'), 'run' => fn () => ($t->data['note'] ?? '') === 'pad'                    ? 'Un écran fêlé s\'allume à ton contact : « NAVETTE HALDE — ' . Escape::partsFitted($this) . '/4 SYSTÈMES — CARBURANT ' . Escape::fuel($this) . '/3 ». ' . Escape::status($this)                    : 'Une vieille console de la colonie. L\'écran est mort, mais les tiroirs ont peut-être gardé quelque chose.'];                break;            case 'totem':                $o[] = ['id' => 'look', 'label' => 'Regarder : ' . ($label ?: 'le totem'), 'run' => fn () => match ((string) ($t->data['note'] ?? '')) {                    'plates' => empty($this->flags['plates_given']) ? 'Des plaques noires, lisses et légères, sont clouées sur le totem comme des écailles : le bouclier thermique de la navette. Les Ouvi les appellent les écailles du ciel.' : 'Le totem paraît nu sans ses écailles.',                    'drowned' => 'Des noms gravés sur un mât pourri : ceux que le marais a pris. Le dernier est récent.',                    default => 'Des visages sculptés, usés par le temps : les ancêtres des Haldi. Une pierre plate est posée à son pied.',                }];                if (($t->data['note'] ?? '') === 'plates' && empty($this->flags['plates_given']) && $this->isNight()) {                    $o[] = ['id' => 'steal', 'label' => 'Arracher les écailles du totem (vol)', 'run' => function (): string {                        $this->flags['plates_given'] = 'theft';                        $this->flags['ouvi_hostile'] = true;                        People::change($this, 'aika', -80);                        $this->give('heat_plates');                        $this->passTime(20);                        foreach ($this->npcs as $n) {                            if ($n->faction === 'ouvi') {                                $c = $n->data['centre'] ?? [$n->x, $n->z];                                People::makeHostile($n, (float) $c[0], (float) $c[1]);                            }                        }                        return 'Tu arraches les plaques une à une dans le noir. Un chien aboie, une torche s\'allume : les Ouvi ne te le pardonneront jamais.';                    }];                }                break;            case 'market_stall':            case 'forge':                $o[] = ['id' => 'look', 'label' => 'Regarder : ' . ($label ?: 'l\'étal'), 'run' => fn () => $t->kind === 'forge' ? 'Une forge de pierre, un soufflet de peau, une enclume taillée dans un bloc de la colonie. Koru y forge des lames.' : 'Des marchandises étalées sur des feuilles. Parle au marchand pour acheter ou vendre.'];                break;            case 'signpost':                $o[] = ['id' => 'read', 'label' => 'Lire : ' . ($label ?: 'le poteau'), 'run' => fn () => (string) ($t->data['note'] ?? 'Les lettres sont effacées.')];                break;            case 'raft':                if ($this->raft === null) {                    $o[] = ['id' => 'board', 'label' => 'Monter sur le radeau', 'run' => fn () => Raft::board($this, $t)];                }                break;            case 'trap_spike':                $o[] = ['id' => 'snare', 'label' => 'Relever le piège à pieux', 'run' => function () use ($t): string {                    $this->removeThing($t);                    $this->give('trap_spike');                    return 'Tu démontes le piège.';                }];                break;        }    }    private function searchOption(Thing $t, array &$o, string $label, bool $showEmpty = true): void    {        if (!empty($t->data['loot'])) {            $o[] = ['id' => 'search', 'label' => $label, 'run' => fn () => $this->search($t)];        } elseif ($showEmpty && $t->kind !== 'wreck_colony') {            $o[] = ['id' => 'look', 'label' => $label . ' (vide)', 'run' => fn () => 'Il n\'y a plus rien d\'utile ici.'];        }    }    // ------------------------------------------------------------------------------------------ actions    public function drinkWater(bool $clean, ?float $risk = null): string    {        $text = $this->body->drink($clean, $risk);        if ($this->body->lastActionOk) {            $this->flags['q_drink'] = true;            $this->passTime(2);        }        return $text;    }    private function fill(bool $clean): string    {        $this->inv->remove('gourd_empty');        $this->give($clean ? 'gourd_clean' : 'gourd_dirty');        $this->passTime(1);        return $clean ? 'Tu remplis ta gourde d\'eau claire.' : 'Tu remplis ta gourde d\'eau trouble. Mieux vaudrait la faire bouillir.';    }    private function fish(): string    {        if ($this->inv->hasTool('harpoon')) {            $this->passTime(10);            $near = false;            foreach ($this->creatures as $c) {                if ($c->species === 'fish' && Wildlife::dist($this, $c) < 12) {                    $near = true;                }            }            if ($this->rng->chance(($near ? 0.75 : 0.35) * ($this->raft !== null ? 1.2 : 1.0))) {                $n = $this->rng->chance(0.3) ? 2 : 1;                $this->give('fish_raw', $n);                $this->flags['fish'] = (int) ($this->flags['fish'] ?? 0) + $n;                return $n > 1 ? 'Le harpon file et revient avec deux poissons embrochés !' : 'Un éclair d\'argent sous l\'eau : le harpon le cloue. Un poisson !';            }            return 'Le harpon fend l\'eau trop tard. Le poisson est déjà loin.';        }        if (!$this->inv->hasTool('fish')) {            return 'Il te faut une ligne de pêche : des fibres et un hameçon d\'os.';        }        $this->passTime(20);        $h = $this->hour();        $p = ($h < 9 && $h > 5) || ($h > 17 && $h < 21) ? 0.75 : 0.5;        if ($this->zone->cave) {            $p *= 0.6;        }        $bait = $this->inv->has('earthworm');        if ($bait) {            // a worm on the hook: the fish bite much better            $this->inv->remove('earthworm');            $p = min(0.95, $p + 0.3);        }        if ($this->rng->chance($p)) {            $this->give('fish_raw');            $this->flags['fish'] = (int) ($this->flags['fish'] ?? 0) + 1;            return $bait ? 'Le ver gigote au bout de l\'hameçon... ça mord ! Un beau poisson argenté.' : 'Ça mord ! Tu sors un poisson argenté de l\'eau.';        }        return $bait ? 'Vingt minutes d\'attente : le poisson a mangé ton ver sans mordre.' : 'Vingt minutes d\'attente... rien ne mord. Un ver de terre en appât aiderait.';    }    private function gather(string $item, int $n, int $minutes, string $text): string    {        if ($minutes > 0) {            $this->passTime($minutes);        }        $this->give($item, $n + $this->forageBonus());        return $text;    }    /** The forager talent: sometimes one more. */    private function forageBonus(): int    {        $p = $this->talents->forageChance();        return $p > 0 && $this->rng->chance($p) ? 1 : 0;    }    /** A part of a thing that runs out (fruit, leaves, resin, sticks), counted in its data. */    private function harvest(Thing $t, string $key, int $max, string $item, int $n, string $text): string    {        $left = (int) ($t->data[$key] ?? $max);        if ($left <= 0) {            return 'Il n\'y a plus rien à prendre.';        }        $t->data[$key] = $left - 1;        $this->touch($t);        $this->passTime(3);        $this->give($item, $n + $this->forageBonus());        return $text;    }    private function pickBush(Thing $t, string $item): string    {        $t->left--;        if ($t->left <= 0) {            $t->data['regrow'] = $this->minutes + 2880;        }        $this->touch($t);        $this->passTime(3);        $this->give($item, 3 + $this->forageBonus());        return $item === 'berries_red'            ? 'Tu cueilles des baies rouges, brillantes... Elles ne t\'inspirent pas confiance.'            : 'Tu cueilles une poignée de baies bleues.';    }    private function pickUp(Thing $t, string $item, int $minutes): string    {        $this->removeThing($t);        if ($minutes > 0) {            $this->passTime($minutes);        }        $this->give($item);        return 'Tu ramasses : ' . Items::name($item) . '.';    }    /** @param array<string, int> $gives */    private function useUp(Thing $t, array $gives, int $minutes, string $text): string    {        $t->left--;        if ($t->left <= 0) {            $this->removeThing($t);        } else {            $this->touch($t);        }        $this->passTime($minutes);        foreach ($gives as $id => $n) {            $this->give($id, $n);        }        return $text;    }    private function chop(Thing $t): string    {        if (!$this->inv->hasTool('chop')) {            return 'Il te faut une hache pour abattre un arbre. Une pierre, un bâton et une liane feront l\'affaire.';        }        $this->fight = 1.0;        $this->passTime(12);        $this->body->train('force', 12.0);        $t->left--;        $wood = $t->kind === 'tree_dead' ? 1 : 2;        if ($t->left <= 0) {            $this->removeThing($t);            $this->give('wood', $wood);            $this->give('stick', 2);            $this->flags['trees'] = (int) ($this->flags['trees'] ?? 0) + 1;            return 'L\'arbre s\'abat dans un craquement. Tu débites ' . $wood . ' bûches et des branches.';        }        $this->touch($t);        $this->give('wood', $wood);        return 'Ta hache mord le tronc. Tu en tires ' . $wood . ' bûche' . ($wood > 1 ? 's' : '') . '.';    }    private function mine(Thing $t, bool $needsTool): string    {        if ($needsTool && !$this->inv->hasTool('chop')) {            return 'Ce rocher est trop gros pour tes mains. Avec une hache, tu pourrais le débiter.';        }        $this->passTime($needsTool ? 10 : 5);        $this->body->train('force', $needsTool ? 10.0 : 5.0);        $t->left--;        if ($t->left <= 0) {            $this->removeThing($t);        } else {            $this->touch($t);        }        $this->give('stone', $needsTool ? 2 : 1);        $flint = $this->rng->chance($needsTool ? 0.4 : 0.25);        if ($flint) {            $this->give('flint');        }        return 'Tu détaches des pierres' . ($flint ? ', et un éclat de silex !' : '.');    }    private function skin(Thing $t): string    {        if (!$this->inv->hasTool('cut')) {            return 'Il faut un couteau pour dépecer une bête. Taille-en un dans du silex.';        }        $this->passTime(20);        $got = [];        foreach (['meat' => 'meat_raw', 'hide' => 'hide', 'fur' => 'fur', 'fat' => 'fat', 'scale' => 'scale_hide', 'crab' => 'crab_meat', 'shell' => 'shell'] as $key => $item) {            $n = (int) ($t->data[$key] ?? 0);            if ($n > 0 && in_array($key, ['meat', 'hide', 'fur', 'fat'], true)) {                $n = $this->talents->butcher($n);            }            if ($n > 0) {                $this->give($item, $n);                $got[$item] = $n;            }        }        $this->give('bone', 2);        $got['bone'] = 2;        $t->kind = 'bones';        $t->data = ['label' => 'Ossements', 'loot' => []];        $this->touch($t);        $this->flags['skinned'] = (int) ($this->flags['skinned'] ?? 0) + 1;        return 'Tu dépèces la bête : ' . Dialogues::list($got) . '.';    }    private function search(Thing $t): string    {        $loot = (array) ($t->data['loot'] ?? []);        if ($loot === []) {            return 'Il n\'y a plus rien d\'utile ici.';        }        $this->passTime(3);        $got = [];        $left = [];        foreach ($loot as $id => $n) {            $added = $this->inv->add((string) $id, (int) $n);            if ($added > 0) {                $got[$id] = $added;            }            if ($added < $n) {                $left[$id] = $n - $added;            }        }        $t->data['loot'] = $left;        $this->touch($t);        $text = $got === [] ? 'Ton sac est plein : tu ne peux rien emporter.' : 'Tu trouves : ' . Dialogues::list($got) . '.';        if ($left !== [] && $got !== []) {            $text .= ' Le reste est trop lourd pour toi.';        }        if (isset($got['colony_log'])) {            $this->flags['q_colony_log'] = true;            $text .= ' ' . $this->logText('colony_log');        }        if (isset($got['keycard']) && ($t->data['note'] ?? '') === 'colonist') {            $text .= ' Sur le badge : « Technicienne Ilia Morvan, accès base Halde ».';        }        if (isset($got['credit'])) {            Economy::known($this);        }        if (isset($got['tuner'])) {            $text .= ' L\'accordeur des Haldi ! Il faut le rapporter à Maëva.';        }        if (isset($got['power_cell'])) {            $text .= ' La cellule d\'énergie est intacte, encore tiède.';        }        if (!empty($t->data['bundle']) && $left === []) {            $this->removeThing($t);        }        return $text;    }    private function readPodLog(): string    {        $this->flags['q_pod_log'] = true;        if (!$this->inv->has('pod_log')) {            $this->give('pod_log');        }        $this->passTime(5);        return $this->logText('pod_log') . ' (Journal ou scanner : « Insérer dans le GPS ».)';    }    private function openBase(Thing $t): string    {        if (!$this->inv->has('keycard')) {            return 'Le sas de la base est scellé. Un lecteur de carte clignote faiblement : il faut une carte d\'accès.';        }        unset($t->data['locked']);        $this->touch($t);        $this->passTime(5);        return 'La carte d\'accès glisse dans le lecteur. Le sas s\'ouvre en grinçant après soixante ans de silence.';    }    private function mastOptions(array &$o): void    {        $this->flags['q_reach_mast'] = true;        $cell = !empty($this->flags['q_fit_cell']);        $tuner = !empty($this->flags['q_fit_tuner']);        $antenna = !empty($this->flags['q_repair_antenna']);        if (!$cell && $this->inv->has('power_cell')) {            $o[] = ['id' => 'fit_cell', 'label' => 'Installer la cellule d\'énergie', 'run' => function () {                $this->inv->remove('power_cell');                $this->flags['q_fit_cell'] = true;                $this->passTime(10);                return 'Tu enclenches la cellule dans son logement. Un voyant ambré s\'allume au pied du mât.';            }];        }        if (!$tuner && $this->inv->has('tuner')) {            $o[] = ['id' => 'fit_tuner', 'label' => 'Installer l\'accordeur', 'run' => function () {                $this->inv->remove('tuner');                $this->flags['q_fit_tuner'] = true;                $this->passTime(10);                return 'L\'accordeur se loge dans le boîtier. Le cristal vibre doucement sous tes doigts.';            }];        }        if (!$antenna && $this->inv->count('antenna_part') >= 2) {            $o[] = ['id' => 'repair', 'label' => 'Réparer l\'antenne (2 pièces)', 'run' => function () {                $this->inv->remove('antenna_part', 2);                $this->flags['q_repair_antenna'] = true;                $this->passTime(40);                return 'Les doigts gelés, tu boulonnes les deux pièces au sommet du mât. L\'antenne est entière.';            }];        }        if ($cell && $tuner && $antenna) {            $o[] = ['id' => 'transmit', 'label' => 'Émettre vers la station', 'run' => fn () => $this->transmit()];            return;        }        $o[] = ['id' => 'look', 'label' => 'Examiner le mât relais', 'run' => function () use ($cell, $tuner, $antenna) {            $miss = [];            if (!$cell) {                $miss[] = 'une cellule d\'énergie';            }            if (!$tuner) {                $miss[] = 'un accordeur';            }            if (!$antenna) {                $miss[] = 'deux pièces d\'antenne (tu en as ' . $this->inv->count('antenna_part') . ')';            }            return 'Le vieux mât de la mission Halde. Pour émettre, il lui manque : ' . implode(', ', $miss) . '.';        }];    }    private function transmit(): string    {        $h = $this->hour();        if (!($h >= 22 || $h < 4)) {            return 'Le mât grésille, mais le ciel est vide : la station ne passe au zénith qu\'en pleine nuit, entre 22 h et 4 h. Il faut attendre.';        }        $this->flags['q_transmit'] = true;        $this->flags['orbit_data'] = true;        $this->say('« Meridian, ici Rob Calder, depuis le mât de la mission Halde. Je suis vivant. »');        $this->say('Un long silence... puis la voix de la station : « Rob ? On te croyait perdu ! Nos navettes ne peuvent pas descendre dans cette atmosphère. Celle de la colonie, oui. Si tu la fais voler, on te récupère en orbite. On t\'envoie nos fenêtres de passage : le soir, de 20 h à 23 h, et à l\'aube. »');        return 'Le mât s\'illumine. Le Meridian te répond, et te donne ses fenêtres de tir.';    }    /** Lights a fire in front of Rob. */    public function lightFire(): string    {        $tool = $this->fireInHand();        if ($tool === null) {            return $this->inv->hasTool('fire') ? 'Prends ton foret à feu en main pour allumer un feu.' : 'Il te faut un outil à feu en main : un foret à feu, ou une torche allumée.';        }        $fx = $this->x + sin($this->yaw) * 1.3;        $fz = $this->z + cos($this->yaw) * 1.3;        if ($this->swimming || $this->zone->waterDepth($fx, $fz) > -0.05) {            return 'Pas de feu dans l\'eau !';        }        $minutes = 0.0;        $kit = $this->inv->has('campfire_kit');        if (!$kit && !$this->inv->has('wood') && !$this->inv->has('stick', 3)) {            return 'Il te faut du bois : une bûche ou trois bâtons.';        }        $this->passTime(10);        $raining = $this->weather !== null && in_array($this->weather['kind'], ['rain', 'storm', 'snow'], true) && !$this->sheltered();        $tinder = $this->inv->has('tinder');        $fail = ($kit ? 0.0 : ($tinder ? 0.05 : 0.25)) + ($raining ? 0.4 * $this->weather['amount'] : 0.0);        if (empty($this->flags['q_fire'])) {            $fail = min($fail, 0.1);   // the first fire of the game is kind        }        if ($this->rng->chance($fail)) {            return $raining ? 'La pluie noie tes étincelles. Abrite-toi, ou réessaie.' : 'Le bois fume mais ne prend pas. De l\'amadou aiderait.';        }        if ($kit) {            $this->inv->remove('campfire_kit');            $minutes = 300.0;        } elseif ($this->inv->has('wood')) {            $this->inv->remove('wood');            $minutes = (float) (Items::get('wood')['fuel'] ?? 120);        } else {            $this->inv->remove('stick', 3);            $minutes = 3 * (float) (Items::get('stick')['fuel'] ?? 25);        }        if ($tinder) {            $this->inv->remove('tinder');        }        $this->fires[] = ['x' => $fx, 'z' => $fz, 'minutes' => $minutes];        if (Wildfire::burnable($this, $fx, $fz) >= 0.9 && $this->wind[2] > 0.5 && $this->rng->chance(0.35 * Wildfire::dryness($this))) {            Wildfire::ignite($this, $fx + $this->wind[0] * 3, $fz + $this->wind[1] * 3, 1.0);            $this->say('Le vent couche les flammes dans l\'herbe sèche : le feu s\'échappe !');        }        $this->flags['q_fire'] = true;        $this->flags['fires'] = (int) ($this->flags['fires'] ?? 0) + 1;        return $tool === 'torch' ? 'Tu glisses la flamme de ta torche sous le bois : le feu prend !' : 'Tu frottes le foret jusqu\'à la braise. Une flamme naît : le feu prend !';    }    private function fireNear(float $r): ?int    {        $best = null;        foreach ($this->fires as $k => $f) {            $d = hypot($f['x'] - $this->x, $f['z'] - $this->z);            if ($f['minutes'] > 0 && $d < $r && ($best === null || $d < $best[1])) {                $best = [$k, $d];            }        }        return $best === null ? null : $best[0];    }    private function feedFire(int $k): string    {        foreach (['wood', 'charcoal', 'resin', 'stick'] as $id) {            if ($this->inv->has($id)) {                $this->inv->remove($id);                $this->fires[$k]['minutes'] = min(600.0, $this->fires[$k]['minutes'] + (float) (Items::get($id)['fuel'] ?? 20));                return 'Tu remets : ' . lcfirst(Items::name($id)) . ' dans le feu. Il reprend de plus belle.';            }        }        return 'Tu n\'as rien à brûler.';    }    /** Sleeps until morning (at night) or a couple of hours, all at once (the scene uses the Dormir screen instead). */    public function sleep(): string    {        $why = $this->startSleep($this->isNight() ? 'dawn' : '2h');        if ($why !== null) {            return $why;        }        return $this->finishSleep();    }    /** Something finds Rob asleep. */    private function ambush(): string    {        $species = $this->zone->cave ? 'crawler' : ($this->zone->id === 'plateau' ? 'glacier_brute' : 'stalker');        $a = $this->rng->range(0, 6.28);        $c = Wildlife::make($this, $species, $this->x + sin($a) * 2.5, $this->z + cos($a) * 2.5);        $c->state = 'attack';        if ($this->zone->solidAt($c->x, $c->z)) {            $c->x = $this->x;            $c->z = $this->z + 1.5;        }        $this->creatures[] = $c;        $part = ['larm', 'rarm', 'lleg', 'rleg', 'torso'][$this->rng->int(0, 4)];        $this->hitPlayer($part, 'bite', $this->rng->range(0.25, 0.45), Wildlife::the($species, true));        return 'Réveillé en sursaut : ' . Wildlife::one($species) . ' t\'attaque !';    }    private function checkSnare(Thing $t): string    {        $set = (float) ($t->data['set'] ?? $this->minutes);        $this->removeThing($t);        $this->give('trap_snare');        if ($this->minutes - $set > 240 && $this->rng->chance(0.6)) {            $this->give('meat_raw', 2);            $this->give('hide', 1);            return 'Un petit animal s\'est pris au collet : de la viande et une peau.';        }        return 'Le collet est vide. Laisse-le plus longtemps, sur un passage de gibier.';    }    // ------------------------------------------------------------------------------------------ items    /**     * Uses an item of the bag (the inventory screen): food and medicine on the body, tools and weapons to the hand,     * clothes worn, kits set up (fire, shelter, snare). Returns what happened (French).     */    public function useItem(string $id, string $part = 'torso'): string    {        if (!$this->inv->has($id)) {            return 'Tu n\'as pas cela.';        }        $d = Items::get($id);        $text = match (true) {            isset(Chests::KINDS[$id]) => Chests::place($this, $id),            $id === 'campfire_kit' => $this->lightFire(),            $id === 'shelter_kit' => $this->placeShelter(),            $id === 'trap_snare' => $this->placeSnare(),            $id === 'trap_spike' => $this->placeSpikes(),            $id === 'pod_log', $id === 'colony_log' => $this->logText($id),            $id === 'water_filter' => $this->filterWater(),            $id === 'purification_tablets' => $this->purifyWater(),            $id === 'scanner' => 'Le scanner s\'allume (touche Tab ou N) : batterie ' . (int) round($this->scanBattery()) . ' %.',            $id === 'patch' => $this->mendClothes(),            in_array($d['kind'], ['weapon', 'tool', 'clothing'], true) => $this->equip($id),            default => null,        };        if ($text === null) {            $food = (float) ($d['food'] ?? 0);            $water = (float) ($d['water'] ?? 0);            $text = $this->inv->use($this->body, $id, $part);            if ($this->body->lastActionOk) {                if ($water > 0) {                    $this->flags['q_drink'] = true;                }                if ($food > 0) {                    $this->flags['q_eat'] = true;                }                $this->passTime(2);            }        }        $this->say($text);        Quest::check($this);        return $text;    }    private function equip(string $id): string    {        $d = Items::get($id);        $left = $this->inv->handLeft;        $right = $this->inv->hand;        $err = $this->inv->equip($id);        if ($err !== null) {            return $err;        }        if ($d['kind'] === 'clothing') {            $this->passTime(['feet' => 2, 'head' => 0.5, 'hands' => 0.5, 'legs' => 3, 'under' => 3][Inventory::slotOf($id)] ?? 4);            return 'Tu enfiles : ' . $this->inv->label($id) . '.';        }        [$nowRight, $nowLeft, $stowed] = self::hands($this->inv);        if ($nowLeft === $id && $nowRight !== $id) {            $put = $right !== null && $nowRight === null ? ' (' . mb_strtolower(Items::name($right)) . ' rangé : il faut les deux mains)' : '';            return 'Tu prends dans la main gauche : ' . $d['name'] . $put . '.';        }        if ($left !== null && $nowLeft === null && $stowed === $left) {            return 'Tu prends à deux mains : ' . $d['name'] . ' (' . mb_strtolower(Items::name($left)) . ' rangé, il reviendra en main gauche).';        }        return 'Tu prends en main : ' . $d['name'] . '.';    }    /** @return array{0: ?string, 1: ?string, 2: ?string} right hand, left hand, the left item stowed */    private static function hands(Inventory $inv): array    {        return [$inv->hand, $inv->handLeft, $inv->stowedLeft];    }    /** Crafts a recipe (Crafting) and lets its time pass. */    public function craft(string $recipeId): string    {        $r = Crafting::recipe($recipeId);        if ($r === null) {            return 'Recette inconnue.';        }        $err = Crafting::craft($recipeId, $this->inv, $this->nearFire());        if ($err !== null) {            $this->say($err);            return $err;        }        $this->passTime((float) $r['minutes'] * $this->talents->craftTimeMul());        $text = 'Tu as fabriqué : ' . Dialogues::list($r['gives']) . '.';        $this->say($text);        $made = (array) ($this->flags['crafted'] ?? []);        $this->gainXp(empty($made[$recipeId]) ? Talents::FEAT_XP['recipe'] : Talents::FEAT_XP['craft'], empty($made[$recipeId]));        $made[$recipeId] = (int) ($made[$recipeId] ?? 0) + 1;        $this->flags['crafted'] = $made;        Quest::check($this);        return $text;    }    private function placeShelter(): string    {        if ($this->zone->cave) {            return 'Inutile ici : la roche t\'abrite déjà.';        }        $this->inv->remove('shelter_kit');        $this->addThing('tent', $this->x + sin($this->yaw) * 2, $this->z + cos($this->yaw) * 2, ['label' => 'Ton abri', 'player' => true], $this->yaw + 3.14);        $this->passTime(20);        return 'Tu montes ton abri de branchages.';    }    private function placeSpikes(): string    {        $this->inv->remove('trap_spike');        $this->addThing('trap_spike', $this->x + sin($this->yaw) * 1.5, $this->z + cos($this->yaw) * 1.5, ['label' => 'Piège à pieux', 'set' => $this->minutes]);        $this->passTime(20);        return 'Tu creuses une fosse peu profonde et la garnis de pieux taillés, couverts de feuilles. Gare à ce qui passera dessus.';    }    /** Beasts that walk onto a spike trap. */    private function springTraps(): void    {        foreach ($this->zone->things as $t) {            if ($t->kind !== 'trap_spike') {                continue;            }            foreach ($this->creatures as $c) {                if (empty($c->data['companion']) && !in_array($c->species, ['bird', 'fish', 'swarm'], true) && abs($c->x - $t->x) < 1.2 && abs($c->z - $t->z) < 1.2) {                    $this->removeThing($t);                    $this->say('Un cri dans les fourrés : ' . Wildlife::the($c->species) . ' est tombé dans ton piège à pieux !');                    Wildlife::hurt($this, $c, (float) (Items::get('trap_spike')['damage'] ?? 40) * 2);                    return;                }            }        }    }    private function placeSnare(): string    {        $this->inv->remove('trap_snare');        $this->addThing('snare', $this->x + sin($this->yaw), $this->z + cos($this->yaw), ['label' => 'Collet', 'set' => $this->minutes]);        $this->passTime(5);        return 'Tu tends un collet sur le sol. Reviens dans quelques heures.';    }    // ------------------------------------------------------------------------------------------ water, worms    /** Boils a gourd of dirty (or filtered) water by the fire: in the pot, else with stones heated in the fire. */    public function boilWater(): string    {        if (!$this->nearFire()) {            return 'Il te faut un feu pour faire bouillir l\'eau.';        }        $src = $this->inv->has('gourd_dirty') ? 'gourd_dirty' : ($this->inv->has('gourd_filtered') ? 'gourd_filtered' : null);        if ($src === null) {            return 'Tu n\'as pas d\'eau à faire bouillir : remplis une gourde au lac.';        }        $recipe = $this->inv->hasTool('pot') ? ($src === 'gourd_filtered' ? 'water_boiled_filtered' : 'water_boiled')            : ($src === 'gourd_dirty' && $this->inv->has('stone') ? 'water_boiled_stones' : null);        if ($recipe === null) {            return 'Il te faut un pot de cuisson, ou une pierre à chauffer dans le feu puis à plonger dans la gourde.';        }        $err = Crafting::craft($recipe, $this->inv, true);        if ($err !== null) {            return $err;        }        $this->passTime((float) (Crafting::recipe($recipe)['minutes'] ?? 15));        $this->flags['boiled'] = (int) ($this->flags['boiled'] ?? 0) + 1;        return $recipe === 'water_boiled_stones'            ? 'Tu chauffes une pierre dans les braises et la plonges dans la gourde : l\'eau frémit, puis bout. Eau bouillie, sûre.'            : 'L\'eau bout un long moment dans le pot. Une fois tiède, elle est sûre : gourde d\'eau bouillie.';    }    /** The water filter: a gourd of dirty water goes through charcoal and sand. */    public function filterWater(): string    {        if (!$this->inv->hasTool('filter')) {            return 'Il te faut un filtre à eau (artisanat : gourde, charbon, sable, fibres).';        }        if (!$this->inv->has('gourd_dirty')) {            return 'Rien à filtrer : il te faut une gourde d\'eau trouble.';        }        $this->inv->remove('gourd_dirty');        $this->give('gourd_filtered');        $this->passTime(10);        return 'L\'eau trouble goutte à travers le charbon et le sable : gourde d\'eau filtrée. Bouillie, elle serait parfaite.';    }    /** A purification tablet in a gourd of dirty water. */    public function purifyWater(): string    {        if (!$this->inv->has('purification_tablets')) {            return 'Plus de pastilles de purification.';        }        if (!$this->inv->has('gourd_dirty') && !$this->inv->has('gourd_filtered')) {            return 'Une pastille se met dans une gourde d\'eau trouble : remplis-en une d\'abord.';        }        $src = $this->inv->has('gourd_dirty') ? 'gourd_dirty' : 'gourd_filtered';        $this->inv->remove('purification_tablets');        $this->inv->remove($src);        $this->give('gourd_purified');        $this->passTime(30);        return 'Tu laisses fondre une pastille dans la gourde et attends une demi-heure : eau purifiée, au goût de chlore.';    }    /** Digs the soil for earthworms: better in mud, after rain, with a stick or a knife. */    public function digWorms(): string    {        $biome = $this->zone->biomeAt($this->x, $this->z);        $tool = $this->inv->hasTool('cut') || $this->inv->has('stick') || $this->inv->hasTool('chop');        $rain = $this->minutes - (float) ($this->flags['rain_at'] ?? -9999.0);        $wet = $rain >= 0 && $rain < 360 ? 1.0 - $rain / 360 : 0.0;        $raining = $this->weather !== null && in_array($this->weather['kind'], ['rain', 'storm'], true) && (float) $this->weather['amount'] > 0.2;        if ($raining) {            $wet = 1.0;        }        $p = ['mud' => 0.5, 'jungle' => 0.4, 'grass' => 0.25][$biome] ?? 0.1;        $p += 0.35 * $wet + ($tool ? 0.15 : 0.0) - ($this->isNight() ? 0.0 : 0.05);        $this->passTime($tool ? 6 : 10);        $this->inv->wear(0.8, ['hands']);        if (!$this->rng->chance(min(0.95, $p))) {            return $wet > 0.3 ? 'Tu retournes la terre mouillée... rien cette fois. Essaie un peu plus loin.'                : 'Tu grattes une terre sèche : pas un ver. Ils remontent après la pluie, dans la boue.';        }        $n = 1 + (int) floor($this->rng->next() * (1 + 3 * $wet + ($biome === 'mud' ? 1 : 0) + ($tool ? 1 : 0)));        $this->give('earthworm', $n);        $this->flags['worms'] = (int) ($this->flags['worms'] ?? 0) + $n;        return 'Tu retournes la terre ' . ($tool ? 'avec ' . ($this->inv->hasTool('cut') ? 'ton couteau' : 'un bâton') : 'à mains nues')            . ' : ' . $n . ' ver' . ($n > 1 ? 's' : '') . ' de terre gigote' . ($n > 1 ? 'nt' : '') . ' dans ta paume.'            . ($wet > 0.5 ? ' La pluie les a fait remonter.' : '');    }    /** The waterfall Rob looks at or stands by (within $r metres), null: none. */    public function fallNear(float $r): ?Thing    {        foreach ($this->zone->thingsNear($this->x, $this->z, $r + 6) as $t) {            if ($t->kind === 'waterfall') {                [$a, $b] = self::fallLocal($t, $this->x, $this->z);                if (abs($b) < (float) ($t->data['w'] ?? 6) / 2 + 2 && $a > -1 && $a < $r) {                    return $t;                }            }        }        return null;    }    /** Is Rob in the falling water (the plunge line of the sheet)? */    public function underFall(Thing $t): bool    {        [$a, $b] = self::fallLocal($t, $this->x, $this->z);        $reach = (float) ($t->data['reach'] ?? 5.4);        return abs($b) < (float) ($t->data['w'] ?? 6) / 2 && abs($a - $reach) < 0.9;    }    /** @return array{0: float, 1: float} a point in the frame of a waterfall: in front of the lip, to the side */    public static function fallLocal(Thing $t, float $x, float $z): array    {        $fx = sin($t->yaw);        $fz = cos($t->yaw);        $dx = $x - $t->x;        $dz = $z - $t->z;        return [$dx * $fx + $dz * $fz, $dx * $fz - $dz * $fx];    }    // ------------------------------------------------------------------------------------------ the GPS    /** @return array{0: float, 1: float} where a zone's (0, 0) lies on Ysor (metres east, metres south of the valley's) */    public static function zoneOrigin(string $zone): array    {        static $o = null;        if ($o === null) {            $o = ['valley' => [0.0, 0.0]];            // walk the doors from the valley: an exit and its arrival are the same place            for ($pass = 0; $pass < 5; $pass++) {                foreach (ZoneFactory::IDS as $id) {                    if (!isset($o[$id])) {                        continue;                    }                    foreach (ZoneFactory::exits($id) as $e) {                        if (!isset($o[$e['to']])) {                            $o[$e['to']] = [$o[$id][0] + $e['x'] - $e['toX'], $o[$id][1] + $e['z'] - $e['toZ']];                        }                    }                }            }        }        return $o[$zone] ?? [0.0, 0.0];    }    /** @return array{0: float, 1: float} latitude (north), longitude (east) in degrees of a point of a zone */    public static function coords(string $zone, float $x, float $z): array    {        [$ox, $oz] = self::zoneOrigin($zone);        $lat = self::GRID_ORIGIN[0] - ($oz + $z) / 111320.0;        $lon = self::GRID_ORIGIN[1] + ($ox + $x) / (111320.0 * cos(deg2rad(self::GRID_ORIGIN[0])));        return [$lat, $lon];    }    /** "41.2093 N / 118.5561 E" */    public static function coordText(string $zone, float $x, float $z): string    {        [$lat, $lon] = self::coords($zone, $x, $z);        return sprintf('%.4f N / %.4f E', $lat, $lon);    }    /**     * The places a log gives the coordinates of: id => [name, zone, x, z].     * @return array<string, array{0: string, 1: string, 2: float, 3: float}>     */    public function logPlaces(string $log): array    {        $v = ZoneFactory::villageCentre($this->seed);        return match ($log) {            'pod_log' => ['halde_base' => ['Base Halde (signal)', 'caves2', 128.0, 140.0]],            'colony_log' => [                'haldi_refuge' => ['Refuge du canyon', 'canyon', (float) $v[0], (float) $v[1]],                'relay_mast' => ['Mât relais', 'plateau', ZoneFactory::MAST[0], ZoneFactory::MAST[1]],            ],            default => [],        };    }    /** The text of a log, with its coordinates. */    public function logText(string $log): string    {        $base = $log === 'colony_log' ? self::COLONY_LOG : self::POD_LOG;        $parts = [];        foreach ($this->logPlaces($log) as [$name, $zone, $x, $z]) {            $parts[] = $name . ' : ' . self::coordText($zone, $x, $z);        }        return $base . ($parts === [] ? '' : ' Coordonnées relevées — ' . implode(' ; ', $parts) . '.');    }    /** Puts the places of a log into the GPS (the first one becomes the active waypoint). Returns what happened. */    public function insertLog(string $log): string    {        $places = $this->logPlaces($log);        if ($places === []) {            return 'Ce journal ne contient aucune coordonnée.';        }        if (!$this->inv->has('scanner')) {            return 'Sans le scanner (et son GPS), ces coordonnées ne te servent à rien.';        }        $new = [];        foreach ($places as $id => [$name, $zone, $x, $z]) {            if (!isset($this->waypoints[$id])) {                $new[] = $name;            }            $this->waypoints[$id] = [$name, $zone, $x, $z];        }        $this->activeWaypoint = (string) array_key_first($places);        $this->flags['gps'] = true;        return $new === [] ? 'Ces coordonnées sont déjà dans le GPS : ' . $this->waypoints[$this->activeWaypoint][0] . ' est le point actif.'            : 'GPS : point' . (count($new) > 1 ? 's' : '') . ' ajouté' . (count($new) > 1 ? 's' : '') . ' — ' . implode(', ', $new) . '. La boussole le montre.';    }    /** Rob's own mark, where he stands. */    public function markHere(string $name = ''): string    {        $n = 1;        while (isset($this->waypoints['mark' . $n])) {            $n++;        }        $id = 'mark' . $n;        $this->waypoints[$id] = [$name !== '' ? $name : 'Repère ' . $n, $this->zone->id, $this->x, $this->z];        $this->activeWaypoint = $id;        return 'GPS : « ' . $this->waypoints[$id][0] . ' » marqué ici (' . self::coordText($this->zone->id, $this->x, $this->z) . ').';    }    public function removeWaypoint(string $id): void    {        unset($this->waypoints[$id]);        if ($this->activeWaypoint === $id) {            $this->activeWaypoint = null;        }    }    public function setActiveWaypoint(?string $id): void    {        $this->activeWaypoint = $id !== null && isset($this->waypoints[$id]) ? $id : null;    }    /**     * Where to walk for the active waypoint, in this zone: the point itself, or the door toward its zone.     * @return array{0: float, 1: float, 2: string, 3: float, 4: bool}|null x, z, label, distance (m), the point itself?     */    public function waypointTarget(?string $id = null): ?array    {        $id ??= $this->activeWaypoint;        if ($id === null || !isset($this->waypoints[$id])) {            return null;        }        [$name, $zone, $x, $z] = $this->waypoints[$id];        if ($zone === $this->zone->id) {            return [$x, $z, $name, hypot($x - $this->x, $z - $this->z), true];        }        $here = self::ROUTE[$this->zone->id] ?? 0;        $there = self::ROUTE[$zone] ?? 0;        $toward = array_search($there > $here ? $here + 1 : $here - 1, self::ROUTE, true);        foreach ($this->zone->exits as $e) {            if ($e['to'] === $toward) {                return [(float) $e['x'], (float) $e['z'], $name . ' (par ' . mb_strtolower($e['label']) . ')', hypot($e['x'] - $this->x, $e['z'] - $this->z), false];            }        }        return null;    }    /** Straight-line distance to a waypoint on Ysor's grid, whatever the zone (metres). */    public function waypointDistance(string $id): float    {        if (!isset($this->waypoints[$id])) {            return 0.0;        }        [, $zone, $x, $z] = $this->waypoints[$id];        [$ax, $az] = self::zoneOrigin($zone);        [$bx, $bz] = self::zoneOrigin($this->zone->id);        return hypot($ax + $x - $bx - $this->x, $az + $z - $bz - $this->z);    }    // ------------------------------------------------------------------------------------------ sleep    public const SLEEP_MODES = ['1h' => 'Une heure', '4h' => 'Quatre heures', 'dawn' => 'Jusqu\'à l\'aube', 'healed' => 'Jusqu\'à être reposé', 'rest' => 'Se reposer (20 min, assis)'];    /** Where Rob would sleep: shelter (a hut, a tent, the caves), fire, ground. */    public function sleepPlace(): string    {        if ($this->sheltered()) {            return $this->nearFire() || ($this->zone->cave && $this->nearFire(6)) ? 'shelter_fire' : 'shelter';        }        return $this->nearFire() ? 'fire' : 'ground';    }    /** 0.6..1.2: how well Rob rests there (bare ground, rain, cold: worse). */    public function sleepComfort(): float    {        $c = ['shelter_fire' => 1.15, 'shelter' => 1.0, 'fire' => 0.95, 'ground' => 0.75][$this->sleepPlace()];        if ($this->inv->wet > 0.5) {            $c -= 0.15;        }        return max(0.5, $c);    }    /**     * What sleeping here means, for the Dormir screen: the place, how well, the risks (label, 0..1).     * @return array{place: string, label: string, comfort: float, risks: list<array{0: string, 1: float}>, can: ?string, night: bool}     */    public function sleepInfo(): array    {        $place = $this->sleepPlace();        $label = ['shelter_fire' => 'À l\'abri, près du feu', 'shelter' => $this->zone->cave ? 'Dans la roche de la caverne' : 'À l\'abri',            'fire' => 'Près du feu, à la belle étoile', 'ground' => 'À même le sol, sans feu ni abri'][$place];        $risks = [];        $air = $this->airTemp() - ($this->isNight() ? 0.0 : 4.0);        $warm = $air + $this->inv->warmth() * 0.6 + ($this->nearFire() ? 12 : 0) + ($this->sheltered() ? 4 : 0) - ($this->inv->wet > 0.5 ? 8 : 0);        if ($warm < 16) {            $risks[] = [$this->nearFire() ? 'Froid si le feu s\'éteint' : 'Froid : la nuit sera glaciale', max(0.2, min(1.0, (16 - $warm) / 12))];        }        $safe = in_array($place, ['shelter_fire', 'fire'], true) || ($place === 'shelter' && !$this->zone->cave);        if (!$safe) {            $risks[] = [$this->zone->cave ? 'Bêtes des cavernes' : 'Prédateurs nocturnes', $this->zone->cave ? 0.5 : ($this->isNight() ? 0.7 : 0.2)];        }        $w = $this->weather;        if ($w !== null && in_array($w['kind'], ['rain', 'storm', 'snow'], true) && !$this->sheltered()) {            $risks[] = [['rain' => 'Pluie : tu seras trempé', 'storm' => 'Orage : trempé, réveillé', 'snow' => 'Neige : froid et mouillé'][$w['kind']], 0.3 + 0.6 * (float) $w['amount']];        }        $bleed = $this->body->vitals()['bleeding'];        if ($bleed > 0.0005) {            $risks[] = ['Une plaie saigne : bande-la d\'abord', 0.9];        }        $v = $this->body->vitals();        if ($v['thirst'] < 25 || $v['hunger'] < 15) {            $risks[] = [$v['thirst'] < 25 ? 'La soif te réveillera' : 'La faim te réveillera', 0.5];        }        $can = null;        if ($this->dangerNear()) {            $can = 'Impossible de dormir : le danger rôde tout près.';        } elseif ($this->swimming) {            $can = 'Pas dans l\'eau !';        }        return ['place' => $place, 'label' => $label, 'comfort' => $this->sleepComfort(), 'risks' => $risks, 'can' => $can, 'night' => $this->isNight()];    }    /** Starts a sleep (or a rest): null when Rob lies down, else why he cannot. */    public function startSleep(string $mode): ?string    {        if (!isset(self::SLEEP_MODES[$mode]) && $mode !== '2h') {            return 'Durée inconnue.';        }        $info = $this->sleepInfo();        if ($info['can'] !== null) {            return $info['can'];        }        $v = $this->body->vitals();        if ($mode !== 'rest' && !$this->isNight() && $v['fatigue'] > 80) {            return 'Tu n\'as pas sommeil.';        }        $h = $this->hour();        $target = match ($mode) {            '1h' => 60.0,            '2h' => 120.0,            '4h' => 240.0,            'rest' => 20.0,            'dawn' => max(30.0, ($h >= 6.5 ? 24 - $h + 6.5 : 6.5 - $h) * 60),            default => 16 * 60.0,        };        $target = min($mode === 'dawn' ? 720.0 : 960.0, $target);        $this->sleeping = ['mode' => $mode, 'place' => $info['place'], 'target' => $target, 'slept' => 0.0, 'woken' => null, 'done' => false,            'rest' => $mode === 'rest', 'fire' => $this->nearFire(), 'night' => $this->isNight(), 'start' => $this->clock(),            'safe' => in_array($info['place'], ['shelter_fire', 'fire'], true) || ($info['place'] === 'shelter' && !$this->zone->cave),            'dreams' => $this->dreams(), 'fatigue0' => $v['fatigue'], 'rain0' => $this->rainingOnRob()];        return null;    }    private function rainingOnRob(): bool    {        $w = $this->weather;        return !$this->sheltered() && $w !== null && in_array($w['kind'], ['rain', 'storm'], true) && (float) $w['amount'] > 0.3;    }    /** @return list<string> what goes through Rob's mind as he falls asleep (French) */    private function dreams(): array    {        $v = $this->body->vitals();        $pool = [            'Tu revois la station Meridian, sa lumière blanche au-dessus des nuages.',            'Le visage de ta sœur, sur le quai d\'embarquement. Elle riait.',            'Le bip régulier de la balise... puis plus rien.',            'Tu rêves que la navette se pose, et que tu ne sais plus marcher.',            'Des voix haldi chantent dans une langue que tu comprends presque.',            'Tu comptes les étoiles d\'Ysor : aucune ne ressemble à celles de chez toi.',            'La nacelle tombe, tombe encore, et le sol ne vient jamais.',            'Une odeur de café, dans la cantine de la station. Ton estomac s\'en souvient.',        ];        if ($this->nearFire()) {            $pool[] = 'Le feu craque doucement. Pour la première fois, tu te sens presque chez toi.';        }        if ($v['temperature'] < 36 || $this->airTemp() < 8) {            $pool[] = 'Le froid te mord les doigts. Tu te recroquevilles sous tes vêtements.';        }        if ($v['hunger'] < 35) {            $pool[] = 'Tu rêves d\'un repas chaud. Ton ventre gronde dans le noir.';        }        if ($this->body->pain() > 0.3) {            $pool[] = 'La douleur te tire du sommeil, puis t\'y replonge.';        }        if ($this->isNight() && !$this->zone->cave) {            $pool[] = 'Au loin, un hurlement. Tu tends l\'oreille, longtemps.';        }        $out = [];        for ($k = 0; $k < 4 && $pool !== []; $k++) {            $i = $this->rng->int(0, count($pool) - 1);            $out[] = $pool[$i];            array_splice($pool, $i, 1);        }        return $out;    }    /**     * Lets $minutes of the sleep pass (the scene: fast, about 90 game minutes a second). Rob wakes up by himself     * (time done, rested), or because of something (a beast, the cold, the rain, thirst, a wound): sleeping['woken'].     */    public function sleepStep(float $minutes): void    {        $s = $this->sleeping;        if ($s === null || $s['done'] || !($minutes > 0) || !is_finite($minutes)) {            return;        }        $left = min($minutes, (float) $s['target'] - (float) $s['slept']);        while ($left > 0 && !$this->sleeping['done']) {            $c = min(10.0, $left);            $left -= $c;            $this->passTime($c, !$this->sleeping['rest']);            $this->sleeping['slept'] += $c;            $why = $this->sleepWake($c);            if ($why !== null) {                $this->sleeping['woken'] = $why;   // (sleepWake() never ends the sleep itself: sleeping stays set)                $this->sleeping['done'] = true;                break;            }            if ($this->sleeping['slept'] >= $this->sleeping['target'] - 0.001) {                $this->sleeping['done'] = true;            }        }    }    /** Something that wakes Rob up during the last $c minutes (French), null: he sleeps on. */    private function sleepWake(float $c): ?string    {        $s = $this->sleeping;        if ($s === null || $this->body->dead()) {            return $this->body->dead() ? 'Tu ne te réveilles pas.' : null;        }        if ($s['rest']) {            return $this->dangerNear() ? 'Un bruit te fait sursauter : quelque chose approche !' : null;        }        $v = $this->body->vitals();        if ($this->dangerNear()) {            return 'Un craquement tout près : tu ouvres les yeux d\'un coup. Une bête rôde autour de toi !';        }        // a beast finds the sleeper (not by a fire, not in a hut, not with someone keeping watch)        if (!$s['safe'] && !Companions::watch($this)) {            $p = ($this->zone->cave ? 0.05 : ($this->isNight() ? 0.06 : 0.01)) * $c / 30;            if ($this->rng->chance($p)) {                if ($this->rng->chance(0.5)) {                    return $this->ambush();                }                $this->prowler();                return 'Un grognement sourd te réveille : une bête rôde à quelques pas, dans le noir.';            }        }        if ($s['fire'] && !$this->nearFire() && $this->airTemp() < 14) {            return 'Le feu s\'est éteint. Le froid te réveille, les membres raides.';        }        if ($v['temperature'] < 35.4) {            return 'Tu grelottes trop pour dormir : il te faut un feu, un abri, des vêtements secs.';        }        if (!$s['rain0'] && $this->rainingOnRob()) {            return 'La pluie te réveille : tu es trempé.';        }        if ($v['bleeding'] > 0.002) {            return 'Une douleur chaude : ta plaie saigne encore. Tu te réveilles en sueur.';        }        if ($v['thirst'] < 8) {            return 'La soif te réveille, la bouche sèche.';        }        if ($v['hunger'] < 5) {            return 'La faim te tord le ventre et te réveille.';        }        // up with the day, or rested enough        if ($s['mode'] === 'healed' && $v['fatigue'] >= 99.5 && ($v['health'] >= 90 || $s['slept'] > 600)) {            $this->sleeping['done'] = true;        }        if ($s['mode'] !== 'dawn' && $s['mode'] !== 'healed' && $v['fatigue'] >= 99.9 && !$this->isNight() && $s['slept'] >= 30) {            $this->sleeping['done'] = true;        }        return null;    }    /** A beast comes near the sleeper without biting (it stalks him). */    private function prowler(): void    {        $species = $this->zone->cave ? 'crawler' : ($this->zone->id === 'plateau' ? 'glacier_brute' : 'stalker');        $a = $this->rng->range(0, 6.28);        $c = Wildlife::make($this, $species, $this->x + sin($a) * 9, $this->z + cos($a) * 9);        if ($this->zone->solidAt($c->x, $c->z)) {            $c->x = $this->x - sin($this->yaw) * 8;            $c->z = $this->z - cos($this->yaw) * 8;        }        $c->state = 'stalk';        $this->creatures[] = $c;    }    /** Ends the sleep at once (the player skips it): the rest of it passes, unless something wakes Rob. Returns the summary. */    public function finishSleep(): string    {        if ($this->sleeping === null) {            return '';        }        $this->sleepStep(max(0.0, (float) $this->sleeping['target'] - (float) $this->sleeping['slept']));        return $this->wake();    }    /** Rob gets up: the summary of the night (French), and the sleep is over. */    public function wake(): string    {        $s = $this->sleeping;        if ($s === null) {            return '';        }        $this->sleeping = null;        $slept = (float) $s['slept'];        $v = $this->body->vitals();        $gain = (int) round($v['fatigue'] - (float) $s['fatigue0']);        if ($s['rest']) {            $text = sprintf('Tu te reposes %d min, assis. Ton souffle se calme (repos %+d).', (int) $slept, $gain);        } else {            if ($s['safe'] && $slept >= min(240.0, (float) $s['target'])) {                $this->flags['q_sleep'] = true;            }            if ($s['night'] && $slept >= 120) {                $this->flags['nights'] = (int) ($this->flags['nights'] ?? 0) + 1;            }            $text = sprintf('Tu dors %d h %02d. Réveil : %s. Repos %+d.', (int) ($slept / 60), (int) fmod($slept, 60), $this->clock(), $gain);            if ($s['woken'] === null) {                $text .= match ($s['place']) {                    'shelter_fire' => ' Bien au chaud, à l\'abri : tu te sens reposé.',                    'shelter' => ' À l\'abri, tu as bien dormi.',                    'fire' => ' Près du feu, ton sommeil a été correct.',                    default => ' À même le sol, ton sommeil a été agité.',                };            }        }        if ($s['woken'] !== null) {            $text .= ' ' . $s['woken'];        }        $this->say($text);        Quest::check($this);        return $text;    }    // ------------------------------------------------------------------------------------------ wave 2 helpers    public function win(): void    {        $this->won = true;    }    public function riverNoise(): Noise    {        return $this->riverNoise ??= ZoneFactory::noiseOf('jungle', $this->seed);    }    /** Rob in the water without his raft: carried to the nearest shore. */    public function toShore(): void    {        $z = $this->zone;        for ($d = 2.0; $d < 120; $d += 2.0) {            for ($a = 0; $a < 6.283; $a += 0.3927) {                $x = $this->x + sin($a) * $d;                $zz = $this->z + cos($a) * $d;                if ($x > 8 && $zz > 8 && $x < $z->size - 8 && $zz < $z->size - 8 && $z->waterDepth($x, $zz) < 0.2 && !$z->solidAt($x, $zz)) {                    $this->x = $x;                    $this->z = $zz;                    $this->y = $z->heightAt($x, $zz);                    $this->passTime(10);                    return;                }            }        }    }    /** Sounds asked by the game (thunder after a flash, shots) since the last call. @return list<array{0: string, 1: float, 2: float}> */    public function takeEvents(): array    {        $e = $this->events;        $this->events = [];        return $e;    }    // ------------------------------------------------------------------------------------------ save    public function toArray(): array    {        $fires = [];        foreach ($this->fires as $f) {            if (empty($f['permanent'])) {                $fires[] = $f;            }        }        return [            'v' => 1, 'seed' => $this->seed, 'zone' => $this->zone->id,            'x' => $this->x, 'y' => $this->y, 'z' => $this->z, 'yaw' => $this->yaw, 'pitch' => $this->pitch, 'minutes' => $this->minutes,            'body' => $this->body->toArray(), 'inv' => $this->inv->toArray(), 'weather' => $this->weather, 'weatherLeft' => $this->weatherLeft,            'fires' => $fires, 'zoneFires' => $this->zoneFires, 'flags' => $this->flags, 'diffs' => $this->diffs,            'log' => array_slice($this->log, -30), 'rng' => $this->rng->state(), 'nextThing' => $this->nextThing, 'nextId' => $this->nextId,            'won' => $this->won, 'torchLeft' => $this->torchLeft, 'weatherTarget' => $this->weatherTarget, 'scanBat' => round($this->scanBat, 2),            'explored' => array_map('base64_encode', $this->explored),            'waypoints' => $this->waypoints, 'activeWaypoint' => $this->activeWaypoint,            'v2' => 1, 'people' => $this->people, 'raft' => $this->raft, 'blazes' => $this->blazes, 'blazeStore' => $this->blazeStore, 'burnt' => $this->burnt,            'wind' => $this->wind, 'companion' => $this->companion, 'companionFed' => $this->companionFed, 'pet' => $this->pet, 'cellShots' => $this->cellShots,            'talents' => $this->talents->toArray(),        ];    }    public static function fromArray(array $a): self    {        $g = new self((int) ($a['seed'] ?? 1));        $g->body = Body::fromArray((array) ($a['body'] ?? []));        $g->inv = Inventory::fromArray((array) ($a['inv'] ?? []));        $g->talents = Talents::fromArray($a['talents'] ?? null);        $g->flags = (array) ($a['flags'] ?? []);        $g->diffs = [];        foreach ((array) ($a['diffs'] ?? []) as $zone => $d) {            $g->diffs[(string) $zone] = ['mod' => [], 'del' => [], 'add' => []];            foreach ((array) ($d['mod'] ?? []) as $id => $m) {                $g->diffs[(string) $zone]['mod'][(int) $id] = (array) $m;            }            foreach ((array) ($d['del'] ?? []) as $id => $v) {                $g->diffs[(string) $zone]['del'][(int) $id] = true;            }            foreach ((array) ($d['add'] ?? []) as $id => $t) {                $g->diffs[(string) $zone]['add'][(int) $id] = (array) $t;            }        }        $g->zoneFires = (array) ($a['zoneFires'] ?? []);        $g->minutes = (float) ($a['minutes'] ?? 0);        $g->weather = isset($a['weather']) && is_array($a['weather']) ? ['kind' => (string) $a['weather']['kind'], 'amount' => (float) $a['weather']['amount']] : null;        $g->weatherLeft = (float) ($a['weatherLeft'] ?? 60);        $g->rng->setState((float) ($a['rng'] ?? 1));        $g->nextThing = (int) ($a['nextThing'] ?? self::ADDED);        $g->nextId = (int) ($a['nextId'] ?? 1000);        $g->won = (bool) ($a['won'] ?? false);        $g->torchLeft = (float) ($a['torchLeft'] ?? 0);        $wt = $a['weatherTarget'] ?? null;        $g->weatherTarget = is_array($wt) && isset($wt['kind']) ? ['kind' => (string) $wt['kind'], 'amount' => (float) ($wt['amount'] ?? 0)] : null;        $bytes = intdiv(self::FOG_CELLS * self::FOG_CELLS, 8);        foreach ((array) ($a['explored'] ?? []) as $zid => $b64) {            $bits = base64_decode((string) $b64, true);            if (is_string($bits) && strlen($bits) === $bytes) {                $g->explored[(string) $zid] = $bits;            }        }        $g->scanBat = (float) ($a['scanBat'] ?? 100.0);        foreach ((array) ($a['waypoints'] ?? []) as $id => $w) {            if (is_array($w) && count($w) >= 4 && in_array((string) $w[1], ZoneFactory::IDS, true)) {                $g->waypoints[(string) $id] = [(string) $w[0], (string) $w[1], (float) $w[2], (float) $w[3]];            }        }        $aw = $a['activeWaypoint'] ?? null;        $g->activeWaypoint = is_string($aw) && isset($g->waypoints[$aw]) ? $aw : null;        foreach ((array) ($a['people'] ?? []) as $k => $p) {            if (isset(People::WHO[(string) $k]) && is_array($p)) {                $g->people[(string) $k] = $p;            }        }        $g->raft = isset($a['raft']) && is_array($a['raft']) ? array_map('floatval', $a['raft']) : null;        $g->blazes = array_values(array_filter((array) ($a['blazes'] ?? []), 'is_array'));        $g->blazeStore = (array) ($a['blazeStore'] ?? []);        $g->burnt = (array) ($a['burnt'] ?? []);        $wind = (array) ($a['wind'] ?? []);        $g->wind = count($wind) === 3 ? array_map('floatval', array_values($wind)) : [1.0, 0.0, 0.2];        $comp = $a['companion'] ?? null;        $g->companion = is_string($comp) && isset(People::WHO[$comp]) ? $comp : null;        $g->companionFed = (float) ($a['companionFed'] ?? 0);        $g->pet = (array) ($a['pet'] ?? []);        $g->cellShots = (int) ($a['cellShots'] ?? 0);        if ($g->companion !== null) {            $g->inv->setCapacity(Inventory::DEFAULT_CAPACITY + Companions::CARRY);        }        if (!isset($a['v2'])) {            self::migrate($g);        }        if (!isset($a['scanBat']) && !$g->inv->has('scanner')) {            // a save of before the scanner: the pod's scanner was in the bag            $g->inv->add('scanner');        }        $zone = (string) ($a['zone'] ?? 'valley');        $g->enterZone(in_array($zone, ZoneFactory::IDS, true) ? $zone : 'valley');        foreach ((array) ($a['fires'] ?? []) as $f) {            $g->fires[] = ['x' => (float) $f['x'], 'z' => (float) $f['z'], 'minutes' => (float) $f['minutes']];        }        $g->x = (float) ($a['x'] ?? ZoneFactory::START[0]);        $g->z = (float) ($a['z'] ?? ZoneFactory::START[1]);        $g->y = (float) ($a['y'] ?? $g->zone->heightAt($g->x, $g->z));        $g->yaw = (float) ($a['yaw'] ?? 0);        $g->pitch = (float) ($a['pitch'] ?? 0);        foreach ((array) ($a['log'] ?? []) as $m) {            $g->log[] = (string) $m;        }        $blazes = $g->blazes;        Wildlife::spawn($g, true);        $g->blazes = $blazes;        $g->reveal();        Quest::check($g);        return $g;    }    /**     * A save of before the escape (wave 1): the story went on toward the mast. The flags keep their meaning; a mast that     * already answered gives the Meridian's orbital windows; a returned tuner made the Haldi trust Rob; the goal is now the     * shuttle (Quest).     */    private static function migrate(self $g): void    {        if (!empty($g->flags['q_return_tuner'])) {            People::change($g, 'maeva', 35, false);        }        if (!empty($g->flags['q_transmit'])) {            $g->flags['orbit_data'] = true;            if (!$g->won) {                $g->say('Le Meridian a répondu à ton appel, mais il ne peut pas descendre : il te transmet ses orbites. La seule navette de cette lune est celle de la colonie, sur la côte volcanique.');            }        }        $g->flags['chapter_told'] = min((int) ($g->flags['chapter_told'] ?? 0), Quest::chapter($g));        $g->flags['migrated_v2'] = true;    }}