diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..5a544bd --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,36 @@ +name: CI + +on: + push: + branches: [dev, main, master] + pull_request: + workflow_dispatch: + +jobs: + test: + name: lint + test (node ${{ matrix.node }}) + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + node: [18, 20, 22] + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-node@v4 + with: + node-version: ${{ matrix.node }} + cache: npm + + - name: Install dependencies + run: npm ci + + - name: Lint + run: npm run lint + + - name: Run test suite (unit + integration, real-time mock flights) + run: node test/run.js + timeout-minutes: 10 + + - name: Pack dry run (verify package contents) + run: npm pack --dry-run diff --git a/.gitignore b/.gitignore index 552f221..fe77477 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,5 @@ node_modules/ *.log + +# legacy monolith — kept on disk for reference, not version-controlled +legacy/ diff --git a/AGENTS.md b/AGENTS.md index 1c62ebb..6ddcd13 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -2,7 +2,20 @@ ## Package Overview -`@eksses/eafe` is a mineflayer plugin for autonomous elytra flight in Minecraft. It handles takeoff, climb, cruise, terrain avoidance, and safe landing automatically. +`@eksses/eafe` is an autonomous elytra flight engine for mineflayer. It handles +takeoff, climb, cruise, terrain avoidance, and safe landing automatically. +`fly()` is **promise-based**: it resolves with the landing position and rejects +with a typed `ElytraFlightError` (`err.code`). + +## Commands + +```bash +node test/run.js # unit + integration (~40s, real-time mock flights) +node test/run.js unit # unit only +node test/run.js integ # integration only +npm run lint # ESLint flat config over src, test, examples +npm pack --dry-run # verify package contents +``` ## Quick Start @@ -13,7 +26,12 @@ const { ElytraFlight } = require('@eksses/eafe'); const bot = mineflayer.createBot({ host: 'localhost', username: 'Bot' }); bot.once('spawn', () => { const flight = new ElytraFlight(bot); - flight.fly(500, 500); + flight.fly(500, 500) + .then((res) => console.log('Landed at', res.landedAt)) + .catch((err) => { + if (err.code === 'STOPPED') return; + console.error(err.code, err.message); + }); }); ``` @@ -21,199 +39,144 @@ bot.once('spawn', () => { ``` src/ -├── index.js # ElytraFlight class (main API) -├── config.js # Server config (host, port, debug) -├── constants.js # MODES, PHASE, HAZARD_SURFACES -├── logger.js # Logger with [E] prefix -├── utils.js # sleep, isAir, isSafeSolidBlock, angleDiff -├── commands.js # Chat command processor +├── index.js # ElytraFlight class (main API, ctx wiring, retry scheduler) +├── constants.js # MODES, PHASE, HAZARD_SURFACES, CARDINAL_YAWS +├── errors.js # ErrorCode (19 codes), ElytraFlightError, NON_RETRYABLE +├── logger.js # Logger with [E] prefix (per-instance) +├── utils.js # sleep, isAir, hasCollision, angleDiff ├── core/ -│ ├── chat.js # safeChat, ownerTell, setPhase │ ├── inventory.js # countRockets, findRocket, autoEquipRocket -│ ├── elytra.js # getElytraSummary, auditAndEquipElytra -│ └── rockets.js # fireRocketDirect, smartFireRocket +│ ├── elytra.js # getElytraSummary, auditAndEquipElytra, damage rate 2/(n+3) +│ └── rockets.js # fireRocketDirect (yaw-gated), smartFireRocket, getBoostTime └── flight/ - ├── spatial.js # getGroundBlockAt, scanFullRenderDistance - ├── phases.js # startFlight, startClimb, startCruise + ├── spatial.js # getGroundBlockAt, scanFullRenderDistance, ground tracking + ├── phases.js # startFlight, startClimb, startCruise, executeTakeoff ├── wander.js # findSafeLandingSpotAround, startWanderScan - └── landing.js # startLanding (spiral descent) -``` - -## Core API + └── landing.js # startLanding (glide-to-goal, spot search, hazard check) -### `new ElytraFlight(bot, options?)` - -Creates flight instance. - -**Options:** -```js -{ - mode: 'MED', // 'FAST' | 'MED' | 'LOW' - cruiseAlt: 180, // Cruise altitude (Y) - maxRetries: 3, // Retry on failure - safety: true, // Pre-flight checks - debug: false, // Verbose logging - ownerUsername: '', // Whisper alerts to - landingMargin: 2, // Blocks from edge - targetX: 0, // Default target - targetZ: 0, // Default target -} -``` - -### `flight.fly(x, z, opts?)` - -Fly to coordinates. Options override constructor options. - -```js -flight.fly(500, 500); -flight.fly(500, 500, { mode: 'FAST', cruiseAlt: 200 }); +legacy/elytraBot.js # pre-12 monolith — reference only, NOT version-controlled ``` -### `flight.stop(reason?)` +All modules are factories taking a `ctx` object built in `index.js` +(`_buildCtx`). Never reach across modules through `flight._ctx` — use the +public options (`hazardCheck`, module switches) instead. -Emergency stop. Lands bot immediately. - -```js -flight.stop(); -flight.stop('out of rockets'); -``` - -### `flight.setMode(mode)` - -Change flight mode: `'FAST'`, `'MED'`, `'LOW'`. - -### `flight.setTarget(x, z)` - -Set target without flying. +## Core API -### `flight.setStatus(x, z)` +### `new ElytraFlight(bot, options?)` -Returns status object: ```js { - phase: 'CRUISE', - mode: 'MED', - pos: { x: 100, y: 180, z: 200 }, - target: { x: 500, z: 500 }, - dist: 350, - elytra: { dur: 400, count: 2, unbreaking: 3 }, - rockets: 20, - flying: true + // Flight profile + mode: 'MED', // 'FAST' | 'MED' | 'LOW' + cruiseAlt: 180, // Cruise altitude (Y) + targetX: 0, targetZ: 0, // Default target + landingMargin: 1, // Margin around landing spot + // Reliability + maxRetries: 3, // Retries for transient in-flight failures + wanderTimeoutMs: 120000, + // Module switches + safety: true, elytraAudit: true, autoRocket: true, + autoRocketCustomStars: false, chunkScan: true, pathfinding: true, + wander: true, landing: true, relocationCanDig: false, + // Behaviour + hazardCheck: null, // (block) => boolean hazard override + ownerUsername: '', // whisper log lines to this player + debug: false, } ``` -### `flight.preflight()` - -Pre-flight check without flying: -```js -const check = await flight.preflight(); -// { ok: true, elytra: { have: 432, need: 50 }, rockets: { have: 20, need: 8 } } -``` - -### `flight.isFlying` - -Boolean — true if elytra is active. +### `flight.fly(x, z, opts?) → Promise` -### `flight.phase` +- Resolves `{ phase: 'IDLE', landedAt: { x, y, z } }`. +- Rejects with `ElytraFlightError` — **branch on `err.code`**, never message text. +- During `CRUISE`/`DEADSTICK` it retargets the active flight and returns the + same pending promise. In other in-flight phases it rejects `IN_FLIGHT` and + does **not** change the active flight's target. +- Retries: deterministic pre-flight failures (`NO_ENTITY`, `NO_ELYTRA`, + `ELYTRA_LOW`, `NO_ROCKETS`, `NO_LAUNCH_SPOT`, `PF_FAILED` — see + `NON_RETRYABLE` in `errors.js`) fail fast with their code. Transient + in-flight failures retry up to `maxRetries`, then reject + `RETRIES_EXHAUSTED` with the last code in `err.cause`. -Current phase: `IDLE`, `AUDIT`, `TAKEOFF`, `CLIMB`, `CRUISE`, `LAND`, `WANDER`, `FAILED`. - -## Events - -```js -flight.on('phase', (phase, msg) => {}); -flight.on('stopped', (reason) => {}); -flight.on('error', (err) => {}); -``` - -## Flight Modes - -| Mode | Speed | Fuel Use | Use Case | -|------|-------|----------|----------| -| `FAST` | 30 m/s | High | Emergency | -| `MED` | 22 m/s | Medium | Default | -| `LOW` | 15 m/s | Low | Long distance | +Other methods: `stop(reason?)`, `setMode(mode)`, `setTarget(x, z)`, +`setStatus(x, z)` (snapshot), `preflight()` (async check), `isFlying`, +`phase`, `targetX`, `targetZ`. ## Flight Phases -1. **AUDIT** — Check elytra durability and rockets -2. **TAKEOFF** — Jump and activate elytra -3. **CLIMB** — Ascend to cruise altitude -4. **CRUISE** — Fly toward target -5. **LAND** — Spiral descent to safe spot -6. **WANDER** — Search for safe landing spot -7. **IDLE** — Landed or stopped -8. **FAILED** — Error occurred - -## Helper Functions - -```js -const { countRockets, getElytraSummary } = require('@eksses/eafe'); - -const rockets = countRockets(bot); // Number -const elytra = getElytraSummary(bot); // { totalDurabilityAcrossAll, count, bestUnbreaking } -``` - -## Common Patterns - -### Multi-stop delivery -```js -const stops = [[100, 200], [300, 400], [500, 600]]; -for (const [x, z] of stops) { - await new Promise(resolve => { - flight.fly(x, z); - flight.once('phase', (p) => { if (p === 'IDLE') resolve(); }); - }); - // drop items here -} -``` - -### Waypoint loop -```js -const waypoints = { base: [0, 0], farm: [500, 200] }; -let current = 'base'; -flight.fly(...waypoints[current]); -flight.on('phase', (p) => { - if (p === 'IDLE') { - current = current === 'base' ? 'farm' : 'base'; - flight.fly(...waypoints[current]); - } -}); -``` +`IDLE → AUDIT → TAKEOFF → CLIMB → CRUISE → LAND → IDLE`, with `DEADSTICK` +(out of fuel → glide), `SCAN` (wander), `RELOC`, and `FAIL` (retrying; note the +string value of `PHASE.FAILED` is `'FAIL'`). -### Status monitoring -```js -setInterval(() => { - if (flight.isFlying) { - const s = flight.setStatus(targetX, targetZ); - console.log(`${s.phase} dist=${s.dist}m rkt=${s.rockets}`); - } -}, 5000); -``` - -## Error Handling +## Events -```js -flight.on('error', (err) => { - if (err.message.includes('no elytra')) { - // equip elytra - } - if (err.message.includes('out of rkt')) { - // restock rockets - } -}); -``` +`phase(phase, msg)`, `stopped(reason)`, `error(err)`. The `error` event is an +optional side-channel: emission is guarded (`listenerCount` check), so a missing +listener never throws. The `fly()` promise rejection is the primary error path. +Drive queue logic (deliveries, waypoints, transfers) with the `fly()` promise — +watching for the `IDLE` phase event double-fires (IDLE is emitted on stop too). + +## Critical invariants (learned from real bugs — do not regress) + +- **Yaw convention** (verified against mineflayer's own `bot.lookAt` and + mineflayer-pathfinder): `yaw = atan2(-dx, -dz)` faces `(dx, dz)`, so + `forward(yaw) = (-sin(yaw), -cos(yaw))` in (x, z). Mock physics must match. +- **`_yawTo` dead zone**: within 3 m of the target column the bearing is + numerically unstable (jitter flips it ~180°) — hold the current heading. + Removing this makes the bot spin and stall above the target. +- **Takeoff fires first**: an elytra at jump apex is already `isFlying()` with + zero boost, so the first `fireRocketDirect` must happen before any + `isFlying()` check; the fire loop polls until a rocket actually leaves + (yaw gate may block the first few calls). +- **Climb fuel-out**: when `autoRocket` is on and the inventory hits 0 mid-climb, + hand off to a DEADSTICK glide (`startCruise({ keepPhase: true })`) instead of + stalling into GROUND_HIT. +- **Landing is glide-to-goal** (aim at the spot, pitch by altitude delta) — the + old spiral orbit circled the target and skimmed the ground far off it. +- **`stop()` clears real handles** (`flyLoop`, `verifyLoop`, `rocketLoop`, + `climbLoop`, `landLoop` + retry/sneak timeouts), emits exactly one `stopped`, + and rejects the pending promise with `STOPPED`. +- **`emit('error')` must stay guarded** — a bare emit throws when no listener is + attached and would break every `.catch()`. + +## Testing + +Zero-dependency runner (`test/run.js`) + mock mineflayer bot +(`test/helpers/mock-bot.js`): real prismarine-world 1.21 terrain, +`entity.velocity` in **blocks/tick**, elytra model with rocket boost decay, +~15:1 glide (12 m/s floor, pitch-follow + induced sink), and stall when +pointing up without a rocket. + +Test gotchas (all hit in practice): +- `stepUntil(cond)` is **async — always `await` it**; an un-awaited call is a + truthy Promise and silently passes assertions. +- Drive the mock until `flight._pending === null`, **not** until + `phase === FAILED` — the phase goes FAILED on every failed attempt while a + retry is pending; stopping physics then starves the retry (bot frozen on the + ground → spurious "jump fail" on every retry). +- Monkey-patching `bot.step` must pass `dt` through (`bot.step = (dt) => + origStep(dt)`) — dropping it makes the physics NaN. +- Long-flight tests need enough rockets for the route (measured with the mock's + defaults, maxRetries=3, cruiseAlt=180: 300 m ≈ 36, 500 m ≈ 38) unless the test + is about running out (`safety: false`). + +Perf guard: a 300 m flight must stay under 500k `blockAt` calls (~45k in +practice) — terrain scans stay bounded by altitude and distance. ## Dependencies -- **mineflayer** `>=4.0.0` — Minecraft bot framework (peer dependency) -- **mineflayer-pathfinder** `^2.4.5` — Pathfinding for relocation -- **vec3** `^0.2.0` — 3D vector math (dev dependency) +- **mineflayer** `>=4.0.0` — peer dependency +- **mineflayer-pathfinder** `^2.4.5` — relocation pathfinding +- **vec3** `^0.2.0` — 3D vectors (mock + src) +- dev: **eslint** + **@eslint/js** (flat config) ## Notes -- Bot must have elytra equipped in chest slot -- Bot must have firework rockets in inventory -- Landing spots require 2 air blocks above + 1 block margin -- Rockets only used for survival (stall prevention, altitude maintenance) -- No rockets during landing or wander scan phases +- Bot must have elytra equipped in the chest slot and rockets in inventory + (unless `autoRocket: false`). +- Landing spots require air above + margin; a cactus/other hazard under the + target is avoided by the spot search, and a hazard touchdown relocates + instead of looping forever. +- No rockets during landing; DEADSTICK is a level glide. +- CommonJS everywhere (`"type": "commonjs"`), Node ≥ 16. diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..898567e --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,97 @@ +# Changelog + +All notable changes to this project are documented here. +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [12.0.0] — 2026-09-22 + +A full modular rewrite of the flight engine. The monolithic `elytraBot.js` is +replaced by focused modules, `fly()` becomes promise-based, and a zero-dependency +mock-bot test suite (27 tests) guards the whole flight lifecycle. + +### Breaking +- **Modular layout.** The single `elytraBot.js` is split into `src/`: + `index.js`, `constants.js`, `errors.js`, `logger.js`, `utils.js`, + `core/{elytra,inventory,rockets}.js`, `flight/{spatial,phases,wander,landing}.js`. + `src/commands.js`, `src/config.js`, and `src/core/chat.js` are removed. + `legacy/elytraBot.js` is kept on disk for reference but excluded from the npm package. +- **`fly(x, z, opts)` returns a Promise.** It resolves with + `{ phase: 'IDLE', landedAt: {x,y,z} }` and rejects with a typed + `ElytraFlightError` (inspect `err.code`, not the message text). +- **Version 11.0.3 → 12.0.0.** Import surface changes (`@eksses/eafe` exports + subpaths such as `@eksses/eafe/errors`); event-only consumers should switch to + the promise + `err.code` pattern. + +### Added +- `src/errors.js` — `ElytraFlightError` with 19 machine-readable codes + (`IN_FLIGHT`, `NO_ENTITY`, `NO_ELYTRA`, `ELYTRA_LOW`, `NO_ROCKETS`, + `NO_LAUNCH_SPOT`, `PF_FAILED`, `GROUND_HIT`, `CLIMB_TIMEOUT`, + `NO_FLIGHT_CONFIRM`, `LOST_FLIGHT`, `NO_SAFE_SPOT`, `LANDING_TIMEOUT`, + `RETRIES_EXHAUSTED`, `STOPPED`, `RESPAWN`, `DISCONNECTED`, `INTERNAL`). +- `hazardCheck` public option — override which blocks count as hazards + (landing spots, terrain scans, ground safety). Replaces the old internal + `_ctx.isHazardous` hook. +- `ownerUsername` option — whispers each flight log line to that player. +- Zero-dependency test suite: `node test/run.js` (unit + integration) and + `test/helpers/mock-bot.js` (a mock mineflayer bot over real prismarine-world + 1.21 terrain with blocks/tick physics). 27 tests cover the full 300 m flight, + cactus/hazard recovery, out-of-rockets deadstick, mid-cruise retarget, and + stop/retry semantics. +- `LICENSE` (MIT), `CHANGELOG.md`, ESLint flat config (`npm run lint`), and a + GitHub Actions workflow running the test suite on Node 18/20/22. + +### Changed +- **Retry semantics.** Deterministic pre-flight preconditions + (`NO_ENTITY`, `NO_ELYTRA`, `ELYTRA_LOW`, `NO_ROCKETS`, `NO_LAUNCH_SPOT`, + `PF_FAILED`) now **fail fast** with their specific code — retrying cannot + change the outcome. Transient in-flight failures are retried and the final + rejection is `RETRIES_EXHAUSTED`, with the last failure's code in + `err.cause` and the message. +- **Retargeting.** Calling `fly()` mid-cruise/deadstick retargets the active + flight and returns the *same* pending promise. A rejected `fly()` no longer + silently retargets the active flight. +- **Landing.** Replaced the spiral-orbit descent with a straight glide-to-goal: + aim directly at the landing spot, pitch by altitude delta. The old spiral + orbited the target and could skim the ground far off it. +- **Elytra damage** uses the `2/(n+3)` unbreaking rate; required durability + scales with distance and best unbreaking level. +- **Landing-surface detection** uses the block's collision shapes (full-cube + check) instead of a name allow-list. + +### Fixed +- **Yaw singularity over the target.** `yawTo()` returned a numerically + unstable bearing when the bot was within ~3 m of the target column — + sub-block jitter flipped it up to 180°, making the bot spin in circles and + never pass the rocket's yaw gate (infinite stall). A 3 m dead-zone now holds + the current heading. +- **Takeoff skipped the first boost.** The loop checked `isFlying()` before the + first `fireRocketDirect`, but an elytra at jump apex is already "flying" with + zero boost — so no rocket ever fired and the bot stalled. It now fires first, + then checks. +- **Out-of-fuel climb died with `GROUND_HIT`.** A 1-rocket launch burned its + only boost at takeoff, then stalled on the ground during climb. The climb now + hands off to a DEADSTICK glide when the inventory runs dry. +- **`emit('error')` threw synchronously** when no `'error'` listener was + attached, turning a cleanly-rejectable `fly()` into a raw throw the caller's + `.catch()` could never see. Error emission is now guarded; the promise + rejection is the primary channel. +- **`PHASE.CRUISE` constant bug.** The retarget branch compared against + `PHASE.CRUISE` (an undefined key — the real key is `CRUISING`), so it never + fired. +- **Zombie timers after stop.** `stop()` now clears the real interval handles + (`flyLoop`, `verifyLoop`, `rocketLoop`, `climbLoop`, `landLoop`) plus the + retry/sneak timeouts, emits exactly one `stopped`, and settles the pending + promise with `STOPPED`. +- **`_pending.promise` was never set**, so mid-cruise retargeting returned + `undefined`. + +### Performance +- Terrain scans are bounded: ground is probed only near the bot's altitude and + the landing trigger uses a distance-based descent window. A 300 m flight now + makes ~45k `blockAt` calls (perf guard `< 500k`) instead of repeatedly + scanning full render distance twice per tick. + +## [11.x] — prior +Monolithic `elytraBot.js` engine (event-driven `fly()`), shipped without a +LICENSE file or automated tests. See the git history for 11.0.3. diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..909583c --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024-2026 eksses + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md index 4153767..de386d5 100644 --- a/README.md +++ b/README.md @@ -31,7 +31,15 @@ const bot = mineflayer.createBot({ host: 'localhost', username: 'Bot' }); bot.once('spawn', () => { const flight = new ElytraFlight(bot); - flight.fly(500, 500); + + // fly() returns a promise: resolves with the landing position, + // rejects with a typed ElytraFlightError (check err.code). + flight.fly(500, 500) + .then((res) => bot.chat(`Landed at (${res.landedAt.x},${res.landedAt.z})`)) + .catch((err) => { + if (err.code === 'STOPPED') return; // expected on flight.stop() + bot.chat(`Flight failed: ${err.code}`); + }); }); ``` @@ -41,14 +49,16 @@ bot.once('spawn', () => { | Feature | Description | |:--------|:------------| -| **3 Flight Modes** | `FAST` (30 m/s), `MED` (22 m/s), `LOW` (15 m/s) | -| **Smart Landing** | Auto land at safe spots with margin check | -| **Elytra Audit** | Checks durability before flight | -| **Auto Rocket** | Equips rockets automatically | -| **Terrain Avoidance** | Scans and avoids obstacles | +| **Promise API** | `fly()` resolves with the landing position, rejects with a typed error code | +| **3 Flight Modes** | `FAST` (22 m/s), `MED` (13 m/s), `LOW` (10 m/s) — rocket boosts exceed these | +| **Smart Landing** | Glide-to-goal descent onto a verified safe spot | +| **Elytra Audit** | Durability + rocket estimates before flight (unbreaking-aware) | +| **Auto Rocket** | Equips and fires rockets automatically | +| **Terrain Avoidance** | Render-distance scans, climb steep into obstacles | +| **Deadstick** | Runs out of rockets mid-flight → glides to the goal | | **Owner Alerts** | Whisper notifications | | **Wander Scan** | Searches for safe spots over any terrain | -| **Retry System** | Auto retry on failure | +| **Retry System** | Retries transient failures; deterministic pre-flight failures fail fast | --- @@ -60,25 +70,55 @@ Create a flight instance. ```js const flight = new ElytraFlight(bot, { - mode: 'MED', // 'FAST' | 'MED' | 'LOW' - cruiseAlt: 180, // Cruise altitude (Y blocks) - maxRetries: 3, // Retry attempts on failure - safety: true, // Pre-flight checks enabled - debug: false, // Verbose logging (false for production) - ownerUsername: '', // Whisper alerts to this player - landingMargin: 2, // Blocks from edge of landing spot - targetX: 0, // Default target X - targetZ: 0, // Default target Z + // Flight profile + mode: 'MED', // 'FAST' | 'MED' | 'LOW' + cruiseAlt: 180, // Cruise altitude (Y blocks) + targetX: 0, // Default target X + targetZ: 0, // Default target Z + landingMargin: 1, // Blocks of margin around the landing spot + + // Reliability + maxRetries: 3, // Retry attempts on transient in-flight failure + wanderTimeoutMs: 120000, // Give up a wander search after this long + + // Module switches + safety: true, // Pre-flight durability/rocket estimates + elytraAudit: true, // Skip only the elytra-durability estimate + autoRocket: true, // false = fly with no rockets at all + autoRocketCustomStars: false, // Count/use rockets with custom stars + chunkScan: true, // Render-distance raycasts (terrain avoidance) + pathfinding: true, // Pathfind to a launch spot when blocked + wander: true, // Wander for a safe landing spot when none at target + landing: true, // false = dive straight at the target column + relocationCanDig: false, // Let the relocation pathfinder dig (keep off on public servers) + + // Behaviour + hazardCheck: null, // (block) => boolean — custom hazard override + ownerUsername: '', // Whisper each flight log line to this player + debug: false, // Verbose logging (false for production) }); ``` -### `flight.fly(x, z, opts?)` +### `flight.fly(x, z, opts?) → Promise` Fly to coordinates. Options override constructor options. +- **Resolves** with `{ phase: 'IDLE', landedAt: { x, y, z } }`. +- **Rejects** with an `ElytraFlightError` — branch on `err.code`, not message text. +- **Mid-cruise/deadstick** a call retargets the active flight and returns the + *same* pending promise; in any other in-flight phase it rejects `IN_FLIGHT` + (and does not change the active flight's target). + ```js -flight.fly(500, 500); -flight.fly(500, 500, { mode: 'FAST', cruiseAlt: 200 }); +flight.fly(500, 500) + .then((res) => console.log('Landed at', res.landedAt)) + .catch((err) => { + if (err.code === 'STOPPED') return; + if (err.code === 'NO_ROCKETS') restock(); + // ... + }); + +flight.fly(500, 500, { mode: 'FAST', cruiseAlt: 200 }); // one-off overrides ``` ### `flight.stop(reason?)` @@ -131,8 +171,8 @@ Pre-flight check without flying. ```js const check = await flight.preflight(); // { -// ok: true, -// elytra: { have: 432, need: 50 }, +// ok: true, // reason: null when ok +// elytra: { have: 432, need: 50, equipped: 400, count: 2, unbreaking: 3 }, // rockets: { have: 20, need: 8 } // } ``` @@ -143,7 +183,8 @@ Boolean — `true` if elytra is active. ### `flight.phase` -Current phase: `IDLE`, `AUDIT`, `TAKEOFF`, `CLIMB`, `CRUISE`, `LAND`, `WANDER`, `FAILED`. +Current phase (string values): `IDLE`, `AUDIT`, `TAKEOFF`, `CLIMB`, `CRUISE`, +`DEADSTICK`, `LAND`, `SCAN`, `RELOC`, `FAIL`. --- @@ -159,19 +200,58 @@ flight.on('stopped', (reason) => { }); flight.on('error', (err) => { - console.error(err.message); + console.error(err.code, err.message); }); ``` +> The `error` event is an optional side-channel. If no `error` listener is +> attached, EAFE never throws — the `fly()` promise rejection is the primary +> error path. + +--- + +## Error codes + +Every rejected `fly()` carries a machine-readable `err.code`: + +| Code | Meaning | Retried? | +|:-----|:--------|:---------| +| `IN_FLIGHT` | `fly()` called while flying (not a retargetable phase) | — | +| `NO_ENTITY` | Bot not spawned (`bot.entity` is null) | fail fast | +| `NO_ELYTRA` | No usable elytra in inventory | fail fast | +| `ELYTRA_LOW` | Total elytra durability below the requirement | fail fast | +| `NO_ROCKETS` | Not enough rockets for the estimated route | fail fast | +| `NO_LAUNCH_SPOT` | Every launch heading blocked and relocation off | fail fast | +| `PF_FAILED` | Pathfinding relocation failed | fail fast | +| `GROUND_HIT` | Hit the ground during climb | retried | +| `CLIMB_TIMEOUT` | Did not reach cruise altitude in time | retried | +| `NO_FLIGHT_CONFIRM` | Elytra flight not confirmed after launch | retried | +| `LOST_FLIGHT` | Elytra flight lost mid-flight, unrecoverable | retried | +| `NO_SAFE_SPOT` | No safe landing spot (wander timed out) | retried | +| `LANDING_TIMEOUT` | Landing did not finish in time | retried | +| `RETRIES_EXHAUSTED` | Max retries used up (last code in `err.cause`) | — | +| `STOPPED` | `flight.stop()` was called | — | +| `RESPAWN` | Bot respawned mid-flight | — | +| `DISCONNECTED` | Bot disconnected | — | +| `INTERNAL` | Unexpected internal error | — | + +Deterministic pre-flight failures (the "fail fast" rows) reject immediately with +their specific code — retrying cannot change the outcome. Transient in-flight +failures are retried up to `maxRetries`, then reject `RETRIES_EXHAUSTED` with the +last failure's code available as `err.cause`. + --- ## Flight Modes -| Mode | Speed | Fuel Use | Use Case | -|:-----|:------|:---------|:---------| -| `FAST` | 30 m/s | High | Emergency, short distance | -| `MED` | 22 m/s | Medium | Default, balanced | -| `LOW` | 15 m/s | Low | Long distance, fuel efficient | +| Mode | Planning speed | Fuel Use | Use Case | +|:-----|:---------------|:---------|:---------| +| `FAST` | 22 m/s | High | Emergency, short distance | +| `MED` | 13 m/s | Medium | Default, balanced | +| `LOW` | 10 m/s | Low | Long distance, fuel efficient | + +Planning speed is the average ground speed used to estimate fuel; rocket +boosts push the bot well above it. --- @@ -179,18 +259,20 @@ flight.on('error', (err) => { ``` AUDIT → TAKEOFF → CLIMB → CRUISE → LAND → IDLE - ↘ WANDER (no spot found) - ↘ FAILED (error) + ↘ DEADSTICK (out of rockets → glide to goal) + ↘ SCAN (no safe spot at target → wander) + ↘ FAIL (error → retry, then settle) ``` 1. **AUDIT** — Check elytra durability and rockets -2. **TAKEOFF** — Jump and activate elytra -3. **CLIMB** — Ascend to cruise altitude -4. **CRUISE** — Fly toward target -5. **LAND** — Spiral descent to safe spot -6. **WANDER** — Search for safe landing spot -7. **IDLE** — Landed or stopped -8. **FAILED** — Error occurred +2. **TAKEOFF** — Jump, activate elytra, fire the first boost +3. **CLIMB** — Ascend to cruise altitude (hands off to DEADSTICK if fuel runs out) +4. **CRUISE** — Fly toward target (a `fly()` call here retargets in place) +5. **DEADSTICK** — Out of rockets: level glide to the goal, then land +6. **LAND** — Glide-to-goal descent onto a verified safe spot +7. **SCAN** — Search for a safe landing spot elsewhere (wander) +8. **IDLE** — Landed or stopped +9. **FAIL** — Error occurred (retries transient failures, then settles) --- @@ -207,6 +289,9 @@ const elytra = getElytraSummary(bot); // { totalDurabilityAcrossAll, count, ## Examples +All examples are promise-driven (`fly().then(...).catch(...)`) and only use the +public API. + | Example | Description | |:--------|:------------| | [`basic.js`](examples/basic.js) | Simple flight | @@ -217,6 +302,9 @@ const elytra = getElytraSummary(bot); // { totalDurabilityAcrossAll, count, | [`multi-bot.js`](examples/multi-bot.js) | Fleet control | | [`inventory-transfer.js`](examples/inventory-transfer.js) | Chest transfer | | [`api-demo.js`](examples/api-demo.js) | API showcase | +| [`advanced.js`](examples/advanced.js) | FAST mode + status polling | +| [`preflight.js`](examples/preflight.js) | Gear check before flying | +| [`custom.js`](examples/custom.js) | Module switches, custom hazard + mode | --- @@ -225,11 +313,27 @@ const elytra = getElytraSummary(bot); // { totalDurabilityAcrossAll, count, - **Node.js** ≥ 16.0.0 - **mineflayer** ≥ 4.0.0 - Bot must have **elytra** equipped in chest slot -- Bot must have **firework rockets** in inventory +- Bot must have **firework rockets** in inventory (unless `autoRocket: false`) + +--- + +## Development + +Zero-dependency test suite — a mock mineflayer bot over real prismarine-world +1.21 terrain with blocks/tick physics. Tests run in real time (~40 s): + +```bash +node test/run.js # unit + integration +node test/run.js unit # unit only +node test/run.js integ # integration only (full mock flights) +npm run lint # ESLint (flat config) +``` + +CI (`.github/workflows/ci.yml`) runs lint + the full suite on Node 18/20/22. --- ## License -MIT +[MIT](LICENSE) diff --git a/eslint.config.js b/eslint.config.js new file mode 100644 index 0000000..925eae4 --- /dev/null +++ b/eslint.config.js @@ -0,0 +1,56 @@ +'use strict'; + +// ESLint flat config (ESLint 9). CommonJS throughout (package "type": "commonjs"). +const js = require('@eslint/js'); + +module.exports = [ + js.configs.recommended, + { + files: ['**/*.js'], + languageOptions: { + ecmaVersion: 2022, + sourceType: 'commonjs', + globals: { + // Node + console: 'readonly', + process: 'readonly', + setTimeout: 'readonly', + clearTimeout: 'readonly', + setInterval: 'readonly', + clearInterval: 'readonly', + require: 'readonly', + module: 'writable', + __dirname: 'readonly', + global: 'writable', + Buffer: 'readonly', + }, + }, + rules: { + 'no-var': 'error', + 'prefer-const': 'error', + eqeqeq: ['error', 'smart'], + 'no-unused-vars': ['error', { + argsIgnorePattern: '^_', + varsIgnorePattern: '^_', + caughtErrors: 'none', // catch (_) { } is a deliberate idiom here + }], + 'no-undef': 'error', + 'no-console': 'off', + 'no-empty': ['error', { allowEmptyCatch: true }], + // Braces required when the body is on its own line(s); one-line + // `if (x) return y;` stays brace-free. + curly: ['error', 'multi-line'], + }, + }, + { + // Tests use a few deliberate globals and looser structure. + files: ['test/**/*.js'], + rules: { + 'no-unused-vars': ['error', { argsIgnorePattern: '^_', varsIgnorePattern: '^_', caughtErrors: 'none' }], + }, + }, + { + // Debug/scratch files are not linted (they are not committed). + ignores: ['**/debug-*.js', 'node_modules/**'], + }, +]; diff --git a/examples/advanced.js b/examples/advanced.js index 92afb40..a5152fa 100644 --- a/examples/advanced.js +++ b/examples/advanced.js @@ -22,12 +22,16 @@ bot.once('spawn', () => { flight.on('error', (e) => console.error('Error:', e.message)); // Fly with overrides - flight.fly(1000, -500, { mode: 'LOW', cruiseAlt: 150 }); + flight.fly(1000, -500, { mode: 'LOW', cruiseAlt: 150 }) + .then((res) => console.log('Landed at', res.landedAt)) + .catch((err) => { + if (err.code !== 'STOPPED') console.error('Flight failed:', err.code, err.message); + }); // Check status anytime setInterval(() => { if (flight.isFlying) { - const s = flight.setStatus(flight._targetX, flight._targetZ); + const s = flight.setStatus(flight.targetX, flight.targetZ); console.log(`${s.phase} pos=(${s.pos.x},${s.pos.y},${s.pos.z}) dist=${s.dist}m e=${s.elytra.dur} rkt=${s.rockets}`); } }, 5000); diff --git a/examples/api-demo.js b/examples/api-demo.js index 0ecf58f..193c912 100644 --- a/examples/api-demo.js +++ b/examples/api-demo.js @@ -63,7 +63,7 @@ bot.once('spawn', async () => { flight.setMode('FAST'); console.log('Mode set'); - const status = flight.setStatus(flight._targetX, flight._targetZ); + const status = flight.setStatus(flight.targetX, flight.targetZ); console.log('Status:', status); } }); diff --git a/examples/basic.js b/examples/basic.js index 47cf8cc..acadc73 100644 --- a/examples/basic.js +++ b/examples/basic.js @@ -15,6 +15,12 @@ bot.once('spawn', () => { flight.on('stopped', (reason) => console.log('Stopped:', reason)); flight.on('error', (err) => console.error('Error:', err.message)); - // Fly to coordinates - flight.fly(500, 500); + // Fly to coordinates — fly() returns a promise that resolves with the + // landing position and rejects with a typed ElytraFlightError (err.code) + flight.fly(500, 500) + .then((res) => console.log('Landed at', res.landedAt)) + .catch((err) => { + if (err.code === 'STOPPED') return; + console.error('Flight failed:', err.code, err.message); + }); }); diff --git a/examples/custom.js b/examples/custom.js index b7754f6..a724de1 100644 --- a/examples/custom.js +++ b/examples/custom.js @@ -1,5 +1,5 @@ const mineflayer = require('mineflayer'); -const { ElytraFlight, Logger, MODES, isHazardousBlock } = require('@eksses/eafe'); +const { ElytraFlight, MODES, countRockets, getElytraSummary } = require('@eksses/eafe'); const bot = mineflayer.createBot({ host: 'localhost', @@ -8,53 +8,44 @@ const bot = mineflayer.createBot({ }); bot.once('spawn', () => { - // ── Disable modules you don't need ── + // ── Disable modules you don't need, plug in your own rules ── const flight = new ElytraFlight(bot, { safety: false, // skip pre-flight durability/rocket checks chunkScan: false, // no render distance scanning pathfinding: false, // no pathfinding to open spots wander: false, // no ocean wander scan - landing: false, // no auto-landing spiral + landing: false, // no landing-spot search (dive straight at target) + autoRocket: false, // you manage rockets yourself (bot.activateItem) + // Real hazard override: EAFE calls this for every block it considers + // (landing spots, terrain scans, ground safety). Default is the built-in + // hazard list — see src/constants.js HAZARD_SURFACES. + hazardCheck: (block) => { + if (!block) return false; + // Only water/lava are dangerous for THIS bot: + return block.name.includes('water') || block.name.includes('lava'); + }, debug: true, }); - // ── Override specific functions ── - - // Custom rocket logic - flight._ctx.smartFireRocket = () => { - const vel = bot.entity.velocity; - const speed = Math.hypot(vel.x, vel.y, vel.z); - if (speed < 0.8 && bot.entity.elytraFlying) { - try { bot.activateItem(true); } catch(_) {} - return true; - } - return false; - }; - - // Custom hazard check - flight._ctx.isHazardous = (block) => { - if (!block) return true; - // Only water/lava are dangerous for MY bot - return block.name.includes('water') || block.name.includes('lava'); - }; - - // Custom mode + // ── Custom mode ── MODES.GOTTA_GO_FAST = { - name: 'GOTTA GO FAST', + name: 'GOTTA_GO_FAST', pitch: 0.02, speedGate: 2.0, speedMps: 30.0, fuelDistDivider: 40.0, }; - flight.on('phase', (p) => console.log(p)); + flight.on('phase', (p, msg) => console.log('Phase:', p, msg || '')); + flight.on('stopped', (reason) => console.log('Stopped:', reason)); - // Use custom mode flight.setMode('GOTTA_GO_FAST'); - flight.fly(2000, 2000); - - // ── Import modules individually ── - const { countRockets, getElytraSummary } = require('eafe'); + flight.fly(2000, 2000) + .then((res) => console.log('Landed at', res.landedAt)) + .catch((err) => { + if (err.code === 'STOPPED') return; // expected when the user stops + console.error('Flight failed:', err.code, err.message); + }); console.log('Rockets:', countRockets(bot)); console.log('Elytra:', getElytraSummary(bot)); diff --git a/examples/delivery.js b/examples/delivery.js index d0ca5cf..0c4e040 100644 --- a/examples/delivery.js +++ b/examples/delivery.js @@ -19,13 +19,10 @@ bot.once('spawn', () => { safety: true, }); - flight.on('phase', (phase) => { - if (phase === 'IDLE' && isDelivering) { - processNextDelivery(); - } + flight.on('phase', (phase, msg) => { + if (msg) console.log(`[${phase}] ${msg}`); }); - - flight.on('error', (err) => console.error('Error:', err.message)); + flight.on('stopped', (reason) => console.log('Stopped:', reason)); bot.on('chat', (user, msg) => { const args = msg.split(' '); @@ -82,25 +79,36 @@ bot.once('spawn', () => { const next = deliveries[0]; bot.chat(`Delivering to (${next.x},${next.z})...`); - flight.fly(next.x, next.z); - - // Wait for arrival - flight.once('phase', function onArrival(phase) { - if (phase === 'IDLE') { - // Drop items - const item = bot.inventory.items().find(i => i.name === next.item); - if (item) { - bot.tossStack(item); - bot.chat(`Delivered ${next.count}x ${next.item} to (${next.x},${next.z})`); - } else { - bot.chat(`No ${next.item} to deliver`); - } - - // Remove from queue - deliveries.shift(); - processNextDelivery(); + + // The fly() promise is the single arrival signal — resolves with the + // landing position, rejects with a typed ElytraFlightError. (The old + // code also watched for the IDLE phase event here, which fired twice + // and double-processed the queue.) + try { + await flight.fly(next.x, next.z); + } catch (err) { + deliveries.shift(); + if (err.code === 'STOPPED') { + bot.chat('Delivery cancelled'); + return; } - }); + bot.chat(`Delivery failed (${err.code}), skipping stop`); + processNextDelivery(); + return; + } + + // Drop items + const item = bot.inventory.items().find(i => i.name === next.item); + if (item) { + bot.tossStack(item); + bot.chat(`Delivered ${next.count}x ${next.item} to (${next.x},${next.z})`); + } else { + bot.chat(`No ${next.item} to deliver`); + } + + // Remove from queue + deliveries.shift(); + processNextDelivery(); } console.log('Delivery bot ready'); diff --git a/examples/demo.js b/examples/demo.js index 8b9878f..4082078 100644 --- a/examples/demo.js +++ b/examples/demo.js @@ -29,7 +29,11 @@ bot.once('spawn', () => { if (args[0] === 'f') { targetX = parseInt(args[1]) || 0; targetZ = parseInt(args[2]) || 0; - flight.fly(targetX, targetZ); + flight.fly(targetX, targetZ) + .then((res) => bot.chat(`Landed at (${res.landedAt.x},${res.landedAt.z})`)) + .catch((err) => { + if (err.code !== 'STOPPED') bot.chat(`Flight failed: ${err.code}`); + }); bot.chat(`Flying to ${targetX} ${targetZ}`); } diff --git a/examples/inventory-transfer.js b/examples/inventory-transfer.js index 4f443ae..4a9f1b6 100644 --- a/examples/inventory-transfer.js +++ b/examples/inventory-transfer.js @@ -23,14 +23,10 @@ bot.once('spawn', () => { debug: true, }); - flight.on('phase', (phase) => { - if (phase === 'IDLE' && transferMode) { - handleTransferArrival(); - } + flight.on('phase', (phase, msg) => { + if (msg) console.log(`[${phase}] ${msg}`); }); - flight.on('error', (err) => console.error('Error:', err.message)); - bot.on('chat', (user, msg) => { const args = msg.split(' '); @@ -50,6 +46,7 @@ bot.once('spawn', () => { // Transfer items if (args[0] === 'transfer' && args[1]) { + if (transferMode) { bot.chat('Transfer already in progress — use cancel'); return; } if (!storage.source || !storage.dest) { bot.chat('Set source and dest first'); return; @@ -58,13 +55,19 @@ bot.once('spawn', () => { transferItem = args[1]; transferMode = true; - // Go to source first + // Go to source first — the fly() promise drives the next step bot.chat(`Going to source to pick up ${transferItem}...`); - flight.fly(storage.source.x, storage.source.z); + flight.fly(storage.source.x, storage.source.z) + .then(() => handleTransferArrival()) + .catch((err) => { + transferMode = false; + if (err.code !== 'STOPPED') bot.chat(`Transfer failed: ${err.code}`); + }); } // Transfer all items if (args[0] === 'transfer-all') { + if (transferMode) { bot.chat('Transfer already in progress — use cancel'); return; } if (!storage.source || !storage.dest) { bot.chat('Set source and dest first'); return; @@ -73,7 +76,12 @@ bot.once('spawn', () => { transferItem = null; transferMode = true; bot.chat('Going to source to pick up all items...'); - flight.fly(storage.source.x, storage.source.z); + flight.fly(storage.source.x, storage.source.z) + .then(() => handleTransferArrival()) + .catch((err) => { + transferMode = false; + if (err.code !== 'STOPPED') bot.chat(`Transfer failed: ${err.code}`); + }); } // Cancel @@ -86,7 +94,7 @@ bot.once('spawn', () => { // Status if (args[0] === 'status') { - const s = flight.setStatus(flight._targetX, flight._targetZ); + const s = flight.setStatus(flight.targetX, flight.targetZ); bot.chat(`${s.phase} | ${s.pos.x},${s.pos.y},${s.pos.z} | ${s.dist}m`); } @@ -127,7 +135,12 @@ bot.once('spawn', () => { // Go to destination setTimeout(() => { bot.chat('Going to destination...'); - flight.fly(storage.dest.x, storage.dest.z); + flight.fly(storage.dest.x, storage.dest.z) + .then(() => handleTransferArrival()) + .catch((err) => { + transferMode = false; + if (err.code !== 'STOPPED') bot.chat(`Transfer failed: ${err.code}`); + }); }, 1000); }).catch(err => { bot.chat(`Cannot open chest: ${err.message}`); diff --git a/examples/multi-bot.js b/examples/multi-bot.js index 4c4b6ce..54cd01e 100644 --- a/examples/multi-bot.js +++ b/examples/multi-bot.js @@ -53,7 +53,11 @@ BOTS.forEach(botOpts => { const flight = flightInstances.get(botOpts.name); const target = flightTargets.get(botOpts.name); if (flight && target) { - flight.fly(target.x, target.z); + flight.fly(target.x, target.z) + .then(() => bot.chat(`Landed at (${target.x},${target.z})`)) + .catch((err) => { + if (err.code !== 'STOPPED') bot.chat(`Flight failed: ${err.code}`); + }); bot.chat(`Flying to (${target.x},${target.z})`); } } @@ -71,7 +75,7 @@ BOTS.forEach(botOpts => { if (args[0] === 'status' && args[1] === botOpts.name) { const flight = flightInstances.get(botOpts.name); if (flight) { - const s = flight.setStatus(flight._targetX, flight._targetZ); + const s = flight.setStatus(flight.targetX, flight.targetZ); bot.chat(`${s.phase} | ${s.pos.x},${s.pos.y},${s.pos.z} | ${s.dist}m | rkt=${s.rockets}`); } } diff --git a/examples/preflight.js b/examples/preflight.js index 968c19c..85df55f 100644 --- a/examples/preflight.js +++ b/examples/preflight.js @@ -1,5 +1,5 @@ const mineflayer = require('mineflayer'); -const { ElytraFlight, countRockets, getElytraSummary } = require('@eksses/eafe'); +const { ElytraFlight } = require('@eksses/eafe'); const bot = mineflayer.createBot({ host: 'localhost', @@ -20,10 +20,10 @@ bot.once('spawn', async () => { // Set target without flying flight.setTarget(100, 200); - console.log('Target set to', flight._targetX, flight._targetZ); + console.log('Target set to', flight.targetX, flight.targetZ); // Get full status - const status = flight.setStatus(flight._targetX, flight._targetZ); + const status = flight.setStatus(flight.targetX, flight.targetZ); console.log('Status:', status); // Then fly diff --git a/examples/rescue-bot.js b/examples/rescue-bot.js index 98567b7..7df6d38 100644 --- a/examples/rescue-bot.js +++ b/examples/rescue-bot.js @@ -19,10 +19,8 @@ bot.once('spawn', () => { ownerUsername: 'Admin', }); - flight.on('phase', (phase) => { - if (phase === 'IDLE' && isRescuing) { - processNextRescue(); - } + flight.on('phase', (phase, msg) => { + if (msg) console.log(`[${phase}] ${msg}`); }); flight.on('error', (err) => { @@ -78,12 +76,12 @@ bot.once('spawn', () => { // Status if (args[0] === 'status') { - const s = flight.setStatus(flight._targetX, flight._targetZ); + const s = flight.setStatus(flight.targetX, flight.targetZ); bot.chat(`${s.phase} | ${s.pos.x},${s.pos.y},${s.pos.z} | ${s.dist}m`); } }); - function processNextRescue() { + async function processNextRescue() { if (rescueQueue.length === 0) { isRescuing = false; bot.chat('All rescues complete'); @@ -94,15 +92,24 @@ bot.once('spawn', () => { const next = rescueQueue[0]; bot.chat(`Rescuing ${next.user} at (${next.x},${next.z})...`); - flight.fly(next.x, next.z); - flight.once('phase', function onArrival(phase) { - if (phase === 'IDLE') { - bot.chat(`Rescued ${next.user}!`); - rescueQueue.shift(); - processNextRescue(); + // fly() promise is the single arrival/failure signal + try { + await flight.fly(next.x, next.z); + } catch (err) { + rescueQueue.shift(); + if (err.code === 'STOPPED') { + bot.chat('Rescues cancelled'); + return; } - }); + bot.chat(`Rescue failed (${err.code}), skipping`); + processNextRescue(); + return; + } + + bot.chat(`Rescued ${next.user}!`); + rescueQueue.shift(); + processNextRescue(); } console.log('Rescue bot ready'); diff --git a/examples/waypoint-travel.js b/examples/waypoint-travel.js index 2565848..35a87ef 100644 --- a/examples/waypoint-travel.js +++ b/examples/waypoint-travel.js @@ -25,21 +25,21 @@ bot.once('spawn', () => { debug: true, }); - flight.on('phase', (phase) => { - if (phase === 'IDLE' && waypointMode) { - goToNextWaypoint(); - } + flight.on('phase', (phase, msg) => { + if (msg) console.log(`[${phase}] ${msg}`); }); - flight.on('error', (err) => console.error('Error:', err.message)); - bot.on('chat', (user, msg) => { const args = msg.split(' '); // Fly to named location if (args[0] === 'goto' && locations[args[1]]) { const loc = locations[args[1]]; - flight.fly(loc.x, loc.z); + flight.fly(loc.x, loc.z) + .then(() => bot.chat(`Landed at ${args[1]}`)) + .catch((err) => { + if (err.code !== 'STOPPED') bot.chat(`Flight failed: ${err.code}`); + }); bot.chat(`Flying to ${args[1]} (${loc.x},${loc.z})`); } @@ -47,12 +47,17 @@ bot.once('spawn', () => { if (args[0] === 'fly') { const x = parseInt(args[1]) || 0; const z = parseInt(args[2]) || 0; - flight.fly(x, z); + flight.fly(x, z) + .then(() => bot.chat(`Landed at (${x},${z})`)) + .catch((err) => { + if (err.code !== 'STOPPED') bot.chat(`Flight failed: ${err.code}`); + }); bot.chat(`Flying to (${x},${z})`); } // Start waypoint mode if (args[0] === 'waypoints') { + if (waypointMode) { bot.chat('Waypoint loop already running — use stop'); return; } waypointMode = true; currentWaypoint = 0; goToNextWaypoint(); @@ -81,7 +86,7 @@ bot.once('spawn', () => { // Status if (args[0] === 'status') { - const s = flight.setStatus(flight._targetX, flight._targetZ); + const s = flight.setStatus(flight.targetX, flight.targetZ); bot.chat(`${s.phase} | ${s.pos.x},${s.pos.y},${s.pos.z} | ${s.dist}m | rkt=${s.rockets}`); } }); @@ -97,8 +102,16 @@ bot.once('spawn', () => { const name = names[currentWaypoint]; const loc = locations[name]; bot.chat(`${currentWaypoint + 1}/${names.length}: ${name} (${loc.x},${loc.z})`); - flight.fly(loc.x, loc.z); currentWaypoint++; + + // Chain the loop through the fly() promise (resolves on landing) + flight.fly(loc.x, loc.z) + .then(() => goToNextWaypoint()) + .catch((err) => { + waypointMode = false; + if (err.code === 'STOPPED') { bot.chat('Waypoints cancelled'); return; } + bot.chat(`Waypoint loop failed: ${err.code}`); + }); } console.log('Travel bot ready'); diff --git a/legacy/elytraBot.js b/legacy/elytraBot.js deleted file mode 100644 index 86bb42d..0000000 --- a/legacy/elytraBot.js +++ /dev/null @@ -1,1679 +0,0 @@ -'use strict'; -/** - * EAFE v10.23 — Anti-Spam Chat Limiter & Minimum Land Mass Precision (2x2 Platform Support) - * ==================================================================================== - * Enhancements: - * 1. Anti-Spam Safe Chat Engine (safeChat): - * - Enforces strict minimum 4.0s cooldown interval across all bot.chat() messages, completely - * eliminating 'Kicked for spamming' server kicks during Elytra low-health alerts and status broadcasts! - * 2. Minimum Land Mass Precision (2x2 / 3x3 Platform Support): - * - Lowest land mass size EAFE can accurately land on is 2x2 blocks (4 m²)! - * - findLandMassCenter maps 2D bounding boxes and calculates the exact geometric centroid - * (Target X, Target Z) in the middle of small platforms away from all edges. - * - Decelerates to 0 m/s forward velocity directly above the centroid before dropping vertically onto the block. - * 3. Dual-Phase Target Orbit (0-200m) & Open-Ocean Wander Engine (200m+). - * - * Commands: f [X Z], setgoal X Z, m fast/med/low, s, status, audit. - */ - -const mineflayer = require('mineflayer'); -const { Vec3 } = require('vec3'); -const readline = require('readline'); -const physicsLoader = require('@nxg-org/mineflayer-physics-util').default; -const { EPhysicsCtx } = require('@nxg-org/mineflayer-physics-util'); -const { pathfinder, Movements, goals: { GoalBlock } } = require('mineflayer-pathfinder'); - -// ─── CONFIG ────────────────────────────────────────────────────────────────── -const HOST = '103.151.60.212'; -const PORT = 25565; -const USERNAME = 'test'; -const DEFAULT_TARGET_X = 100; -const DEFAULT_TARGET_Z = 100; -const CRUISE_ALT = 180; // Safe target cruise altitude (Y=180) -const MAX_RETRIES = 3; // retries before giving up - -// ─── FLIGHT MODES ──────────────────────────────────────────────────────────── -const MODES = { - FAST: { - name: 'FAST (High Speed Sprint)', - pitch: 0.02, - speedGate: 1.1, // 22 m/s - speedMps: 22.0, - fuelDistDivider: 50.0, // ~50m per rocket - }, - MEDIUM: { - name: 'MEDIUM (Balanced Glide)', - pitch: -0.04, // Nose-down gravity pitch to convert potential energy to speed! - speedGate: 0.55, // 11 m/s (USES 50% FEWER ROCKETS!) - speedMps: 13.0, - fuelDistDivider: 120.0, // ~120m per rocket - }, - EFFICIENT: { - name: 'EFFICIENT (True Rocket Saver)', - pitch: -0.05, // Steeper nose-down gravity glide pitch - speedGate: 0.40, // 8 m/s (USES ABSOLUTE MINIMUM ROCKETS POSSIBLE!) - speedMps: 10.0, - fuelDistDivider: 180.0, // ~180m per rocket (80% fuel savings!) - } -}; - -// ─── PHASE STATE ───────────────────────────────────────────────────────────── -const PHASE = { - IDLE: 'IDLE', - AUDIT: 'AUDIT', // pre-flight inventory, fuel & spatial audit - RELOCATING: 'RELOCATING', // A* pathfinding & block-digging en route to open launch spot - TAKEOFF: 'TAKEOFF', // 150ms jump apex + elytraFly() + instant off-hand rocket - CLIMBING: 'CLIMBING', // continuous nose up (+0.65 to +0.75), gaining altitude - CRUISING: 'CRUISING', // level (+0.05), heading to target - WANDER_SCAN: 'WANDER_SCAN', // High-altitude straight-line grid ocean scan - DEAD_STICK: 'DEAD_STICK', // unpowered glide cruise (0 rockets remaining) - LANDING: 'LANDING', // Archimedean spiral & surface glide (-0.30) - FAILED: 'FAILED', // flight failed, auto-retry scheduled -}; - -// Hazardous surfaces that can hurt or drown the bot -const HAZARD_SURFACES = new Set([ - 'water', 'flowing_water', 'lava', 'flowing_lava', 'magma_block', - 'fire', 'soul_fire', 'sweet_berry_bush', 'cactus', 'powder_snow' -]); - -// Whitelisted safe landing & launch surfaces (STRICT: NO WATER, NO LAVA, NO MAGMA) -const SAFE_SURFACES = new Set([ - 'grass_block', 'dirt', 'coarse_dirt', 'podzol', 'stone', 'cobblestone', - 'smooth_stone', 'granite', 'diorite', 'andesite', 'sand', 'red_sand', - 'gravel', 'sandstone', 'obsidian', 'netherrack', 'end_stone', 'planks', - 'oak_planks', 'spruce_planks', 'birch_planks', 'jungle_planks', 'acacia_planks', - 'dark_oak_planks', 'stone_bricks', 'deepslate', 'terracotta', 'concrete' -]); - -function isHazardousBlock(block) { - if (!block) return true; // Missing block = unknown hazard - if (HAZARD_SURFACES.has(block.name)) return true; - return block.name.includes('water') || block.name.includes('lava') || block.name.includes('magma'); -} - -function isSafeSolidBlock(block) { - if (!block || isAir(block) || isHazardousBlock(block)) return false; - return true; // Any solid, non-hazardous block is safe! -} - -// Cardinal Yaw Directions for Straight-Line Grid Flying -const CARDINAL_YAWS = [ - Math.PI, // North (-Z) - -Math.PI / 2, // East (+X) - 0, // South (+Z) - Math.PI / 2, // West (-X) -]; - -// ─── UTIL ──────────────────────────────────────────────────────────────────── -function sleep(ms) { return new Promise(r => setTimeout(r, ms)); } - -function isAir(block) { - if (!block) return true; - return block.name === 'air' || block.name === 'cave_air' || block.name === 'void_air'; -} - -function isWaterOrLava(block) { - return isHazardousBlock(block); -} - -function angleDiff(a, b) { - let diff = (a - b) % (2 * Math.PI); - if (diff < -Math.PI) diff += 2 * Math.PI; - if (diff > Math.PI) diff -= 2 * Math.PI; - return Math.abs(diff); -} - -// ─── BOT FACTORY ───────────────────────────────────────────────────────────── -function createBot() { - const bot = mineflayer.createBot({ - host: HOST, port: PORT, username: USERNAME, - version: false, auth: 'offline', - checkTimeoutInterval: 60_000, - }); - - bot.loadPlugin(physicsLoader); - bot.loadPlugin(pathfinder); - - // ── session state ── - let phase = PHASE.IDLE; - let currentMode = MODES.MEDIUM; // Default: Medium (Balanced) - let activeTargetX = DEFAULT_TARGET_X; - let activeTargetZ = DEFAULT_TARGET_Z; - let retries = 0; - let spatialClear = false; // Checkmark flag for ground clearance - let activeLaunchYaw = 0; // Selected takeoff heading - let lastTerrainWarn = 0; // Rate-limiter timestamp for terrain warnings - - // Flight Trail Memory: Records last known solid safe land surface passed over - let lastKnownSafeGround = null; - let flightStartPos = null; - - // Parallel Lawnmower Grid Search state - let lawnState = 'SWEEP'; // 'SWEEP' or 'SHIFT' - let sweepDirection = 0; // 0=North, 2=South - let trackCount = 1; // Current parallel track number - let legStartPos = null; // Start position of current straight leg - const scannedChunks = new Set(); // Chunk Memory Map ("cx,cz") - - let physEngine = null; - let flyLoop = null; - let verifyLoop = null; - let rocketLoop = null; - let climbLoop = null; - - // ─── Timer cleanup ──────────────────────────────────────────────────────── - function clearAllTimers() { - [flyLoop, verifyLoop, rocketLoop, climbLoop].forEach(h => { if (h) clearInterval(h); }); - flyLoop = verifyLoop = rocketLoop = climbLoop = null; - } - - let lastChatTimestamp = 0; - /** - * Anti-Spam Safe Chat Helper: Enforces minimum 4-second delay between chat messages - * to eliminate 'Kicked for spamming' server kicks! - */ - function safeChat(msg) { - if (!msg || typeof msg !== 'string') return; - if (Date.now() - lastChatTimestamp < 4000) return; - lastChatTimestamp = Date.now(); - try { bot.chat(msg.substring(0, 256)); } catch(_) {} - } - - // ─── Emergency stop ─────────────────────────────────────────────────────── - function emergencyStop(reason) { - phase = PHASE.IDLE; - spatialClear = false; - clearAllTimers(); - try { bot.pathfinder.stop(); } catch(_) {} - ['sprint','forward','back','left','right','jump','sneak'].forEach(k => { - try { bot.setControlState(k, false); } catch(_) {} - }); - try { bot.setControlState('sneak', true); } catch(_) {} - setTimeout(() => { try { bot.setControlState('sneak', false); } catch(_) {} }, 600); - console.log(`[EAFE] ⛔ STOP — ${reason}`); - safeChat(`[EAFE] ⛔ Stopped: ${reason}`); - } - - // ─── Set phase (logs + chat) ────────────────────────────────────────────── - function setPhase(p, msg) { - phase = p; - const line = `[EAFE] [${p}] ${msg || ''}`; - console.log(line); - safeChat(line.substring(0, 256)); - } - - // ─── REAL-TIME SERVER RENDER DISTANCE ENGINE ──────────────────────────────── - /** - * Dynamically measures the server's real-time render/view distance in chunks and blocks! - * Audits loaded chunk column memory in bot.world. - */ - function getServerRenderDistance() { - if (!bot.entity || !bot.world) return { chunks: 6, blocks: 96, scanAlt: 120 }; - - const bX = Math.floor(bot.entity.position.x) >> 4; - const bZ = Math.floor(bot.entity.position.z) >> 4; - let maxDistChunks = 0; - - try { - const columns = bot.world.getColumns(); - for (const col of columns) { - if (!col) continue; - const dx = Math.abs(col.chunkX - bX); - const dz = Math.abs(col.chunkZ - bZ); - const dist = Math.max(dx, dz); - if (dist > maxDistChunks) maxDistChunks = dist; - } - } catch(_) {} - - // Clamp detected render distance between 4 and 16 chunks - const chunks = Math.min(Math.max(maxDistChunks, 4), 16); - const blocks = chunks * 16; - - // Calculate optimal scanning altitude: Y_scan = clamp(60 + blocks * 0.6, 90, 160) - const scanAlt = Math.min(Math.max(Math.round(60 + blocks * 0.6), 90), 160); - - return { chunks, blocks, scanAlt }; - } - - // ─── Inventory & Off-Hand Firework Equipment ──────────────────────────────── - function countRockets() { - let count = 0; - for (let slot = 0; slot <= 45; slot++) { - const i = bot.inventory.slots[slot]; - if (i && i.name === 'firework_rocket') { - try { if (i.nbt?.value?.Fireworks?.value?.Explosions) continue; } catch(_) {} - count += i.count; - } - } - return count; - } - - function findRocket() { - const offhand = bot.inventory.slots[45]; - if (offhand && offhand.name === 'firework_rocket') return offhand; - - for (let slot = 0; slot <= 44; slot++) { - const i = bot.inventory.slots[slot]; - if (i && i.name === 'firework_rocket') { - try { if (i.nbt?.value?.Fireworks?.value?.Explosions) continue; } catch(_) {} - return i; - } - } - return null; - } - - /** - * Auto-equip Firework Rockets directly into OFF-HAND (slot 45) for 100% reliable packet firing! - */ - async function autoEquipRocket() { - const offhand = bot.inventory.slots[45]; - if (offhand?.name === 'firework_rocket') return true; - - const rocket = findRocket(); - if (!rocket) { - console.warn('[EAFE] ⚠ No firework rockets found in inventory!'); - return false; - } - - try { - await bot.equip(rocket, 'off-hand'); - console.log('[EAFE] 🚀 Firework rockets equipped to OFF-HAND (slot 45)'); - return true; - } catch(e) { - console.warn('[EAFE] ⚠ Equip off-hand rocket failed:', e.message); - return false; - } - } - - // ─── DYNAMIC UNBREAKING-AWARE ELYTRA ENGINE ───────────────────────────────── - - /** - * Audits Unbreaking enchantment level (0, 1, 2, 3) on an item - */ - function getUnbreakingLevel(item) { - if (!item) return 0; - if (item.enchants && Array.isArray(item.enchants)) { - const u = item.enchants.find(e => e.name === 'unbreaking' || e.name === 'durability'); - if (u) return u.lvl ?? 1; - } - try { - const enchs = item.nbt?.value?.Enchantments?.value?.value || item.nbt?.value?.ench?.value?.value; - if (enchs && Array.isArray(enchs)) { - const u = enchs.find(e => e.id?.value === 'unbreaking' || e.id?.value === 34); - if (u) return u.lvl?.value ?? 1; - } - } catch(_) {} - return 0; - } - - /** - * Durability consumption rate per second based on Unbreaking level: - * Unbreaking 0: 1.00 dur/sec - * Unbreaking I: 0.50 dur/sec - * Unbreaking II: 0.333 dur/sec - * Unbreaking III: 0.25 dur/sec (4x lifespan!) - */ - function getElytraDamageRate(unbreakingLvl) { - switch (unbreakingLvl) { - case 1: return 0.50; - case 2: return 0.333; - case 3: return 0.25; - default: return 1.0; - } - } - - /** - * Calculates exact required Elytra durability for a given distance and mode velocity! - */ - function calculateRequiredElytraDurability(d2d, speedMps, unbreakingLvl) { - const flightTimeSec = d2d / Math.max(speedMps, 10.0); - const damageRate = getElytraDamageRate(unbreakingLvl); - const reqDur = Math.ceil(flightTimeSec * damageRate); - const reserveBuffer = 15; // 15 durability points safety buffer - return reqDur + reserveBuffer; - } - - /** - * Scans inventory and equips best Elytra ONLY if currently equipped Elytra has <= 10 durability points! - */ - async function auditAndEquipElytra() { - const chest = bot.inventory.slots[6]; - let currentEquippedDur = -1; - if (chest?.name === 'elytra') { - currentEquippedDur = chest.maxDurability ? (chest.maxDurability - chest.durabilityUsed) : 432; - } - - // STRICT USER RULE: Only swap if currently equipped Elytra is missing OR has 10 or less durability points! - if (currentEquippedDur > 10) { - return true; - } - - // Equipped Elytra is <= 10 points (or missing) — find highest durability spare in inventory! - let bestSlot = null; - let bestDur = -1; - - for (let s = 0; s <= 45; s++) { - if (s === 6) continue; - const item = bot.inventory.slots[s]; - if (item && item.name === 'elytra') { - const dur = item.maxDurability ? (item.maxDurability - item.durabilityUsed) : 432; - if (dur > bestDur && dur > 10) { - bestDur = dur; - bestSlot = s; - } - } - } - - if (bestSlot === null) { - console.warn(`[EAFE] ⚠ No usable spare Elytra found (durability > 10). Currently equipped: ${currentEquippedDur > 0 ? currentEquippedDur : 0}/432`); - safeChat(`[EAFE] ⚠ Elytra health critical (${currentEquippedDur > 0 ? currentEquippedDur : 0}/432)! Please give me a fresh Elytra!`); - return false; - } - - // Auto-swap to best spare Elytra from inventory into chest slot 6 - const spareItem = bot.inventory.slots[bestSlot]; - try { - await bot.equip(spareItem, 'torso'); - console.log(`[EAFE] 🎽 Auto-swapped to best Elytra from slot ${bestSlot} (Durability: ${bestDur}/432, old was ${currentEquippedDur}/432)`); - safeChat(`[EAFE] 🎽 Auto-swapped to best Elytra (${bestDur}/432 durability)`); - return true; - } catch(e) { - console.error('[EAFE] ✗ Equip best elytra failed:', e.message); - return false; - } - } - - /** - * Mid-Flight Elytra Auto-Swap & Flight State Recovery Failsafe - * Triggers ONLY when equipped Elytra drops to <= 10 durability points during active flight. - */ - async function checkMidFlightElytraSwap() { - const chest = bot.inventory.slots[6]; - if (!chest || chest.name !== 'elytra') return; - - const dur = chest.maxDurability ? (chest.maxDurability - chest.durabilityUsed) : 432; - if (dur <= 10) { - console.warn(`[EAFE] 🎽 Equipped Elytra durability critical (${dur}/432) — executing mid-flight auto-swap!`); - const swapped = await auditAndEquipElytra(); - if (swapped) { - console.log('[EAFE] 🎽 Mid-flight Elytra swapped — re-issuing elytraFly() & rocket boost!'); - try { await bot.elytraFly(); } catch(_) {} - fireRocketDirect(); - } else { - console.error('[EAFE] ⚠ Out of spare Elytras! Emergency landing initiated...'); - safeChat('[EAFE] ⚠ Elytra durability critical (<=10) & no spares! Emergency landing!'); - startLanding(); - } - } - } - - /** - * Summary diagnostics of all Elytras in inventory & equipment - */ - function getElytraSummary() { - let count = 0; - let equippedDur = 0; - let maxDur = 0; - let totalDurabilityAcrossAll = 0; - let bestUnbreaking = 0; - - const chest = bot.inventory.slots[6]; - if (chest?.name === 'elytra') { - equippedDur = chest.maxDurability ? (chest.maxDurability - chest.durabilityUsed) : 432; - count++; - totalDurabilityAcrossAll += equippedDur; - if (equippedDur > maxDur) maxDur = equippedDur; - const u = getUnbreakingLevel(chest); - if (u > bestUnbreaking) bestUnbreaking = u; - } - - for (let s = 0; s <= 45; s++) { - if (s === 6) continue; - const item = bot.inventory.slots[s]; - if (item && item.name === 'elytra') { - const dur = item.maxDurability ? (item.maxDurability - item.durabilityUsed) : 432; - count++; - totalDurabilityAcrossAll += dur; - if (dur > maxDur) maxDur = dur; - const u = getUnbreakingLevel(item); - if (u > bestUnbreaking) bestUnbreaking = u; - } - } - - return { count, equippedDur, maxDur, totalDurabilityAcrossAll, bestUnbreaking }; - } - - // ─── Mineflayer Navigation Helpers (CORRECTED YAW FORMULA) ─────────────────── - function yawTo(x, z) { - const p = bot.entity.position; - return Math.atan2(-(x - p.x), -(z - p.z)); - } - - function dist2D(x, z) { - const p = bot.entity.position; - return Math.hypot((x ?? activeTargetX) - p.x, (z ?? activeTargetZ) - p.z); - } - - function lookForce(yaw, pitch) { - bot.look(yaw, pitch, true); - } - - /** - * Empirically Verified Firework Fuel Calculation - * Formula: - * N_req = N_distance + N_climb + N_retry_waste + N_wander_landing - */ - function calculateRequiredRockets(d2d, deltaY) { - const dReq = Math.ceil(d2d / currentMode.fuelDistDivider); - const yReq = Math.ceil(Math.abs(deltaY) / 10.0); - const retryWasteBuffer = MAX_RETRIES * 3; // 9 rockets buffer for up to 3 failed retries - const wanderLandingBuffer = 12; // 12 rockets unconditionally reserved for landing & wander - - return dReq + yReq + retryWasteBuffer + wanderLandingBuffer; - } - - let dolphinBoostTime = 0; // Timestamp of last rocket boost for Sine-Wave pitch oscillation - - /** - * Bulletproof Firework Rocket Activation (Off-Hand Packet Firing + Yaw-Lock Failsafe) - */ - function fireRocketDirect(targetYawCheck = null) { - if (!bot.entity.elytraFlying) return false; - - // Safety Cooldown: Minimum 500ms safety interval to prevent packet overflow - if (Date.now() - dolphinBoostTime < 500) { - return false; - } - - // Failsafe 1: Verify yaw alignment before applying rocket thrust (must be within 15° = 0.26 rad) - if (targetYawCheck !== null) { - const err = angleDiff(bot.entity.yaw, targetYawCheck); - if (err > 0.26) { - lookForce(targetYawCheck, currentMode.pitch); - return false; - } - } - - // Failsafe 2: Verify off-hand equipment - const offhand = bot.inventory.slots[45]; - if (offhand?.name !== 'firework_rocket') { - autoEquipRocket().catch(() => {}); - } - - try { - bot.activateItem(true); // Fire off-hand firework rocket! - dolphinBoostTime = Date.now(); - console.log(`[EAFE] 🚀 OFF-HAND Rocket Boost Fired! (Y=${bot.entity.position.y.toFixed(1)}, Rockets=${countRockets() - 1})`); - return true; - } catch(e) { - console.warn('[EAFE] Rocket activation error:', e.message); - return false; - } - } - - /** - * DYNAMIC PHYSICS ROCKET EVALUATOR (No Strict Hardcoded Cooldowns!) - * Dynamically determines if a rocket is required based on real-time speed, - * altitude, descent rate, and altitude ceiling limits. - */ - function shouldFireRocketDynamic(pos, vel, maxAltCeiling = 180) { - if (!bot.entity.elytraFlying || countRockets() === 0) return false; - - // Rule 1: Do NOT fire if currently in post-boost climb phase (< 1.2s after rocket boost) - if (Date.now() - dolphinBoostTime < 1200) return false; - - // Rule 2: Ceiling Limit — Never fire if altitude is already above max ceiling - if (pos.y >= maxAltCeiling) return false; - - const speed = Math.hypot(vel.x, vel.y, vel.z); - - // Rule 3: Dynamic Physics Energy Check: - // Fire rocket IF speed has dropped below 10.0 m/s (speed < 0.50) - // OR if altitude has dropped low (pos.y < maxAltCeiling - 25) AND speed < 14.0 m/s (0.70)! - if (speed < 0.50) { - return true; // Speed depleted — needs rocket boost! - } - - if (pos.y < maxAltCeiling - 25 && speed < 0.70) { - return true; // Altitude and speed both dropping — needs rocket boost! - } - - return false; - } - - /** - * Smart Rocket Consumption Algorithm (Used ONLY during Cruise phase) - */ - function smartFireRocket() { - if (!bot.entity.elytraFlying) return false; - - const vel = bot.entity.velocity; - const speed = Math.hypot(vel.x, vel.y, vel.z); - - if (speed >= currentMode.speedGate) { - console.log(`[EAFE] 🍃 Rocket skipped — speed optimal (${(speed * 20).toFixed(1)} m/s, mode=${currentMode.name})`); - return false; - } - - const ping = bot.player?.ping ?? 50; - if (ping > 500) { - console.warn(`[EAFE] ⚠ High server ping (${ping}ms) — throttling rocket`); - return false; - } - - const targetYaw = yawTo(activeTargetX, activeTargetZ); - return fireRocketDirect(targetYaw); - } - - // ─── Fly state verification ─────────────────────────────────────────────── - function isFlying() { - const e = bot.entity; - if (!e) return false; - const server = e.elytraFlying === true || e.fallFlying === true; - let sim = false; - if (physEngine) { - try { const ctx = EPhysicsCtx.FROM_BOT(physEngine, bot); sim = ctx.state.fallFlying === true; } - catch(_) {} - } - return (server || sim) && !e.onGround; - } - - // ───────────────────────────────────────────────────────────────────────── - // DYNAMIC RENDER DISTANCE RAYCAST & SPATIAL SCAN - // ───────────────────────────────────────────────────────────────────────── - - /** - * Raycast along flight vector up to active server render distance! - */ - function scanFullRenderDistance(yaw, currentPitch) { - const pos = bot.entity.position; - const eyePos = pos.offset(0, 1.6, 0); - - const rDist = getServerRenderDistance(); - const maxRaycastBlocks = rDist.blocks; // Raycast up to detected server render distance - - const cosPitch = Math.cos(currentPitch); - const sinPitch = Math.sin(currentPitch); - const dirX = -Math.sin(yaw) * cosPitch; - const dirY = sinPitch; - const dirZ = Math.cos(yaw) * cosPitch; - - for (let d = 1; d <= maxRaycastBlocks; d += 2) { - const checkPos = eyePos.offset(dirX * d, dirY * d, dirZ * d); - const b = bot.blockAt(checkPos); - if (b && !isAir(b) && !isWaterOrLava(b)) { - return { hit: true, dist: d, block: b.name, pos: checkPos }; - } - } - - return { hit: false, dist: maxRaycastBlocks, block: null, pos: null }; - } - - /** - * Checks runway clearance at a specific yaw - */ - function checkRunwayDirection(testYaw) { - const pos = bot.entity.position; - - // Overhead Column (Y+1 to Y+5) - for (let dy = 1; dy <= 5; dy++) { - const b = bot.blockAt(pos.offset(0, dy, 0)); - if (!isAir(b)) return { clear: false, reason: `Overhead blocked at Y+${dy} (${b?.name})` }; - } - - // Forward Runway at specified yaw (4m ahead, Y+1 & Y+2) - const dirX = -Math.sin(testYaw); - const dirZ = Math.cos(testYaw); - - for (let d = 1; d <= 4; d++) { - for (let dy = 1; dy <= 2; dy++) { - const bPos = pos.offset(Math.round(dirX * d), dy, Math.round(dirZ * d)); - const b = bot.blockAt(bPos); - if (!isAir(b)) return { clear: false, reason: `Runway blocked at ${d}m ahead (Y+${dy}: ${b?.name})` }; - } - } - - // Ground check: not liquid - const blockUnder = bot.blockAt(pos.offset(0, -0.5, 0)); - if (isWaterOrLava(blockUnder)) return { clear: false, reason: `Standing in liquid (${blockUnder?.name})` }; - - return { clear: true, reason: 'Clear corridor' }; - } - - /** - * Directional Opening Awareness Scan - */ - function findBestLaunchHeading() { - const targetYaw = yawTo(activeTargetX, activeTargetZ); - - const targetCheck = checkRunwayDirection(targetYaw); - if (targetCheck.clear) { - return { yaw: targetYaw, headingName: 'Direct Target', clear: true }; - } - - const COMPASS = [ - { name: 'West (270°)', yaw: Math.PI / 2 }, - { name: 'North (180°)', yaw: Math.PI }, - { name: 'East (90°)', yaw: -Math.PI / 2 }, - { name: 'South (0°)', yaw: 0 }, - { name: 'North-West (225°)', yaw: 3 * Math.PI / 4 }, - { name: 'South-West (315°)', yaw: Math.PI / 4 }, - { name: 'North-East (135°)', yaw: -3 * Math.PI / 4 }, - { name: 'South-East (45°)', yaw: -Math.PI / 4 }, - ]; - - for (const dir of COMPASS) { - const check = checkRunwayDirection(dir.yaw); - if (check.clear) { - console.log(`[EAFE] 🧭 Target heading blocked, but open launch corridor found facing ${dir.name}!`); - try { - bot.chat(`[EAFE] 🧭 Target heading blocked — taking off facing ${dir.name} then turning to goal!`); - } catch(_) {} - return { yaw: dir.yaw, headingName: dir.name, clear: true }; - } - } - - return { yaw: targetYaw, headingName: 'Blocked', clear: false }; - } - - function findElevatedOpenSpot() { - const pos = bot.entity.position; - const baseY = Math.floor(pos.y); - let best = null; - - for (let dx = -7; dx <= 7; dx += 2) { - for (let dz = -7; dz <= 7; dz += 2) { - const cx = Math.floor(pos.x) + dx; - const cz = Math.floor(pos.z) + dz; - - let groundBlock = null; - let groundY = null; - - for (let dy = 1; dy >= -4; dy--) { - const b = bot.blockAt(new Vec3(cx, baseY + dy, cz)); - if (b && !isAir(b)) { - groundBlock = b; - groundY = baseY + dy + 1; - break; - } - } - - if (!groundBlock || isWaterOrLava(groundBlock) || !SAFE_SURFACES.has(groundBlock.name)) { - continue; - } - - let openAir = 0; - for (let dy = 0; dy < 15; dy++) { - if (isAir(bot.blockAt(new Vec3(cx, groundY + dy, cz)))) openAir++; - else break; - } - - if (openAir >= 5) { - const dist = Math.hypot(dx, dz); - const score = openAir - dist * 0.5; - if (score > (best?.score ?? -999)) { - best = { x: cx, y: groundY, z: cz, score, openAir, blockName: groundBlock.name }; - } - } - } - } - - return best; - } - - async function pathfindToSpot(tx, ty, tz) { - console.log(`[EAFE] 🗺 Pathfinding & breaking path blocks to launch spot (${tx}, ${ty}, ${tz})...`); - - const defaultMove = new Movements(bot); - defaultMove.canDig = true; // BREAK BLOCKS EN ROUTE TO DESTINATION! - defaultMove.allow1by1tunnels = true; // Dig 1x1/1x2 tunnels if path is blocked - defaultMove.allowParkour = true; // Jump over gaps & up ledges - defaultMove.canSwim = false; // NO WATER - defaultMove.liquidCost = 100; // HIGH PENALTY FOR LIQUIDS - - bot.pathfinder.setMovements(defaultMove); - bot.pathfinder.setGoal(new GoalBlock(tx, ty, tz)); - - const TIMEOUT = 15_000; - const start = Date.now(); - - return new Promise(resolve => { - const checkGoal = setInterval(() => { - const p = bot.entity.position; - const dist = Math.hypot(tx - p.x, tz - p.z); - if (dist <= 1.5 || !bot.pathfinder.isMoving()) { - clearInterval(checkGoal); - bot.pathfinder.stop(); - console.log(`[EAFE] 🗺 Pathfinding completed (dist=${dist.toFixed(1)}m)`); - resolve(dist <= 2.5); - } - if (Date.now() - start > TIMEOUT) { - clearInterval(checkGoal); - bot.pathfinder.stop(); - console.warn('[EAFE] ⚠ Pathfinding timed out'); - resolve(false); - } - }, 200); - }); - } - - // ───────────────────────────────────────────────────────────────────────── - // FLIGHT PHASES - // ───────────────────────────────────────────────────────────────────────── - - async function startFlight() { - if (phase !== PHASE.IDLE && phase !== PHASE.FAILED) { - try { bot.chat('[EAFE] Flight already in progress — use s to stop'); } catch(_) {} - return; - } - - flightStartPos = bot.entity.position.clone(); - lastKnownSafeGround = null; - - const rDist = getServerRenderDistance(); - setPhase(PHASE.AUDIT, `Running pre-flight inventory, fuel & spatial audit [Mode:${currentMode.name} RenderDist:${rDist.chunks}ch/${rDist.blocks}m] to (${activeTargetX}, ${activeTargetZ})...`); - - // 1. Best Elytra auto-swap audit - const elytraOk = await auditAndEquipElytra(); - if (!elytraOk) { - setPhase(PHASE.FAILED, '✗ Pre-flight failed: No usable Elytra (durability > 15)'); - return; - } - - // 2. Dynamic Unbreaking-Aware Elytra Health Audit - const d2d = dist2D(activeTargetX, activeTargetZ); - const elytraInfo = getElytraSummary(); - const reqElytraDur = calculateRequiredElytraDurability(d2d, currentMode.speedMps, elytraInfo.bestUnbreaking); - - console.log( - `[EAFE] 🎽 Pre-Flight Elytra Health Audit: Total Available Durability=${elytraInfo.totalDurabilityAcrossAll}/${elytraInfo.count * 432} ` + - `(${elytraInfo.count} Elytras, Unbreaking ${elytraInfo.bestUnbreaking}) | Required Durability=${reqElytraDur} (dist=${d2d.toFixed(0)}m)` - ); - - if (elytraInfo.totalDurabilityAcrossAll < reqElytraDur) { - const neededDur = reqElytraDur - elytraInfo.totalDurabilityAcrossAll; - setPhase(PHASE.FAILED, `✗ Insufficient Elytra durability for ${d2d.toFixed(0)}m flight! Have ${elytraInfo.totalDurabilityAcrossAll}/${reqElytraDur} points. Please give more Elytras!`); - try { - bot.chat(`[EAFE] ✗ Insufficient Elytra durability for ${d2d.toFixed(0)}m flight! Have ${elytraInfo.totalDurabilityAcrossAll}/${reqElytraDur} points. Need ${neededDur} more durability!`); - } catch(_) {} - return; // Do NOT launch until sufficient Elytra health is supplied! - } - - // 3. Equip Firework Rockets to OFF-HAND - await autoEquipRocket(); - - // 4. Dynamic Firework Calculation BEFORE Flight - const rocketsAvail = countRockets(); - const startY = bot.entity.position.y; - const reqRockets = calculateRequiredRockets(d2d, CRUISE_ALT - startY); - - console.log( - `[EAFE] 🎆 Pre-Flight Rocket Audit [Mode=${currentMode.name} Target=(${activeTargetX}, ${activeTargetZ})]: ` + - `Rockets=${rocketsAvail}/${reqRockets}` - ); - - if (rocketsAvail < reqRockets) { - const needed = reqRockets - rocketsAvail; - setPhase(PHASE.FAILED, `✗ Insufficient fireworks for ${currentMode.name}! Have ${rocketsAvail}/${reqRockets}. Please give ${needed} more rockets!`); - try { - bot.chat(`[EAFE] ✗ Need ${reqRockets} fireworks for ${currentMode.name}, only have ${rocketsAvail}! Please give me ${needed} more rockets.`); - } catch(_) {} - return; // Do NOT launch until fireworks are supplied! - } - - console.log(`[EAFE] ✓ Pre-Flight Audit PASSED (ElytraDur=${elytraInfo.totalDurabilityAcrossAll}/${reqElytraDur}, Rockets=${rocketsAvail}/${reqRockets})`); - - // 5. Directional Opening Awareness & Spatial Clearance Checkmark - if (!spatialClear) { - let heading = findBestLaunchHeading(); - console.log(`[EAFE] Directional Opening Scan: clear=${heading.clear} heading=${heading.headingName}`); - - if (!heading.clear) { - console.log('[EAFE] Launch blocked in all 8 headings — pathfinding to open launch spot...'); - try { bot.chat('[EAFE] ⚠ Launch blocked in all directions — pathfinding to open launch spot...'); } catch(_) {} - - const spot = findElevatedOpenSpot(); - if (!spot) { - setPhase(PHASE.FAILED, '✗ Obstacles/liquids detected — no safe open launch spot nearby'); - scheduleRetry(); - return; - } - - setPhase(PHASE.RELOCATING, `Pathfinding to open spot (${spot.x}, ${spot.y}, ${spot.z}) on ${spot.blockName}`); - const arrived = await pathfindToSpot(spot.x, spot.y, spot.z); - if (!arrived) { - setPhase(PHASE.FAILED, '✗ Could not pathfind to launch spot'); - scheduleRetry(); - return; - } - - heading = findBestLaunchHeading(); - if (!heading.clear) { - setPhase(PHASE.FAILED, '✗ Spatial envelope still blocked in all directions after relocation'); - scheduleRetry(); - return; - } - } - - activeLaunchYaw = heading.yaw; - spatialClear = true; - console.log(`[EAFE] ✓ Ground & Spatial Clearance PASSED (Launch Heading: ${heading.headingName})`); - } else { - console.log(`[EAFE] ✓ Spatial Clearance already approved — launching on heading`); - } - - // ── TAKEOFF ── - await executeTakeoff(); - } - - /** - * 150ms Jump Apex Rule Takeoff (INSTANT OFF-HAND ROCKET THRUST) - */ - async function executeTakeoff() { - if (phase === PHASE.FAILED) return; - setPhase(PHASE.TAKEOFF, `Jumping & activating elytra facing launch corridor...`); - - ['sprint','forward','back','left','right','sneak'].forEach(k => { - try { bot.setControlState(k, false); } catch(_) {} - }); - - await autoEquipRocket(); - - lookForce(activeLaunchYaw, 0.5); - - // Jump - bot.setControlState('jump', true); - - const airborne = await new Promise(resolve => { - let t = 0; - const chk = setInterval(() => { - t++; - if (!bot.entity.onGround) { clearInterval(chk); resolve(true); return; } - if (t > 20) { clearInterval(chk); resolve(false); } - }, 50); - }); - - bot.setControlState('jump', false); - - if (!airborne) { - setPhase(PHASE.FAILED, '✗ Takeoff failed: Jump failed (bot remained on ground)'); - scheduleRetry(); - return; - } - - console.log(`[EAFE] ✓ Airborne (Y=${bot.entity.position.y.toFixed(2)}) — calling elytraFly()`); - - try { - await bot.elytraFly(); - console.log('[EAFE] ✓ elytraFly() packet sent'); - } catch(e) { - console.error('[EAFE] ✗ Takeoff failed: elytraFly() rejected:', e.message); - setPhase(PHASE.FAILED, '✗ Takeoff failed: elytraFly rejected: ' + e.message); - scheduleRetry(); - return; - } - - fireRocketDirect(); - - await sleep(200); - if (!isFlying()) { - console.warn('[EAFE] ⚠ Fly state false after launch — retrying elytraFly + rocket'); - try { await bot.elytraFly(); } catch(_) {} - fireRocketDirect(); - await sleep(250); - if (!isFlying()) { - setPhase(PHASE.FAILED, '✗ Takeoff failed: Server never confirmed elytraFlying=true'); - scheduleRetry(); - return; - } - } - - console.log('[EAFE] ✓ Elytra flight CONFIRMED — starting climb'); - startClimb(); - } - - // ─── CLIMB & CONTINUOUS UNINTERRUPTED ROCKET PROPULSION ─────────────────── - function startClimb() { - setPhase(PHASE.CLIMBING, `Climbing to Y=${CRUISE_ALT}...`); - - let climbTicks = 0; - const launchPosY = bot.entity.position.y; - - lookForce(activeLaunchYaw, 0.45); // Smooth initial pitch - fireRocketDirect(null, 0); // Initial launch rocket boost! - - if (rocketLoop) { clearInterval(rocketLoop); rocketLoop = null; } - - if (climbLoop) clearInterval(climbLoop); - climbLoop = setInterval(() => { - if (phase !== PHASE.CLIMBING) { clearInterval(climbLoop); climbLoop = null; return; } - - climbTicks++; - const pos = bot.entity.position; - const targetYaw = yawTo(activeTargetX, activeTargetZ); - - // Mid-flight Elytra Auto-Swap check - checkMidFlightElytraSwap(); - - // Record Flight Trail Memory: Track solid land passed over on climb - const groundUnder = getGroundBlockAt(Math.round(pos.x), Math.round(pos.z)); - if (groundUnder && isSafeSolidBlock(groundUnder)) { - lastKnownSafeGround = { x: Math.round(pos.x), y: Math.round(pos.y), z: Math.round(pos.z), blockName: groundUnder.name }; - } - - // MID-AIR YAW CURVE: Once Y >= 95m, smoothly curve yaw towards destination - let currentYaw = activeLaunchYaw; - if (pos.y >= 95) { - currentYaw = targetYaw; - } - - let climbPitch = (climbTicks <= 4) ? 0.45 : 0.65; // Ramp pitch smoothly from 0.45 to 0.65 - const terrainScan = scanFullRenderDistance(currentYaw, climbPitch); - if (terrainScan.hit) { - if (Date.now() - lastTerrainWarn > 3000) { - console.warn(`[EAFE] 🏔 Terrain obstacle (${terrainScan.block}) detected at ${terrainScan.dist}m — steepening climb pitch (+0.75 rad)`); - lastTerrainWarn = Date.now(); - } - climbPitch = 0.75; - fireRocketDirect(null, 1500); - } - - const vel = bot.entity.velocity; - const speed = Math.hypot(vel.x, vel.y, vel.z); - - // DYNAMIC THROTTLED CLIMB BOOST: Fire rocket ONLY when speed drops below 0.65 (13 m/s) with 2.2s minimum interval! - if (speed < 0.65 && countRockets() > 0) { - fireRocketDirect(null, 2200); - } - - console.log(`[EAFE] [CLIMB] Y=${pos.y.toFixed(1)} pitch=${climbPitch} speed=${(speed*20).toFixed(1)}m/s rockets=${countRockets()}`); - - lookForce(currentYaw, climbPitch); - - // Grace Period Failsafe - if (bot.entity.onGround && pos.y < CRUISE_ALT - 10 && climbTicks > 5 && (pos.y < launchPosY - 2.0)) { - clearInterval(climbLoop); climbLoop = null; - setPhase(PHASE.FAILED, '✗ Unexpected ground contact during climb'); - scheduleRetry(); - return; - } - - if (!isFlying() && !bot.entity.onGround) { - console.warn('[EAFE] ⚠ Lost fly state mid-climb — re-issuing elytraFly'); - bot.elytraFly().catch(() => {}); - fireRocketDirect(null, 1500); - return; - } - - // Reached target altitude Y=180 - if (pos.y >= CRUISE_ALT) { - clearInterval(climbLoop); climbLoop = null; - startCruise(); - } - }, 200); - } - - // ─── CRUISE & PERIODIC 2-SECOND COURSE CHECKER ──────────────────────────── - function startCruise() { - setPhase(PHASE.CRUISING, `Cruising to (${activeTargetX}, ?, ${activeTargetZ}) [Mode: ${currentMode.name}]`); - - if (rocketLoop) clearInterval(rocketLoop); - rocketLoop = setInterval(() => { - if (phase !== PHASE.CRUISING && phase !== PHASE.DEAD_STICK) { clearInterval(rocketLoop); rocketLoop = null; return; } - - if (countRockets() === 0 && phase !== PHASE.DEAD_STICK) { - setPhase(PHASE.DEAD_STICK, '⚠ Out of fireworks — engaging Dead-Stick L/D Glide'); - } - - if (phase === PHASE.CRUISING) { - smartFireRocket(); - } - }, 1200); - - if (flyLoop) clearInterval(flyLoop); - flyLoop = setInterval(() => { - if (phase !== PHASE.CRUISING && phase !== PHASE.DEAD_STICK) { clearInterval(flyLoop); flyLoop = null; return; } - - const pos = bot.entity.position; - - // Mid-flight Elytra Auto-Swap check - checkMidFlightElytraSwap(); - - // Record Flight Trail Memory: Track solid land passed over on cruise - const groundUnder = getGroundBlockAt(Math.round(pos.x), Math.round(pos.z)); - if (groundUnder && !isWaterOrLava(groundUnder) && SAFE_SURFACES.has(groundUnder.name)) { - lastKnownSafeGround = { x: Math.round(pos.x), y: Math.round(pos.y), z: Math.round(pos.z), blockName: groundUnder.name }; - } - - const d = dist2D(activeTargetX, activeTargetZ); - if (d < 25) { - clearInterval(flyLoop); flyLoop = null; - clearInterval(rocketLoop); rocketLoop = null; - startLanding(); - return; - } - - // ACCURATE YAW ALIGNMENT TOWARDS TARGET - const yaw = yawTo(activeTargetX, activeTargetZ); - const vel = bot.entity.velocity; - - // ── OPTIMAL AERODYNAMIC L/D GLIDE ENGINE (Ultra-Smooth Speed-to-Distance Ratio) ── - const timeSinceBoostMs = Date.now() - dolphinBoostTime; - let cruisePitch = (phase === PHASE.DEAD_STICK) ? 0.02 : currentMode.pitch; - - if (phase === PHASE.CRUISING) { - if (timeSinceBoostMs < 1000) { - // Phase A: Gentle Post-Boost Micro-Climb (+0.15 rad) -> Smoothly converts thrust to altitude without speed drop! - cruisePitch = 0.15; - } else { - // Phase B: Optimal L/D Gravity Glide (-0.04 rad) -> Maximum distance-to-speed ratio! - cruisePitch = -0.04; - } - - // Dynamic Physics Rocket Need Check (No hardcoded timers!) - if (shouldFireRocketDynamic(pos, vel, CRUISE_ALT)) { - fireRocketDirect(yaw); - } - } - - // Dynamic Render Distance Raycast Scan - const terrainScan = scanFullRenderDistance(yaw, cruisePitch); - if (terrainScan.hit && terrainScan.dist < 60) { - if (Date.now() - lastTerrainWarn > 3000) { - console.warn(`[EAFE] 🏔 Terrain obstacle (${terrainScan.block}) ahead at ${terrainScan.dist}m — pitching UP to climb over`); - lastTerrainWarn = Date.now(); - } - cruisePitch = 0.55; - if (countRockets() > 0) fireRocketDirect(yaw); - } - - if (Math.hypot(vel.x, vel.y, vel.z) < 0.05 && bot.entity.position.y > 60) { - console.warn('[EAFE] ⚠ Wall collision / stall detected! Executing 180° pitch boost...'); - lookForce(yaw + Math.PI, 0.70); - fireRocketDirect(); - return; - } - - lookForce(yaw, cruisePitch); - }, 50); - - // ── PERIODIC 2-SECOND COURSE & DISTANCE CHECKER ── - if (verifyLoop) clearInterval(verifyLoop); - let lastDist = dist2D(activeTargetX, activeTargetZ); - verifyLoop = setInterval(() => { - if (phase !== PHASE.CRUISING && phase !== PHASE.DEAD_STICK) { clearInterval(verifyLoop); verifyLoop = null; return; } - - const pos = bot.entity.position; - const curDist = dist2D(activeTargetX, activeTargetZ); - const targetYaw = yawTo(activeTargetX, activeTargetZ); - - // Distance Increase Alarm Check (Bot moving away from goal) - if (curDist > lastDist + 5) { - console.warn(`[EAFE] ⚠ Course drift alarm: Distance increased (${lastDist.toFixed(0)}m -> ${curDist.toFixed(0)}m) — forcing instant yaw re-alignment!`); - lookForce(targetYaw, currentMode.pitch); - } - - const elytraInfo = getElytraSummary(); - console.log( - `[EAFE] [2s Check] pos=(${pos.x.toFixed(1)}, ${pos.y.toFixed(1)}, ${pos.z.toFixed(1)}) ` + - `speed=${(Math.hypot(bot.entity.velocity.x, bot.entity.velocity.y, bot.entity.velocity.z)*20).toFixed(1)}m/s ` + - `dist=${curDist.toFixed(0)}m rockets=${countRockets()} elytraDur=${elytraInfo.equippedDur}/432` - ); - - if (!isFlying() && !bot.entity.onGround) { - console.warn('[EAFE] ⚠ Fly state false during cruise — attempting recovery'); - auditAndEquipElytra().then(() => { - if (phase !== PHASE.CRUISING && phase !== PHASE.DEAD_STICK) return; - bot.elytraFly().catch(e => { - setPhase(PHASE.FAILED, '✗ Lost flight state: ' + e.message); - scheduleRetry(); - }); - if (countRockets() > 0) fireRocketDirect(targetYaw); - }); - return; - } - - lastDist = curDist; - }, 2000); - } - - // ───────────────────────────────────────────────────────────────────────── - // STRAIGHT-LINE GRID LAWN-MOWER SEARCH ENGINE WITH CHUNK MEMORY MAP - // ───────────────────────────────────────────────────────────────────────── - - /** - * Calculates the geometric CENTER of the solid land mass around (anchorX, anchorZ). - * Scans bounding box of the land mass and returns the exact middle coordinate (centerX, centerZ) - * away from all edges! - */ - function findLandMassCenter(anchorX, anchorZ) { - let minX = anchorX, maxX = anchorX; - let minZ = anchorZ, maxZ = anchorZ; - - const maxBound = 15; // Scan up to 15 blocks in 4 directions to map land boundaries - - for (let dx = 1; dx <= maxBound; dx++) { - const b = getGroundBlockAt(anchorX - dx, anchorZ); - if (b && isSafeSolidBlock(b)) minX = anchorX - dx; - else break; - } - for (let dx = 1; dx <= maxBound; dx++) { - const b = getGroundBlockAt(anchorX + dx, anchorZ); - if (b && isSafeSolidBlock(b)) maxX = anchorX + dx; - else break; - } - for (let dz = 1; dz <= maxBound; dz++) { - const b = getGroundBlockAt(anchorX, anchorZ - dz); - if (b && isSafeSolidBlock(b)) minZ = anchorZ - dz; - else break; - } - for (let dz = 1; dz <= maxBound; dz++) { - const b = getGroundBlockAt(anchorX, anchorZ + dz); - if (b && isSafeSolidBlock(b)) maxZ = anchorZ + dz; - else break; - } - - const midX = Math.round((minX + maxX) / 2); - const midZ = Math.round((minZ + maxZ) / 2); - - const midBlock = getGroundBlockAt(midX, midZ); - if (midBlock && isSafeSolidBlock(midBlock)) { - return { x: midX, z: midZ, blockName: midBlock.name, safe: true }; - } - - const anchorBlock = getGroundBlockAt(anchorX, anchorZ); - return { x: anchorX, z: anchorZ, blockName: anchorBlock?.name || 'stone', safe: true }; - } - - /** - * Locates the CLOSEST solid safe land mass to (centerX, centerZ) and targets the - * GEOMETRIC CENTER of that land mass (never landing on edges or far away)! - */ - function findSafeLandingSpotAround(centerX, centerZ) { - const rDist = getServerRenderDistance(); - const maxSearchRadius = rDist.blocks; // Use real-time detected server view radius! - - let bestSpot = null; - let bestDist = Infinity; - - // Scan expanding radius rings outward from target (centerX, centerZ) - for (let r = 0; r <= maxSearchRadius; r += 2) { - const stepAngle = Math.max(Math.PI / 16, Math.PI / (r * 0.5 + 1)); - for (let angle = 0; angle < Math.PI * 2; angle += stepAngle) { - const sx = Math.round(centerX + r * Math.cos(angle)); - const sz = Math.round(centerZ + r * Math.sin(angle)); - const sb = getGroundBlockAt(sx, sz); - if (sb && isSafeSolidBlock(sb)) { - const centerSpot = findLandMassCenter(sx, sz); - const d = Math.hypot(centerSpot.x - centerX, centerSpot.z - centerZ); - if (d < bestDist) { - bestDist = d; - bestSpot = centerSpot; - } - } - } - // If solid land was discovered in this ring, return its geometric center immediately! - if (bestSpot) { - console.log(`[EAFE] 🏝 Solid land platform discovered ${bestDist.toFixed(0)}m from goal! Landing at Land-Mass Center (${bestSpot.x}, ${bestSpot.z}) [${bestSpot.blockName}]`); - return bestSpot; - } - } - - return { x: centerX, z: centerZ, blockName: 'unknown', safe: false }; - } - - /** - * Low-Altitude Concentric Ring Ocean Search (WANDER_SCAN Phase) - * - Concentric Ring Orbit: Flies expanding square rings directly centered on (activeTargetX, activeTargetZ) - * - Stays 100% focused on destination area (never flies 500m+ away)! - * - Low Altitude Ceiling (Y = 85m to 95m): Direct line-of-sight to ocean floor & nearby coastlines! - */ - function startWanderScan() { - currentMode = MODES.EFFICIENT; - - const rDist = getServerRenderDistance(); - const targetScanAlt = 90; // Low scan altitude (Y=90m) for crystal clear ocean floor & coast visibility! - let scanTicks = 0; - let ringLegIndex = 0; - let ringSize = 40; // Initial 40m search box around destination - let ringLegProgress = 0; - - const originX = activeTargetX; - const originZ = activeTargetZ; - - setPhase(PHASE.WANDER_SCAN, `🌊 Concentric Ocean Scan initiated at Y=${targetScanAlt} around (${originX}, ${originZ}) [RenderDist: ${rDist.chunks}ch / ${rDist.blocks}m]...`); - - scannedChunks.clear(); - - if (flyLoop) clearInterval(flyLoop); - flyLoop = setInterval(() => { - if (phase !== PHASE.WANDER_SCAN) { clearInterval(flyLoop); flyLoop = null; return; } - - scanTicks++; - const pos = bot.entity.position; - const rCount = countRockets(); - - // Mid-flight Elytra Auto-Swap check - checkMidFlightElytraSwap(); - - // 0. TOUCHDOWN RECOGNITION FAILSAFE: Check if bot has safely landed on solid ground - if (bot.entity.onGround) { - const groundUnder = getGroundBlockAt(Math.round(pos.x), Math.round(pos.z)); - if (groundUnder && isSafeSolidBlock(groundUnder)) { - clearInterval(flyLoop); flyLoop = null; - clearInterval(verifyLoop); verifyLoop = null; - retries = 0; - spatialClear = false; - - const rRem = countRockets(); - const landingMsg = `✅ Destination Reached! Arrived safely at (${Math.round(pos.x)}, ${Math.round(pos.y)}, ${Math.round(pos.z)}) on ${groundUnder.name} | Scanned chunks: ${scannedChunks.size} | Rockets remaining: ${rRem}`; - setPhase(PHASE.IDLE, landingMsg); - try { bot.chat(`[EAFE] ${landingMsg}`); } catch(_) {} - return; - } - } - - // 1. Audit & Record loaded chunks into Chunk Memory Map - const bX = Math.floor(pos.x) >> 4; - const bZ = Math.floor(pos.z) >> 4; - for (let dx = -rDist.chunks; dx <= rDist.chunks; dx++) { - for (let dz = -rDist.chunks; dz <= rDist.chunks; dz++) { - scannedChunks.add(`${bX + dx},${bZ + dz}`); - } - } - - // 2. Scan all loaded chunks within server render distance around current position - const foundSpot = findSafeLandingSpotAround(originX, originZ); - if (foundSpot.safe) { - clearInterval(flyLoop); flyLoop = null; - console.log(`[EAFE] 🏝 SOLID LAND DISCOVERED at (${foundSpot.x}, ${foundSpot.z}) [${foundSpot.blockName}]! (Scanned chunks: ${scannedChunks.size})`); - try { - bot.chat(`[EAFE] 🏝 Solid land discovered at (${foundSpot.x}, ${foundSpot.z}) on ${foundSpot.blockName}! Re-routing landing...`); - } catch(_) {} - - activeTargetX = foundSpot.x; - activeTargetZ = foundSpot.z; - startLanding(); - return; - } - - // Failsafe 3b. 10% Backtrack Limit Rule (Evaluated ONLY after 5 seconds of goal scanning) - if (scanTicks > 25 && lastKnownSafeGround && flightStartPos) { - const totalTripDist = Math.hypot(activeTargetX - flightStartPos.x, activeTargetZ - flightStartPos.z); - const backtrackDist = Math.hypot(lastKnownSafeGround.x - pos.x, lastKnownSafeGround.z - pos.z); - const maxBacktrackAllowed = Math.max(totalTripDist * 0.10, 40); - - if (backtrackDist <= maxBacktrackAllowed) { - clearInterval(flyLoop); flyLoop = null; - console.warn(`[EAFE] 🏝 10% Backtrack Lock: Safe coastline found ${backtrackDist.toFixed(0)}m away (<= 10% of ${totalTripDist.toFixed(0)}m trip)! Re-routing to (${lastKnownSafeGround.x}, ${lastKnownSafeGround.z})...`); - try { - bot.chat(`[EAFE] 🏝 Safe coast found within 10% backtrack (${backtrackDist.toFixed(0)}m)! Landing at (${lastKnownSafeGround.x}, ${lastKnownSafeGround.z}) on ${lastKnownSafeGround.blockName}!`); - } catch(_) {} - - activeTargetX = lastKnownSafeGround.x; - activeTargetZ = lastKnownSafeGround.z; - startLanding(); - return; - } - } - - // 4. Dual-Phase Concentric Ring Orbit & Open-Ocean Wander Navigation - const targetYaw = CARDINAL_YAWS[ringLegIndex % 4]; - - if (!legStartPos) legStartPos = pos.clone(); - const distOnLeg = Math.hypot(pos.x - legStartPos.x, pos.z - legStartPos.z); - - if (distOnLeg >= ringSize) { - ringLegIndex++; - if (ringLegIndex % 2 === 0) { - ringSize += Math.round(rDist.blocks * 0.8); // Smoothly expand search ring outward! - } - legStartPos = pos.clone(); - const dirNames = ['North', 'East', 'South', 'West']; - const modeLabel = (ringSize <= 200) ? 'DESTINATION_ORBIT (0-200m)' : 'OPEN_OCEAN_WANDER (200m+)'; - console.log(`[EAFE] 🧭 Leg ${ringLegIndex} complete! [Mode: ${modeLabel}] Facing ${dirNames[ringLegIndex % 4]} (Search Radius: ${ringSize}m)...`); - } - - // ── DYNAMIC TERRAIN SAFETY & COLLISION AVOIDANCE ENGINE ── - const scanHeading = targetYaw ?? bot.entity.yaw; - const terrainScan = scanFullRenderDistance(scanHeading, 0.20); - const groundUnder = getGroundBlockAt(Math.round(pos.x), Math.round(pos.z)); - const groundY = groundUnder?.position?.y ?? 60; - const minSafeY = groundY + 20; - - if (terrainScan.hit && terrainScan.dist < 80) { - if (Date.now() - lastTerrainWarn > 2000) { - console.warn(`[EAFE] 🏔 Hill/Obstacle (${terrainScan.block}) detected ${terrainScan.dist}m ahead — EMERGENCY ASCENT (+0.65 rad) over terrain!`); - lastTerrainWarn = Date.now(); - } - lookForce(scanHeading, 0.65); - if (rCount > 0) fireRocketDirect(scanHeading); - return; - } - - if (pos.y < minSafeY && rCount > 0 && !bot.entity.onGround) { - lookForce(scanHeading, 0.50); - fireRocketDirect(scanHeading); - return; - } - - const vel = bot.entity.velocity; - const speed = Math.hypot(vel.x, vel.y, vel.z); - - // Wall Stall & Friction Failsafe (Stuck on hill escape) - if (speed < 0.05 && !bot.entity.onGround && pos.y > 60) { - console.warn('[EAFE] ⚠ Wall stall detected during ocean scan — turning 180° & boosting upward!'); - lookForce(scanHeading + Math.PI, 0.65); - if (rCount > 0) fireRocketDirect(); - return; - } - - // ── OPTIMAL AERODYNAMIC L/D GLIDE ENGINE ── - const timeSinceBoostMs = Date.now() - dolphinBoostTime; - let scanPitch = -0.04; - - if (timeSinceBoostMs < 1000 && pos.y < 100) { - scanPitch = 0.15; // Gentle Post-Boost Micro-Climb (+0.15 rad) - } else { - scanPitch = -0.04; // Optimal L/D Gravity Glide (-0.04 rad) - } - - if (speed < 0.40 && pos.y < 82 && rCount > 0 && !bot.entity.onGround) { - fireRocketDirect(targetYaw); - } - - lookForce(targetYaw, scanPitch); - - const dirNames = ['North', 'East', 'South', 'West']; - const phaseTag = (ringSize <= 200) ? 'DEST_ORBIT' : 'OCEAN_WANDER'; - console.log(`[EAFE] [${phaseTag}] Y=${pos.y.toFixed(1)} dir=${dirNames[ringLegIndex % 4]} radius=${ringSize}m speed=${(speed*20).toFixed(1)}m/s rockets=${rCount} scannedChunks=${scannedChunks.size}`); - }, 200); - } - - function startLanding() { - const rDist = getServerRenderDistance(); - setPhase(PHASE.LANDING, `Arrived at target area — scanning arrival chunks (${rDist.chunks}ch/${rDist.blocks}m) at (${activeTargetX}, ${activeTargetZ})...`); - - // Real-Time Arrival Chunk Scan across loaded chunk memory - const safeSpot = findSafeLandingSpotAround(activeTargetX, activeTargetZ); - - let targetX = safeSpot.x; - let targetZ = safeSpot.z; - - // IF NO SOLID GROUND IN IMMEDIATE ARRIVAL CHUNKS: - if (!safeSpot.safe) { - if (phase !== PHASE.WANDER_SCAN) { - console.warn(`[EAFE] 🌊 Target area (${activeTargetX}, ${activeTargetZ}) is open ocean! Initiating Straight-Line Lawnmower Scan around goal location first...`); - startWanderScan(); - } - return; - } - - console.log(`[EAFE] ✓ Arrival Chunk Scan: Solid landing spot approved at (${targetX}, ${targetZ}) on [${safeSpot.blockName}]`); - - const landCheck = setInterval(() => { - if (phase !== PHASE.LANDING) { clearInterval(landCheck); return; } - - const pos = bot.entity.position; - const groundBlock = getGroundBlockAt(targetX, targetZ); - const relY = pos.y - (groundBlock?.position?.y ?? 60); - - // Mid-flight Elytra Auto-Swap check - checkMidFlightElytraSwap(); - - const currentBlockUnder = getGroundBlockAt(Math.round(pos.x), Math.round(pos.z)); - const overLiquid = !currentBlockUnder || isWaterOrLava(currentBlockUnder) || !SAFE_SURFACES.has(currentBlockUnder.name); - - if ((overLiquid || dist2D(targetX, targetZ) > 1.5) && pos.y < 65) { - if (countRockets() > 0) { - console.warn(`[EAFE] 🌊 Hovering near ledge/liquid (Y=${pos.y.toFixed(1)}, dist=${dist2D(targetX, targetZ).toFixed(1)}m) — firing impulse rocket to center of land mass (${targetX}, ${targetZ})!`); - lookForce(yawTo(targetX, targetZ), 0.40); - fireRocketDirect(); - } else { - lookForce(yawTo(targetX, targetZ), 0.05); // Unpowered glide push to land center - } - } else if (relY <= 4.0) { - lookForce(yawTo(targetX, targetZ), 0.10); // Nose UP flare - try { bot.setControlState('sneak', true); } catch(_) {} - } else { - lookForce(yawTo(targetX, targetZ), -0.30); // Nose DOWN glide descent - } - - console.log(`[EAFE] [LAND] Y=${pos.y.toFixed(1)} dist=${dist2D(targetX, targetZ).toFixed(1)}m ground=${bot.entity.onGround}`); - - if (bot.entity.onGround) { - clearInterval(landCheck); - clearInterval(verifyLoop); verifyLoop = null; - try { bot.setControlState('sneak', false); } catch(_) {} - retries = 0; - spatialClear = false; // Reset spatial checkmark on touchdown - - const rRem = countRockets(); - const arrivalMsg = `✅ Destination Reached! Arrived safely at (${Math.round(pos.x)}, ${Math.round(pos.y)}, ${Math.round(pos.z)}) on ${currentBlockUnder?.name || 'solid ground'} | Rockets remaining: ${rRem}`; - setPhase(PHASE.IDLE, arrivalMsg); - try { bot.chat(`[EAFE] ${arrivalMsg}`); } catch(_) {} - } - }, 200); - } - - function getGroundBlockAt(x, z) { - const pos = bot.entity.position; - const baseY = Math.floor(pos.y); - for (let dy = 5; dy >= -15; dy--) { - const b = bot.blockAt(new Vec3(x, baseY + dy, z)); - if (b && !isAir(b)) return b; - } - return null; - } - - // ─── RETRY MECHANISM ───────────────────────────────────────────────────── - function scheduleRetry() { - if (retries >= MAX_RETRIES) { - setPhase(PHASE.FAILED, `✗ FLIGHT FAILED permanently after ${MAX_RETRIES} attempts`); - spatialClear = false; - return; - } - retries++; - const delay = retries * 3000; - console.log(`[EAFE] Auto-retry ${retries}/${MAX_RETRIES} in ${delay / 1000}s...`); - try { bot.chat(`[EAFE] Auto-retry ${retries}/${MAX_RETRIES} in ${delay / 1000}s`); } catch(_) {} - setTimeout(() => { - phase = PHASE.IDLE; - startFlight(); - }, delay); - } - - // ─── UNIFIED USER COMMAND PROCESSOR ─────────────────────────────────────── - function processUserCommand(cmd) { - cmd = cmd.trim().toLowerCase(); - if (!cmd) return; - - const tokens = cmd.split(/\s+/); - const mainCmd = tokens[0]; - - // Flight command: "f", "fly", "f 500 -1200", "fly 2500 3000" - if (mainCmd === 'f' || mainCmd === 'fly') { - if (tokens.length >= 3) { - const nx = parseInt(tokens[1], 10); - const nz = parseInt(tokens[2], 10); - if (!isNaN(nx) && !isNaN(nz)) { - activeTargetX = nx; - activeTargetZ = nz; - console.log(`[EAFE] 🎯 Target coordinates updated to (${activeTargetX}, ${activeTargetZ})`); - try { bot.chat(`[EAFE] 🎯 Target set to (${activeTargetX}, ${activeTargetZ}) — starting flight!`); } catch(_) {} - } - } else if (tokens.length === 1) { - console.log(`[EAFE] 🎯 Flying to target coordinates (${activeTargetX}, ${activeTargetZ})`); - } - - retries = 0; - spatialClear = false; - startFlight(); - - // Set goal without immediate takeoff: "setgoal 500 -1200", "target 500 -1200" - } else if (mainCmd === 'setgoal' || mainCmd === 'target' || mainCmd === 'settarget') { - if (tokens.length >= 3) { - const nx = parseInt(tokens[1], 10); - const nz = parseInt(tokens[2], 10); - if (!isNaN(nx) && !isNaN(nz)) { - activeTargetX = nx; - activeTargetZ = nz; - console.log(`[EAFE] 🎯 Target coordinates updated to (${activeTargetX}, ${activeTargetZ})`); - try { bot.chat(`[EAFE] 🎯 Target updated to (${activeTargetX}, ${activeTargetZ}) | Type 'f' to fly!`); } catch(_) {} - } - } - - } else if (cmd === 'mode fast' || cmd === 'm fast' || cmd === 'fast') { - currentMode = MODES.FAST; - console.log(`[EAFE] ⚡ Flight Mode set to ${MODES.FAST.name}`); - try { bot.chat(`[EAFE] ⚡ Flight Mode set to ${MODES.FAST.name}`); } catch(_) {} - - } else if (cmd === 'mode med' || cmd === 'm med' || cmd === 'mode medium' || cmd === 'med' || cmd === 'medium') { - currentMode = MODES.MEDIUM; - console.log(`[EAFE] ⚖ Flight Mode set to ${MODES.MEDIUM.name}`); - try { bot.chat(`[EAFE] ⚖ Flight Mode set to ${MODES.MEDIUM.name}`); } catch(_) {} - - } else if (cmd === 'mode low' || cmd === 'm low' || cmd === 'mode efficient' || cmd === 'low' || cmd === 'efficient') { - currentMode = MODES.EFFICIENT; - console.log(`[EAFE] 🍃 Flight Mode set to ${MODES.EFFICIENT.name}`); - try { bot.chat(`[EAFE] 🍃 Flight Mode set to ${MODES.EFFICIENT.name}`); } catch(_) {} - - } else if (cmd === 's' || cmd === 'stop') { - retries = MAX_RETRIES; - emergencyStop('user command'); - - } else if (cmd === 'status') { - const p = bot.entity.position; - const elytraInfo = getElytraSummary(); - const rDist = getServerRenderDistance(); - const statusMsg = `phase=${phase} mode=${currentMode.name} renderDist=${rDist.chunks}ch/${rDist.blocks}m target=(${activeTargetX},${activeTargetZ}) pos=(${p.x.toFixed(0)},${p.y.toFixed(0)},${p.z.toFixed(0)}) elytra=${bot.entity.elytraFlying} totalElytraDur=${elytraInfo.totalDurabilityAcrossAll}/${elytraInfo.count * 432} rockets=${countRockets()} spatialClear=${spatialClear?'✓':'✗'} dist=${dist2D().toFixed(0)}m scannedChunks=${scannedChunks.size}`; - console.log(`[EAFE] [STATUS] ${statusMsg}`); - try { bot.chat(statusMsg); } catch(_) {} - - } else if (cmd === 'audit') { - const rocketsAvail = countRockets(); - const d2d = dist2D(activeTargetX, activeTargetZ); - const reqRockets = calculateRequiredRockets(d2d, CRUISE_ALT - bot.entity.position.y); - const heading = findBestLaunchHeading(); - const elytraInfo = getElytraSummary(); - const reqDur = calculateRequiredElytraDurability(d2d, currentMode.speedMps, elytraInfo.bestUnbreaking); - const rDist = getServerRenderDistance(); - const auditMsg = `Audit [${currentMode.name} Target=(${activeTargetX},${activeTargetZ}) RenderDist=${rDist.chunks}ch]: Rockets=${rocketsAvail}/${reqRockets} ElytraDur=${elytraInfo.totalDurabilityAcrossAll}/${reqDur} (Unbreaking ${elytraInfo.bestUnbreaking}) Heading=${heading.headingName} Checkmark=${spatialClear?'✓':'✗'}`; - console.log(`[EAFE] [AUDIT] ${auditMsg}`); - try { bot.chat(auditMsg); } catch(_) {} - } - } - - // Handle in-game chat commands - bot.on('chat', (user, msg) => { - if (user === bot.username) return; - processUserCommand(msg); - }); - - // Handle terminal console stdin commands - if (process.stdin.isTTY || process.env.NODE_ENV !== 'test') { - const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); - rl.on('line', (line) => { - console.log(`[CONSOLE COMMAND] > ${line}`); - processUserCommand(line); - }); - } - - // ─── SPAWN & PACKET LISTENERS ────────────────────────────────────────────── - bot.once('spawn', () => { - console.log('[EAFE] ✓ Spawned'); - - if (bot.physicsUtil) { - physEngine = bot.physicsUtil.engine; - console.log('[EAFE] ✓ physicsUtil engine initialized'); - } - - // ── Knockback: entity_velocity packet ──────────────────────────────── - bot._client.on('entity_velocity', packet => { - if (!bot.entity || packet.entityId !== bot.entity.id) return; - const vx = packet.velocity.x / 8000; - const vy = packet.velocity.y / 8000; - const vz = packet.velocity.z / 8000; - bot.entity.velocity.x = vx; - bot.entity.velocity.y = vy; - bot.entity.velocity.z = vz; - console.log(`[EAFE] ⚡ Velocity packet: (${vx.toFixed(3)}, ${vy.toFixed(3)}, ${vz.toFixed(3)})`); - }); - - // ── Knockback: explosion packet ────────────────────────────────────── - bot._client.on('explosion', expl => { - if (!bot.entity) return; - if (expl.playerKnockback) { - bot.entity.velocity.x += expl.playerKnockback.x; - bot.entity.velocity.y += expl.playerKnockback.y; - bot.entity.velocity.z += expl.playerKnockback.z; - console.log('[EAFE] 💥 Explosion knockback applied'); - } else if ('playerMotionX' in expl) { - bot.entity.velocity.x += expl.playerMotionX; - bot.entity.velocity.y += expl.playerMotionY; - bot.entity.velocity.z += expl.playerMotionZ; - console.log('[EAFE] 💥 Explosion knockback applied (legacy)'); - } - }); - - // ── Auto-equip elytra & off-hand rockets on spawn ────────────────── - setTimeout(() => { - auditAndEquipElytra().then(ok => { - autoEquipRocket().then(() => { - const count = countRockets(); - const elytraInfo = getElytraSummary(); - const rDist = getServerRenderDistance(); - console.log(`[EAFE] Inventory audit: elytra=${ok} (${elytraInfo.equippedDur}/432, totalDurability=${elytraInfo.totalDurabilityAcrossAll}, unbreaking=${elytraInfo.bestUnbreaking}) rockets=${count} mode=${currentMode.name} renderDist=${rDist.chunks}chunks`); - try { - bot.chat(`[EAFE] Ready Target:(${activeTargetX},${activeTargetZ}) Mode:${currentMode.name} RenderDist:${rDist.chunks}ch Elytras:${elytraInfo.count} (Dur:${elytraInfo.totalDurabilityAcrossAll}, Unbreaking ${elytraInfo.bestUnbreaking}) Rockets:${count} | f [X Z] m fast/med/low s=stop`); - } catch(_) {} - }); - }); - }, 2000); - - // ── Auto-equip when picked up or received (ONLY WHEN IDLE) ──────────────────── - bot.on('playerCollect', collector => { - if (collector.username !== bot.username) return; - if (phase !== PHASE.IDLE) return; - setTimeout(() => { - auditAndEquipElytra().catch(() => {}); - autoEquipRocket().catch(() => {}); - }, 300); - }); - - bot.inventory.on('updateSlot', (slot, oldItem, newItem) => { - if (phase !== PHASE.IDLE) return; - if (newItem?.name === 'elytra') { - setTimeout(() => auditAndEquipElytra().catch(() => {}), 200); - } - if (newItem?.name === 'firework_rocket') { - setTimeout(() => autoEquipRocket().catch(() => {}), 200); - } - }); - - console.log('[EAFE] Commands: f [X Z] setgoal X Z m fast/med/low s=stop status audit'); - }); - - // ─── DISCONNECT ─────────────────────────────────────────────────────────── - bot._client?.on('error', () => {}); - bot.on('error', e => console.error('[BOT] error:', e.message || e)); - bot.on('kicked', r => console.warn('[BOT] kicked:', typeof r === 'string' ? r : JSON.stringify(r))); - bot.on('end', reason => { - console.log('[BOT] disconnected:', reason, '— reconnecting in 10s'); - clearAllTimers(); - setTimeout(createBot, 10_000); - }); -} - -// ─── BANNER ────────────────────────────────────────────────────────────────── -console.log('╔═════════════════════════════════════════════════════════════╗'); -console.log('║ EAFE v10.3 — Unbreaking Elytra Health & Mid-Flight Swap ║'); -console.log('║ Unbreaking Audit: Audits Unbreaking 1-3 damage rate (25-50%)║'); -console.log('║ Multi-Elytra Pre-Flight: Sums total durability across inventory║'); -console.log('║ Mid-Flight Auto-Swap: Auto-swaps <=15 dur & restores flight ║'); -console.log('║ Flight Trail Lock: Re-routes to last known coastline flown ║'); -console.log(`║ Host: ${HOST}:${PORT}`.padEnd(61) + '║'); -console.log('╚═════════════════════════════════════════════════════════════╝'); - -createBot(); diff --git a/package-lock.json b/package-lock.json index 033d5a8..e151511 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,27 +1,26 @@ { - "name": "eafe", - "version": "11.0.3", + "name": "@eksses/eafe", + "version": "12.0.0", "lockfileVersion": 3, "requires": true, "packages": { "": { - "name": "eafe", - "version": "11.0.3", + "name": "@eksses/eafe", + "version": "12.0.0", "license": "MIT", "dependencies": { - "mineflayer-pathfinder": "^2.4.5" + "mineflayer-pathfinder": "^2.4.5", + "vec3": "^0.2.0" }, "devDependencies": { - "npm-run-all2": "^9.0.3", - "vec3": "^0.2.0" + "@eslint/js": "^9.39.5", + "eslint": "^9.39.5" + }, + "engines": { + "node": ">=16.0.0" }, "peerDependencies": { "mineflayer": ">=4.0.0" - }, - "peerDependenciesMeta": { - "mineflayer": { - "optional": false - } } }, "node_modules/@azure/msal-common": { @@ -49,6 +48,230 @@ "node": ">=16" } }, + "node_modules/@eslint-community/eslint-utils": { + "version": "4.10.1", + "resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.10.1.tgz", + "integrity": "sha512-cuadcxVFE8sDK6iWJbs8Sn0av2Nrh2QSGQhVlBW9AaAHqHwjWsZHT8LJ4hFGPh7ASBV2deFdM7H/DPjulmh8rg==", + "dev": true, + "license": "MIT", + "dependencies": { + "eslint-visitor-keys": "^3.4.3" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + }, + "peerDependencies": { + "eslint": "^6.0.0 || ^7.0.0 || >=8.0.0" + } + }, + "node_modules/@eslint-community/eslint-utils/node_modules/eslint-visitor-keys": { + "version": "3.4.3", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.4.3.tgz", + "integrity": "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/@eslint-community/regexpp": { + "version": "4.12.2", + "resolved": "https://registry.npmjs.org/@eslint-community/regexpp/-/regexpp-4.12.2.tgz", + "integrity": "sha512-EriSTlt5OC9/7SXkRSCAhfSxxoSUgBm33OH+IkwbdpgoqsSsUg7y3uh+IICI/Qg4BBWr3U2i39RpmycbxMq4ew==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^12.0.0 || ^14.0.0 || >=16.0.0" + } + }, + "node_modules/@eslint/config-array": { + "version": "0.21.2", + "resolved": "https://registry.npmjs.org/@eslint/config-array/-/config-array-0.21.2.tgz", + "integrity": "sha512-nJl2KGTlrf9GjLimgIru+V/mzgSK0ABCDQRvxw5BjURL7WfH5uoWmizbH7QB6MmnMBd8cIC9uceWnezL1VZWWw==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@eslint/object-schema": "^2.1.7", + "debug": "^4.3.1", + "minimatch": "^3.1.5" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@eslint/config-helpers": { + "version": "0.4.2", + "resolved": "https://registry.npmjs.org/@eslint/config-helpers/-/config-helpers-0.4.2.tgz", + "integrity": "sha512-gBrxN88gOIf3R7ja5K9slwNayVcZgK6SOUORm2uBzTeIEfeVaIhOpCtTox3P6R7o2jLFwLFTLnC7kU/RGcYEgw==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@eslint/core": "^0.17.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@eslint/core": { + "version": "0.17.0", + "resolved": "https://registry.npmjs.org/@eslint/core/-/core-0.17.0.tgz", + "integrity": "sha512-yL/sLrpmtDaFEiUj1osRP4TI2MDz1AddJL+jZ7KSqvBuliN4xqYY54IfdN8qD8Toa6g1iloph1fxQNkjOxrrpQ==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@types/json-schema": "^7.0.15" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@eslint/eslintrc": { + "version": "3.3.7", + "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-3.3.7.tgz", + "integrity": "sha512-F42g89Qd5oAWtp0k0nnSrjziAKza7w8SVT4mStc18LZMaRb4J1HQAHLCalEtDCxrTuksx7NU9qsmeLwpOfPqWw==", + "dev": true, + "license": "MIT", + "dependencies": { + "ajv": "^6.14.0", + "debug": "^4.3.2", + "espree": "^10.0.1", + "globals": "^14.0.0", + "ignore": "^5.2.0", + "import-fresh": "^3.2.1", + "js-yaml": "^4.3.2", + "minimatch": "^3.1.5", + "strip-json-comments": "^3.1.1" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/@eslint/js": { + "version": "9.39.5", + "resolved": "https://registry.npmjs.org/@eslint/js/-/js-9.39.5.tgz", + "integrity": "sha512-QywQuszQh77pIXCsq998c8hbhSTI/azTty1Z6N53dmAudKHhy573j3yvRLsX2BSp8YpLtoCEG8E9DJe+8zUh4A==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://eslint.org/donate" + } + }, + "node_modules/@eslint/object-schema": { + "version": "2.1.7", + "resolved": "https://registry.npmjs.org/@eslint/object-schema/-/object-schema-2.1.7.tgz", + "integrity": "sha512-VtAOaymWVfZcmZbp6E2mympDIHvyjXs/12LqWYjVw6qjrfF+VK+fyG33kChz3nnK+SU5/NeHOqrTEHS8sXO3OA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@eslint/plugin-kit": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/@eslint/plugin-kit/-/plugin-kit-0.4.1.tgz", + "integrity": "sha512-43/qtrDUokr7LJqoF2c3+RInu/t4zfrpYdoSDfYyhg52rwLV6TnOvdG4fXm7IkSB3wErkcmJS9iEhjVtOSEjjA==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@eslint/core": "^0.17.0", + "levn": "^0.4.1" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@humanfs/core": { + "version": "0.19.2", + "resolved": "https://registry.npmjs.org/@humanfs/core/-/core-0.19.2.tgz", + "integrity": "sha512-UhXNm+CFMWcbChXywFwkmhqjs3PRCmcSa/hfBgLIb7oQ5HNb1wS0icWsGtSAUNgefHeI+eBrA8I1fxmbHsGdvA==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@humanfs/types": "^0.15.0" + }, + "engines": { + "node": ">=18.18.0" + } + }, + "node_modules/@humanfs/node": { + "version": "0.16.8", + "resolved": "https://registry.npmjs.org/@humanfs/node/-/node-0.16.8.tgz", + "integrity": "sha512-gE1eQNZ3R++kTzFUpdGlpmy8kDZD/MLyHqDwqjkVQI0JMdI1D51sy1H958PNXYkM2rAac7e5/CnIKZrHtPh3BQ==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@humanfs/core": "^0.19.2", + "@humanfs/types": "^0.15.0", + "@humanwhocodes/retry": "^0.4.0" + }, + "engines": { + "node": ">=18.18.0" + } + }, + "node_modules/@humanfs/types": { + "version": "0.15.0", + "resolved": "https://registry.npmjs.org/@humanfs/types/-/types-0.15.0.tgz", + "integrity": "sha512-ZZ1w0aoQkwuUuC7Yf+7sdeaNfqQiiLcSRbfI08oAxqLtpXQr9AIVX7Ay7HLDuiLYAaFPu8oBYNq/QIi9URHJ3Q==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18.18.0" + } + }, + "node_modules/@humanwhocodes/module-importer": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@humanwhocodes/module-importer/-/module-importer-1.0.1.tgz", + "integrity": "sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=12.22" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/nzakas" + } + }, + "node_modules/@humanwhocodes/retry": { + "version": "0.4.3", + "resolved": "https://registry.npmjs.org/@humanwhocodes/retry/-/retry-0.4.3.tgz", + "integrity": "sha512-bV0Tgo9K4hfPCek+aMAn81RppFKv2ySDQeMoSZuvTASywNTnVJCArCZE2FWqpvIatKu7VMRLWlR1EazvVhDyhQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18.18" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/nzakas" + } + }, + "node_modules/@types/estree": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz", + "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/json-schema": { + "version": "7.0.15", + "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz", + "integrity": "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==", + "dev": true, + "license": "MIT" + }, "node_modules/@types/node": { "version": "26.1.2", "resolved": "https://registry.npmjs.org/@types/node/-/node-26.1.2.tgz", @@ -101,6 +324,29 @@ "node": ">=6.5" } }, + "node_modules/acorn": { + "version": "8.18.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.18.0.tgz", + "integrity": "sha512-lGq+9yr1/GuAWaVYIHRjvvySG5/4VfKIvC8EWxStPdcDh/Ka7FG3twP6v4d5BkravUilhIAsG4Qj83t02LWUPQ==", + "dev": true, + "license": "MIT", + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/acorn-jsx": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.3.2.tgz", + "integrity": "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" + } + }, "node_modules/aes-js": { "version": "3.1.2", "resolved": "https://registry.npmjs.org/aes-js/-/aes-js-3.1.2.tgz", @@ -124,18 +370,12 @@ "url": "https://github.com/sponsors/epoberezkin" } }, - "node_modules/ansi-styles": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-7.0.0.tgz", - "integrity": "sha512-kKvt3m4uwzqL0wlkPd09CmljPJGOZZ4D0fP65sqFSvPkMRKhNi+74MgIJ5QxE6SxqB4t4KyUFGg8+n5zjo6hew==", + "node_modules/argparse": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", + "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", "dev": true, - "license": "MIT", - "engines": { - "node": ">=22" - }, - "funding": { - "url": "https://github.com/chalk/ansi-styles?sponsor=1" - } + "license": "Python-2.0" }, "node_modules/asn1": { "version": "0.2.3", @@ -144,6 +384,13 @@ "license": "MIT", "peer": true }, + "node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "dev": true, + "license": "MIT" + }, "node_modules/base64-js": { "version": "1.5.1", "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", @@ -164,6 +411,17 @@ ], "license": "MIT" }, + "node_modules/brace-expansion": { + "version": "1.1.21", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.21.tgz", + "integrity": "sha512-9zeA+KLZNNzglF2TPKRQEDyx6Yby7daAkuy8MiPzpXPsYDWi/DRM8jmwUDxokQjYqBpv5DgPiwD4h4ZZSy1Ujw==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, "node_modules/buffer": { "version": "6.0.3", "resolved": "https://registry.npmjs.org/buffer/-/buffer-6.0.3.tgz", @@ -208,12 +466,82 @@ "license": "BSD-3-Clause", "peer": true }, + "node_modules/callsites": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", + "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/chalk/node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true, + "license": "MIT" + }, "node_modules/commander": { "version": "2.20.3", "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.3.tgz", "integrity": "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==", "license": "MIT" }, + "node_modules/concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==", + "dev": true, + "license": "MIT" + }, "node_modules/cross-spawn": { "version": "7.0.6", "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", @@ -269,6 +597,13 @@ } } }, + "node_modules/deep-is": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz", + "integrity": "sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==", + "dev": true, + "license": "MIT" + }, "node_modules/discontinuous-range": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/discontinuous-range/-/discontinuous-range-1.0.0.tgz", @@ -292,6 +627,174 @@ "license": "MIT", "peer": true }, + "node_modules/escape-string-regexp": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", + "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/eslint": { + "version": "9.39.5", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-9.39.5.tgz", + "integrity": "sha512-DgZS62aPLXKlnxILS/AYCoRvHaZeXceIzlXPkkGGzJWSow1aEk0lbTlxUSlyjC8jcaKxAdOnTDz+o1JFSBsyjw==", + "deprecated": "This version is no longer supported. Please see https://eslint.org/version-support for other options.", + "dev": true, + "license": "MIT", + "dependencies": { + "@eslint-community/eslint-utils": "^4.8.0", + "@eslint-community/regexpp": "^4.12.1", + "@eslint/config-array": "^0.21.2", + "@eslint/config-helpers": "^0.4.2", + "@eslint/core": "^0.17.0", + "@eslint/eslintrc": "^3.3.6", + "@eslint/js": "9.39.5", + "@eslint/plugin-kit": "^0.4.1", + "@humanfs/node": "^0.16.6", + "@humanwhocodes/module-importer": "^1.0.1", + "@humanwhocodes/retry": "^0.4.2", + "@types/estree": "^1.0.6", + "ajv": "^6.14.0", + "chalk": "^4.0.0", + "cross-spawn": "^7.0.6", + "debug": "^4.3.2", + "escape-string-regexp": "^4.0.0", + "eslint-scope": "^8.4.0", + "eslint-visitor-keys": "^4.2.1", + "espree": "^10.4.0", + "esquery": "^1.5.0", + "esutils": "^2.0.2", + "fast-deep-equal": "^3.1.3", + "file-entry-cache": "^8.0.0", + "find-up": "^5.0.0", + "glob-parent": "^6.0.2", + "ignore": "^5.2.0", + "imurmurhash": "^0.1.4", + "is-glob": "^4.0.0", + "json-stable-stringify-without-jsonify": "^1.0.1", + "lodash.merge": "^4.6.2", + "minimatch": "^3.1.5", + "natural-compare": "^1.4.0", + "optionator": "^0.9.3" + }, + "bin": { + "eslint": "bin/eslint.js" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://eslint.org/donate" + }, + "peerDependencies": { + "jiti": "*" + }, + "peerDependenciesMeta": { + "jiti": { + "optional": true + } + } + }, + "node_modules/eslint-scope": { + "version": "8.4.0", + "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-8.4.0.tgz", + "integrity": "sha512-sNXOfKCn74rt8RICKMvJS7XKV/Xk9kA7DyJr8mJik3S7Cwgy3qlkkmyS2uQB3jiJg6VNdZd/pDBJu0nvG2NlTg==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "esrecurse": "^4.3.0", + "estraverse": "^5.2.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/eslint-visitor-keys": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-4.2.1.tgz", + "integrity": "sha512-Uhdk5sfqcee/9H/rCOJikYz67o0a2Tw2hGRPOG2Y1R2dg7brRe1uG0yaNQDHu+TO/uQPF/5eCapvYSmHUjt7JQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/espree": { + "version": "10.4.0", + "resolved": "https://registry.npmjs.org/espree/-/espree-10.4.0.tgz", + "integrity": "sha512-j6PAQ2uUr79PZhBjP5C5fhl8e39FmRnOjsD5lGnWrFU8i2G776tBK7+nP8KuQUTTyAZUwfQqXAgrVH5MbH9CYQ==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "acorn": "^8.15.0", + "acorn-jsx": "^5.3.2", + "eslint-visitor-keys": "^4.2.1" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/esquery": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/esquery/-/esquery-1.7.0.tgz", + "integrity": "sha512-Ap6G0WQwcU/LHsvLwON1fAQX9Zp0A2Y6Y/cJBl9r/JbW90Zyg4/zbG6zzKa2OTALELarYHmKu0GhpM5EO+7T0g==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "estraverse": "^5.1.0" + }, + "engines": { + "node": ">=0.10" + } + }, + "node_modules/esrecurse": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.3.0.tgz", + "integrity": "sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "estraverse": "^5.2.0" + }, + "engines": { + "node": ">=4.0" + } + }, + "node_modules/estraverse": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", + "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=4.0" + } + }, + "node_modules/esutils": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz", + "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/event-target-shim": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/event-target-shim/-/event-target-shim-5.0.1.tgz", @@ -322,6 +825,100 @@ "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==", "license": "MIT" }, + "node_modules/fast-levenshtein": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz", + "integrity": "sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==", + "dev": true, + "license": "MIT" + }, + "node_modules/file-entry-cache": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-8.0.0.tgz", + "integrity": "sha512-XXTUwCvisa5oacNGRP9SfNtYBNAMi+RPwBFmblZEF7N7swHYQS6/Zfk7SRwx4D5j3CH211YNRco1DEMNVfZCnQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "flat-cache": "^4.0.0" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/find-up": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz", + "integrity": "sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==", + "dev": true, + "license": "MIT", + "dependencies": { + "locate-path": "^6.0.0", + "path-exists": "^4.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/flat-cache": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-4.0.1.tgz", + "integrity": "sha512-f7ccFPK3SXFHpx15UIGyRJ/FJQctuKZ0zVuN3frBo4HnK3cay9VEW0R6yPYFHC0AgqhukPzKjq22t5DmAyqGyw==", + "dev": true, + "license": "MIT", + "dependencies": { + "flatted": "^3.2.9", + "keyv": "^4.5.4" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/flatted": { + "version": "3.4.4", + "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.4.4.tgz", + "integrity": "sha512-5+ybhBZANEJxaH3X5evAFatUxLfEHSr7n6kYJ+1Qd0mUqr4eu9gIf6GDbWHf8RJijHrjjO8G+la14SlL2SeS1Q==", + "dev": true, + "license": "ISC" + }, + "node_modules/glob-parent": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz", + "integrity": "sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==", + "dev": true, + "license": "ISC", + "dependencies": { + "is-glob": "^4.0.3" + }, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/globals": { + "version": "14.0.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-14.0.0.tgz", + "integrity": "sha512-oahGvuMGQlPw/ivIYBjVSrWAfWLBeku5tpPE2fOPLi+WHffIWbuh2tCjhyQhTBPMf5E9jDEH4FOmTYgYwbKwtQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, "node_modules/ieee754": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", @@ -342,32 +939,109 @@ ], "license": "BSD-3-Clause" }, - "node_modules/isexe": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/isexe/-/isexe-4.0.0.tgz", - "integrity": "sha512-FFUtZMpoZ8RqHS3XeXEmHWLA4thH+ZxCv2lOiPIn1Xc7CxrqhWzNSDzD+/chS/zbYezmiwWLdQC09JdQKmthOw==", + "node_modules/ignore": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz", + "integrity": "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==", "dev": true, - "license": "BlueOak-1.0.0", + "license": "MIT", "engines": { - "node": ">=20" + "node": ">= 4" } }, - "node_modules/json-parse-even-better-errors": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-6.0.0.tgz", - "integrity": "sha512-2/8adwnK1/+Fdjyts4r6wSpfANWw8zdNhU9U/Llk59c6O+DjSisPWPykwoL8gZmocP9Dy64S7oie2g+Mia123A==", + "node_modules/import-fresh": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.1.tgz", + "integrity": "sha512-TR3KfrTZTYLPB6jUjfx6MF9WcWrHL9su5TObK4ZkYgBdWKPOFoSoQIdEuTuR82pmtxH2spWG9h6etwfr1pLBqQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "parent-module": "^1.0.0", + "resolve-from": "^4.0.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/imurmurhash": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", + "integrity": "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.8.19" + } + }, + "node_modules/is-extglob": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-glob": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", + "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", "dev": true, "license": "MIT", + "dependencies": { + "is-extglob": "^2.1.1" + }, "engines": { - "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + "node": ">=0.10.0" + } + }, + "node_modules/js-yaml": { + "version": "4.3.2", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.2.tgz", + "integrity": "sha512-SFNOvSJ+Dgf/9An904Yx+CgSlIPCkIpao4qo51lpee25TIRejdH3rhR4EZMGoNx3/TP3O+wzWuiTFl4sqbltzA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/puzrin" + }, + { + "type": "github", + "url": "https://github.com/sponsors/nodeca" + } + ], + "license": "MIT", + "dependencies": { + "argparse": "^2.0.1" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" } }, + "node_modules/json-buffer": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/json-buffer/-/json-buffer-3.0.1.tgz", + "integrity": "sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ==", + "dev": true, + "license": "MIT" + }, "node_modules/json-schema-traverse": { "version": "0.4.1", "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", "license": "MIT" }, + "node_modules/json-stable-stringify-without-jsonify": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz", + "integrity": "sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==", + "dev": true, + "license": "MIT" + }, "node_modules/jsonwebtoken": { "version": "9.0.3", "resolved": "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-9.0.3.tgz", @@ -414,6 +1088,46 @@ "safe-buffer": "^5.0.1" } }, + "node_modules/keyv": { + "version": "4.5.4", + "resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.4.tgz", + "integrity": "sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw==", + "dev": true, + "license": "MIT", + "dependencies": { + "json-buffer": "3.0.1" + } + }, + "node_modules/levn": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/levn/-/levn-0.4.1.tgz", + "integrity": "sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "prelude-ls": "^1.2.1", + "type-check": "~0.4.0" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/locate-path": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz", + "integrity": "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==", + "dev": true, + "license": "MIT", + "dependencies": { + "p-locate": "^5.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/lodash.includes": { "version": "4.3.0", "resolved": "https://registry.npmjs.org/lodash.includes/-/lodash.includes-4.3.0.tgz", @@ -460,8 +1174,7 @@ "version": "4.6.2", "resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz", "integrity": "sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==", - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/lodash.once": { "version": "4.1.1", @@ -483,15 +1196,6 @@ "license": "MIT", "peer": true }, - "node_modules/memorystream": { - "version": "0.3.1", - "resolved": "https://registry.npmjs.org/memorystream/-/memorystream-0.3.1.tgz", - "integrity": "sha512-S3UwM3yj5mtUSEfP41UZmt/0SCoVYUcU1rkXv+BQ5Ig8ndL4sPoJNBUJERafdPb5jjHJGuMgytgKvKIf58XNBw==", - "dev": true, - "engines": { - "node": ">= 0.10.0" - } - }, "node_modules/minecraft-data": { "version": "3.112.0", "resolved": "https://registry.npmjs.org/minecraft-data/-/minecraft-data-3.112.0.tgz", @@ -595,6 +1299,19 @@ "license": "BSD", "peer": true }, + "node_modules/minimatch": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", + "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==", + "dev": true, + "license": "ISC", + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, "node_modules/mojangson": { "version": "2.0.4", "resolved": "https://registry.npmjs.org/mojangson/-/mojangson-2.0.4.tgz", @@ -616,6 +1333,13 @@ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", "license": "MIT" }, + "node_modules/natural-compare": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz", + "integrity": "sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==", + "dev": true, + "license": "MIT" + }, "node_modules/nearley": { "version": "2.20.1", "resolved": "https://registry.npmjs.org/nearley/-/nearley-2.20.1.tgz", @@ -669,77 +1393,97 @@ "asn1": "0.2.3" } }, - "node_modules/npm-normalize-package-bin": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/npm-normalize-package-bin/-/npm-normalize-package-bin-6.0.0.tgz", - "integrity": "sha512-tdt4aFn9QamlhdN3HV2D2ccpBwO5/fyjjbXUxYA6uBjyekMZcZvDq0aSj9t5Jo+tih6AYFnt/cuIRn9013e0Uw==", + "node_modules/optionator": { + "version": "0.9.4", + "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz", + "integrity": "sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g==", "dev": true, - "license": "ISC", + "license": "MIT", + "dependencies": { + "deep-is": "^0.1.3", + "fast-levenshtein": "^2.0.6", + "levn": "^0.4.1", + "prelude-ls": "^1.2.1", + "type-check": "^0.4.0", + "word-wrap": "^1.2.5" + }, "engines": { - "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + "node": ">= 0.8.0" } }, - "node_modules/npm-run-all2": { - "version": "9.0.3", - "resolved": "https://registry.npmjs.org/npm-run-all2/-/npm-run-all2-9.0.3.tgz", - "integrity": "sha512-BQAEdU1PtYc48qYRdghW2BVTQT3VqWCoFQmO87NlM1h1PYwMCKQpUWaNyB20V26caNzFsXQDfyOdznLlHCih6g==", + "node_modules/p-limit": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz", + "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==", "dev": true, "license": "MIT", "dependencies": { - "ansi-styles": "^7.0.0", - "cross-spawn": "^7.0.6", - "memorystream": "^0.3.1", - "picomatch": "^4.0.2", - "pidtree": "^1.0.0", - "read-package-json-fast": "^6.0.0", - "shell-quote": "^1.8.4", - "which": "^7.0.0" + "yocto-queue": "^0.1.0" }, - "bin": { - "npm-run-all": "bin/npm-run-all/index.js", - "npm-run-all2": "bin/npm-run-all/index.js", - "run-p": "bin/run-p/index.js", - "run-s": "bin/run-s/index.js" + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-locate": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-5.0.0.tgz", + "integrity": "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==", + "dev": true, + "license": "MIT", + "dependencies": { + "p-limit": "^3.0.2" }, "engines": { - "node": "^22.22.2 || ^24.15.0 || >=26.0.0", - "npm": ">= 10" + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/path-key": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", - "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "node_modules/parent-module": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz", + "integrity": "sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==", + "dev": true, + "license": "MIT", + "dependencies": { + "callsites": "^3.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/path-exists": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", + "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", "dev": true, "license": "MIT", "engines": { "node": ">=8" } }, - "node_modules/picomatch": { - "version": "4.0.5", - "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.5.tgz", - "integrity": "sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A==", + "node_modules/path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", "dev": true, "license": "MIT", "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/sponsors/jonschlinkert" + "node": ">=8" } }, - "node_modules/pidtree": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/pidtree/-/pidtree-1.0.0.tgz", - "integrity": "sha512-avfAvjB9Dd0wdj3rjJX//yS+G79OO0KrS5pJHFJENjYGX6N4SMgEDBBI/yFy0lloOYSaC6XQxzpOAMPfSYFV/Q==", + "node_modules/prelude-ls": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz", + "integrity": "sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==", "dev": true, "license": "MIT", - "bin": { - "pidtree": "bin/pidtree.js" - }, "engines": { - "node": ">=18" + "node": ">= 0.8.0" } }, "node_modules/prismarine-auth": { @@ -1003,20 +1747,6 @@ "node": ">=0.12" } }, - "node_modules/read-package-json-fast": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/read-package-json-fast/-/read-package-json-fast-6.0.0.tgz", - "integrity": "sha512-PNaGjoCnw9DBA2Kl8D+8po957z778q/HOPuY2u3Bkw/JO3eC8MDx7jn/PgMtSgpcBbs+6UOjDbwReGpXmRvs0g==", - "dev": true, - "license": "ISC", - "dependencies": { - "json-parse-even-better-errors": "^6.0.0", - "npm-normalize-package-bin": "^6.0.0" - }, - "engines": { - "node": "^22.22.2 || ^24.15.0 || >=26.0.0" - } - }, "node_modules/readable-stream": { "version": "4.7.0", "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-4.7.0.tgz", @@ -1033,6 +1763,16 @@ "node": "^12.22.0 || ^14.17.0 || >=16.0.0" } }, + "node_modules/resolve-from": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz", + "integrity": "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, "node_modules/ret": { "version": "0.1.15", "resolved": "https://registry.npmjs.org/ret/-/ret-0.1.15.tgz", @@ -1109,19 +1849,6 @@ "node": ">=8" } }, - "node_modules/shell-quote": { - "version": "1.10.0", - "resolved": "https://registry.npmjs.org/shell-quote/-/shell-quote-1.10.0.tgz", - "integrity": "sha512-w1aiOKwKuRgtwAReIIj89puqg+I7GvX4IbLrvmhXbzQsj1+Zwi4VO3+fa6ZF91TWSjIxoEkKnMeHcLEODK5ZXA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, "node_modules/smart-buffer": { "version": "4.2.0", "resolved": "https://registry.npmjs.org/smart-buffer/-/smart-buffer-4.2.0.tgz", @@ -1142,6 +1869,32 @@ "safe-buffer": "~5.2.0" } }, + "node_modules/strip-json-comments": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz", + "integrity": "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/tr46": { "version": "0.0.3", "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz", @@ -1157,6 +1910,19 @@ "optional": true, "peer": true }, + "node_modules/type-check": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz", + "integrity": "sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==", + "dev": true, + "license": "MIT", + "dependencies": { + "prelude-ls": "^1.2.1" + }, + "engines": { + "node": ">= 0.8.0" + } + }, "node_modules/typed-emitter": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/typed-emitter/-/typed-emitter-1.4.0.tgz", @@ -1232,20 +1998,14 @@ "webidl-conversions": "^3.0.0" } }, - "node_modules/which": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/which/-/which-7.0.0.tgz", - "integrity": "sha512-RancgH2dmbLdHl6LRhEqvklWMgl/Hdnun0Y90KhBOLkMefg8Qa7/Zel8Sm+8HEcP6DEjzsWzpkuBQEZok58isA==", + "node_modules/word-wrap": { + "version": "1.2.5", + "resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz", + "integrity": "sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==", "dev": true, - "license": "ISC", - "dependencies": { - "isexe": "^4.0.0" - }, - "bin": { - "node-which": "bin/which.js" - }, + "license": "MIT", "engines": { - "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + "node": ">=0.10.0" } }, "node_modules/xxhash-wasm": { @@ -1280,6 +2040,19 @@ "bin": { "uuid": "dist/bin/uuid" } + }, + "node_modules/yocto-queue": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", + "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } } } } diff --git a/package.json b/package.json index 97b0f48..eaba7f3 100644 --- a/package.json +++ b/package.json @@ -1,12 +1,13 @@ { "name": "@eksses/eafe", - "version": "11.0.3", + "version": "12.0.0", "description": "Autonomous elytra flight engine for mineflayer — fly anywhere in Minecraft with 3 lines of code. Handles takeoff, climb, cruise, terrain avoidance, and safe landing automatically.", "main": "src/index.js", "exports": { ".": "./src/index.js", "./logger": "./src/logger.js", "./constants": "./src/constants.js", + "./errors": "./src/errors.js", "./utils": "./src/utils.js", "./inventory": "./src/core/inventory.js", "./elytra": "./src/core/elytra.js", @@ -18,7 +19,8 @@ }, "scripts": { "start": "node examples/basic.js", - "test": "node -e \"require('./src/index.js'); console.log('OK')\"", + "test": "node test/run.js", + "lint": "eslint src test examples", "demo": "node examples/demo.js" }, "repository": { @@ -50,16 +52,12 @@ }, "homepage": "https://github.com/eksses/EAFE#readme", "dependencies": { - "mineflayer-pathfinder": "^2.4.5" + "mineflayer-pathfinder": "^2.4.5", + "vec3": "^0.2.0" }, "peerDependencies": { "mineflayer": ">=4.0.0" }, - "peerDependenciesMeta": { - "mineflayer": { - "optional": false - } - }, "files": [ "src/", "README.md", @@ -67,8 +65,8 @@ "LICENSE" ], "devDependencies": { - "npm-run-all2": "^9.0.3", - "vec3": "^0.2.0" + "@eslint/js": "^9.39.5", + "eslint": "^9.39.5" }, "engines": { "node": ">=16.0.0" diff --git a/src/commands.js b/src/commands.js deleted file mode 100644 index 56119e6..0000000 --- a/src/commands.js +++ /dev/null @@ -1,99 +0,0 @@ -'use strict'; - -const config = require('./config'); -const { MODES } = require('./constants'); -const Logger = require('./logger'); - -function createCommandProcessor(ctx) { - const { bot, state } = ctx; - - function processUserCommand(cmd) { - cmd = cmd.trim().toLowerCase(); - if (!cmd) return; - - const tokens = cmd.split(/\s+/); - const mainCmd = tokens[0]; - - if (mainCmd === 'f' || mainCmd === 'fly') { - if (tokens.length >= 3) { - const nx = parseInt(tokens[1], 10); - const nz = parseInt(tokens[2], 10); - if (!isNaN(nx) && !isNaN(nz)) { - state.activeTargetX = nx; - state.activeTargetZ = nz; - Logger.info(`target (${state.activeTargetX},${state.activeTargetZ})`); - try { bot.chat(`Target: (${state.activeTargetX},${state.activeTargetZ})`); } catch(_) {} - } - } else if (tokens.length === 1) { - Logger.info(`fly -> (${state.activeTargetX},${state.activeTargetZ})`); - } - - state.retries = 0; - state.spatialClear = false; - ctx.startFlight(); - - } else if (mainCmd === 'setgoal' || mainCmd === 'target' || mainCmd === 'settarget') { - if (tokens.length >= 3) { - const nx = parseInt(tokens[1], 10); - const nz = parseInt(tokens[2], 10); - if (!isNaN(nx) && !isNaN(nz)) { - state.activeTargetX = nx; - state.activeTargetZ = nz; - Logger.info(`target (${state.activeTargetX},${state.activeTargetZ})`); - try { bot.chat(`Target: (${state.activeTargetX},${state.activeTargetZ}) -- f to fly`); } catch(_) {} - } - } - - } else if (cmd === 'mode fast' || cmd === 'm fast' || cmd === 'fast') { - state.currentMode = MODES.FAST; - Logger.info(`mode ${MODES.FAST.name}`); - try { bot.chat(`Mode: ${MODES.FAST.fullName}`); } catch(_) {} - - } else if (cmd === 'mode med' || cmd === 'm med' || cmd === 'mode medium' || cmd === 'med' || cmd === 'medium') { - state.currentMode = MODES.MEDIUM; - Logger.info(`mode ${MODES.MEDIUM.name}`); - try { bot.chat(`Mode: ${MODES.MEDIUM.fullName}`); } catch(_) {} - - } else if (cmd === 'mode low' || cmd === 'm low' || cmd === 'mode efficient' || cmd === 'low' || cmd === 'efficient') { - state.currentMode = MODES.EFFICIENT; - Logger.info(`mode ${MODES.EFFICIENT.name}`); - try { bot.chat(`Mode: ${MODES.EFFICIENT.fullName}`); } catch(_) {} - - } else if (cmd === 's' || cmd === 'stop') { - state.retries = ctx.MAX_RETRIES; - ctx.emergencyStop('user cmd'); - - } else if (cmd === 'debug on' || cmd === 'debug') { - Logger.setDebug(true); - Logger.info('debug ON'); - - } else if (cmd === 'debug off') { - Logger.setDebug(false); - Logger.info('debug OFF'); - - } else if (cmd === 'status') { - const p = bot.entity.position; - const elytraInfo = ctx.getElytraSummary(bot); - const rDist = ctx.spatial.getServerRenderDistance(); - const status = `phase=${state.phase} m=${state.currentMode.name} r=${rDist.chunks}ch t=(${state.activeTargetX},${state.activeTargetZ}) pos=(${p.x.toFixed(0)},${p.y.toFixed(0)},${p.z.toFixed(0)}) fly=${bot.entity.elytraFlying} e=${elytraInfo.totalDurabilityAcrossAll} rkt=${ctx.countRockets(bot)}`; - Logger.info(status); - try { bot.chat(status); } catch(_) {} - - } else if (cmd === 'audit') { - const rocketsAvail = ctx.countRockets(bot); - const d2d = ctx.dist2D(state.activeTargetX, state.activeTargetZ); - const reqRockets = ctx.calculateRequiredRockets(d2d, ctx.CRUISE_ALT - bot.entity.position.y); - const heading = ctx.spatial.findBestLaunchHeading(); - const elytraInfo = ctx.getElytraSummary(bot); - const reqDur = ctx.calculateRequiredElytraDurability(d2d, state.currentMode.speedMps, elytraInfo.bestUnbreaking); - const rDist = ctx.spatial.getServerRenderDistance(); - const audit = `audit [${state.currentMode.name} ${rDist.chunks}ch]: rkt=${rocketsAvail}/${reqRockets} e=${elytraInfo.totalDurabilityAcrossAll}/${reqDur} U${elytraInfo.bestUnbreaking} hdg=${heading.headingName}`; - Logger.info(audit); - try { bot.chat(audit); } catch(_) {} - } - } - - return { processUserCommand }; -} - -module.exports = { createCommandProcessor }; diff --git a/src/config.js b/src/config.js deleted file mode 100644 index 524507e..0000000 --- a/src/config.js +++ /dev/null @@ -1,20 +0,0 @@ -'use strict'; - -module.exports = { - // Server connection (used by examples only, not the library) - HOST: 'localhost', - PORT: 25565, - USERNAME: 'Bot', - - // Default flight settings - DEFAULT_TARGET_X: 0, - DEFAULT_TARGET_Z: 0, - CRUISE_ALT: 180, - MAX_RETRIES: 3, - - // Owner: receives important whispers (set to '' to disable) - OWNER_USERNAME: '', - - // Debug logging (set to false for production) - DEBUG: false, -}; diff --git a/src/constants.js b/src/constants.js index c2e7acc..147e3e6 100644 --- a/src/constants.js +++ b/src/constants.js @@ -1,5 +1,15 @@ 'use strict'; +/** + * Flight modes. + * + * speedMps — expected average ground speed (m/s) used for planning. + * pitch — steady cruise pitch (radians, negative = descending). + * speedGate — fire a rocket when speed drops below this (blocks/tick, + * 1 block/tick = 20 m/s). + * fuelDistDivider — horizontal meters of flight covered per rocket when + * estimating fuel (lower = more rockets budgeted). + */ const MODES = { FAST: { name: 'FAST', @@ -27,6 +37,10 @@ const MODES = { }, }; +// Documented aliases so 'MED' / 'LOW' resolve (previously fell back to MED silently). +MODES.MED = MODES.MEDIUM; +MODES.LOW = MODES.EFFICIENT; + const PHASE = { IDLE: 'IDLE', AUDIT: 'AUDIT', @@ -40,6 +54,7 @@ const PHASE = { FAILED: 'FAIL', }; +/** Surfaces the bot must not land on / fly through. Exact names only. */ const HAZARD_SURFACES = new Set([ 'water', 'flowing_water', 'lava', 'flowing_lava', 'magma_block', 'fire', 'soul_fire', 'sweet_berry_bush', 'cactus', 'powder_snow', diff --git a/src/core/chat.js b/src/core/chat.js deleted file mode 100644 index f73cb90..0000000 --- a/src/core/chat.js +++ /dev/null @@ -1,46 +0,0 @@ -'use strict'; - -const config = require('../config'); -const Logger = require('../logger'); - -function createChat(ctx) { - let lastChatTimestamp = 0; - - function safeChat(msg) { - if (!msg || typeof msg !== 'string') return; - if (Date.now() - lastChatTimestamp < 4000) return; - lastChatTimestamp = Date.now(); - try { ctx.bot.chat(msg.substring(0, 256)); } catch(_) {} - } - - function ownerTell(msg) { - if (!config.OWNER_USERNAME) return; - if (!msg || typeof msg !== 'string') return; - try { ctx.bot.whisper(config.OWNER_USERNAME, msg.substring(0, 256)); } catch(_) {} - } - - function setPhase(p, msg) { - ctx.state.phase = p; - const line = msg ? `[${p}] ${msg}` : `[${p}]`; - Logger.info(line); - ownerTell(line); - } - - function emergencyStop(reason) { - ctx.state.phase = ctx.PHASE.IDLE; - ctx.state.spatialClear = false; - ctx.clearTimers(); - try { ctx.bot.pathfinder.stop(); } catch(_) {} - ['sprint','forward','back','left','right','jump','sneak'].forEach(k => { - try { ctx.bot.setControlState(k, false); } catch(_) {} - }); - try { ctx.bot.setControlState('sneak', true); } catch(_) {} - setTimeout(() => { try { ctx.bot.setControlState('sneak', false); } catch(_) {} }, 600); - Logger.info(`STOP ${reason}`); - ownerTell(`STOP: ${reason}`); - } - - return { safeChat, setPhase, emergencyStop, ownerTell }; -} - -module.exports = { createChat }; diff --git a/src/core/elytra.js b/src/core/elytra.js index 091598f..bffcd92 100644 --- a/src/core/elytra.js +++ b/src/core/elytra.js @@ -2,29 +2,53 @@ const Logger = require('../logger'); +/** + * Detect Unbreaking level across mineflayer item shapes: + * - pre-1.20.5: item.enchants = [{ name: 'unbreaking', lvl: 3 }] + * - 1.20.5+: item.enchants = [{ id: 'minecraft:unbreaking', lvl: 3 }] (item components) + * - raw NBT: item.nbt.value.Enchantments.value.value = [{ id: 34, lvl: 3 }] + */ function getUnbreakingLevel(item) { if (!item) return 0; - if (item.enchants && Array.isArray(item.enchants)) { - const u = item.enchants.find(e => e.name === 'unbreaking' || e.name === 'durability'); + + const enchs = item.enchants; + if (Array.isArray(enchs)) { + const u = enchs.find(e => + e.name === 'unbreaking' || e.name === 'durability' || + e.id === 'minecraft:unbreaking' || e.id === 'unbreaking' || e.id === 34 + ); if (u) return u.lvl ?? 1; } + try { - const enchs = item.nbt?.value?.Enchantments?.value?.value || item.nbt?.value?.ench?.value?.value; - if (enchs && Array.isArray(enchs)) { - const u = enchs.find(e => e.id?.value === 'unbreaking' || e.id?.value === 34); - if (u) return u.lvl?.value ?? 1; + const raw = item.nbt?.value?.Enchantments?.value?.value; + if (raw && Array.isArray(raw)) { + const u = raw.find(e => { + const id = e.id?.value ?? e.id; + return id === 34 || id === 'unbreaking' || id === 'minecraft:unbreaking'; + }); + if (u) { + const lvl = u.lvl?.value ?? u.lvl; + return Number(lvl) || 1; + } } - } catch(_) {} + } catch (_) { /* NBT shape varies by version — fall through */ } + return 0; } +/** + * Expected elytra durability loss per second of flight. + * + * Unbreaking n deals damage with probability 2/(n+3) (no damage with + * probability (n+1)/(n+3)), so the expected rate is `2 / (n + 3)`: + * unenchanted 1.0, U1 0.5, U2 0.4, U3 ~0.333, U4 ~0.286 ... + * (The old 1/(n+1) table under-estimated U3 by 25% — preflight could pass + * while the elytra broke mid-flight.) + */ function getElytraDamageRate(unbreakingLvl) { - switch (unbreakingLvl) { - case 1: return 0.50; - case 2: return 0.333; - case 3: return 0.25; - default: return 1.0; - } + if (!unbreakingLvl || unbreakingLvl < 1) return 1.0; + return 2 / (unbreakingLvl + 3); } function calculateRequiredElytraDurability(d2d, speedMps, unbreakingLvl) { @@ -67,7 +91,18 @@ function getElytraSummary(bot) { return { count, equippedDur, maxDur, totalDurabilityAcrossAll, bestUnbreaking }; } -async function auditAndEquipElytra(ctx) { +/** + * Ensure the chest slot holds the best elytra. + * + * @param {object} ctx flight context (needs bot, safeChat, logger) + * @param {object} [options] + * @param {boolean} [options.equip=true] actually swap items. Pass false for a + * pure "check" (used by preflight()). + * @returns {Promise} true when an elytra with durability > 10 is (or + * will be) equipped. + */ +async function auditAndEquipElytra(ctx, options = {}) { + const { equip = true } = options; const { bot } = ctx; const chest = bot.inventory.slots[6]; let currentEquippedDur = -1; @@ -98,13 +133,15 @@ async function auditAndEquipElytra(ctx) { return false; } + if (!equip) return true; // check-only: a good spare exists + const spareItem = bot.inventory.slots[bestSlot]; try { await bot.equip(spareItem, 'torso'); Logger.info(`elytra swap slot${bestSlot} dur=${bestDur}/432 (was ${currentEquippedDur})`); ctx.safeChat(`Elytra swapped (${bestDur}/432)`); return true; - } catch(e) { + } catch (e) { Logger.error('equip elytra fail:', e.message); return false; } diff --git a/src/core/inventory.js b/src/core/inventory.js index 299520b..97c9b34 100644 --- a/src/core/inventory.js +++ b/src/core/inventory.js @@ -2,39 +2,63 @@ const Logger = require('../logger'); -function countRockets(bot) { +/** + * Rockets that carry a custom star (NBT `Fireworks.Explosions`) are NOT + * counted by default — the engine only plans around plain rockets. Pass + * `{ includeCustom: true }` to count them as well. + */ +function hasCustomStar(item) { + try { return Boolean(item.nbt?.value?.Fireworks?.value?.Explosions); } catch (_) { return false; } +} + +function countRockets(bot, { includeCustom = false } = {}) { let count = 0; for (let slot = 0; slot <= 45; slot++) { const i = bot.inventory.slots[slot]; if (i && i.name === 'firework_rocket') { - try { if (i.nbt?.value?.Fireworks?.value?.Explosions) continue; } catch(_) {} + if (!includeCustom && hasCustomStar(i)) continue; count += i.count; } } return count; } -function findRocket(bot) { +function getRocketSummary(bot) { + let plain = 0; + let custom = 0; + for (let slot = 0; slot <= 45; slot++) { + const i = bot.inventory.slots[slot]; + if (i && i.name === 'firework_rocket') { + if (hasCustomStar(i)) custom += i.count; + else plain += i.count; + } + } + return { plain, custom, total: plain + custom }; +} + +function findRocket(bot, { includeCustom = false } = {}) { const offhand = bot.inventory.slots[45]; - if (offhand && offhand.name === 'firework_rocket') return offhand; + if (offhand && offhand.name === 'firework_rocket' && (includeCustom || !hasCustomStar(offhand))) { + return offhand; + } for (let slot = 0; slot <= 44; slot++) { const i = bot.inventory.slots[slot]; - if (i && i.name === 'firework_rocket') { - try { if (i.nbt?.value?.Fireworks?.value?.Explosions) continue; } catch(_) {} + if (i && i.name === 'firework_rocket' && (includeCustom || !hasCustomStar(i))) { return i; } } return null; } -async function autoEquipRocket(bot) { +async function autoEquipRocket(bot, { includeCustom = false } = {}) { const offhand = bot.inventory.slots[45]; if (offhand?.name === 'firework_rocket') return true; - const rocket = findRocket(bot); + const rocket = findRocket(bot, { includeCustom }); if (!rocket) { - Logger.warn('no rockets in inventory'); + const s = getRocketSummary(bot); + Logger.warn(`no plain rockets (custom star rockets: ${s.custom})`); return false; } @@ -42,10 +66,10 @@ async function autoEquipRocket(bot) { await bot.equip(rocket, 'off-hand'); Logger.debug('rkt equip offhand'); return true; - } catch(e) { + } catch (e) { Logger.warn('equip rkt fail:', e.message); return false; } } -module.exports = { countRockets, findRocket, autoEquipRocket }; +module.exports = { countRockets, getRocketSummary, findRocket, autoEquipRocket }; diff --git a/src/core/rockets.js b/src/core/rockets.js index 2976971..0037820 100644 --- a/src/core/rockets.js +++ b/src/core/rockets.js @@ -1,25 +1,26 @@ 'use strict'; -const Logger = require('../logger'); const { angleDiff } = require('../utils'); const { countRockets, autoEquipRocket } = require('./inventory'); function createRocketEngine(ctx) { - let dolphinBoostTime = 0; + let lastRocketTime = 0; let lastSkipLog = 0; /** * Fire rocket directly. Returns true if fired. - * @param {number|null} targetYawCheck - if set, aligns yaw before firing + * @param {number|null} targetYawCheck - if set, waits (returns false) until + * yaw is within 0.26 rad of the heading, so the boost goes the right + * way. The caller should retry on the next tick. */ function fireRocketDirect(targetYawCheck = null) { const { bot } = ctx; if (!bot.entity.elytraFlying) return false; // 1.5s cooldown between rockets - if (Date.now() - dolphinBoostTime < 1500) return false; + if (Date.now() - lastRocketTime < 1500) return false; - // Align yaw if needed + // Align yaw if needed (never fire a boost in the wrong direction) if (targetYawCheck !== null) { const err = angleDiff(bot.entity.yaw, targetYawCheck); if (err > 0.26) { @@ -28,25 +29,27 @@ function createRocketEngine(ctx) { } } - // Ensure rocket in offhand + // Ensure rocket in offhand — never fire an empty offhand (the old code + // fired anyway and consumed the cooldown) const offhand = bot.inventory.slots[45]; if (offhand?.name !== 'firework_rocket') { - autoEquipRocket(bot).catch(() => {}); + autoEquipRocket(bot, { includeCustom: ctx.opts.autoRocketCustomStars }).catch(() => {}); + return false; } try { bot.activateItem(true); - dolphinBoostTime = Date.now(); - Logger.debug(`rocket Y=${bot.entity.position.y.toFixed(1)} rkt=${countRockets(bot) - 1}`); + lastRocketTime = Date.now(); + ctx.logger.debug(`rocket Y=${bot.entity.position.y.toFixed(1)} rkt=${countRockets(bot) - 1}`); return true; - } catch(e) { - Logger.warn('rocket err:', e.message); + } catch (e) { + ctx.logger.warn('rocket err:', e.message); return false; } } /** - * Smart fire — respects speed gate and cooldown. + * Smart fire — respects speed gate, high ping and cooldown. */ function smartFireRocket() { const { bot, state } = ctx; @@ -58,7 +61,7 @@ function createRocketEngine(ctx) { // Skip if at speed gate if (speed >= state.currentMode.speedGate) { if (Date.now() - lastSkipLog > 5000) { - Logger.debug(`rkt skip ${(speed * 20).toFixed(0)}m/s`); + ctx.logger.debug(`rkt skip ${(speed * 20).toFixed(0)}m/s`); lastSkipLog = Date.now(); } return false; @@ -68,13 +71,13 @@ function createRocketEngine(ctx) { if ((bot.player?.ping ?? 50) > 500) return false; // 3s cooldown - if (Date.now() - dolphinBoostTime < 3000) return false; + if (Date.now() - lastRocketTime < 3000) return false; return fireRocketDirect(ctx.yawTo(state.activeTargetX, state.activeTargetZ)); } function getBoostTime() { - return dolphinBoostTime; + return lastRocketTime; } return { fireRocketDirect, smartFireRocket, getBoostTime }; diff --git a/src/errors.js b/src/errors.js new file mode 100644 index 0000000..dfe3803 --- /dev/null +++ b/src/errors.js @@ -0,0 +1,79 @@ +'use strict'; + +/** + * Machine-readable error codes emitted by ElytraFlight. + * + * Consumers should match on `err.code` (not on message text): + * + * flight.fly(500, 500).catch(err => { + * if (err.code === 'NO_ROCKETS') restock(err); + * }); + */ +const ErrorCode = Object.freeze({ + /** fly() called while already flying (and not in a retargetable phase). */ + IN_FLIGHT: 'IN_FLIGHT', + /** Called before the bot spawned (no bot.entity). */ + NO_ENTITY: 'NO_ENTITY', + /** No elytra with usable durability in the inventory. */ + NO_ELYTRA: 'NO_ELYTRA', + /** Total elytra durability below the requirement for this distance. */ + ELYTRA_LOW: 'ELYTRA_LOW', + /** Not enough firework rockets for the estimated route. */ + NO_ROCKETS: 'NO_ROCKETS', + /** Every launch heading is blocked and relocation was disabled. */ + NO_LAUNCH_SPOT: 'NO_LAUNCH_SPOT', + /** Pathfinding relocation to a launch spot failed. */ + PF_FAILED: 'PF_FAILED', + /** The bot hit the ground during climb. */ + GROUND_HIT: 'GROUND_HIT', + /** Climb did not reach cruise altitude in time. */ + CLIMB_TIMEOUT: 'CLIMB_TIMEOUT', + /** Elytra flight could not be confirmed after launch. */ + NO_FLIGHT_CONFIRM: 'NO_FLIGHT_CONFIRM', + /** Elytra flight was lost mid-flight and could not be recovered. */ + LOST_FLIGHT: 'LOST_FLIGHT', + /** No safe landing spot could be found (wander scan timed out). */ + NO_SAFE_SPOT: 'NO_SAFE_SPOT', + /** Spiral landing did not finish in time. */ + LANDING_TIMEOUT: 'LANDING_TIMEOUT', + /** Max retries exhausted. */ + RETRIES_EXHAUSTED: 'RETRIES_EXHAUSTED', + /** flight.stop() was called. */ + STOPPED: 'STOPPED', + /** The bot respawned mid-flight. */ + RESPAWN: 'RESPAWN', + /** The bot disconnected. */ + DISCONNECTED: 'DISCONNECTED', + /** Unexpected internal error. */ + INTERNAL: 'INTERNAL', +}); + +/** + * Pre-flight precondition failures. These are deterministic — retrying + * cannot change the outcome (the bot is still not spawned, the inventory + * is still short of rockets) — so fly() fails fast with the specific code + * instead of burning the retry budget and re-reporting RETRIES_EXHAUSTED. + * Every other failure code is considered transient and gets retried. + */ +const NON_RETRYABLE = new Set(Object.freeze([ + ErrorCode.NO_ENTITY, + ErrorCode.NO_ELYTRA, + ErrorCode.ELYTRA_LOW, + ErrorCode.NO_ROCKETS, + ErrorCode.NO_LAUNCH_SPOT, + ErrorCode.PF_FAILED, +])); + +class ElytraFlightError extends Error { + /** + * @param {string} code one of {@link ErrorCode} + * @param {string} [message] + */ + constructor(code, message) { + super(message || code.toLowerCase().replace(/_/g, ' ')); + this.name = 'ElytraFlightError'; + this.code = code; + } +} + +module.exports = { ErrorCode, ElytraFlightError, NON_RETRYABLE }; diff --git a/src/flight/landing.js b/src/flight/landing.js index 6044bd3..e1aafdf 100644 --- a/src/flight/landing.js +++ b/src/flight/landing.js @@ -1,35 +1,60 @@ 'use strict'; -const Logger = require('../logger'); -const { isSafeSolidBlock } = require('../utils'); +const { ErrorCode } = require('../errors'); function createLandingEngine(ctx) { - const { bot, state } = ctx; + const { bot } = ctx; /** - * Spiral descent toward landing spot. + * Spiral descent toward a landing spot. * Pitch adjusts by altitude: high → steep, low → shallow. - * No rockets — gravity only. + * No rockets — gravity only (unless the bot touches a hazard and must + * relocate, which needs a boost). + * + * @param {object} [options] + * @param {{x:number,z:number,y:number,blockName?:string}|null} [options.spot] + * Pre-verified spot. When omitted, one is searched in the first + * three ticks (or the scan hands off to wander). + * @param {boolean} [options.skipSpotSearch] land directly at the target + * column (used when `landing: false`). */ - function startLanding() { + function startLanding(options = {}) { + const { spot = null, skipSpotSearch = false } = options; + if (ctx.rocketLoop) { clearInterval(ctx.rocketLoop); ctx.rocketLoop = null; } if (ctx.flyLoop) { clearInterval(ctx.flyLoop); ctx.flyLoop = null; } if (ctx.verifyLoop) { clearInterval(ctx.verifyLoop); ctx.verifyLoop = null; } if (ctx.climbLoop) { clearInterval(ctx.climbLoop); ctx.climbLoop = null; } + if (ctx.landLoop) { clearInterval(ctx.landLoop); ctx.landLoop = null; } const rDist = ctx.spatial.getServerRenderDistance(); - ctx.setPhase(ctx.PHASE.LANDING, `scan ${rDist.chunks}ch (${state.activeTargetX},${state.activeTargetZ})`); + ctx.setPhase(ctx.PHASE.LANDING, `scan ${rDist.chunks}ch (${ctx.state.activeTargetX},${ctx.state.activeTargetZ})`); - let tx = state.activeTargetX; - let tz = state.activeTargetZ; + let tx = ctx.state.activeTargetX; + let tz = ctx.state.activeTargetZ; let tY = null; let spotFound = false; let tick = 0; let lastLog = 0; - let spiralAngle = 0; - const landLoop = setInterval(() => { - if (state.phase !== ctx.PHASE.LANDING) { clearInterval(landLoop); return; } + if (skipSpotSearch) { + // Direct dive at the target column (no spot search / no wander) + const g = ctx.spatial.getGroundBlockAt(tx, tz, bot.entity.position.y + 10); + tY = (g?.position?.y ?? 60) + 1; + spotFound = true; + } else if (spot && spot.safe) { + tx = spot.x; + tz = spot.z; + tY = spot.y; + spotFound = true; + ctx.logger.info(`goal (${tx},${tY},${tz}) [${spot.blockName}]`); + try { bot.chat(`Landing at (${tx},${tY},${tz})`); } catch (_) { /* bot gone */ } + } + + const MAX_TICKS = 2400; // 50ms ticks = 120s + + ctx.landLoop = setInterval(() => { + if (ctx.state.phase !== ctx.PHASE.LANDING) { clearInterval(ctx.landLoop); ctx.landLoop = null; return; } tick++; const p = bot.entity.position; @@ -38,31 +63,43 @@ function createLandingEngine(ctx) { const dH = Math.hypot(p.x - tx, p.z - tz); const dV = tY !== null ? p.y - tY : 200; + // Landing timeout + if (tick > MAX_TICKS) { + clearInterval(ctx.landLoop); ctx.landLoop = null; + ctx.failFlight(ErrorCode.LANDING_TIMEOUT, `dV=${dV.toFixed(0)} dH=${dH.toFixed(0)}`); + return; + } + // Keep elytra active if (!ctx.isFlying() && !bot.entity.onGround) { - try { bot.elytraFly(); } catch(_) {} + try { bot.elytraFly(); } catch (_) { /* already flying */ } } - // FIND SPOT: first3 ticks only + // FIND SPOT: first 3 ticks only (searches are expensive — never repeat + // the full ring scan every tick) if (!spotFound) { - ctx.lookForce(ctx.yawTo(state.activeTargetX, state.activeTargetZ), -0.10); + ctx.lookForce(ctx.yawTo(ctx.state.activeTargetX, ctx.state.activeTargetZ), -0.10); if (tick <= 3) { - const spot = ctx.wander.findSafeLandingSpotAround(state.activeTargetX, state.activeTargetZ); - if (spot.safe) { - tx = spot.x; - tz = spot.z; - tY = spot.y; + const found = ctx.wander.findSafeLandingSpotAround(ctx.state.activeTargetX, ctx.state.activeTargetZ); + if (found.safe) { + tx = found.x; + tz = found.z; + tY = found.y; spotFound = true; - Logger.info(`goal (${tx},${tY},${tz}) [${spot.blockName}]`); - try { bot.chat(`Landing at (${tx},${tY},${tz})`); } catch(_) {} + ctx.logger.info(`goal (${tx},${tY},${tz}) [${found.blockName}]`); + try { bot.chat(`Landing at (${tx},${tY},${tz})`); } catch (_) { /* bot gone */ } } } if (!spotFound && tick > 3) { - Logger.info(`no spot at (${state.activeTargetX},${state.activeTargetZ}) -- wander`); - clearInterval(landLoop); - ctx.startWanderScan(); + clearInterval(ctx.landLoop); ctx.landLoop = null; + if (ctx.opts.wander) { + ctx.logger.info(`no spot at (${ctx.state.activeTargetX},${ctx.state.activeTargetZ}) -- wander`); + ctx.startWanderScan(); + } else { + ctx.failFlight(ErrorCode.NO_SAFE_SPOT, 'no landing spot (wander off)'); + } return; } @@ -71,67 +108,56 @@ function createLandingEngine(ctx) { // LANDED if (bot.entity.onGround) { - clearInterval(landLoop); + clearInterval(ctx.landLoop); ctx.landLoop = null; // Check if landed on safe ground - const landedBlock = ctx.spatial.getGroundBlockAt(Math.round(p.x), Math.round(p.z)); - if (!landedBlock || !isSafeSolidBlock(landedBlock)) { - // Landed on water/lava/hazard — look up and search again - Logger.warn(`landed on ${landedBlock?.name || 'hazard'} -- searching`); - ctx.lookForce(ctx.yawTo(tx, tz), 0.50); - spotFound = false; - tick = 0; + const landedBlock = ctx.spatial.getGroundBlockAt(Math.round(p.x), Math.round(p.z), p.y + 10); + if (!landedBlock || !ctx.isSafeSolid(landedBlock)) { + // On a hazard (cactus, berry bush, powder snow, ...). The old code + // just reset the search timer and looped forever standing on it. + ctx.logger.warn(`landed on ${landedBlock?.name || 'hazard'} -- relocating`); + if (ctx.opts.autoRocket && ctx.countRockets() > 0) { + ctx.startWanderScan(); + } else { + // Can't get airborne — retry the flight (may find a different spot) + ctx.failFlight(ErrorCode.NO_SAFE_SPOT, `unsafe ground ${landedBlock?.name || 'hazard'}`); + } return; } - try { bot.setControlState('sneak', false); } catch(_) {} - state.retries = 0; - state.spatialClear = false; + try { bot.setControlState('sneak', false); } catch (_) { /* bot gone */ } const errH = Math.hypot(p.x - tx, p.z - tz); - Logger.info(`landed (${Math.round(p.x)},${Math.round(p.y)},${Math.round(p.z)}) [${landedBlock.name}] err=${errH.toFixed(1)} rkt=${ctx.countRockets(bot)}`); - ctx.setPhase(ctx.PHASE.IDLE, `land (${Math.round(p.x)},${Math.round(p.y)},${Math.round(p.z)}) ${landedBlock.name} err=${errH.toFixed(1)}`); + ctx.logger.info(`landed (${Math.round(p.x)},${Math.round(p.y)},${Math.round(p.z)}) [${landedBlock.name}] err=${errH.toFixed(1)} rkt=${ctx.countRockets()}`); + ctx.completeFlight(); return; } - // DEATH PROTECTION + // DEATH PROTECTION — descending fast and close to the spot: level out. + // (A shallow 0.30 instead of 0.40: the old steep look-up traded hard + // dives for permanent hover-orbits.) if (v.y < -0.15 && dV < 8) { - ctx.lookForce(ctx.yawTo(tx, tz), 0.40); + ctx.lookForce(ctx.yawTo(tx, tz), 0.30); return; } - // SPIRAL DESCENT - if (dV > 5 || spd > 0.5) { - const r = dV > 30 ? 3.0 : dV > 15 ? 2.0 : 1.2; - spiralAngle += dV > 20 ? 0.08 : 0.12; - - const sx = tx + Math.cos(spiralAngle) * r; - const sz = tz + Math.sin(spiralAngle) * r; - const pitch = dV > 50 ? -0.25 : dV > 30 ? -0.15 : dV > 15 ? -0.08 : dV > 5 ? -0.03 : 0.0; - - ctx.lookForce(ctx.yawTo(sx, sz), pitch); - - if (tick - lastLog > 20) { - Logger.debug(`spiral spd=${(spd * 20).toFixed(0)} dH=${dH.toFixed(0)} dV=${dV.toFixed(0)}`); - lastLog = tick; - } + // FINAL APPROACH — over the spot and almost on the ground: settle + if (dV < 1.5 && dH < 2) { + ctx.lookForce(ctx.yawTo(tx, tz), 0.10); return; } - // FINAL APPROACH - if (dV < 1.5 && dH < 2) { - ctx.lookForce(ctx.yawTo(tx, tz), 0.15); - try { bot.setControlState('sneak', true); } catch(_) {} - } else { - const ideal = dH > 0.5 ? Math.atan2(-dV, dH) : -0.20; - const cur = bot.entity.pitch; - const err = ideal - cur; - const pitch = Math.abs(err) > 0.1 ? cur + err * 0.15 : ideal; - ctx.lookForce(ctx.yawTo(tx, tz), pitch); - } + // GLIDE TO GOAL — aim straight at the spot. The aim point is the goal + // itself (the old code orbited a point around the goal, which made a + // fast bot circle the target and skim the ground far away from it). + // Horizontal closure is always >= speed*cos(0.5), so this converges + // from any distance the landing trigger can produce. + const ideal = dH > 0.5 ? Math.atan2(-Math.min(dV, 40), dH) : -0.30; + const pitch = Math.max(-0.5, Math.min(-0.02, ideal)); + ctx.lookForce(ctx.yawTo(tx, tz), pitch); if (tick - lastLog > 15) { - Logger.debug(`final spd=${(spd * 20).toFixed(0)} dH=${dH.toFixed(1)} dV=${dV.toFixed(1)}`); + ctx.logger.debug(`glide spd=${(spd * 20).toFixed(0)} dH=${dH.toFixed(1)} dV=${dV.toFixed(1)}`); lastLog = tick; } }, 50); diff --git a/src/flight/phases.js b/src/flight/phases.js index eebe917..126cd75 100644 --- a/src/flight/phases.js +++ b/src/flight/phases.js @@ -1,14 +1,22 @@ 'use strict'; -const Logger = require('../logger'); -const { isSafeSolidBlock } = require('../utils'); +const { ErrorCode } = require('../errors'); function createFlightPhases(ctx) { const { bot, state } = ctx; + const canRocket = () => ctx.opts.autoRocket && ctx.countRockets(bot) > 0; + async function startFlight() { if (state.phase !== ctx.PHASE.IDLE && state.phase !== ctx.PHASE.FAILED) { - try { bot.chat('In flight -- s to stop'); } catch(_) {} + // Retargeting mid-cruise is safe (the cruise loop reads the target + // live) — fly() handles that case before calling here. + try { bot.chat('In flight -- use stop to abort'); } catch (_) { /* bot gone */ } + return; + } + + if (!bot.entity) { + ctx.failFlight(ErrorCode.NO_ENTITY, 'bot not spawned'); return; } @@ -21,65 +29,73 @@ function createFlightPhases(ctx) { const elytraOk = await ctx.auditAndEquipElytra(); if (!elytraOk) { - ctx.setPhase(ctx.PHASE.FAILED, 'no elytra dur>15'); + ctx.failFlight(ErrorCode.NO_ELYTRA, 'no elytra dur>15'); return; } - // Check elytra durability vs distance - const d2d = ctx.dist2D(state.activeTargetX, state.activeTargetZ); - const elytraInfo = ctx.getElytraSummary(bot); - const reqDur = ctx.calculateRequiredElytraDurability(d2d, state.currentMode.speedMps, elytraInfo.bestUnbreaking); + if (ctx.opts.safety && ctx.opts.elytraAudit) { + const d2d = ctx.dist2D(state.activeTargetX, state.activeTargetZ); + const elytraInfo = ctx.getElytraSummary(); + const reqDur = ctx.calculateRequiredElytraDurability(d2d, state.currentMode.speedMps, elytraInfo.bestUnbreaking); - Logger.debug(`e: ${elytraInfo.totalDurabilityAcrossAll}/${reqDur} ${elytraInfo.count}x U${elytraInfo.bestUnbreaking}`); + ctx.logger.debug(`e: ${elytraInfo.totalDurabilityAcrossAll}/${reqDur} ${elytraInfo.count}x U${elytraInfo.bestUnbreaking}`); - if (elytraInfo.totalDurabilityAcrossAll < reqDur) { - ctx.setPhase(ctx.PHASE.FAILED, `need ${reqDur} dur, have ${elytraInfo.totalDurabilityAcrossAll}`); - return; + if (elytraInfo.totalDurabilityAcrossAll < reqDur) { + ctx.failFlight(ErrorCode.ELYTRA_LOW, `need ${reqDur} dur, have ${elytraInfo.totalDurabilityAcrossAll}`); + return; + } } - // Check rockets - await ctx.autoEquipRocket(bot); - const rockets = ctx.countRockets(bot); - const startY = bot.entity.position.y; - const reqRkt = ctx.calculateRequiredRockets(d2d, ctx.CRUISE_ALT - startY); + if (ctx.opts.safety) { + if (ctx.opts.autoRocket) await ctx.autoEquipRocket(); + const rockets = ctx.countRockets(); + const startY = bot.entity.position.y; + const reqRkt = ctx.calculateRequiredRockets(ctx.dist2D(state.activeTargetX, state.activeTargetZ), ctx.CRUISE_ALT - startY); - Logger.debug(`rkt: ${rockets}/${reqRkt}`); + ctx.logger.debug(`rkt: ${rockets}/${reqRkt}`); - if (rockets < reqRkt) { - ctx.setPhase(ctx.PHASE.FAILED, `need ${reqRkt} rkt, have ${rockets}`); - return; + if (ctx.opts.autoRocket && rockets < reqRkt) { + ctx.failFlight(ErrorCode.NO_ROCKETS, `need ${reqRkt} rkt, have ${rockets}`); + return; + } } - Logger.debug('audit PASS'); + ctx.logger.debug('audit PASS'); // Find launch heading if (!state.spatialClear) { - let heading = ctx.spatial.findBestLaunchHeading(); - Logger.debug(`heading: ${heading.headingName}`); + let heading = ctx.opts.chunkScan + ? ctx.spatial.findBestLaunchHeading() + : { yaw: ctx.yawTo(state.activeTargetX, state.activeTargetZ), headingName: 'direct', clear: true }; + ctx.logger.debug(`heading: ${heading.headingName}`); if (!heading.clear) { - Logger.warn('all blocked -- pathfinding'); - try { bot.chat('All headings blocked -- relocating'); } catch(_) {} + if (!ctx.opts.pathfinding) { + ctx.failFlight(ErrorCode.NO_LAUNCH_SPOT, 'all headings blocked (pathfinding off)'); + return; + } + + ctx.logger.warn('all blocked -- pathfinding'); + try { bot.chat('All headings blocked -- relocating'); } catch (_) { /* bot gone */ } const spot = ctx.spatial.findElevatedOpenSpot(); if (!spot) { - ctx.setPhase(ctx.PHASE.FAILED, 'no launch spot'); - ctx.scheduleRetry(); + ctx.failFlight(ErrorCode.NO_LAUNCH_SPOT, 'no launch spot'); return; } ctx.setPhase(ctx.PHASE.RELOCATING, `-> (${spot.x},${spot.y},${spot.z})`); const arrived = await ctx.spatial.pathfindToSpot(spot.x, spot.y, spot.z); if (!arrived) { - ctx.setPhase(ctx.PHASE.FAILED, 'pf failed'); - ctx.scheduleRetry(); + ctx.failFlight(ErrorCode.PF_FAILED, 'pf failed'); return; } - heading = ctx.spatial.findBestLaunchHeading(); + heading = ctx.opts.chunkScan + ? ctx.spatial.findBestLaunchHeading() + : { yaw: ctx.yawTo(state.activeTargetX, state.activeTargetZ), headingName: 'direct', clear: true }; if (!heading.clear) { - ctx.setPhase(ctx.PHASE.FAILED, 'still blocked'); - ctx.scheduleRetry(); + ctx.failFlight(ErrorCode.NO_LAUNCH_SPOT, 'still blocked'); return; } } @@ -95,11 +111,12 @@ function createFlightPhases(ctx) { if (state.phase === ctx.PHASE.FAILED) return; ctx.setPhase(ctx.PHASE.TAKEOFF, 'jump+elytra'); - ['sprint','forward','back','left','right','sneak'].forEach(k => { - try { bot.setControlState(k, false); } catch(_) {} + ['sprint', 'forward', 'back', 'left', 'right', 'sneak'].forEach(k => { + try { bot.setControlState(k, false); } catch (_) { /* bot gone */ } }); - await ctx.autoEquipRocket(bot); + if (ctx.opts.autoRocket) await ctx.autoEquipRocket(); + ctx.lookForce(state.activeLaunchYaw, 0.5); bot.setControlState('jump', true); @@ -116,38 +133,43 @@ function createFlightPhases(ctx) { bot.setControlState('jump', false); if (!airborne) { - ctx.setPhase(ctx.PHASE.FAILED, 'jump fail'); - ctx.scheduleRetry(); + ctx.failFlight(ErrorCode.NO_FLIGHT_CONFIRM, 'jump fail'); return; } - Logger.debug(`airborne Y=${bot.entity.position.y.toFixed(1)}`); + ctx.logger.debug(`airborne Y=${bot.entity.position.y.toFixed(1)}`); try { await bot.elytraFly(); - } catch(e) { - Logger.error('elytraFly:', e.message); - ctx.setPhase(ctx.PHASE.FAILED, 'elytraFly fail'); - ctx.scheduleRetry(); + } catch (e) { + ctx.logger.error('elytraFly:', e.message); + ctx.failFlight(ErrorCode.NO_FLIGHT_CONFIRM, 'elytraFly fail'); return; } - ctx.fireRocketDirect(); + // Poll until a rocket actually leaves. fireRocketDirect self-gates on + // yaw alignment and offhand contents, so the first boost goes toward + // the launch heading (previously it fired immediately and could launch + // the bot the wrong way). Break on `fired`, NOT on isFlying: at jump + // apex an elytra is already "flying" (elytraFlying && !onGround) with + // zero boost, so breaking on isFlying skipped the first fire whenever + // the yaw gate blocked it (180° heading change at takeoff). + let fired = false; + let grounded = 0; + for (let i = 0; i < 20 && !fired; i++) { + fired = await ctx.fireRocketDirect(state.activeLaunchYaw); + if (fired) break; + grounded = bot.entity.onGround ? grounded + 1 : 0; + if (grounded > 12) break; // ~1.2 s grounded without a boost → retry loop takes over + await ctx.sleep(100); + } - await ctx.sleep(200); if (!ctx.isFlying()) { - Logger.warn('fly=false post-launch -- retry'); - try { await bot.elytraFly(); } catch(_) {} - ctx.fireRocketDirect(); - await ctx.sleep(250); - if (!ctx.isFlying()) { - ctx.setPhase(ctx.PHASE.FAILED, 'no flight confirm'); - ctx.scheduleRetry(); - return; - } + ctx.failFlight(ErrorCode.NO_FLIGHT_CONFIRM, 'no flight confirm'); + return; } - Logger.debug('flight OK, climb'); + ctx.logger.debug('flight OK, climb'); startClimb(); } @@ -155,12 +177,11 @@ function createFlightPhases(ctx) { ctx.setPhase(ctx.PHASE.CLIMBING, `-> Y=${ctx.CRUISE_ALT}`); let climbTicks = 0; - const launchPosY = bot.entity.position.y; ctx.lookForce(state.activeLaunchYaw, 0.45); if (ctx.rocketLoop) { clearInterval(ctx.rocketLoop); ctx.rocketLoop = null; } - if (ctx.climbLoop) clearInterval(ctx.climbLoop); + if (ctx.climbLoop) { clearInterval(ctx.climbLoop); ctx.climbLoop = null; } ctx.climbLoop = setInterval(() => { if (state.phase !== ctx.PHASE.CLIMBING) { clearInterval(ctx.climbLoop); ctx.climbLoop = null; return; } @@ -171,45 +192,73 @@ function createFlightPhases(ctx) { ctx.checkMidFlightElytraSwap(); - // Track safe ground - const groundUnder = ctx.spatial.getGroundBlockAt(Math.round(pos.x), Math.round(pos.z)); - if (groundUnder && isSafeSolidBlock(groundUnder)) { - state.lastKnownSafeGround = { x: Math.round(pos.x), y: Math.round(pos.y), z: Math.round(pos.z), blockName: groundUnder.name }; + // Out of fuel mid-climb: stop climbing toward altitude we can no + // longer buy — hand off to the cruise loops in DEADSTICK. They + // already run in DEADSTICK (no rockets, level glide) and steer to + // the goal. Without this, a 1-rocket launch burns its only boost + // at takeoff, stalls on the ground during climb, and dies with + // GROUND_HIT before ever reaching the cruise altitude where + // rocketLoop would have noticed the empty inventory. + if (ctx.opts.autoRocket && ctx.countRockets() === 0 && climbTicks > 3) { + clearInterval(ctx.climbLoop); ctx.climbLoop = null; + ctx.setPhase(ctx.PHASE.DEAD_STICK, 'out of rkt'); + startCruise({ keepPhase: true }); + return; } - // Yaw toward target after Y=95 - const currentYaw = pos.y >= 95 ? targetYaw : state.activeLaunchYaw; + // Track safe ground + const groundUnder = ctx.spatial.getGroundBlockAt(Math.round(pos.x), Math.round(pos.z), pos.y + 10); + if (groundUnder && ctx.isSafeSolid(groundUnder)) { + state.lastKnownSafeGround = { x: Math.round(pos.x), y: groundUnder.position?.y ?? Math.round(pos.y), z: Math.round(pos.z), blockName: groundUnder.name }; + } - // Pitch: steeper if terrain ahead + // Terrain scan with the current heading let pitch = climbTicks <= 4 ? 0.45 : 0.65; - const scan = ctx.spatial.scanFullRenderDistance(currentYaw, pitch); - if (scan.hit) { - if (Date.now() - state.lastTerrainWarn > 3000) { - Logger.warn(`terrain ${scan.block} d=${scan.dist}m -- climb steep`); - state.lastTerrainWarn = Date.now(); + let terrainAhead = false; + if (ctx.opts.chunkScan) { + const currentYaw = pos.y >= 95 ? targetYaw : state.activeLaunchYaw; + const scan = ctx.spatial.scanFullRenderDistance(currentYaw, pitch); + terrainAhead = scan.hit; + if (scan.hit) { + if (Date.now() - state.lastTerrainWarn > 3000) { + ctx.logger.warn(`terrain ${scan.block} d=${scan.dist}m -- climb steep`); + state.lastTerrainWarn = Date.now(); + } + pitch = 0.75; } - pitch = 0.75; } + // Turn toward the target once high enough — or immediately when the + // way is clear, instead of holding a detour heading until Y=95. + const currentYaw = (pos.y >= 95 || !terrainAhead) ? targetYaw : state.activeLaunchYaw; + // Rockets: only when slow and 2s+ since last const speed = Math.hypot(bot.entity.velocity.x, bot.entity.velocity.y, bot.entity.velocity.z); - if (speed < 0.65 && Date.now() - ctx.getBoostTime() > 2000 && ctx.countRockets(bot) > 0) { + if (ctx.opts.autoRocket && speed < 0.65 && Date.now() - ctx.getBoostTime() > 2000 && canRocket()) { ctx.fireRocketDirect(currentYaw); } ctx.lookForce(currentYaw, pitch); - // Ground hit during climb - if (bot.entity.onGround && pos.y < ctx.CRUISE_ALT - 10 && climbTicks > 5 && pos.y < launchPosY - 2) { + // Any sustained ground contact during climb = failure (covers the old + // "fell below launch point" case AND the ledge-stuck case where the + // bot sat at Y just under cruise altitude forever). + if (bot.entity.onGround && climbTicks > 10 && !ctx.isFlying()) { clearInterval(ctx.climbLoop); ctx.climbLoop = null; - ctx.setPhase(ctx.PHASE.FAILED, 'ground hit climb'); - ctx.scheduleRetry(); + ctx.failFlight(ErrorCode.GROUND_HIT, `ground hit climb Y=${Math.round(pos.y)}`); + return; + } + + // Hard climb timeout (90s) as a safety net + if (climbTicks > 450) { + clearInterval(ctx.climbLoop); ctx.climbLoop = null; + ctx.failFlight(ErrorCode.CLIMB_TIMEOUT, `stuck at Y=${Math.round(pos.y)}`); return; } // Lost flight if (!ctx.isFlying() && !bot.entity.onGround) { - Logger.warn('fly=false mid-climb'); + ctx.logger.warn('fly=false mid-climb'); bot.elytraFly().catch(() => {}); return; } @@ -222,14 +271,16 @@ function createFlightPhases(ctx) { }, 200); } - function startCruise() { - ctx.setPhase(ctx.PHASE.CRUISING, `-> (${state.activeTargetX},?,${state.activeTargetZ}) [${state.currentMode.name}]`); + function startCruise(opts = {}) { + if (!opts.keepPhase) { + ctx.setPhase(ctx.PHASE.CRUISING, `-> (${state.activeTargetX},?,${state.activeTargetZ}) [${state.currentMode.name}]`); + } // Rocket check loop — 3s interval if (ctx.rocketLoop) clearInterval(ctx.rocketLoop); ctx.rocketLoop = setInterval(() => { if (state.phase !== ctx.PHASE.CRUISING && state.phase !== ctx.PHASE.DEAD_STICK) { clearInterval(ctx.rocketLoop); ctx.rocketLoop = null; return; } - if (ctx.countRockets(bot) === 0 && state.phase !== ctx.PHASE.DEAD_STICK) { + if (ctx.opts.autoRocket && ctx.countRockets() === 0 && state.phase !== ctx.PHASE.DEAD_STICK) { ctx.setPhase(ctx.PHASE.DEAD_STICK, 'out of rkt'); } }, 3000); @@ -243,65 +294,91 @@ function createFlightPhases(ctx) { ctx.checkMidFlightElytraSwap(); // Track safe ground - const groundUnder = ctx.spatial.getGroundBlockAt(Math.round(pos.x), Math.round(pos.z)); - if (groundUnder && isSafeSolidBlock(groundUnder)) { - state.lastKnownSafeGround = { x: Math.round(pos.x), y: Math.round(pos.y), z: Math.round(pos.z), blockName: groundUnder.name }; + const groundUnder = ctx.spatial.getGroundBlockAt(Math.round(pos.x), Math.round(pos.z), pos.y + 10); + if (groundUnder && ctx.isSafeSolid(groundUnder)) { + state.lastKnownSafeGround = { x: Math.round(pos.x), y: groundUnder.position?.y ?? Math.round(pos.y), z: Math.round(pos.z), blockName: groundUnder.name }; } const d = ctx.dist2D(state.activeTargetX, state.activeTargetZ); - const groundY = ctx.spatial.getGroundBlockAt(state.activeTargetX, state.activeTargetZ)?.position?.y ?? 60; - const dV = pos.y - groundY; + + // Ground height under the target (scan only near the bot's altitude — + // a full 320-deep scan twice per 50ms tick was pure waste). + const groundY = ctx.spatial.getGroundBlockAt(state.activeTargetX, state.activeTargetZ, pos.y + 30)?.position?.y ?? 60; + const dV = Math.max(0, pos.y - groundY); + + // ── Approach geometry ── + // Descent starts far enough out that the elytra's glide ratio can bring + // the bot to dV<60 before it reaches the target. (The old "start + // descending within 100m" rule made the trigger `d<40 && dV<50` + // unreachable: the bot flew past the target still 90+ blocks up.) + const descentStart = Math.max(100, (dV - 50) * 2.1 + 60); + const inDescent = d < descentStart; + const lowEnough = dV < 60; // Landing trigger - if (d < 40 && dV < 50) { + if (lowEnough && inDescent) { clearInterval(ctx.flyLoop); ctx.flyLoop = null; clearInterval(ctx.rocketLoop); ctx.rocketLoop = null; - clearInterval(ctx.verifyLoop); ctx.verifyLoop = null; + if (ctx.verifyLoop) { clearInterval(ctx.verifyLoop); ctx.verifyLoop = null; } + + if (!ctx.opts.landing) { + // No spot search — dive straight at the target column + ctx.startLanding({ skipSpotSearch: true }); + return; + } const spot = ctx.wander.findSafeLandingSpotAround(state.activeTargetX, state.activeTargetZ); if (spot.safe) { - ctx.startLanding(); - } else { - Logger.info(`no spot at (${state.activeTargetX},${state.activeTargetZ}) -- wander`); + ctx.startLanding({ spot }); + } else if (ctx.opts.wander) { + ctx.logger.info(`no spot at (${state.activeTargetX},${state.activeTargetZ}) -- wander`); ctx.startWanderScan(); + } else { + ctx.failFlight(ErrorCode.NO_SAFE_SPOT, 'no landing spot (wander off)'); } return; } - // Cruise pitch + // Cruise / descent pitch const yaw = ctx.yawTo(state.activeTargetX, state.activeTargetZ); - const timeSinceBoost = Date.now() - ctx.getBoostTime(); - let pitch = state.phase === ctx.PHASE.DEAD_STICK ? 0.02 : state.currentMode.pitch; - - if (state.phase === ctx.PHASE.CRUISING) { - pitch = timeSinceBoost < 1000 ? 0.15 : -0.04; - - if (d < 100 && dV > 50) pitch = -0.20; - else if (d < 60 && dV > 30) pitch = -0.12; - - // Rockets: below cruise alt AND far from target - if (pos.y < ctx.CRUISE_ALT && d > 100) { - ctx.smartFireRocket(); + let pitch; + + if (inDescent) { + // Steady ~26° dive; no rockets — gravity does the work and the + // dive builds speed on its own. + pitch = -0.45; + } else { + const timeSinceBoost = Date.now() - ctx.getBoostTime(); + pitch = state.phase === ctx.PHASE.DEAD_STICK ? 0.02 : state.currentMode.pitch; + if (state.phase === ctx.PHASE.CRUISING) { + pitch = timeSinceBoost < 1000 ? 0.15 : -0.04; + + // Rockets: below cruise alt AND far from target + if (ctx.opts.autoRocket && pos.y < ctx.CRUISE_ALT && d > 100) { + ctx.smartFireRocket(); + } } } // Terrain avoidance - const scan = ctx.spatial.scanFullRenderDistance(yaw, pitch); - if (scan.hit && scan.dist < 60) { - if (Date.now() - state.lastTerrainWarn > 3000) { - Logger.warn(`terrain ${scan.block} d=${scan.dist}m -- over`); - state.lastTerrainWarn = Date.now(); + if (ctx.opts.chunkScan) { + const scan = ctx.spatial.scanFullRenderDistance(yaw, pitch); + if (scan.hit && scan.dist < 60) { + if (Date.now() - state.lastTerrainWarn > 3000) { + ctx.logger.warn(`terrain ${scan.block} d=${scan.dist}m -- over`); + state.lastTerrainWarn = Date.now(); + } + pitch = 0.55; + if (ctx.opts.autoRocket && canRocket()) ctx.fireRocketDirect(yaw); } - pitch = 0.55; - if (ctx.countRockets(bot) > 0) ctx.fireRocketDirect(yaw); } // Stall recovery const speed = Math.hypot(bot.entity.velocity.x, bot.entity.velocity.y, bot.entity.velocity.z); if (speed < 0.05 && pos.y > 60) { - Logger.warn('stall -- 180 boost'); + ctx.logger.warn('stall -- 180 boost'); ctx.lookForce(yaw + Math.PI, 0.70); - ctx.fireRocketDirect(); + if (ctx.opts.autoRocket) ctx.fireRocketDirect(); return; } @@ -316,27 +393,26 @@ function createFlightPhases(ctx) { if (state.phase !== ctx.PHASE.CRUISING && state.phase !== ctx.PHASE.DEAD_STICK) { clearInterval(ctx.verifyLoop); ctx.verifyLoop = null; return; } const curDist = ctx.dist2D(state.activeTargetX, state.activeTargetZ); + const prevDist = lastDist; + lastDist = curDist; const targetYaw = ctx.yawTo(state.activeTargetX, state.activeTargetZ); - if (curDist > lastDist + 5) { - Logger.warn(`drift ${lastDist.toFixed(0)}->${curDist.toFixed(0)}m -- realign`); + if (curDist > prevDist + 5) { + ctx.logger.warn(`drift -- realign`); ctx.lookForce(targetYaw, state.currentMode.pitch); } if (!ctx.isFlying() && !bot.entity.onGround) { - Logger.warn('fly=false cruise -- recover'); + ctx.logger.warn('fly=false cruise -- recover'); ctx.auditAndEquipElytra().then(() => { if (state.phase !== ctx.PHASE.CRUISING && state.phase !== ctx.PHASE.DEAD_STICK) return; bot.elytraFly().catch(e => { - ctx.setPhase(ctx.PHASE.FAILED, 'lost flight: ' + e.message); - ctx.scheduleRetry(); + ctx.failFlight(ErrorCode.LOST_FLIGHT, 'lost flight: ' + e.message); }); - if (ctx.countRockets(bot) > 0) ctx.fireRocketDirect(targetYaw); + if (ctx.opts.autoRocket && canRocket()) ctx.fireRocketDirect(targetYaw); }); return; } - - lastDist = curDist; }, 2000); } diff --git a/src/flight/spatial.js b/src/flight/spatial.js index 046a4bc..6aa04a8 100644 --- a/src/flight/spatial.js +++ b/src/flight/spatial.js @@ -1,15 +1,22 @@ 'use strict'; const { Vec3 } = require('vec3'); -const { Movements, goals: { GoalBlock } } = require('mineflayer-pathfinder'); -const Logger = require('../logger'); -const { isAir, isHazardousBlock, isSafeSolidBlock } = require('../utils'); +const { Movements, goals: { GoalNear } } = require('mineflayer-pathfinder'); +const { isAir } = require('../utils'); function createSpatialEngine(ctx) { const { bot } = ctx; - function getServerRenderDistance() { - if (!bot.entity || !bot.world) return { chunks: 6, blocks: 96, scanAlt: 120 }; + // ── Render distance (cached — iterating every loaded column on each 50ms + // raycast tick was a steady GC/CPU drain on large worlds) ── + let rdistCache = null; + let rdistCacheTime = 0; + const RDIST_CACHE_MS = 5000; + + function getServerRenderDistance(force = false) { + if (!force && rdistCache && Date.now() - rdistCacheTime < RDIST_CACHE_MS) return rdistCache; + + if (!bot.entity || !bot.world) return { chunks: 6, blocks: 96 }; const bX = Math.floor(bot.entity.position.x) >> 4; const bZ = Math.floor(bot.entity.position.z) >> 4; @@ -24,20 +31,23 @@ function createSpatialEngine(ctx) { const dist = Math.max(dx, dz); if (dist > maxDistChunks) maxDistChunks = dist; } - } catch(_) {} + } catch (_) { /* world not ready */ } - const chunks = Math.min(Math.max(maxDistChunks, 4), 16); - const blocks = chunks * 16; - const scanAlt = Math.min(Math.max(Math.round(60 + blocks * 0.6), 90), 160); - - return { chunks, blocks, scanAlt }; + rdistCache = { chunks: Math.min(Math.max(maxDistChunks, 4), 16) }; + rdistCache.blocks = rdistCache.chunks * 16; + rdistCacheTime = Date.now(); + return rdistCache; } + /** + * Raycast from the eye along (yaw, pitch). + * 1-block steps within 40 m (thin structures can no longer be tunneled + * through), 2-block steps beyond. + */ function scanFullRenderDistance(yaw, currentPitch) { const pos = bot.entity.position; const eyePos = pos.offset(0, 1.6, 0); - const rDist = getServerRenderDistance(); - const maxRaycastBlocks = rDist.blocks; + const maxRaycastBlocks = getServerRenderDistance().blocks; const cosPitch = Math.cos(currentPitch); const sinPitch = Math.sin(currentPitch); @@ -45,10 +55,10 @@ function createSpatialEngine(ctx) { const dirY = sinPitch; const dirZ = Math.cos(yaw) * cosPitch; - for (let d = 1; d <= maxRaycastBlocks; d += 2) { + for (let d = 1; d <= maxRaycastBlocks; d += d <= 40 ? 1 : 2) { const checkPos = eyePos.offset(dirX * d, dirY * d, dirZ * d); const b = bot.blockAt(checkPos); - if (b && !isAir(b) && !isHazardousBlock(b)) { + if (b && !isAir(b) && !ctx.isHazardous(b)) { return { hit: true, dist: d, block: b.name, pos: checkPos }; } } @@ -56,6 +66,10 @@ function createSpatialEngine(ctx) { return { hit: false, dist: maxRaycastBlocks, block: null, pos: null }; } + /** + * Check the launch corridor: 5 blocks overhead and 16 blocks ahead at foot + * and head level. Returns { clear, reason }. + */ function checkRunwayDirection(testYaw) { const pos = bot.entity.position; @@ -67,20 +81,36 @@ function createSpatialEngine(ctx) { const dirX = -Math.sin(testYaw); const dirZ = Math.cos(testYaw); - for (let d = 1; d <= 4; d++) { + for (let d = 1; d <= 16; d++) { for (let dy = 1; dy <= 2; dy++) { - const bPos = pos.offset(Math.round(dirX * d), dy, Math.round(dirZ * d)); + const bPos = pos.offset(dirX * d, dy, dirZ * d); const b = bot.blockAt(bPos); if (!isAir(b)) return { clear: false, reason: `ahead ${d}m Y+${dy} ${b?.name}` }; } } const blockUnder = bot.blockAt(pos.offset(0, -0.5, 0)); - if (isHazardousBlock(blockUnder)) return { clear: false, reason: `liquid ${blockUnder?.name}` }; + if (ctx.isHazardous(blockUnder)) return { clear: false, reason: `liquid ${blockUnder?.name}` }; return { clear: true, reason: 'clear' }; } + const COMPASS = [ + { name: 'S', yaw: 0 }, + { name: 'E', yaw: -Math.PI / 2 }, + { name: 'N', yaw: Math.PI }, + { name: 'W', yaw: Math.PI / 2 }, + { name: 'SE', yaw: -Math.PI / 4 }, + { name: 'NE', yaw: -3 * Math.PI / 4 }, + { name: 'SW', yaw: Math.PI / 4 }, + { name: 'NW', yaw: 3 * Math.PI / 4 }, + ]; + + /** + * Pick the best clear launch heading, preferring directions closest to the + * target (the old code always tried W, N, E, S first and could launch the + * bot 90-180 degrees away from where it was going). + */ function findBestLaunchHeading() { const targetYaw = ctx.yawTo(ctx.state.activeTargetX, ctx.state.activeTargetZ); const targetCheck = checkRunwayDirection(targetYaw); @@ -88,21 +118,13 @@ function createSpatialEngine(ctx) { return { yaw: targetYaw, headingName: 'direct', clear: true }; } - const COMPASS = [ - { name: 'W', yaw: Math.PI / 2 }, - { name: 'N', yaw: Math.PI }, - { name: 'E', yaw: -Math.PI / 2 }, - { name: 'S', yaw: 0 }, - { name: 'NW', yaw: 3 * Math.PI / 4 }, - { name: 'SW', yaw: Math.PI / 4 }, - { name: 'NE', yaw: -3 * Math.PI / 4 }, - { name: 'SE', yaw: -Math.PI / 4 }, - ]; - - for (const dir of COMPASS) { - const check = checkRunwayDirection(dir.yaw); - if (check.clear) { - try { bot.chat(`Target blocked -- heading ${dir.name}`); } catch(_) {} + const ordered = [...COMPASS] + .map(dir => ({ ...dir, diff: Math.abs(((dir.yaw - targetYaw) % (2 * Math.PI) + 3 * Math.PI) % (2 * Math.PI) - Math.PI) })) + .sort((a, b) => a.diff - b.diff); + + for (const dir of ordered) { + if (checkRunwayDirection(dir.yaw).clear) { + ctx.logger.warn(`target blocked -- heading ${dir.name}`); return { yaw: dir.yaw, headingName: dir.name, clear: true }; } } @@ -123,7 +145,9 @@ function createSpatialEngine(ctx) { let groundBlock = null; let groundY = null; - for (let dy = 1; dy >= -4; dy--) { + // Look a few blocks up as well — the old code only checked down and + // could "arrive" at the base of a wall it could never launch from. + for (let dy = 4; dy >= -4; dy--) { const b = bot.blockAt(new Vec3(cx, baseY + dy, cz)); if (b && !isAir(b)) { groundBlock = b; @@ -132,7 +156,7 @@ function createSpatialEngine(ctx) { } } - if (!groundBlock || !isSafeSolidBlock(groundBlock)) continue; + if (!groundBlock || !ctx.isSafeSolid(groundBlock)) continue; let openAir = 0; for (let dy = 0; dy < 15; dy++) { @@ -153,18 +177,33 @@ function createSpatialEngine(ctx) { return best; } + /** + * Pathfind to a launch spot. Refuses gracefully when the pathfinder plugin + * is unavailable. Digging is OFF by default (old code tunneled through + * players' builds); opt in with `relocationCanDig: true`. + */ async function pathfindToSpot(tx, ty, tz) { - Logger.debug(`pf -> (${tx},${ty},${tz})`); + ctx.logger.debug(`pf -> (${tx},${ty},${tz})`); + + if (!bot.pathfinder) { + ctx.logger.warn('pathfinder plugin unavailable -- cannot relocate'); + return false; + } const defaultMove = new Movements(bot); - defaultMove.canDig = true; - defaultMove.allow1by1tunnels = true; + defaultMove.canDig = Boolean(ctx.opts.relocationCanDig); + defaultMove.allow1by1tunnels = Boolean(ctx.opts.relocationCanDig); defaultMove.allowParkour = true; defaultMove.canSwim = false; defaultMove.liquidCost = 100; - bot.pathfinder.setMovements(defaultMove); - bot.pathfinder.setGoal(new GoalBlock(tx, ty, tz)); + try { + bot.pathfinder.setMovements(defaultMove); + bot.pathfinder.setGoal(new GoalNear(tx, ty, tz, 2)); + } catch (e) { + ctx.logger.warn('pathfinder goal fail:', e.message); + return false; + } const TIMEOUT = 15_000; const start = Date.now(); @@ -176,23 +215,29 @@ function createSpatialEngine(ctx) { if (dist <= 1.5 || !bot.pathfinder.isMoving()) { clearInterval(checkGoal); bot.pathfinder.stop(); - Logger.debug(`pf done d=${dist.toFixed(1)}m`); + ctx.logger.debug(`pf done d=${dist.toFixed(1)}m`); resolve(dist <= 2.5); + return; } if (Date.now() - start > TIMEOUT) { clearInterval(checkGoal); bot.pathfinder.stop(); - Logger.warn('pf timeout'); + ctx.logger.warn('pf timeout'); resolve(false); } }, 200); }); } - function getGroundBlockAt(x, z) { - for (let y = 256; y >= 0; y--) { + /** + * Topmost collision block at (x, z), scanning DOWN from `maxY` (default + * 256). Pass the bot's altitude to skip the hundreds of calls spent in the + * sky every tick. + */ + function getGroundBlockAt(x, z, maxY = 256) { + for (let y = Math.min(Math.floor(maxY), 320); y >= 0; y--) { const b = bot.blockAt(new Vec3(x, y, z)); - if (b && !isAir(b)) return b; + if (b && !isAir(b) && b.boundingBox !== 'empty' && b.shapes && b.shapes.length > 0) return b; } return null; } diff --git a/src/flight/wander.js b/src/flight/wander.js index 48cbd3a..a5a7f62 100644 --- a/src/flight/wander.js +++ b/src/flight/wander.js @@ -1,87 +1,93 @@ 'use strict'; const { Vec3 } = require('vec3'); -const Logger = require('../logger'); -const { isAir, isSafeSolidBlock } = require('../utils'); +const { isAir } = require('../utils'); +const { ErrorCode } = require('../errors'); function createWanderEngine(ctx) { - const { bot, state } = ctx; + const { bot } = ctx; /** - * Find safe landing spot near coordinates. - * Scans Y from bot altitude downward, checks 2 air blocks above. - * No margin check — faster scan, safe for delivery bots. + * Check one column for a landing spot: + * - topmost collision block from `botY + 10` downward + * - not hazardous, has collision + * - 2 air blocks above + * - `landingMargin` blocks of safe solid in every surrounding direction */ - function findSafeLandingSpotAround(centerX, centerZ) { - const cx = Math.round(centerX); - const cz = Math.round(centerZ); + function checkSpotColumn(x, z) { const botY = Math.round(bot.entity.position.y); - - function hasOpenAir(x, y, z) { - const a1 = bot.blockAt(new Vec3(x, y + 1, z)); - const a2 = bot.blockAt(new Vec3(x, y + 2, z)); - return (!a1 || isAir(a1)) && (!a2 || isAir(a2)); - } - - function checkSpot(x, z) { - const maxY = Math.min(botY + 10, 256); - for (let y = maxY; y >= 0; y--) { - const b = bot.blockAt(new Vec3(x, y, z)); - if (b && !isAir(b)) { - if (!isSafeSolidBlock(b)) return null; - const gy = y + 1; - if (!hasOpenAir(x, gy, z)) return null; - // Margin: 1 block in each cardinal direction - for (const [dx, dz] of [[-1,0],[1,0],[0,-1],[0,1]]) { - const nb = bot.blockAt(new Vec3(x + dx, gy - 1, z + dz)); - if (!nb || !isSafeSolidBlock(nb)) return null; - } - return { x, z, y: gy, blockName: b.name, safe: true }; + const margin = Math.max(1, ctx.opts.landingMargin | 0); + const maxY = Math.min(botY + 10, 320); + + for (let y = maxY; y >= 0; y--) { + const b = bot.blockAt(new Vec3(x, y, z)); + if (!b || isAir(b)) continue; + if (!ctx.isSafeSolid(b)) continue; // first collision block is the ground + + const gy = y + 1; + const a1 = bot.blockAt(new Vec3(x, gy, z)); + const a2 = bot.blockAt(new Vec3(x, gy + 1, z)); + if ((a1 && !isAir(a1)) || (a2 && !isAir(a2))) return null; + + for (let dx = -margin; dx <= margin; dx++) { + for (let dz = -margin; dz <= margin; dz++) { + if (dx === 0 && dz === 0) continue; + const nb = bot.blockAt(new Vec3(x + dx, gy - 1, z + dz)); + if (!nb || !ctx.isSafeSolid(nb)) return null; } } - return null; + + return { x, z, y: gy, blockName: b.name, safe: true }; } + return null; + } - // 1. Exact target - const exact = checkSpot(cx, cz); + /** + * Find a safe landing spot near (centerX, centerZ). + * 1) exact target, 2) expanding rings (8 positions, up to 30 radii), + * 3) fallback to the bot's own column. + */ + function findSafeLandingSpotAround(centerX, centerZ) { + const cx = Math.round(centerX); + const cz = Math.round(centerZ); + + const exact = checkSpotColumn(cx, cz); if (exact) return exact; - // 2. Expanding ring — 8 positions per radius, up to 30 radii for (let r = 1; r <= 30; r++) { const spots = [ [cx + r, cz], [cx - r, cz], [cx, cz + r], [cx, cz - r], [cx + r, cz + r], [cx - r, cz - r], [cx + r, cz - r], [cx - r, cz + r], ]; for (const [sx, sz] of spots) { - const spot = checkSpot(sx, sz); + const spot = checkSpotColumn(sx, sz); if (spot) return spot; } } - // 3. Fallback — bot position - const bx = Math.round(bot.entity.position.x); - const bz = Math.round(bot.entity.position.z); - const fb = checkSpot(bx, bz); + const fb = checkSpotColumn(Math.round(bot.entity.position.x), Math.round(bot.entity.position.z)); if (fb) return fb; return { x: cx, z: cz, y: 64, blockName: 'unknown', safe: false }; } /** - * Wander scan — fly toward target, check ground below every tick. - * Land when safe ground found. Rockets only for survival. + * Wander scan — glide toward the target, check the ground below each tick, + * land when safe ground is found. Rockets only for survival. + * Times out after 120 s (the old version could loop forever over hostile + * terrain, draining the elytra). */ function startWanderScan() { - const originX = state.activeTargetX; - const originZ = state.activeTargetZ; + const originX = ctx.state.activeTargetX; + const originZ = ctx.state.activeTargetZ; let scanTicks = 0; + const MAX_TICKS = Math.max(10, Math.round((ctx.opts.wanderTimeoutMs || 120000) / 200)); ctx.setPhase(ctx.PHASE.WANDER_SCAN, `scan (${originX},${originZ})`); - state.scannedChunks.clear(); if (ctx.flyLoop) clearInterval(ctx.flyLoop); ctx.flyLoop = setInterval(() => { - if (state.phase !== ctx.PHASE.WANDER_SCAN) { + if (ctx.state.phase !== ctx.PHASE.WANDER_SCAN) { clearInterval(ctx.flyLoop); ctx.flyLoop = null; return; @@ -92,58 +98,54 @@ function createWanderEngine(ctx) { ctx.checkMidFlightElytraSwap(); + // Wander timeout — no safe spot found + if (scanTicks > MAX_TICKS) { + clearInterval(ctx.flyLoop); + ctx.flyLoop = null; + ctx.failFlight(ErrorCode.NO_SAFE_SPOT, 'wander timeout'); + return; + } + // On ground — check if safe, land if (bot.entity.onGround) { - const ground = ctx.spatial.getGroundBlockAt(Math.round(pos.x), Math.round(pos.z)); - if (ground && isSafeSolidBlock(ground)) { + const ground = ctx.spatial.getGroundBlockAt(Math.round(pos.x), Math.round(pos.z), pos.y + 10); + if (ground && ctx.isSafeSolid(ground)) { clearInterval(ctx.flyLoop); ctx.flyLoop = null; - clearInterval(ctx.verifyLoop); - ctx.verifyLoop = null; - state.retries = 0; - state.spatialClear = false; - ctx.setPhase(ctx.PHASE.IDLE, `land (${Math.round(pos.x)},${Math.round(pos.y)},${Math.round(pos.z)}) ${ground.name}`); + if (ctx.verifyLoop) { clearInterval(ctx.verifyLoop); ctx.verifyLoop = null; } + ctx.logger.info(`landed (${Math.round(pos.x)},${Math.round(pos.y)},${Math.round(pos.z)}) [${ground.name}]`); + ctx.completeFlight(); return; } } // Check ground below — land if safe (with margin) - const groundBelow = ctx.spatial.getGroundBlockAt(Math.round(pos.x), Math.round(pos.z)); - if (groundBelow && isSafeSolidBlock(groundBelow)) { - const gy = (groundBelow.position?.y ?? 60) + 1; - const a1 = bot.blockAt(new Vec3(Math.round(pos.x), gy, Math.round(pos.z))); - const a2 = bot.blockAt(new Vec3(Math.round(pos.x), gy + 1, Math.round(pos.z))); - if ((!a1 || isAir(a1)) && (!a2 || isAir(a2))) { - // Check 1-block margin - let marginOk = true; - for (const [dx, dz] of [[-1,0],[1,0],[0,-1],[0,1]]) { - const nb = bot.blockAt(new Vec3(Math.round(pos.x) + dx, gy - 1, Math.round(pos.z) + dz)); - if (!nb || !isSafeSolidBlock(nb)) { marginOk = false; break; } - } - if (marginOk) { - clearInterval(ctx.flyLoop); - ctx.flyLoop = null; - state.activeTargetX = Math.round(pos.x); - state.activeTargetZ = Math.round(pos.z); - ctx.startLanding(); - return; - } - } + const spot = checkSpotColumn(Math.round(pos.x), Math.round(pos.z)); + if (spot) { + clearInterval(ctx.flyLoop); + ctx.flyLoop = null; + ctx.state.activeTargetX = spot.x; + ctx.state.activeTargetZ = spot.z; + ctx.startLanding({ spot }); + return; } // Glide toward target const targetYaw = Math.atan2(-(originX - pos.x), -(originZ - pos.z)); const speed = Math.hypot(bot.entity.velocity.x, bot.entity.velocity.y, bot.entity.velocity.z); - // Stall — look up to regain speed + // Stall — look up to regain speed (rocket if available, like cruise) if (speed < 0.05 && !bot.entity.onGround && pos.y > 60) { + ctx.logger.warn('wander stall -- boost'); ctx.lookForce(targetYaw + Math.PI, 0.50); + if (ctx.opts.autoRocket && ctx.countRockets() > 0) ctx.fireRocketDirect(); return; } // Too low — rocket to survive + const groundBelow = ctx.spatial.getGroundBlockAt(Math.round(pos.x), Math.round(pos.z), pos.y + 10); const groundY = groundBelow?.position?.y ?? 60; - if (pos.y < groundY + 20 && !bot.entity.onGround && ctx.countRockets(bot) > 0) { + if (pos.y < groundY + 20 && !bot.entity.onGround && ctx.opts.autoRocket && ctx.countRockets() > 0) { ctx.lookForce(targetYaw, 0.40); ctx.fireRocketDirect(targetYaw); return; diff --git a/src/index.js b/src/index.js index 00058a2..5fe0713 100644 --- a/src/index.js +++ b/src/index.js @@ -2,36 +2,44 @@ const { EventEmitter } = require('events'); const { PHASE, MODES, HAZARD_SURFACES, CARDINAL_YAWS } = require('./constants'); -const { sleep, isAir, isHazardousBlock, isSafeSolidBlock, angleDiff } = require('./utils'); +const { sleep, isAir, isHazardousBlock, hasCollision, isSafeSolidBlock, isLandingSurface, angleDiff } = require('./utils'); const Logger = require('./logger'); +const { createLogger } = Logger; +const { ErrorCode, ElytraFlightError, NON_RETRYABLE } = require('./errors'); -const { countRockets, findRocket, autoEquipRocket } = require('./core/inventory'); -const { getElytraSummary, auditAndEquipElytra, calculateRequiredElytraDurability, getUnbreakingLevel } = require('./core/elytra'); +const { countRockets, getRocketSummary, findRocket, autoEquipRocket } = require('./core/inventory'); +const { getElytraSummary, auditAndEquipElytra, calculateRequiredElytraDurability, getUnbreakingLevel, getElytraDamageRate } = require('./core/elytra'); const { createRocketEngine } = require('./core/rockets'); const { createSpatialEngine } = require('./flight/spatial'); const { createFlightPhases } = require('./flight/phases'); const { createWanderEngine } = require('./flight/wander'); const { createLandingEngine } = require('./flight/landing'); -const DEFAULTS = { +const DEFAULTS = Object.freeze({ cruiseAlt: 180, maxRetries: 3, ownerUsername: '', debug: false, - - safety: true, - pathfinding: true, - chunkScan: true, - autoRocket: true, - elytraAudit: true, - landing: true, - wander: true, - + mode: 'MED', + landingMargin: 1, targetX: 0, targetZ: 0, - mode: 'MED', - landingMargin: 2, -}; + + // Module switches (all honoured): + safety: true, // pre-flight durability / rocket estimates + elytraAudit: true, // skip only the elytra-durability estimate + autoRocket: true, // false = fly with no rockets at all + chunkScan: true, // render-distance raycasts (terrain avoidance + headings) + pathfinding: true, // pathfind to a launch spot when blocked + wander: true, // wander for a safe landing spot when none at target + landing: true, // glide-to-goal landing with spot search (false = direct dive) + wanderTimeoutMs: 120000, // give up (typed error + retry) after this long + + // Safety valves: + relocationCanDig: false, // allow the relocation pathfinder to dig (public servers: keep off) + autoRocketCustomStars: false, // count/use firework rockets with custom stars + hazardCheck: null, // custom (block) => boolean hazard override +}); class ElytraFlight extends EventEmitter { constructor(bot, options = {}) { @@ -42,30 +50,63 @@ class ElytraFlight extends EventEmitter { this.opts = { ...DEFAULTS, ...options }; this.mode = MODES[this.opts.mode] || MODES.MEDIUM; + // Per-instance logger (multiple flights no longer share debug state) + this._logger = this.opts.logger || createLogger({ debug: Boolean(this.opts.debug), prefix: this.opts.logPrefix || '[E]' }); + if (this.opts.debug) this._logger.setDebug(true); + // Session state this._phase = PHASE.IDLE; this._targetX = this.opts.targetX; this._targetZ = this.opts.targetZ; this._retries = 0; this._spatialClear = false; - this._launchYaw = 0; - this._lastTerrainWarn = 0; - this._lastKnownSafeGround = null; - this._flightStartPos = null; - this._legStartPos = null; - this._scannedChunks = new Set(); + + // One stable state object shared by all modules (previously every + // `ctx.state` access returned a fresh object, so writes like + // `state.retries = 0` landed in throwaway copies). + const self = this; + this._state = { + get phase() { return self._phase; }, + set phase(v) { self._phase = v; self.emit('phase', v); }, + get currentMode() { return self.mode; }, + get activeTargetX() { return self._targetX; }, + set activeTargetX(v) { self._targetX = v; }, + get activeTargetZ() { return self._targetZ; }, + set activeTargetZ(v) { self._targetZ = v; }, + get spatialClear() { return self._spatialClear; }, + set spatialClear(v) { self._spatialClear = v; }, + get retries() { return self._retries; }, + set retries(v) { self._retries = v; }, + activeLaunchYaw: 0, + lastTerrainWarn: 0, + lastKnownSafeGround: null, + flightStartPos: null, + legStartPos: null, + scannedChunks: new Set(), + }; + + // Pending fly() promise + this._pending = null; // Timer handles - this._flyLoop = null; - this._verifyLoop = null; - this._rocketLoop = null; - this._climbLoop = null; + this._retryTimer = null; + this._sneakTimer = null; + + // Pathfinding: EAFE depends on mineflayer-pathfinder — load it if the + // user hasn't (the old code assumed the user knew to, silently). + try { + if (!bot.pathfinder) bot.loadPlugin(require('mineflayer-pathfinder').pathfinder); + } catch (e) { + this._logger.warn('pathfinder unavailable (relocation disabled):', e.message); + } - // Logger - this._logger = Logger; - if (this.opts.debug) this._logger.setDebug(true); + // Block classification (custom hooks honoured — examples can override) + this._isHazardous = this.opts.hazardCheck || isHazardousBlock; + this._isSafeSolid = (b) => { + if (!b || isAir(b) || this._isHazardous(b)) return false; + return hasCollision(b); + }; - // Build context first (modules need it) this._buildCtx(); // Create modules with full ctx @@ -87,69 +128,174 @@ class ElytraFlight extends EventEmitter { this._ctx.startClimb = this._phases.startClimb; this._ctx.startCruise = this._phases.startCruise; + // Mid-flight elytra swap + this._ctx.checkMidFlightElytraSwap = this._checkMidFlightElytraSwap.bind(this); + // Reset state on respawn this.bot.on('spawn', () => { if (this._phase !== PHASE.IDLE && this._phase !== PHASE.FAILED) { this._logger.warn(`respawn during ${this._phase} -- reset`); - this._emergencyStop('respawn'); + this._emergencyStop('respawn', ErrorCode.RESPAWN); } }); + this.bot.once('end', () => { + this._emergencyStop('disconnected', ErrorCode.DISCONNECTED); + }); } // ─── Public API ─────────────────────────────────────────── get phase() { return this._phase; } get isFlying() { return this._ctx.isFlying(); } - + get targetX() { return this._targetX; } + get targetZ() { return this._targetZ; } + get state() { return this._state; } + + /** + * Fly to (x, z). Returns a Promise that: + * - resolves `{ landedAt: {x,y,z} }` when the bot lands + * - rejects with an ElytraFlightError (err.code) on failure/stop/respawn + * + * While in CRUISE/DEADSTICK, calling fly() retargets the in-progress + * flight and returns its existing promise. + */ fly(x, z, opts = {}) { - if (typeof x === 'object') { opts = x; x = opts.x; z = opts.z; } + if (typeof x === 'object' && x !== null) { opts = x; x = opts.x; z = opts.z; } + if ((x !== undefined && !Number.isFinite(x)) || (z !== undefined && !Number.isFinite(z))) { + const err = new ElytraFlightError(ErrorCode.INTERNAL, 'fly(x, z) expects finite numbers'); + this._emitError(err); + return Promise.reject(err); + } + + const p = this._phase; + if (p === PHASE.CRUISING || p === PHASE.DEAD_STICK) { + // Retarget mid-cruise — the cruise loop reads the target live. + // (Applied BEFORE the in-flight check: a rejected call must not + // silently retarget the active flight.) + if (x !== undefined) this._targetX = x; + if (z !== undefined) this._targetZ = z; + if (opts.mode) this.setMode(opts.mode); + if (opts.cruiseAlt !== undefined && Number.isFinite(opts.cruiseAlt) && opts.cruiseAlt > 0) { + this.opts.cruiseAlt = opts.cruiseAlt; + } + if (this._pending) return this._pending.promise; + } + if (p !== PHASE.IDLE && p !== PHASE.FAILED) { + const err = new ElytraFlightError(ErrorCode.IN_FLIGHT, `in ${p} -- stop() first`); + this._emitError(err); + return Promise.reject(err); + } + + // New flight from IDLE/FAILED — target + per-call options apply. if (x !== undefined) this._targetX = x; if (z !== undefined) this._targetZ = z; - if (opts.mode) this.mode = MODES[opts.mode] || this.mode; - if (opts.cruiseAlt) this.opts.cruiseAlt = opts.cruiseAlt; + if (opts.mode) this.setMode(opts.mode); + if (opts.cruiseAlt !== undefined) { + if (Number.isFinite(opts.cruiseAlt) && opts.cruiseAlt > 0) this.opts.cruiseAlt = opts.cruiseAlt; + } this._retries = 0; this._spatialClear = false; - this._phases.startFlight(); - return this; + const pending = {}; + this._pending = pending; + pending.promise = new Promise((resolve, reject) => { + pending.resolve = resolve; + pending.reject = reject; + }); + const promise = pending.promise; + + this._phases.startFlight().catch(err => { + if (!this._pending) return; + this._logger.error('startFlight error:', err.message); + this._ctx.setPhase(PHASE.FAILED, `error: ${err.message}`); + this._rejectPending(new ElytraFlightError(ErrorCode.INTERNAL, err.message)); + this._emitError(new ElytraFlightError(ErrorCode.INTERNAL, err.message)); + }); + + return promise; } + /** + * Emergency stop. Emits 'stopped' (exactly once) and phase IDLE. + * A pending fly() promise rejects with code 'STOPPED'. + */ stop(reason = 'user') { - this._ctx.emergencyStop(reason); - this.emit('stopped', reason); + this._emergencyStop(reason, ErrorCode.STOPPED); return this; } setTarget(x, z) { - this._targetX = x; - this._targetZ = z; + if (Number.isFinite(x)) this._targetX = x; + if (Number.isFinite(z)) this._targetZ = z; return this; } setMode(mode) { - this.mode = MODES[mode] || MODES.MEDIUM; + const m = MODES[mode]; + if (!m) { + this._logger.warn(`unknown mode '${mode}' -- keeping ${this.mode.name}`); + return this; + } + this.mode = m; return this; } + /** + * Status snapshot (get-style name kept for API compatibility). + */ setStatus(x, z) { - const pos = this.bot.entity.position; + const pos = this.bot.entity ? this.bot.entity.position : { x: 0, y: 0, z: 0 }; const elytra = getElytraSummary(this.bot); - const rockets = countRockets(this.bot); + const rockets = countRockets(this.bot, { includeCustom: this.opts.autoRocketCustomStars }); const dist = this._dist2D(x, z); return { phase: this._phase, mode: this.mode.name, pos: { x: Math.round(pos.x), y: Math.round(pos.y), z: Math.round(pos.z) }, - target: { x, z }, + target: { x: x ?? this._targetX, z: z ?? this._targetZ }, dist: Math.round(dist), elytra: { dur: elytra.totalDurabilityAcrossAll, count: elytra.count, unbreaking: elytra.bestUnbreaking }, rockets, - flying: this.bot.entity.elytraFlying, + flying: this.bot.entity ? this.bot.entity.elytraFlying : false, }; } - preflight() { - return this._doPreflight(); + /** + * Pre-flight check without flying. Pure (no equipping side effects) and + * always returns the documented shape: + * { ok, reason, elytra: {have, need, equipped, count, unbreaking}, rockets: {have, need} } + */ + async preflight() { + if (!this.bot.entity) { + return { + ok: false, reason: 'not spawned', + elytra: { have: 0, need: 0, equipped: 0, count: 0, unbreaking: 0 }, + rockets: { have: 0, need: 0 }, + }; + } + + const elytra = getElytraSummary(this.bot); + const hasElytra = await auditAndEquipElytra(this._ctx, { equip: false }); + const rockets = countRockets(this.bot, { includeCustom: this.opts.autoRocketCustomStars }); + const d2d = this._dist2D(this._targetX, this._targetZ); + const reqDur = calculateRequiredElytraDurability(d2d, this.mode.speedMps, elytra.bestUnbreaking); + const reqRockets = this._ctx.calculateRequiredRockets(d2d, this.opts.cruiseAlt - this.bot.entity.position.y); + + const elytraOk = elytra.totalDurabilityAcrossAll >= reqDur; + const rocketsOk = this.opts.autoRocket ? rockets >= reqRockets : true; + + return { + ok: hasElytra && elytraOk && rocketsOk, + reason: !hasElytra ? 'no elytra' : !elytraOk ? 'elytra low' : !rocketsOk ? 'no rockets' : null, + elytra: { + have: elytra.totalDurabilityAcrossAll, + need: reqDur, + equipped: elytra.equippedDur, + count: elytra.count, + unbreaking: elytra.bestUnbreaking, + }, + rockets: { have: rockets, need: reqRockets }, + }; } getLandingStats() { @@ -166,41 +312,30 @@ class ElytraFlight extends EventEmitter { _buildCtx() { const self = this; + const includeCustom = () => self.opts.autoRocketCustomStars; this._ctx = { bot: this.bot, - get state() { - return { - get phase() { return self._phase; }, - set phase(v) { self._phase = v; self.emit('phase', v); }, - currentMode: self.mode, - get activeTargetX() { return self._targetX; }, - set activeTargetX(v) { self._targetX = v; }, - get activeTargetZ() { return self._targetZ; }, - set activeTargetZ(v) { self._targetZ = v; }, - retries: 0, - get spatialClear() { return self._spatialClear; }, - set spatialClear(v) { self._spatialClear = v; }, - activeLaunchYaw: 0, - lastTerrainWarn: 0, - lastKnownSafeGround: null, - flightStartPos: null, - legStartPos: null, - scannedChunks: new Set(), - }; - }, + opts: this.opts, + logger: this._logger, + state: this._state, PHASE, get CRUISE_ALT() { return self.opts.cruiseAlt; }, get MAX_RETRIES() { return self.opts.maxRetries; }, + isHazardous: (b) => self._isHazardous(b), + isSafeSolid: (b) => self._isSafeSolid(b), + clearTimers: () => self._clearTimers(), yawTo: (x, z) => self._yawTo(x, z), dist2D: (x, z) => self._dist2D(x, z), lookForce: (yaw, pitch) => { self._smoothLook(yaw, pitch); }, sleep, - countRockets, - autoEquipRocket, + + countRockets: () => countRockets(self.bot, { includeCustom: includeCustom() }), + autoEquipRocket: () => autoEquipRocket(self.bot, { includeCustom: includeCustom() }), getElytraSummary: () => getElytraSummary(self.bot), + auditAndEquipElytra: (options) => auditAndEquipElytra(self._ctx, options), calculateRequiredElytraDurability, getUnbreakingLevel, @@ -213,14 +348,12 @@ class ElytraFlight extends EventEmitter { isFlying: () => { const e = self.bot.entity; if (!e) return false; - return (e.elytraFlying || e.fallFlying) && !e.onGround; + return e.elytraFlying && !e.onGround; }, - scheduleRetry: () => self._scheduleRetry(), - safeChat: (msg) => { if (!msg || typeof msg !== 'string') return; - try { self.bot.chat(msg.substring(0, 256)); } catch(_) {} + try { self.bot.chat(msg.substring(0, 256)); } catch (_) { /* bot gone */ } }, setPhase: (p, msg) => { @@ -229,11 +362,33 @@ class ElytraFlight extends EventEmitter { self._logger.info(line); self.emit('phase', p, msg); if (self.opts.ownerUsername) { - try { self.bot.whisper(self.opts.ownerUsername, line); } catch(_) {} + try { self.bot.whisper(self.opts.ownerUsername, line); } catch (_) { /* bot gone */ } } }, - emergencyStop: (reason) => self._emergencyStop(reason), + /** Phase FAILED + retry (or final failure with typed error). */ + failFlight: (code, msg) => { + self._logger.warn(`FAIL ${msg}`); + self._ctx.setPhase(PHASE.FAILED, msg); + self._scheduleRetry(code, msg); + }, + + /** Successful landing: reset, phase IDLE, resolve pending fly(). */ + completeFlight: (details = {}) => { + self._retries = 0; + self._spatialClear = false; + const p = self.bot.entity ? self.bot.entity.position : { x: 0, y: 0, z: 0 }; + const msg = details.msg || `land (${Math.round(p.x)},${Math.round(p.y)},${Math.round(p.z)})`; + self._ctx.setPhase(PHASE.IDLE, msg); + const pending = self._pending; + self._pending = null; + if (pending) { + pending.resolve({ + phase: PHASE.IDLE, + landedAt: { x: Math.round(p.x), y: Math.round(p.y), z: Math.round(p.z) }, + }); + } + }, // Module references — populated after module creation fireRocketDirect: null, @@ -247,41 +402,82 @@ class ElytraFlight extends EventEmitter { startClimb: null, startCruise: null, checkMidFlightElytraSwap: null, - auditAndEquipElytra: () => auditAndEquipElytra(self._ctx), }; + } - // Mid-flight elytra swap - this._ctx.checkMidFlightElytraSwap = async () => { - if (!this.opts.safety) return; - const chest = this.bot.inventory.slots[6]; - if (!chest || chest.name !== 'elytra') return; - const dur = chest.maxDurability ? (chest.maxDurability - chest.durabilityUsed) : 432; - if (dur <= 10) { - this._logger.warn(`elytra dur=${dur}/432 -- swap`); - const swapped = await auditAndEquipElytra(this._ctx); - if (swapped) { - try { await this.bot.elytraFly(); } catch(_) {} - this._ctx.fireRocketDirect(); - } else { - this._logger.error('no spare elytras -- land'); - this._ctx.startLanding(); - } + async _checkMidFlightElytraSwap() { + if (!this.opts.safety) return; + const chest = this.bot.inventory.slots[6]; + if (!chest || chest.name !== 'elytra') return; + const dur = chest.maxDurability ? (chest.maxDurability - chest.durabilityUsed) : 432; + if (dur <= 10) { + this._logger.warn(`elytra dur=${dur}/432 -- swap`); + const swapped = await auditAndEquipElytra(this._ctx); + if (swapped) { + try { await this.bot.elytraFly(); } catch (_) { /* already flying */ } + this._ctx.fireRocketDirect(); + } else { + this._logger.error('no spare elytras -- land'); + this._ctx.startLanding({}); } - }; + } } // ─── Internal Helpers ───────────────────────────────────── + _rejectPending(err) { + const pending = this._pending; + this._pending = null; + if (pending) pending.reject(err); + } + + /** + * Emit 'error' only when a listener is attached. EventEmitter semantics + * make a bare emit('error') THROW synchronously when no 'error' listener + * exists — which would turn a cleanly-rejectable fly() into a raw throw + * the caller's .catch() can never see. The promise rejection remains the + * primary error channel; this is an observability side-channel. + */ + _emitError(err) { + if (this.listenerCount('error') > 0) this.emit('error', err); + } + + /** + * Clears the REAL interval handles (stored on ctx by the flight modules) + * plus the retry/sneak timeouts. The old implementation cleared instance + * fields that were never set, so stop() relied on phase checks alone. + */ _clearTimers() { - [this._flyLoop, this._verifyLoop, this._rocketLoop, this._climbLoop].forEach(h => { - if (h) clearInterval(h); - }); - this._flyLoop = this._verifyLoop = this._rocketLoop = this._climbLoop = null; + const c = this._ctx; + for (const key of ['flyLoop', 'verifyLoop', 'rocketLoop', 'climbLoop', 'landLoop']) { + if (c && c[key]) { + clearInterval(c[key]); + c[key] = null; + } + } + if (this._retryTimer) { + clearTimeout(this._retryTimer); + this._retryTimer = null; + } + if (this._sneakTimer) { + clearTimeout(this._sneakTimer); + this._sneakTimer = null; + } } _yawTo(x, z) { const p = this.bot.entity.position; - return Math.atan2(-(x - p.x), -(z - p.z)); + const dx = x - p.x; + const dz = z - p.z; + // Near the target column: the bearing is numerically unstable — + // position jitter of a fraction of a block flips it up to 180° tick + // to tick, which made the bot spin in circles (and never fire a + // rocket, whose yaw gate then never passed). Within 3 m of the + // column the bearing is noise; hold the current heading. (3 m is + // negligible for flight geometry — the landing logic settles the + // final blocks on its own.) + if (Math.hypot(dx, dz) < 3) return this.bot.entity.yaw; + return Math.atan2(-dx, -dz); } _smoothLook(targetYaw, targetPitch) { @@ -296,67 +492,94 @@ class ElytraFlight extends EventEmitter { while (dy < -Math.PI) dy += 2 * Math.PI; const dp = targetPitch - curPitch; - const lerp = 0.15 + Math.random() * 0.10; + // Adaptive lerp: big heading corrections (takeoff alignment, hazard + // avoidance, 180° turns) converge in 2-3 ticks; small corrections + // (cruise trim, landing glide) stay smooth. The old flat 15-25%/tick + // took ~0.8 s to close 90°, which is longer than jump airtime — the + // bot used to land before its first takeoff rocket could be fired. + const lerp = 0.30 + Math.random() * 0.10 + Math.min(0.40, Math.abs(dy) * 0.30); const jitterY = (Math.random() - 0.5) * 0.008; const jitterP = (Math.random() - 0.5) * 0.005; const newYaw = curYaw + dy * lerp + jitterY; const newPitch = Math.max(-Math.PI / 2, Math.min(Math.PI / 2, curPitch + dp * lerp + jitterP)); - try { bot.look(newYaw, newPitch, false); } catch(_) {} + try { bot.look(newYaw, newPitch, false); } catch (_) { /* bot gone */ } } _dist2D(x, z) { + if (!this.bot.entity) return 0; const p = this.bot.entity.position; return Math.hypot((x ?? this._targetX) - p.x, (z ?? this._targetZ) - p.z); } - _emergencyStop(reason) { - this._phase = PHASE.IDLE; + _emergencyStop(reason, code = ErrorCode.STOPPED) { + const wasInFlight = this._phase !== PHASE.IDLE && this._phase !== PHASE.FAILED; this._spatialClear = false; this._clearTimers(); - try { this.bot.pathfinder.stop(); } catch(_) {} - ['sprint','forward','back','left','right','jump','sneak'].forEach(k => { - try { this.bot.setControlState(k, false); } catch(_) {} + try { this.bot.pathfinder && this.bot.pathfinder.stop(); } catch (_) { /* bot gone */ } + ['sprint', 'forward', 'back', 'left', 'right', 'jump', 'sneak'].forEach(k => { + try { this.bot.setControlState(k, false); } catch (_) { /* bot gone */ } }); - try { this.bot.setControlState('sneak', true); } catch(_) {} - setTimeout(() => { try { this.bot.setControlState('sneak', false); } catch(_) {} }, 600); + try { this.bot.setControlState('sneak', true); } catch (_) { /* bot gone */ } + this._sneakTimer = setTimeout(() => { + this._sneakTimer = null; + try { this.bot.setControlState('sneak', false); } catch (_) { /* bot gone */ } + }, 600); this._logger.info(`STOP ${reason}`); + + // Emit phase IDLE so event consumers don't hang waiting for it + this._phase = PHASE.IDLE; + this.emit('phase', PHASE.IDLE, reason); + this.emit('stopped', reason); + if (wasInFlight || this._pending) { + this._rejectPending(new ElytraFlightError(code, reason)); + } } - _scheduleRetry() { + _scheduleRetry(finalCode, finalMsg) { + // Deterministic pre-flight precondition failures (no entity, no + // elytra, not enough rockets, ...) can't change outcome on retry — + // fail fast with the specific code instead of burning the retry + // budget and masking the cause behind RETRIES_EXHAUSTED. + if (NON_RETRYABLE.has(finalCode)) { + const err = new ElytraFlightError(finalCode, finalMsg || finalCode); + this._logger.error(err.message); + this._rejectPending(err); + this._emitError(err); + return; + } if (this._retries >= this.opts.maxRetries) { - this._ctx.setPhase(PHASE.FAILED, `FAIL after ${this.opts.maxRetries} retries`); - this._spatialClear = false; - this.emit('error', new Error(`Flight failed after ${this.opts.maxRetries} retries`)); + // The final rejection is always RETRIES_EXHAUSTED (the engine-level + // "gave up"); the last failure's code travels in the message and as + // `err.cause` so automation can branch on the real reason. + const err = new ElytraFlightError( + ErrorCode.RETRIES_EXHAUSTED, + `Flight failed after ${this._retries} retries${finalMsg ? ` (${finalMsg})` : ''}` + ); + err.cause = finalCode; + this._logger.error(err.message); + this._rejectPending(err); + this._emitError(err); return; } this._retries++; const delay = this._retries * 3000; this._logger.warn(`retry ${this._retries}/${this.opts.maxRetries} in ${delay / 1000}s`); - setTimeout(() => { - this._phase = PHASE.IDLE; - this._ctx.startFlight(); + this._retryTimer = setTimeout(() => { + this._retryTimer = null; + // Only retry if we're still failed (stop()/fly() changed phase since) + if (this._phase !== PHASE.FAILED) return; + this._phases.startFlight().catch(err => { + if (!this._pending) return; + this._logger.error('startFlight error:', err.message); + this._ctx.setPhase(PHASE.FAILED, `error: ${err.message}`); + this._rejectPending(new ElytraFlightError(ErrorCode.INTERNAL, err.message)); + this._emitError(new ElytraFlightError(ErrorCode.INTERNAL, err.message)); + }); }, delay); } - - async _doPreflight() { - const elytraOk = await auditAndEquipElytra(this._ctx); - if (!elytraOk) return { ok: false, reason: 'no elytra' }; - - const rockets = countRockets(this.bot); - const d2d = this._dist2D(this._targetX, this._targetZ); - const elytra = getElytraSummary(this.bot); - const reqDur = calculateRequiredElytraDurability(d2d, this.mode.speedMps, elytra.bestUnbreaking); - const reqRockets = this._ctx.calculateRequiredRockets(d2d, this.opts.cruiseAlt - this.bot.entity.position.y); - - return { - ok: elytra.totalDurabilityAcrossAll >= reqDur && rockets >= reqRockets, - elytra: { have: elytra.totalDurabilityAcrossAll, need: reqDur }, - rockets: { have: rockets, need: reqRockets }, - }; - } } module.exports = ElytraFlight; @@ -366,15 +589,22 @@ module.exports.PHASE = PHASE; module.exports.HAZARD_SURFACES = HAZARD_SURFACES; module.exports.CARDINAL_YAWS = CARDINAL_YAWS; module.exports.Logger = Logger; +module.exports.createLogger = createLogger; +module.exports.ErrorCode = ErrorCode; +module.exports.ElytraFlightError = ElytraFlightError; module.exports.countRockets = countRockets; +module.exports.getRocketSummary = getRocketSummary; module.exports.findRocket = findRocket; module.exports.autoEquipRocket = autoEquipRocket; module.exports.getElytraSummary = getElytraSummary; module.exports.auditAndEquipElytra = auditAndEquipElytra; module.exports.calculateRequiredElytraDurability = calculateRequiredElytraDurability; module.exports.getUnbreakingLevel = getUnbreakingLevel; +module.exports.getElytraDamageRate = getElytraDamageRate; module.exports.isAir = isAir; module.exports.isHazardousBlock = isHazardousBlock; +module.exports.hasCollision = hasCollision; module.exports.isSafeSolidBlock = isSafeSolidBlock; +module.exports.isLandingSurface = isLandingSurface; module.exports.angleDiff = angleDiff; module.exports.sleep = sleep; diff --git a/src/logger.js b/src/logger.js index 2710a19..53668dd 100644 --- a/src/logger.js +++ b/src/logger.js @@ -1,28 +1,29 @@ 'use strict'; -const config = require('./config'); - -let _debug = config.DEBUG; - -const Logger = { - setDebug(on) { _debug = on; }, - isDebug() { return _debug; }, - - debug(...args) { - if (_debug) console.log('[E]', ...args); - }, - - info(...args) { - console.log('[E]', ...args); - }, - - warn(...args) { - console.warn('[E]', ...args); - }, - - error(...args) { - console.error('[E]', ...args); - }, -}; +/** + * Lightweight prefixed logger. + * + * Use {@link createLogger} for per-instance loggers (recommended — multiple + * ElytraFlight instances no longer share global debug state): + * + * const log = createLogger({ debug: true, prefix: '[E:Scout1]' }); + * + * The default singleton (module export) is kept for backward compatibility. + */ +function createLogger({ debug = false, prefix = '[E]', console: sink = console } = {}) { + let _debug = debug; + return { + setDebug(on) { _debug = Boolean(on); }, + isDebug() { return _debug; }, + debug(...args) { if (_debug) sink.log(prefix, ...args); }, + info(...args) { sink.log(prefix, ...args); }, + warn(...args) { sink.warn(prefix, ...args); }, + error(...args) { sink.error(prefix, ...args); }, + }; +} + +const Logger = createLogger({ debug: false }); module.exports = Logger; +module.exports.Logger = Logger; +module.exports.createLogger = createLogger; diff --git a/src/utils.js b/src/utils.js index 5961a94..ad04685 100644 --- a/src/utils.js +++ b/src/utils.js @@ -11,15 +11,43 @@ function isAir(block) { return block.name === 'air' || block.name === 'cave_air' || block.name === 'void_air'; } +/** + * Default hazard check — exact block names only (the old `name.includes('water')` + * false-positived on safe blocks such as `water_strainer`). + */ function isHazardousBlock(block) { if (!block) return true; - if (HAZARD_SURFACES.has(block.name)) return true; - return block.name.includes('water') || block.name.includes('lava') || block.name.includes('magma'); + return HAZARD_SURFACES.has(block.name); } +/** + * True when the block has a collision box (you can stand on / bounce off it). + * Verified against prismarine-block runtime data: `boundingBox` is 'block' + * for collision blocks and 'empty' for pass-through blocks. + */ +function hasCollision(block) { + return Boolean(block) && block.boundingBox !== 'empty' && block.shapes && block.shapes.length > 0; +} + +/** + * Safe to build flight decisions on: solid, collision, not hazardous. + * (The previous version accepted flowers/saplings/torches as "solid".) + */ function isSafeSolidBlock(block) { if (!block || isAir(block) || isHazardousBlock(block)) return false; - return true; + return hasCollision(block); +} + +/** + * Stricter surface test for actual landing: the top of the block must be a + * full walkable cube (stone = [0,0,0,1,1,1]; a top slab = [0,0.5,0,1,1,1] fails). + */ +function isLandingSurface(block) { + if (!isSafeSolidBlock(block)) return false; + return block.shapes.some(s => + s[0] === 0 && s[1] === 0 && s[2] === 0 && + s[3] === 1 && s[4] === 1 && s[5] === 1 + ); } function angleDiff(a, b) { @@ -29,4 +57,12 @@ function angleDiff(a, b) { return Math.abs(diff); } -module.exports = { sleep, isAir, isHazardousBlock, isSafeSolidBlock, angleDiff }; +module.exports = { + sleep, + isAir, + isHazardousBlock, + hasCollision, + isSafeSolidBlock, + isLandingSurface, + angleDiff, +}; diff --git a/test/helpers/mock-bot.js b/test/helpers/mock-bot.js new file mode 100644 index 0000000..47c026a --- /dev/null +++ b/test/helpers/mock-bot.js @@ -0,0 +1,259 @@ +'use strict'; + +/** + * Mock mineflayer bot for integration tests. + * + * - Real prismarine-world terrain (1.21) so block data (boundingBox, shapes) + * matches production. + * - Faithful velocity units: `entity.velocity` in BLOCKS/TICK (as the real + * mineflayer reports), so EAFE's speed gates (blocks/tick) behave correctly. + * - Elytra model: rocket boost decays, glide floor ~8 m/s, gravity, and + * ground contact stops the elytra (server behaviour). + * - Records chat/whisper output and counts EAFE's blockAt calls (perf guard). + */ +const { Vec3 } = require('vec3'); +const { EventEmitter } = require('events'); +const minecraftData = require('minecraft-data'); +const World = require('prismarine-world'); +const Chunk = require('prismarine-chunk'); +const BlockLib = require('prismarine-block'); + +const md = minecraftData('1.21'); +const WorldCtor = World(md); +const ChunkCtor = Chunk(md); +const BlockCtor = BlockLib(md); + +const GROUND = 64; +const TICKS_PER_SEC = 20; + +function blockByName(name) { + const b = md.blocksByName[name]; + if (!b) throw new Error(`unknown block in mock world: ${name}`); + return b; +} + +class MockBot extends EventEmitter { + constructor({ startX = 0, startY = GROUND + 1, startZ = 0, rockets = 20, elytraDur = 432, unbreaking = 3, features = [] } = {}) { + super(); + this.chatLog = []; + this.whisperLog = []; + this.eafeBlockAtCalls = 0; // only what EAFE asks for + + // ── world ─ + this.world = new WorldCtor(null, null).sync; + this._buildFlatWorld(startX, startZ, 20); + for (const f of features) this.setBlock(f.x, f.y, f.z, f.name); + + // ── entity ── + this.entity = { + id: 1, + position: new Vec3(startX, startY, startZ), + velocity: new Vec3(0, 0, 0), + yaw: 0, + pitch: 0, + onGround: true, + elytraFlying: false, + isInWater: false, + eyeHeight: 1.62, + }; + this._speedMps = 0; // internal speed in m/s + this._rocketUntil = 0; + this.jump = false; + + // ── player / inventory ── + this.player = { ping: 20, entity: this.entity }; + this.players = {}; + this.inventory = { + slots: new Array(46).fill(null), + items() { return this.slots.filter(Boolean); }, + }; + this.inventory.slots[6] = { + name: 'elytra', count: 1, + maxDurability: 432, durabilityUsed: 432 - elytraDur, + enchants: unbreaking > 0 ? [{ name: 'unbreaking', lvl: unbreaking }] : [], + }; + this.inventory.slots[0] = rockets > 0 ? { name: 'firework_rocket', count: rockets } : null; + + // ── pathfinder (pre-set so EAFE skips plugin loading) ── + this.pathfinder = { + _goal: null, + _moving: false, + setMovements() {}, + setGoal(g) { this._goal = g; this._moving = false; }, + isMoving() { return this._moving; }, + stop() { this._moving = false; }, + }; + this.loadPlugin = () => { /* mock: plugins pre-set */ }; + } + + _buildFlatWorld(cx, cz, radiusChunks) { + const stoneId = blockByName('stone').id; + const airId = blockByName('air').id; + for (let x = Math.floor(cx / 16) - radiusChunks; x < Math.floor(cx / 16) + radiusChunks; x++) { + for (let z = Math.floor(cz / 16) - radiusChunks; z < Math.floor(cz / 16) + radiusChunks; z++) { + const col = new ChunkCtor({ minY: -64, worldHeight: 320 }); + for (let y = -64; y <= GROUND; y++) { + for (let lx = 0; lx < 16; lx++) { + for (let lz = 0; lz < 16; lz++) { + col.setBlockStateId(new Vec3(lx, y, lz), y === GROUND ? stoneId : airId); + } + } + } + this.world.setColumn(x, z, col); + } + } + } + + /** Uncounted block read — mock internals (physics) only. */ + rawBlockAt(pos) { + return this.world.getBlock(pos); + } + + /** EAFE-facing block read (counted for the perf guard). */ + blockAt(pos) { + this.eafeBlockAtCalls++; + const b = this.world.getBlock(pos); + if (b) b.position = pos.floored(); + return b; + } + + /** Top of the walkable ground at (x, z): topmost collision block + 1. */ + groundY(x, z) { + for (let y = 320; y >= 0; y--) { + const b = this.rawBlockAt(new Vec3(x, y, z)); + if (b && b.boundingBox !== 'empty' && b.shapes && b.shapes.length > 0) return y + 1; + } + return GROUND + 1; + } + + setBlock(x, y, z, name) { + const col = this.world.getColumn(Math.floor(x / 16), Math.floor(z / 16)); + if (!col) throw new Error('column not built in mock world'); + const lx = ((x % 16) + 16) % 16; + const lz = ((z % 16) + 16) % 16; + col.setBlockStateId(new Vec3(lx, y, lz), blockByName(name).minStateId); + } + + chat(msg) { this.chatLog.push(msg); } + whisper(user, msg) { this.whisperLog.push({ user, msg }); } + setControlState(k, v) { this[k] = Boolean(v); } + look(yaw, pitch) { this.entity.yaw = yaw; this.entity.pitch = pitch; } + + async elytraFly() { + const e = this.entity; + if (e.elytraFlying) throw new Error('Already elytra flying'); + if (e.onGround) throw new Error('Unable to fly from ground'); + if (e.isInWater) throw new Error('Unable to elytra fly while in water'); + const chest = this.inventory.slots[6]; + if (!chest || chest.name !== 'elytra') throw new Error('Elytra must be equip to start flying'); + e.elytraFlying = true; + } + + async equip(item, destination) { + const destSlot = destination === 'torso' ? 6 : destination === 'off-hand' ? 45 : null; + if (destSlot === null) throw new Error('bad equip slot ' + destination); + const slots = this.inventory.slots; + const fromSlot = slots.indexOf(item); + if (fromSlot === -1) throw new Error('item not in inventory'); + if (fromSlot !== destSlot) { + const tmp = slots[destSlot]; + slots[destSlot] = item; + slots[fromSlot] = tmp; + } + } + + activateItem() { + const offhand = this.inventory.slots[45]; + if (offhand && offhand.name === 'firework_rocket') { + offhand.count--; + if (offhand.count <= 0) this.inventory.slots[45] = null; + this._rocketUntil = Date.now() + 2500; + this._speedMps = Math.min(this._speedMps + 20, 48); + } + } + + /** + * Advance mock physics by dt seconds (real time). EAFE's own loops run on + * real timers and read entity state on their 50/200 ms ticks. + */ + step(dt) { + const e = this.entity; + const now = Date.now(); + const ticks = dt * TICKS_PER_SEC; + + if (this.jump && e.onGround) { + e.velocity.y = 0.42; // blocks/tick, like the server + e.onGround = false; + } + + if (e.elytraFlying) { + const g = this.groundY(Math.round(e.position.x), Math.round(e.position.z)); + if (e.position.y <= g) { + e.position.y = g; + e.onGround = true; + e.elytraFlying = false; + e.velocity = new Vec3(0, 0, 0); + this._speedMps = 0; + return; + } + + const boosting = now < this._rocketUntil; + const targetSpeed = boosting ? 24 : 12; + this._speedMps += (targetSpeed - this._speedMps) * Math.min(1, dt * (boosting ? 4 : 0.8)); + if (boosting) this._speedMps = Math.min(this._speedMps, 26); + + const vT = this._speedMps / TICKS_PER_SEC; // blocks/tick + const cp = Math.cos(e.pitch); + const sp = Math.sin(e.pitch); + // mineflayer convention (verified against mineflayer's own lookAt and + // mineflayer-pathfinder: yaw = atan2(-dx, -dz) to face (dx, dz)): + // forward(yaw) = (-sin(yaw), -cos(yaw)) in (x, z). + let tvx = -Math.sin(e.yaw) * cp * vT; + let tvz = -Math.cos(e.yaw) * cp * vT; + let tvy; + if (boosting) { + tvy = sp * vT; // rocket: full thrust along view + } else if (sp > 0.05) { + // pointing up without a rocket = stall: no sustained climb, + // sink ~2 m/s, slow drift + tvy = -0.10; + tvx *= 0.5; + tvz *= 0.5; + } else { + // level or diving: healthy glide. Sink follows the pitch plus + // ~0.8 m/s induced drag — a real elytra glides ~15:1 around + // 12 m/s, it does not deep-stall at 8 m/s. + tvy = sp * vT - 0.04 - 0.04 * Math.abs(sp); + } + const k = Math.min(1, dt * 6); + e.velocity.x += (tvx - e.velocity.x) * k; + e.velocity.y += (tvy - e.velocity.y) * k; + e.velocity.z += (tvz - e.velocity.z) * k; + e.position = e.position.plus(e.velocity.scaled(ticks)); + } else if (!e.onGround) { + e.velocity = e.velocity.plus(new Vec3(0, -0.08 * ticks, 0)); + e.position = e.position.plus(e.velocity.scaled(ticks)); + const g = this.groundY(Math.round(e.position.x), Math.round(e.position.z)); + if (e.position.y <= g) { + e.position.y = g; + e.onGround = true; + e.velocity = new Vec3(0, 0, 0); + } + } else { + e.velocity = new Vec3(0, 0, 0); + } + } + + /** Run physics in real time until cond() or timeout. Returns success. */ + async stepUntil(cond, timeoutMs = 30000, { dt = 0.02, interval = 20 } = {}) { + const start = Date.now(); + while (Date.now() - start < timeoutMs) { + this.step(dt); + if (cond()) return true; + await new Promise(r => setTimeout(r, interval)); + } + return false; + } +} + +module.exports = { MockBot, md, BlockCtor, GROUND }; diff --git a/test/integration.test.js b/test/integration.test.js new file mode 100644 index 0000000..32ca8f8 --- /dev/null +++ b/test/integration.test.js @@ -0,0 +1,253 @@ +'use strict'; + +/** + * Integration tests — EAFE against a mock mineflayer bot with a real 1.21 + * prismarine world and simplified elytra physics. Runs in real time + * (EAFE loops use real timers); total budget ~2 minutes. + */ +const { test, assert, assertClose, suite } = require('./test-harness'); +const E = require('../src/index.js'); +const ElytraFlight = E.ElytraFlight; +const { PHASE, ErrorCode } = E; +const { MockBot, GROUND } = require('./helpers/mock-bot'); + +const sleep = ms => new Promise(r => setTimeout(r, ms)); + +function phasesSeen(flight) { + const seen = []; + flight.on('phase', p => { if (!seen.includes(p)) seen.push(p); }); + return seen; +} + +/** + * Run physics until the fly() promise settles. IMPORTANT: the condition is + * `_pending === null`, NOT "phase === FAILED" — the phase goes FAILED on + * every failed attempt, but EAFE then schedules a retry and keeps the SAME + * pending promise alive. Stopping the mock's physics at the first FAILED + * starves the retry: the bot sits frozen on the ground, the retry's + * airborne poll never sees the jump, and every retry fails with + * "jump fail" no matter what the real cause was. + */ +async function runFlightUntilSettled(bot, flight, timeoutMs = 90000) { + return bot.stepUntil(() => flight._pending === null, timeoutMs); +} + +suite('Integration: full flight'); + +test('flies 300 m, lands near target (approach/trigger regression)', async () => { + const bot = new MockBot({ startX: 0, startZ: 0, rockets: 40 }); + const flight = new ElytraFlight(bot, { debug: false, cruiseAlt: 130 }); + const seen = phasesSeen(flight); + let resolved = null; + let rejected = null; + + flight.fly(300, 0).then(r => { resolved = r; }, e => { rejected = e; }); + const done = await runFlightUntilSettled(bot, flight, 90000); + + assert(done, `settled within 90s (phase=${flight.phase})`); + assert(flight.phase === PHASE.IDLE, `landed, got phase=${flight.phase}`); + assert(!rejected, `no rejection (got ${rejected && rejected.message})`); + assert(resolved, 'fly() promise resolved'); + assert(resolved.landedAt, 'resolved with landedAt'); + assertClose(resolved.landedAt.x, 300, 40, 'landed near target X'); + assertClose(resolved.landedAt.z, 0, 40, 'landed near target Z'); + assertClose(resolved.landedAt.y, GROUND + 1, 3, 'landed on ground'); + + for (const ph of [PHASE.AUDIT, PHASE.TAKEOFF, PHASE.CLIMBING, PHASE.CRUISING, PHASE.LANDING]) { + assert(seen.includes(ph), `saw phase ${ph} (saw: ${seen.join(',')})`); + } + assert(bot.eafeBlockAtCalls < 500000, `perf guard: ${bot.eafeBlockAtCalls} blockAt calls < 500k`); +}); + +test('fly() rejects IN_FLIGHT during climb; retarget works during cruise', async () => { + const bot = new MockBot({ startX: 0, startZ: 0, rockets: 60 }); + const flight = new ElytraFlight(bot, { cruiseAlt: 130 }); + const raw = flight.fly(400, 0); + const p1 = raw.catch(e => e); + + // wait until climbing + await bot.stepUntil(() => flight.phase === PHASE.CLIMBING, 30000); + const r = await flight.fly(500, 0).catch(e => e); + assert(r instanceof Error, 'second fly() rejected while climbing'); + assert(r.code === ErrorCode.IN_FLIGHT, `code IN_FLIGHT, got ${r.code && r.code}`); + assert(flight._targetX === 400, 'rejected fly() must not retarget the active flight'); + + // retarget mid-cruise returns the SAME pending promise + const arrived = await bot.stepUntil(() => flight.phase === PHASE.CRUISING, 45000); + assert(arrived, 'reached cruise'); + const p2 = flight.fly(300, 0); + assert(p2 === raw, 'retarget returns existing promise'); + + const settled = await runFlightUntilSettled(bot, flight, 90000); + assert(settled && flight.phase === PHASE.IDLE, `settled (phase=${flight.phase})`); + const res = await p1; + assertClose(res.landedAt.x, 300, 40, 'landed at retargeted X'); +}); + +suite('Integration: stop / retry / errors'); + +test('stop() emits stopped exactly once, phase IDLE, rejects with STOPPED', async () => { + const bot = new MockBot({ startX: 0, startZ: 0, rockets: 60 }); + const flight = new ElytraFlight(bot, { cruiseAlt: 130 }); + let stoppedCount = 0; + flight.on('stopped', () => stoppedCount++); + let idleEmitted = false; + flight.on('phase', p => { if (p === PHASE.IDLE) idleEmitted = true; }); + + const p = flight.fly(400, 0).catch(e => e); + await bot.stepUntil(() => flight.phase === PHASE.CLIMBING, 30000); + flight.stop('test'); + + const err = await p; + assert(err.code === ErrorCode.STOPPED, `code STOPPED, got ${err && err.code}`); + assert(stoppedCount === 1, `exactly one 'stopped' event (got ${stoppedCount})`); + assert(idleEmitted, "phase IDLE emitted on stop (consumers must not hang)"); + assert(flight.phase === PHASE.IDLE, 'phase is IDLE'); +}); + +test('stop during pending retry cancels the retry (no re-takeoff)', async () => { + const bot = new MockBot({ startX: 0, startZ: 0, rockets: 40 }); + // Sabotage the jump so takeoff fails -> GROUND_HIT -> retry in 3s + const origStep = bot.step.bind(bot); + bot.step = (dt) => { bot.jump = false; origStep(dt); }; + + const flight = new ElytraFlight(bot, { cruiseAlt: 130, maxRetries: 3 }); + const seen = phasesSeen(flight); + const p = flight.fly(300, 0).catch(e => e); + + // Wait for the first failure + scheduled retry + const failedOnce = await bot.stepUntil(() => flight.phase === PHASE.FAILED, 30000); + assert(failedOnce, 'first attempt failed (jump sabotaged)'); + assert(seen.includes(PHASE.TAKEOFF), 'was in takeoff'); + + await sleep(500); // retry is pending (fires in ~3s) + flight.stop('cancel'); + + // The old bug: retry fired after stop and re-took-off + await sleep(4500); + assert(flight.phase === PHASE.IDLE, `still IDLE after retry window (phase=${flight.phase})`); + const takeoffsAfterStop = bot.chatLog.length; // sanity only + const err = await p; + assert(err.code === ErrorCode.STOPPED, `promise rejected STOPPED, got ${err.code}`); + void takeoffsAfterStop; +}); + +test('fly() before spawn rejects NO_ENTITY without crashing', async () => { + const bot = new MockBot(); + bot.entity = null; + const flight = new ElytraFlight(bot); + const err = await flight.fly(100, 100).catch(e => e); + assert(err.code === ErrorCode.NO_ENTITY, `code NO_ENTITY, got ${err && err.code}`); +}); + +test('retries then rejects with typed RETRIES_EXHAUSTED', async () => { + // 40 rockets so the audit PASSES and the sabotaged jump (a transient + // in-flight failure, NO_FLIGHT_CONFIRM) is what actually gets retried. + // A deterministic precondition failure (e.g. NO_ROCKETS) would fail fast + // with its own code instead. + const bot = new MockBot({ startX: 0, startZ: 0, rockets: 40 }); + const origStep = bot.step.bind(bot); + bot.step = (dt) => { bot.jump = false; origStep(dt); }; + + const flight = new ElytraFlight(bot, { cruiseAlt: 130, maxRetries: 1 }); + const p = flight.fly(300, 0).catch(e => e); + const err = await p; // 1 retry (3s) then exhausted + assert(err.code === ErrorCode.RETRIES_EXHAUSTED, `code RETRIES_EXHAUSTED, got ${err.code}`); + assert(err instanceof E.ElytraFlightError, 'typed error class'); + assert(err.cause === ErrorCode.NO_FLIGHT_CONFIRM, `cause is the last failure code, got ${err.cause}`); + assert(flight.phase === PHASE.FAILED, 'phase FAILED'); +}); + +suite('Integration: inventory & elytra handling'); + +test('mode LOW / MED aliases resolve through constructor and fly()', () => { + const bot = new MockBot(); + const f1 = new ElytraFlight(bot, { mode: 'LOW' }); + assert(f1.mode.name === 'LOW' && f1.mode.speedMps === 10, 'constructor LOW'); + const f2 = new ElytraFlight(bot, { mode: 'MED' }); + assert(f2.mode.name === 'MED' && f2.mode.speedMps === 13, 'constructor MED'); + f2.setMode('LOW'); + assert(f2.mode.name === 'LOW', 'setMode LOW'); + f2.setMode('GOTTA_GO_FAST'); + assert(f2.mode.name === 'LOW', 'unknown mode keeps current (no silent reset)'); +}); + +test('preflight() is pure and returns a consistent shape', async () => { + const bot = new MockBot({ rockets: 50 }); + const flight = new ElytraFlight(bot); + const chestBefore = bot.inventory.slots[6]; + flight.setTarget(200, 0); + const check = await flight.preflight(); + assert(typeof check.ok === 'boolean', 'ok boolean'); + assert(check.elytra && typeof check.elytra.have === 'number', 'elytra shape'); + assert(check.rockets && typeof check.rockets.need === 'number', 'rockets shape'); + assert(bot.inventory.slots[6] === chestBefore, 'no equip side effect'); + assert(check.ok === true, `expected ok with plenty of gear (got reason=${check.reason})`); +}); + +test('preflight() reports unbreaking correctly (U3 detected)', async () => { + const bot = new MockBot({ unbreaking: 3 }); + const flight = new ElytraFlight(bot); + const check = await flight.preflight(); + assert(check.elytra.unbreaking === 3, `U3 detected (got ${check.elytra.unbreaking})`); +}); + +test('worn elytra is swapped from spare inventory', async () => { + const bot = new MockBot({ elytraDur: 5, unbreaking: 0 }); + const spare = { name: 'elytra', count: 1, maxDurability: 432, durabilityUsed: 0, enchants: [] }; + bot.inventory.slots[0] = spare; // no rockets in slot 0 for this test + const flight = new ElytraFlight(bot); + const ok = await flight._ctx.auditAndEquipElytra({ equip: true }); + assert(ok === true, 'swap succeeded'); + assert(bot.inventory.slots[6] === spare, 'fresh elytra equipped'); + assert(bot.inventory.slots[0] !== null || bot.inventory.slots[0].name === 'elytra', 'worn elytra back in bag'); +}); + +test('flowers are skipped by landing spot search (solid detection)', async () => { + const bot = new MockBot({ startX: 0, startZ: 0, features: [ + { x: 10, y: GROUND + 1, z: 0, name: 'poppy' }, // flower on top of the target column + ] }); + const flight = new ElytraFlight(bot); + const spot = flight._ctx.wander.findSafeLandingSpotAround(10, 0); + assert(spot.safe, 'spot safe'); + assert(spot.blockName === 'stone', `ground is stone not poppy (got ${spot.blockName})`); + assert(spot.y === GROUND + 1, `ground height (got ${spot.y})`); +}); + +test('landing on a cactus recovers instead of looping forever', async () => { + // cactus directly under the target column. The old bug: a cactus + // touchdown reset the search timer and looped forever standing on it. + // The bot must end safely: spot search avoids the hazard column, or a + // cactus touchdown relocates — either way it reaches IDLE (or a clean, + // finite failure) and is NOT sitting on the cactus. + const bot = new MockBot({ startX: 0, startZ: 0, rockets: 40, features: [ + { x: 60, y: GROUND + 1, z: 0, name: 'cactus' }, + ] }); + const flight = new ElytraFlight(bot, { cruiseAlt: 130, wanderTimeoutMs: 3000, maxRetries: 3 }); + let resolved = null, rejected = null; + const pp = flight.fly(60, 0).then(r => { resolved = r; }, e => { rejected = e; }); + const settled = await runFlightUntilSettled(bot, flight, 120000); + assert(settled, 'settled (did not loop forever)'); + await pp; // let the fly() promise's settle handlers run + assert(flight.phase === PHASE.IDLE, `recovered to IDLE (phase=${flight.phase})`); + assert(!rejected, `no error (got ${rejected && rejected.code})`); + assert(resolved && resolved.landedAt, 'fly() resolved with landedAt'); + const ex = Math.round(bot.entity.position.x); + assert(!(ex === 60 && Math.abs(bot.entity.position.z) < 1 && bot.entity.position.y <= GROUND + 2), + 'not sitting on the cactus'); +}); + +suite('Integration: fuel & fuel-out'); + +test('out of rockets enters DEADSTICK and still lands', async () => { + const bot = new MockBot({ startX: 0, startZ: 0, rockets: 1 }); + const flight = new ElytraFlight(bot, { cruiseAlt: 130, safety: false }); + const seen = phasesSeen(flight); + const p = flight.fly(300, 0).catch(e => e); + const done = await runFlightUntilSettled(bot, flight, 120000); + assert(done, `settled (phase=${flight.phase})`); + assert(seen.includes(PHASE.DEAD_STICK), `entered DEADSTICK (saw: ${seen.join(',')})`); + const r = await p; + assert(flight.phase === PHASE.IDLE, `landed (phase=${flight.phase})`); + assertClose(r.landedAt.x, 300, 80, 'landed reasonably near target'); +}); diff --git a/test/run.js b/test/run.js new file mode 100644 index 0000000..0c99300 --- /dev/null +++ b/test/run.js @@ -0,0 +1,57 @@ +'use strict'; + +/** + * Zero-dependency test runner: node test/run.js [name-filter] + * Runs every *.test.js in this directory, awaits all tests, exits 1 on failure. + */ +const fs = require('fs'); +const path = require('path'); + +const filter = process.argv[2] || ''; +const files = fs.readdirSync(__dirname) + .filter(f => f.endsWith('.test.js')) + .sort() + .filter(f => f.includes(filter)); + +let passed = 0; +let failed = 0; +const failures = []; +const t0 = Date.now(); + +const harness = { + pass(msg) { + passed++; + console.log(` \u2713 ${msg}`); + }, + fail(msg, err) { + failed++; + failures.push({ msg, err: err && err.message }); + console.log(` \u2717 ${msg}${err ? ` -- ${err.message}` : ''}`); + }, + suite(name) { + console.log(`\n${name}`); + }, +}; + +global.__harness = harness; + +(async () => { + for (const file of files) { + try { + require(path.join(__dirname, file)); + } catch (err) { + harness.fail(`suite load: ${file}`, err); + } + // let this file's registered tests settle before loading the next one + // (keeps per-file timing honest for slow integration suites) + await Promise.allSettled(require(path.join(__dirname, 'test-harness')).pending.splice(0)); + } + + const ms = Date.now() - t0; + console.log(`\n${passed} passed, ${failed} failed (${(ms / 1000).toFixed(1)}s)`); + if (failed > 0) { + console.log('\nFailures:'); + for (const f of failures) console.log(` - ${f.msg}${f.err ? `: ${f.err}` : ''}`); + process.exit(1); + } +})(); diff --git a/test/smoke-flight.js b/test/smoke-flight.js new file mode 100644 index 0000000..88cbc89 --- /dev/null +++ b/test/smoke-flight.js @@ -0,0 +1,24 @@ +'use strict'; +// quick smoke: full 300m flight +const { ElytraFlight, PHASE } = require('../src/index.js'); +const { MockBot } = require('./helpers/mock-bot'); + +(async () => { + const bot = new MockBot({ startX: 0, startZ: 0, rockets: 40 }); + const flight = new ElytraFlight(bot, { debug: false, cruiseAlt: 130 }); + const seen = []; + flight.on('phase', (p, m) => { if (!seen.includes(p)) seen.push(p); console.log(` phase ${p} ${m || ''}`); }); + + const p = flight.fly(300, 0); + const t0 = Date.now(); + await bot.stepUntil(() => flight.phase === PHASE.IDLE || flight.phase === PHASE.FAILED, 90000); + try { + const res = await p; + console.log(`LANDED in ${((Date.now() - t0) / 1000).toFixed(1)}s at`, res.landedAt, `target (300,0) err=${Math.hypot(res.landedAt.x - 300, res.landedAt.z).toFixed(1)}m`); + console.log('blockAt calls:', bot.eafeBlockAtCalls); + } catch (e) { + console.log('FAILED:', e.code, e.message, `phase=${flight.phase} after ${((Date.now() - t0) / 1000).toFixed(1)}s`); + console.log('pos:', bot.entity.position, 'phases:', seen.join(',')); + } + process.exit(0); +})(); diff --git a/test/test-harness.js b/test/test-harness.js new file mode 100644 index 0000000..a66ed51 --- /dev/null +++ b/test/test-harness.js @@ -0,0 +1,26 @@ +'use strict'; + +const { suite, pass, fail } = global.__harness; + +const pending = []; + +function test(name, fn) { + const p = Promise.resolve() + .then(() => fn()) + .then(() => pass(name)) + .catch(err => fail(name, err)); + pending.push(p); + return p; +} + +function assert(cond, msg = 'assertion failed') { + if (!cond) throw new Error(msg); +} + +function assertClose(actual, expected, tol, msg) { + if (Math.abs(actual - expected) > tol) { + throw new Error(`${msg || 'not close'}: expected ${expected} ±${tol}, got ${actual}`); + } +} + +module.exports = { test, assert, assertClose, suite, pending }; diff --git a/test/unit.test.js b/test/unit.test.js new file mode 100644 index 0000000..bc48120 --- /dev/null +++ b/test/unit.test.js @@ -0,0 +1,150 @@ +'use strict'; + +const { test, assert, assertClose, suite } = require('./test-harness'); +const E = require('../src/index.js'); +const { MODES, PHASE, ErrorCode, ElytraFlightError } = E; +const { + isAir, isHazardousBlock, hasCollision, isSafeSolidBlock, isLandingSurface, angleDiff, +} = E; +const { + getUnbreakingLevel, getElytraDamageRate, calculateRequiredElytraDurability, +} = E; +const { countRockets, getRocketSummary } = E; + +const { md, BlockCtor } = require('./helpers/mock-bot'); +function B(name) { + const be = md.blocksByName[name]; + if (!be) throw new Error('no block ' + name); + return BlockCtor.fromStateId(be.minStateId, 0); +} + +suite('Unit: constants & modes'); + +test('mode aliases resolve (LOW->EFFICIENT, MED->MEDIUM)', () => { + assert(MODES.LOW === MODES.EFFICIENT, 'LOW alias'); + assert(MODES.MED === MODES.MEDIUM, 'MED alias'); + assert(MODES.FAST, 'FAST exists'); +}); + +test('phase values are the documented short names', () => { + assert(PHASE.CRUISING === 'CRUISE', 'CRUISE'); + assert(PHASE.CLIMBING === 'CLIMB', 'CLIMB'); + assert(PHASE.LANDING === 'LAND', 'LAND'); + assert(PHASE.FAILED === 'FAIL', 'FAIL'); +}); + +test('error codes are a stable frozen set', () => { + assert(Object.isFrozen(ErrorCode), 'frozen'); + for (const c of ['NO_ELYTRA', 'NO_ROCKETS', 'STOPPED', 'RESPAWN', 'NO_SAFE_SPOT', 'IN_FLIGHT', 'RETRIES_EXHAUSTED']) { + assert(ErrorCode[c] === c, `code ${c}`); + } +}); + +test('ElytraFlightError carries code', () => { + const e = new ElytraFlightError(ErrorCode.NO_ROCKETS, 'need 5 rkt, have 0'); + assert(e instanceof Error, 'is Error'); + assert(e.code === 'NO_ROCKETS', 'code set'); + assert(e.message.includes('need 5'), 'message kept'); +}); + +suite('Unit: block classification (real 1.21 data)'); + +test('isAir', () => { + assert(isAir(B('air')), 'air'); + assert(isAir(null), 'null'); + assert(!isAir(B('stone')), 'stone'); +}); + +test('isHazardousBlock: exact names only (no substring false positives)', () => { + assert(isHazardousBlock(B('water')), 'water'); + assert(isHazardousBlock(B('lava')), 'lava'); + assert(isHazardousBlock(B('cactus')), 'cactus'); + assert(isHazardousBlock(B('powder_snow')), 'powder_snow'); + assert(isHazardousBlock(null), 'null unsafe'); + assert(!isHazardousBlock(B('stone')), 'stone'); + // The old substring match flagged water_strainer — a safe solid block. + const ws = md.blocksByName.water_strainer; + if (ws) assert(!isHazardousBlock(BlockCtor.fromStateId(ws.minStateId, 0)), 'water_strainer NOT hazard'); +}); + +test('hasCollision / isSafeSolidBlock reject pass-through blocks', () => { + assert(hasCollision(B('stone')), 'stone'); + assert(hasCollision(B('glass')), 'glass'); + assert(!hasCollision(B('poppy')), 'poppy'); + assert(!hasCollision(B('oak_sapling')), 'sapling'); + assert(!hasCollision(B('torch')), 'torch'); + assert(!hasCollision(B('tall_grass')), 'tall grass'); + assert(!hasCollision(B('water')), 'water'); + assert(isSafeSolidBlock(B('stone')), 'stone safe'); + assert(!isSafeSolidBlock(B('poppy')), 'poppy not safe'); + assert(!isSafeSolidBlock(B('torch')), 'torch not safe'); +}); + +test('isLandingSurface requires a full-cube top', () => { + assert(isLandingSurface(B('stone')), 'stone'); + assert(!isLandingSurface(B('poppy')), 'poppy'); + const slab = B('oak_slab'); // [0,0.5,0,1,1,1] default state = not a full cube top + assert(!isLandingSurface(slab), 'half slab not full-cube'); +}); + +test('angleDiff wraps correctly', () => { + assertClose(angleDiff(0, 0), 0, 1e-9); + assertClose(angleDiff(Math.PI, -Math.PI), 0, 1e-9, 'antipodal wrap'); + assertClose(angleDiff(Math.PI / 2, 0), Math.PI / 2, 1e-9); +}); + +suite('Unit: elytra math'); + +test('unbreaking detection across mineflayer item shapes', () => { + assert(getUnbreakingLevel({ enchants: [{ name: 'unbreaking', lvl: 3 }] }) === 3, 'pre-1.20.5 array name'); + assert(getUnbreakingLevel({ enchants: [{ id: 'minecraft:unbreaking', lvl: 4 }] }) === 4, '1.20.5+ component id'); + assert(getUnbreakingLevel({ enchants: [{ id: 34, lvl: 2 }] }) === 2, 'numeric id'); + assert(getUnbreakingLevel({ enchants: [] }) === 0, 'none'); + assert(getUnbreakingLevel(null) === 0, 'null'); + // raw NBT shape: { value: { Enchantments: { value: { value: [{ id: 34, lvl: 3 }] } } } } + const nbtItem = { nbt: { value: { Enchantments: { value: { value: [{ id: 34, lvl: 3 }] } } } } }; + assert(getUnbreakingLevel(nbtItem) === 3, 'raw NBT'); +}); + +test('damage rate = 2/(n+3), monotonically decreasing, U4 handled', () => { + assertClose(getElytraDamageRate(0), 1.0, 1e-9); + assertClose(getElytraDamageRate(1), 0.5, 1e-9); + assertClose(getElytraDamageRate(2), 2 / 5, 1e-9); + assertClose(getElytraDamageRate(3), 1 / 3, 1e-9); + assertClose(getElytraDamageRate(4), 2 / 7, 1e-9, 'U4 (old code returned 1.0!)'); + assert(getElytraDamageRate(5) < getElytraDamageRate(4), 'U5 < U4'); +}); + +test('required durability scales with distance and unbreaking', () => { + const base = calculateRequiredElytraDurability(1000, 13, 0); + const u3 = calculateRequiredElytraDurability(1000, 13, 3); + assert(u3 < base, 'U3 needs less'); + assert(base > 0, 'positive'); + assert(calculateRequiredElytraDurability(2000, 13, 0) > base, 'farther = more'); +}); + +suite('Unit: rockets'); + +test('countRockets excludes custom stars by default', () => { + const fakeBot = { inventory: { slots: new Array(46).fill(null) } }; + fakeBot.inventory.slots[0] = { name: 'firework_rocket', count: 5 }; + fakeBot.inventory.slots[1] = { + name: 'firework_rocket', count: 3, + nbt: { value: { Fireworks: { value: { Explosions: [{}] } } } }, + }; + assert(countRockets(fakeBot) === 5, 'plain only'); + assert(countRockets(fakeBot, { includeCustom: true }) === 8, 'with custom'); + const s = getRocketSummary(fakeBot); + assert(s.plain === 5 && s.custom === 3 && s.total === 8, 'summary'); +}); + +test('calculateRequiredRockets shape (real ctx)', () => { + const { MockBot } = require('./helpers/mock-bot'); + const bot = new MockBot(); + const flight = new E(bot); + const calc = flight._ctx.calculateRequiredRockets; + assert(calc(0, 0) === 12 + flight.opts.maxRetries * 3, 'baseline margin 12 + 3*retries'); + assert(calc(200, 0) > calc(60, 0), 'distance adds'); + assert(calc(0, 100) > calc(0, 0), 'climb adds'); + assert(calc(0, -100) === calc(0, 100), 'descend symmetric'); +});