### Install prismarine-viewer Source: https://github.com/prismarinejs/prismarine-viewer/blob/master/README.md Install the prismarine-viewer package using npm. ```bash npm install prismarine-viewer ``` -------------------------------- ### Basic Mineflayer Bot Viewer Setup Source: https://github.com/prismarinejs/prismarine-viewer/blob/master/README.md Integrates prismarine-viewer with a mineflayer bot to visualize its surroundings. Starts a web server on port 3000 and draws the bot's movement path. ```javascript const mineflayer = require('mineflayer') const mineflayerViewer = require('prismarine-viewer').mineflayer const bot = mineflayer.createBot({ username: 'Bot' }) bot.once('spawn', () => { mineflayerViewer(bot, { port: 3000 }) // Start the viewing server on port 3000 // Draw the path followed by the bot const path = [bot.entity.position.clone()] bot.on('move', () => { if (path[path.length - 1].distanceTo(bot.entity.position) > 1) { path.push(bot.entity.position.clone()) bot.viewer.drawLine('path', path) } }) }) ``` -------------------------------- ### standalone(options) Source: https://context7.com/prismarinejs/prismarine-viewer/llms.txt Starts a web viewer that renders any `prismarine-world` instance without requiring a bot. Returns a viewer object with an `update()` method. ```APIDOC ## `standalone(options)` — Render a world without a bot Starts a web viewer that renders any `prismarine-world` instance, with no bot required. Returns a `viewer` object with an `update()` method to push new chunk data to connected clients. Useful for visualizing procedurally generated worlds or replays. ### Parameters #### Options - **version** (string) - Required - Minecraft version string (default: '1.13.2'). - **world** (object) - Required - A prismarine-world instance. - **center** (Vec3) - Optional - Camera center position (default: Vec3(0,0,0)). - **viewDistance** (number) - Optional - Chunk radius (default: 4). - **port** (number) - Optional - HTTP port (default: 3000). ### Request Example ```javascript const viewer = standaloneViewer({ version: '1.16.4', world: world, center: new Vec3(0, 51, 0), viewDistance: 6, port: 3000 }) // After modifying the world, call update() to push changes to clients viewer.update() ``` ``` -------------------------------- ### Initialize and Render with Viewer Class Source: https://context7.com/prismarinejs/prismarine-viewer/llms.txt Sets up a Three.js renderer, initializes the Viewer with a specific Minecraft version, configures lighting and camera, and starts the render loop. Requires a DOM element for the renderer. ```javascript const THREE = require('three') const { Viewer, WorldView } = require('prismarine-viewer').viewer const { Vec3 } = require('vec3') // Set up a Three.js renderer (browser context) const renderer = new THREE.WebGLRenderer() renderer.setSize(window.innerWidth, window.innerHeight) document.body.appendChild(renderer.domElement) const viewer = new Viewer(renderer) // Set the Minecraft version (returns false if unsupported) if (!viewer.setVersion('1.18.1')) { throw new Error('Version not supported') } // Adjust lighting viewer.ambientLight.intensity = 0.8 viewer.directionalLight.intensity = 0.6 // Position the first-person camera viewer.setFirstPersonCamera(new Vec3(0, 65, 0), Math.PI, 0) // pos, yaw, pitch // Wire up a WorldView to stream chunks into the Viewer const worldView = new WorldView(world, 4, new Vec3(0, 64, 0)) viewer.listen(worldView) worldView.init(new Vec3(0, 64, 0)) // Render loop ;(function animate () { requestAnimationFrame(animate) viewer.update() // must be called every frame renderer.render(viewer.scene, viewer.camera) })() // Wait until all pending chunks have been meshed viewer.waitForChunksToRender().then(() => { console.log('All chunks rendered') }) ``` -------------------------------- ### Standalone World Viewer Setup Source: https://github.com/prismarinejs/prismarine-viewer/blob/master/README.md Sets up a web server to visualize a Minecraft world without a bot. Allows customization of version, world generation, and view distance. ```javascript const { standalone } = require('prismarine-viewer') ``` -------------------------------- ### Render a world without a bot using standalone(options) Source: https://context7.com/prismarinejs/prismarine-viewer/llms.txt Starts a web viewer for a `prismarine-world` instance without a bot. Useful for visualizing procedurally generated worlds or replays. Requires `prismarine-world`. ```javascript const standaloneViewer = require('prismarine-viewer').standalone const { Vec3 } = require('vec3') const version = '1.16.4' const World = require('prismarine-world')(version) const Chunk = require('prismarine-chunk')(version) // A flat stone world generator const world = new World((chunkX, chunkZ) => { const chunk = new Chunk() for (let x = 0; x < 16; x++) { for (let z = 0; z < 16; z++) { chunk.setBlockStateId(new Vec3(x, 0, z), 1) // stone at y=0 } } return chunk }) const viewer = standaloneViewer({ version, // Minecraft version string (default: '1.13.2') world, // prismarine-world instance center: new Vec3(0, 51, 0), // camera center position (default: Vec3(0,0,0)) viewDistance: 6, // chunk radius (default: 4) port: 3000 // HTTP port (default: 3000) }) // After modifying the world, call update() to push changes to clients ;(async () => { await world.setBlockStateId(new Vec3(0, 1, 0), 2) // place grass viewer.update() console.log('World updated, visit http://localhost:3000') })() ``` -------------------------------- ### standalone Visualization Source: https://github.com/prismarinejs/prismarine-viewer/blob/master/README.md Starts a web server to visualize a Minecraft world without a bot. Allows for custom world generation and view centering. ```APIDOC ## standalone Serve a webserver allowing to visualize a world. ```js const { standalone } = require('prismarine-viewer') ``` ### Options * `version` the version to use, default: `1.13.2` * `generator` a world generator function, default: `(x, y, z) => 0` * `center` a vec3 to center the view on, default: `new Vec3(0, 0, 0)` * `viewDistance` view radius, in chunks, default: `6` * `port` the port for the webserver, default: `3000` [example](https://github.com/PrismarineJS/prismarine-viewer/blob/master/examples/standalone.js) ``` -------------------------------- ### Generate Screenshots and 3D Models Source: https://github.com/prismarinejs/prismarine-viewer/blob/master/examples/exporter/README.md Run `node screenshot.js` to generate screenshots or `node 3dmodel.js` to generate 3D models. Ensure you have installed the necessary dependencies by running `npm install` in the exporter directory. ```bash npm install ``` ```bash node screenshot.js ``` ```bash node 3dmodel.js ``` -------------------------------- ### mineflayer(bot, options) Source: https://context7.com/prismarinejs/prismarine-viewer/llms.txt Starts an Express + Socket.IO web server that streams the bot's world, position, and entity data to any connected browser. Attaches `bot.viewer` as an EventEmitter with drawing methods. Visit `http://localhost:` in a browser to see the live view. ```APIDOC ## mineflayer(bot, options) — Attach a live viewer to a mineflayer bot ### Description Starts an Express + Socket.IO web server that streams the bot's world, position, and entity data to any connected browser. Attaches `bot.viewer` as an EventEmitter with drawing methods. Visit `http://localhost:` in a browser to see the live view. ### Parameters #### Path Parameters None #### Query Parameters - **port** (number) - Optional - HTTP port for the web server (default: 3000) - **viewDistance** (number) - Optional - Chunk view radius (default: 6) - **firstPerson** (boolean) - Optional - true = first-person camera (default: false) - **prefix** (string) - Optional - URL path prefix (default: '') ### Request Example ```javascript const mineflayer = require('mineflayer') const mineflayerViewer = require('prismarine-viewer').mineflayer const bot = mineflayer.createBot({ username: 'Bot', host: 'localhost', port: 25565 }) bot.once('spawn', () => { // Start viewer on port 3000, third-person, 6-chunk view radius mineflayerViewer(bot, { port: 3000, viewDistance: 6, firstPerson: false, prefix: '' }) // bot.viewer is now available as an EventEmitter console.log('Viewer running at http://localhost:3000') // Track and draw the bot's movement path const path = [bot.entity.position.clone()] bot.on('move', () => { if (path[path.length - 1].distanceTo(bot.entity.position) > 1) { path.push(bot.entity.position.clone()) bot.viewer.drawLine('path', path, 0x00ff00) // green line } }) // Stop the server when done // bot.viewer.close() }) ``` ### Response #### Success Response (200) None explicitly documented. #### Response Example None explicitly documented. ``` -------------------------------- ### mineflayer Integration Source: https://github.com/prismarinejs/prismarine-viewer/blob/master/README.md Integrates prismarine-viewer with a mineflayer bot to visualize the bot's surroundings. It starts a web server to display the view. ```APIDOC ## mineflayer Serve a webserver allowing to visualize the bot surrounding, in first or third person. Comes with drawing functionnalities. ```js const { mineflayer } = require('prismarine-viewer') ``` ### Options * `viewDistance` view radius, in chunks, default: `6` * `firstPerson` is the view first person ? default: `false` * `port` the port for the webserver, default: `3000` [example](https://github.com/PrismarineJS/prismarine-viewer/blob/master/examples/bot.js) ``` -------------------------------- ### Attach mineflayer viewer to a bot Source: https://context7.com/prismarinejs/prismarine-viewer/llms.txt Starts an Express + Socket.IO web server to stream bot world data to a browser. The bot.viewer EventEmitter is attached with drawing methods. Visit http://localhost: to see the live view. ```javascript const mineflayer = require('mineflayer') const mineflayerViewer = require('prismarine-viewer').mineflayer const bot = mineflayer.createBot({ username: 'Bot', host: 'localhost', port: 25565 }) bot.once('spawn', () => { // Start viewer on port 3000, third-person, 6-chunk view radius mineflayerViewer(bot, { port: 3000, // HTTP port for the web server (default: 3000) viewDistance: 6, // Chunk view radius (default: 6) firstPerson: false, // true = first-person camera (default: false) prefix: '' // URL path prefix (default: '') }) // bot.viewer is now available as an EventEmitter console.log('Viewer running at http://localhost:3000') // Track and draw the bot's movement path const path = [bot.entity.position.clone()] bot.on('move', () => { if (path[path.length - 1].distanceTo(bot.entity.position) > 1) { path.push(bot.entity.position.clone()) bot.viewer.drawLine('path', path, 0x00ff00) // green line } }) // Stop the server when done // bot.viewer.close() }) ``` -------------------------------- ### bot.viewer.drawBoxGrid(id, start, end, color) Source: https://context7.com/prismarinejs/prismarine-viewer/llms.txt Renders an axis-aligned box grid outline between two corner positions. Useful for selection regions or area highlights. `start` and `end` are plain objects with `x`, `y`, `z` number properties; `color` is a CSS color string (default `'aqua'`). ```APIDOC ## bot.viewer.drawBoxGrid(id, start, end, color) — Draw a wireframe bounding box ### Description Renders an axis-aligned box grid outline between two corner positions. Useful for selection regions or area highlights. `start` and `end` are plain objects with `x`, `y`, `z` number properties; `color` is a CSS color string (default `'aqua'`). ### Method POST (implied by drawing operation) ### Endpoint `/viewer/drawBoxGrid` (implied) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **id** (string) - Required - Unique identifier for the box grid. - **start** (object) - Required - An object with `x`, `y`, `z` number properties representing the starting corner. - **end** (object) - Required - An object with `x`, `y`, `z` number properties representing the ending corner. - **color** (string) - Optional - CSS color string (default: `'aqua'`). ### Request Example ```javascript bot.once('spawn', () => { mineflayerViewer(bot, { port: 3000 }) // Draw a selection box (e.g. after the user right-clicks two blocks) const pos1 = bot.entity.position.floored() const pos2 = bot.entity.position.offset(5, 3, 5).floored() bot.viewer.drawBoxGrid('selection', { x: Math.min(pos1.x, pos2.x), y: Math.min(pos1.y, pos2.y), z: Math.min(pos1.z, pos2.z) }, { x: Math.max(pos1.x, pos2.x) + 1, y: Math.max(pos1.y, pos2.y) + 1, z: Math.max(pos1.z, pos2.z) + 1 }, 'lime') }) ``` ### Response #### Success Response (200) None explicitly documented. #### Response Example None explicitly documented. ``` -------------------------------- ### headless Source: https://github.com/prismarinejs/prismarine-viewer/blob/master/README.md Render the bot view and stream it to a file or over TCP. ```APIDOC ## headless ### Description Render the bot view and stream it to a file or over TCP. ### Usage ```js const { headless } = require('prismarine-viewer') ``` ### Options * `viewDistance` (number) - View radius, in chunks, default: `6` * `output` (string) - The output file or a `host:port` address to stream to, default: `output.mp4` * `frames` (number) - Number of frames to record, `-1` for infinite, default: `200` * `width` (number) - The width of a frame, default: `512` * `height` (number) - The height of a frame, default: `512` ``` -------------------------------- ### Import Headless Mode Source: https://github.com/prismarinejs/prismarine-viewer/blob/master/README.md Import the headless function from the prismarine-viewer library. This is used for rendering bot views to files or over TCP. ```javascript const { headless } = require('prismarine-viewer') ``` -------------------------------- ### Import mineflayer viewer module Source: https://github.com/prismarinejs/prismarine-viewer/blob/master/README.md Import the mineflayer viewer functionality from the prismarine-viewer package. ```javascript const { mineflayer } = require('prismarine-viewer') ``` -------------------------------- ### Record bot's view to video with headless(bot, options) Source: https://context7.com/prismarinejs/prismarine-viewer/llms.txt Performs server-side rendering and pipes frames to FFmpeg for video recording or streaming. Requires `node-canvas-webgl`. Returns FFmpeg process or false if unsupported. ```javascript // Requires: npm install PrismarineJS/node-canvas-webgl try { require('node-canvas-webgl') } catch (e) { throw Error('node-canvas-webgl required') } const mineflayer = require('mineflayer') const headlessViewer = require('prismarine-viewer').headless const bot = mineflayer.createBot({ username: 'Recorder' }) bot.once('spawn', () => { // Record 300 frames (≈5 seconds at ~60fps) at 1280x720 to an MP4 file const client = headlessViewer(bot, { output: 'recording.mp4', // file path, 'host:port' for TCP, or 'rtmp://...' for RTMP frames: 300, // number of frames (-1 = infinite, default: 200) width: 1280, // frame width in pixels (default: 512) height: 720, // frame height in pixels (default: 512) viewDistance: 4, // chunk view radius (default: 6) logFFMPEG: true, // log ffmpeg stdout/stderr (default: false) jpegOptions: { quality: 0.9 } // node-canvas JPEG options }) if (!client) { console.error('Unsupported Minecraft version') return } client.on('close', () => console.log('Recording finished: recording.mp4')) bot.setControlState('forward', true) // move the bot while recording }) ``` -------------------------------- ### headless(bot, options) Source: https://context7.com/prismarinejs/prismarine-viewer/llms.txt Performs server-side rendering using `node-canvas-webgl` and pipes frames to FFmpeg for video recording or streaming. ```APIDOC ## `headless(bot, options)` — Record the bot's view to a video file or stream Performs server-side (headless) rendering using `node-canvas-webgl` and pipes frames to FFmpeg, producing an MP4 file, an RTMP stream, or a raw JPEG frame stream over TCP. Returns the FFmpeg child process or TCP socket, or `false` if the version is unsupported. ### Parameters #### Options - **output** (string) - Required - File path, 'host:port' for TCP, or 'rtmp://...' for RTMP. - **frames** (number) - Optional - Number of frames (-1 = infinite, default: 200). - **width** (number) - Optional - Frame width in pixels (default: 512). - **height** (number) - Optional - Frame height in pixels (default: 512). - **viewDistance** (number) - Optional - Chunk view radius (default: 6). - **logFFMPEG** (boolean) - Optional - Log ffmpeg stdout/stderr (default: false). - **jpegOptions** (object) - Optional - node-canvas JPEG options. - **quality** (number) - JPEG quality (0.9). ### Request Example ```javascript const client = headlessViewer(bot, { output: 'recording.mp4', frames: 300, width: 1280, height: 720, viewDistance: 4, logFFMPEG: true, jpegOptions: { quality: 0.9 } }) ``` ``` -------------------------------- ### Run in Headless Environment Source: https://github.com/prismarinejs/prismarine-viewer/blob/master/examples/exporter/README.md To execute the 3D model generation script in a headless environment, use `xvfb-run` with the specified display options. This is useful for running on servers without a graphical interface. ```bash xvfb-run -s "-ac -screen 0 1280x1024x24" node 3dmodel.js ``` -------------------------------- ### Initialize and Manage WorldView Source: https://context7.com/prismarinejs/prismarine-viewer/llms.txt Demonstrates standalone usage of WorldView for managing chunks and handling world events. Can be initialized with a position and updated to load/unload chunks. Supports listening to bot events or remote sockets. ```javascript const { WorldView } = require('prismarine-viewer').viewer const { Vec3 } = require('vec3') // Standalone usage: WorldView as its own emitter const worldView = new WorldView( world, // prismarine-world instance 6, // viewDistance in chunks new Vec3(0, 64, 0), // initial camera position null // emitter: null = use self; pass a socket.io socket for remote ) // Initialize: loads all chunks in view radius await worldView.init(new Vec3(0, 64, 0)) // Move the camera — unloads out-of-range chunks, loads new ones await worldView.updatePosition(new Vec3(16, 64, 0)) // Attach to a mineflayer bot for automatic chunk and entity sync worldView.listenToBot(bot) // Listen for block click raycasts worldView.on('blockClicked', (block, face, button) => { console.log(`Block clicked at ${block.position}, face ${face}, button ${button}`) }) // Detach from the bot (e.g. on socket disconnect) worldView.removeListenersFromBot(bot) ``` -------------------------------- ### Configure MapControls for Camera Interaction Source: https://context7.com/prismarinejs/prismarine-viewer/llms.txt Sets up interactive third-person camera controls with customizable key bindings and movement speeds. Requires a Three.js camera and renderer's DOM element. Damping can be enabled for smoother movement. ```javascript const { MapControls } = require('prismarine-viewer').viewer const THREE = require('three') const renderer = new THREE.WebGLRenderer() renderer.setSize(window.innerWidth, window.innerHeight) document.body.appendChild(renderer.domElement) const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000) camera.position.set(0, 80, 0) const controls = new MapControls(camera, renderer.domElement) // Customize key bindings controls.controlMap = { MOVE_FORWARD: ['KeyW', 'ArrowUp'], MOVE_BACKWARD: ['KeyS', 'ArrowDown'], MOVE_LEFT: ['KeyA', 'ArrowLeft'], MOVE_RIGHT: ['KeyD', 'ArrowRight'], MOVE_DOWN: 'ShiftLeft', MOVE_UP: 'Space' } // Tune movement speed controls.keyPanSpeed = 15 controls.keyPanDistance = 40 controls.verticalTranslationSpeed = 0.8 // Set orbit center to a specific block controls.setRotationOrigin(new THREE.Vector3(0, 64, 0)) // Enable damping (inertia) controls.enableDamping = true controls.dampingFactor = 0.05 // Save and restore camera state controls.saveState() // ... later: // controls.reset() // Disable DOM event listeners when not needed // controls.unregisterHandlers() // controls.registerHandlers() ;(function animate () { requestAnimationFrame(animate) controls.update() // must call in render loop when damping is enabled renderer.render(scene, camera) })() ``` -------------------------------- ### Draw a point cloud in the viewer Source: https://context7.com/prismarinejs/prismarine-viewer/llms.txt Renders floating point markers at given world positions. Useful for visualizing pathfinding nodes or scan results. Color and size are optional. ```javascript bot.once('spawn', () => { mineflayerViewer(bot, { port: 3000 }) const { Vec3 } = require('vec3') // Highlight blocks in a 3x3 area around the bot const positions = [] for (let dx = -1; dx <= 1; dx++) { for (let dz = -1; dz <= 1; dz++) { positions.push(bot.entity.position.offset(dx, 0, dz)) } } bot.viewer.drawPoints('scanArea', positions, 0xffff00, 8) // yellow, size 8 }) ``` -------------------------------- ### bot.viewer.drawPoints(id, points, color, size) Source: https://context7.com/prismarinejs/prismarine-viewer/llms.txt Renders a set of floating point markers at the given world positions. Useful for visualizing pathfinding nodes, scan results, or block targets. All parameters after `id` are optional; `color` defaults to `0xff0000` and `size` defaults to `5`. ```APIDOC ## bot.viewer.drawPoints(id, points, color, size) — Draw a point cloud ### Description Renders a set of floating point markers at the given world positions. Useful for visualizing pathfinding nodes, scan results, or block targets. All parameters after `id` are optional; `color` defaults to `0xff0000` and `size` defaults to `5`. ### Method POST (implied by drawing operation) ### Endpoint `/viewer/drawPoints` (implied) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **id** (string) - Required - Unique identifier for the points. - **points** (Array) - Required - An array of `Vec3` objects representing the positions of the points. - **color** (number) - Optional - Hexadecimal color integer (default: `0xff0000`). - **size** (number) - Optional - Size of the markers (default: `5`). ### Request Example ```javascript bot.once('spawn', () => { mineflayerViewer(bot, { port: 3000 }) const { Vec3 } = require('vec3') // Highlight blocks in a 3x3 area around the bot const positions = [] for (let dx = -1; dx <= 1; dx++) { for (let dz = -1; dz <= 1; dz++) { positions.push(bot.entity.position.offset(dx, 0, dz)) } } bot.viewer.drawPoints('scanArea', positions, 0xffff00, 8) // yellow, size 8 }) ``` ### Response #### Success Response (200) None explicitly documented. #### Response Example None explicitly documented. ``` -------------------------------- ### Viewer Class Source: https://github.com/prismarinejs/prismarine-viewer/blob/master/viewer/README.md The Viewer class provides methods to render a Minecraft world using a three.js renderer. ```APIDOC ## Viewer(renderer) ### Description Builds the viewer instance. ### Parameters * renderer (WebGLRenderer) - A [WebGLRenderer](https://threejs.org/docs/#api/en/renderers/WebGLRenderer) instance. ``` ```APIDOC ## version ### Description Gets the currently used Minecraft version. ### Returns string - The current Minecraft version. ``` ```APIDOC ## setVersion(version) ### Description Sets the Minecraft version for the viewer. ### Parameters * version (string) - The desired Minecraft version (e.g., "1.16.4"). ### Returns boolean - Returns false if the version is not supported. ``` ```APIDOC ## addColumn(x, z, chunk) ### Description Adds a world column to the viewer. ### Parameters * x (number) - The chunk's x position. * z (number) - The chunk's z position. * chunk (object) - The prismarine-chunk object to add. ``` ```APIDOC ## removeColumn(x, z) ### Description Removes a world column from the viewer. ### Parameters * x (number) - The chunk's x position. * z (number) - The chunk's z position. ``` ```APIDOC ## setBlockStateId(pos, stateId) ### Description Sets the state ID for a block at a specific position. ### Parameters * pos (Vec3) - The position of the block. * stateId (number) - The new state ID for the block. ``` ```APIDOC ## updateEntity(e) ### Description Updates an entity in the viewer. ### Parameters * e (object) - The prismarine-entity object to update. ``` ```APIDOC ## updatePrimitive(p) ### Description Updates a Three.js primitive in the viewer. ### Parameters * p (object) - The Three.js primitive object to update. ``` ```APIDOC ## setFirstPersonCamera(pos, yaw, pitch) ### Description Sets the first-person camera's position, yaw, and pitch. ### Parameters * pos (Vec3 | null) - The new position for the camera. If null, only yaw and pitch are updated. * yaw (number) - The yaw angle in degrees. * pitch (number) - The pitch angle in degrees. ``` ```APIDOC ## listen(emitter) ### Description Listens to an emitter for world modification events and applies them. ### Parameters * emitter (object) - The event emitter to listen to. Expected events: 'entity(e)', 'primitive(p)', 'loadChunk({x, z, chunk})', 'unloadChunk({x, z})', 'blockUpdate({pos, stateId})', 'mouseClick({ origin, direction, button }). ``` ```APIDOC ## update() ### Description Updates the world. This method should be called in the animation loop before rendering. ``` ```APIDOC ## waitForChunksToRender() ### Description Returns a promise that resolves when all marked dirty chunks have been rendered by worker threads. Useful for waiting for chunks to appear. ### Returns Promise - A promise that resolves when rendering is complete. ``` -------------------------------- ### bot.viewer.close Source: https://github.com/prismarinejs/prismarine-viewer/blob/master/README.md Stop the server and disconnect users. ```APIDOC ## bot.viewer.close ### Description Stop the server and disconnect users. ``` -------------------------------- ### List Supported Minecraft Versions Source: https://context7.com/prismarinejs/prismarine-viewer/llms.txt Access the `supportedVersions` array to validate user input or enumerate available Minecraft versions for the viewer. The `setVersion()` function automatically maps unsupported patch versions to the nearest supported version in the same minor series. ```javascript const { supportedVersions } = require('prismarine-viewer') console.log(supportedVersions) // ['1.8.8', '1.9.4', '1.10.2', '1.11.2', '1.12.2', '1.13.2', // '1.14.4', '1.15.2', '1.16.1', '1.16.4', '1.17.1', '1.18.1', // '1.19', '1.20.1', '1.21.1', '1.21.4'] const userVersion = '1.18.0' if (supportedVersions.includes(userVersion)) { console.log('Exact match') } else { // The Viewer's setVersion() automatically maps unsupported patch versions // to the nearest supported version in the same minor series: // e.g. '1.18.0' → '1.18.1', '1.16.3' → '1.16.4' console.log('Will be mapped to nearest supported version') } ``` -------------------------------- ### Draw Line with Prismarine Viewer Source: https://github.com/prismarinejs/prismarine-viewer/blob/master/README.md Draw a line on the viewer by providing a unique ID, an array of points, and an optional color. The ID can be used later to erase the primitive. ```javascript bot.viewer.drawLine(id, points, color=0xff0000) ``` -------------------------------- ### MapControls Class - Interactive third-person camera controls Source: https://context7.com/prismarinejs/prismarine-viewer/llms.txt Provides Minecraft-style keyboard and mouse orbit/pan/zoom controls for the Three.js camera in a browser context. ```APIDOC ## MapControls Class - Interactive third-person camera controls ### Description Provides Minecraft-style keyboard and mouse orbit/pan/zoom controls for the Three.js camera in a browser context. Keyboard defaults: W/Z = forward, S = back, A/Q = left, D = right, Space = up, Shift = down. ### Usage Example ```js const { MapControls } = require('prismarine-viewer').viewer const THREE = require('three') const renderer = new THREE.WebGLRenderer() renderer.setSize(window.innerWidth, window.innerHeight) document.body.appendChild(renderer.domElement) const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000) camera.position.set(0, 80, 0) const controls = new MapControls(camera, renderer.domElement) // Customize key bindings controls.controlMap = { MOVE_FORWARD: ['KeyW', 'ArrowUp'], MOVE_BACKWARD: ['KeyS', 'ArrowDown'], MOVE_LEFT: ['KeyA', 'ArrowLeft'], MOVE_RIGHT: ['KeyD', 'ArrowRight'], MOVE_DOWN: 'ShiftLeft', MOVE_UP: 'Space' } // Tune movement speed controls.keyPanSpeed = 15 controls.keyPanDistance = 40 controls.verticalTranslationSpeed = 0.8 // Set orbit center to a specific block controls.setRotationOrigin(new THREE.Vector3(0, 64, 0)) // Enable damping (inertia) controls.enableDamping = true controls.dampingFactor = 0.05 // Save and restore camera state controls.saveState() // ... later: // controls.reset() // Disable DOM event listeners when not needed // controls.unregisterHandlers() // controls.registerHandlers() ;(function animate () { requestAnimationFrame(animate) controls.update() // must call in render loop when damping is enabled renderer.render(scene, camera) })() ``` ``` -------------------------------- ### bot.viewer.drawLine(id, points, color) Source: https://context7.com/prismarinejs/prismarine-viewer/llms.txt Renders a 3D polyline connecting an array of `Vec3` points visible to all browser clients. Uses a unique string `id` so the line can be updated in place on subsequent calls or removed with `erase`. Color is a hex integer (default `0xff0000`). ```APIDOC ## bot.viewer.drawLine(id, points, color) — Draw a polyline in the viewer ### Description Renders a 3D polyline connecting an array of `Vec3` points visible to all browser clients. Uses a unique string `id` so the line can be updated in place on subsequent calls or removed with `erase`. Color is a hex integer (default `0xff0000`). ### Method POST (implied by drawing operation) ### Endpoint `/viewer/drawLine` (implied) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **id** (string) - Required - Unique identifier for the line. - **points** (Array) - Required - An array of `Vec3` objects representing the points of the polyline. - **color** (number) - Optional - Hexadecimal color integer (default: `0xff0000`). ### Request Example ```javascript bot.once('spawn', () => { mineflayerViewer(bot, { port: 3000 }) // Draw a static diagonal line const { Vec3 } = require('vec3') bot.viewer.drawLine('myLine', [ new Vec3(0, 64, 0), new Vec3(10, 70, 10), new Vec3(20, 64, 20) ], 0xff00ff) // magenta // Overwrite the same line with updated points setTimeout(() => { bot.viewer.drawLine('myLine', [ new Vec3(0, 64, 0), new Vec3(5, 80, 5) ], 0x0000ff) // blue }, 5000) }) ``` ### Response #### Success Response (200) None explicitly documented. #### Response Example None explicitly documented. ``` -------------------------------- ### Close Prismarine Viewer Server Source: https://github.com/prismarinejs/prismarine-viewer/blob/master/README.md Stop the viewer server and disconnect any connected users. ```javascript bot.viewer.close() ``` -------------------------------- ### MapControls Source: https://github.com/prismarinejs/prismarine-viewer/blob/master/viewer/README.md Provides default third-person controls based on three.js OrbitControls. ```APIDOC ## MapControls ### Description Default third-person controls. Requires calling `controls.update()` in your render loop. Refer to [three.js OrbitControls documentation](https://threejs.org/docs/#examples/en/controls/OrbitControls) for more details. ### Properties * `.controlMap` (object) - Defines keyboard controls. Can be an array for multiple keys per action. Defaults to: ```javascript { MOVE_FORWARD: ['KeyW', 'KeyZ'], MOVE_BACKWARD: 'KeyS', MOVE_LEFT: ['KeyA', 'KeyQ'], MOVE_RIGHT: 'KeyD', MOVE_DOWN: 'ShiftLeft', MOVE_UP: 'Space' } ``` * `.verticalTranslationSpeed` (number) - Controls the speed of vertical movement (y-axis offset). * `.enableTouchZoom` (boolean) - Toggles touch-based zooming. * `.enableTouchRotate` (boolean) - Toggles touch-based rotation. * `.enableTouchPan` (boolean) - Toggles touch-based panning. ### Methods * `setRotationOrigin(pos: THREE.Vector3)` - Sets the center point for rotations. * `registerHandlers()` - Enables DOM event handling. * `unregisterHandlers()` - Disables DOM event handling. ``` -------------------------------- ### Stop the viewer server with bot.viewer.close() Source: https://context7.com/prismarinejs/prismarine-viewer/llms.txt Shuts down the HTTP server and disconnects all connected Socket.IO clients. Use this to gracefully stop the viewer. ```javascript bot.once('spawn', () => { mineflayerViewer(bot, { port: 3000 }) // Stop the viewer after 60 seconds setTimeout(() => { bot.viewer.close() console.log('Viewer closed') }, 60000) }) ``` -------------------------------- ### bot.viewer.drawLine Source: https://github.com/prismarinejs/prismarine-viewer/blob/master/README.md Draw a line passing through all the `points`. ```APIDOC ## bot.viewer.drawLine ### Description Draw a line passing through all the `points`. ### Parameters * `id` (any) - A unique identifier for the line. * `points` (Array) - An array of points defining the line. Each point should be an object with `x`, `y`, and `z` properties. * `color` (number) - The color of the line in RGB hex format, default: `0xff0000` (red). ``` -------------------------------- ### React to block clicks in the browser with bot.viewer event 'blockClicked' Source: https://context7.com/prismarinejs/prismarine-viewer/llms.txt Emitted when a user clicks a block in the browser. Integrates with pathfinding for click-to-move functionality. Requires `mineflayer-pathfinder`. ```javascript const mineflayer = require('mineflayer') const mineflayerViewer = require('prismarine-viewer').mineflayer const { pathfinder, Movements } = require('mineflayer-pathfinder') const { GoalBlock } = require('mineflayer-pathfinder').goals const bot = mineflayer.createBot({ username: 'Bot' }) bot.loadPlugin(pathfinder) bot.once('spawn', () => { mineflayerViewer(bot, { port: 3000 }) const mcData = require('minecraft-data')(bot.version) bot.pathfinder.setMovements(new Movements(bot, mcData)) // Navigate to any block the user right-clicks bot.viewer.on('blockClicked', (block, face, button) => { if (button !== 2) return // right-click only const target = block.position.offset(0, 1, 0) bot.pathfinder.setGoal(new GoalBlock(target.x, target.y, target.z)) console.log(`Navigating to ${target}`) }) }) ``` -------------------------------- ### Viewer Class - Low-level Three.js rendering API Source: https://context7.com/prismarinejs/prismarine-viewer/llms.txt The core renderer that wraps a Three.js WebGLRenderer and manages the scene, camera, world chunks, entities, and primitives. It is suitable for custom frontends. ```APIDOC ## Viewer Class - Low-level Three.js rendering API ### Description The core renderer. Wraps a Three.js `WebGLRenderer` and manages the scene, camera, world chunks, entities, and primitives. Used internally by all modes; also suitable for custom frontends (Electron apps, embedded canvases). ### Usage Example ```js const THREE = require('three') const { Viewer, WorldView } = require('prismarine-viewer').viewer const { Vec3 } = require('vec3') // Set up a Three.js renderer (browser context) const renderer = new THREE.WebGLRenderer() renderer.setSize(window.innerWidth, window.innerHeight) document.body.appendChild(renderer.domElement) const viewer = new Viewer(renderer) // Set the Minecraft version (returns false if unsupported) if (!viewer.setVersion('1.18.1')) { throw new Error('Version not supported') } // Adjust lighting viewer.ambientLight.intensity = 0.8 viewer.directionalLight.intensity = 0.6 // Position the first-person camera viewer.setFirstPersonCamera(new Vec3(0, 65, 0), Math.PI, 0) // pos, yaw, pitch // Wire up a WorldView to stream chunks into the Viewer const worldView = new WorldView(world, 4, new Vec3(0, 64, 0)) viewer.listen(worldView) worldView.init(new Vec3(0, 64, 0)) // Render loop ;(function animate () { requestAnimationFrame(animate) viewer.update() // must be called every frame renderer.render(viewer.scene, viewer.camera) })() // Wait until all pending chunks have been meshed viewer.waitForChunksToRender().then(() => { console.log('All chunks rendered') }) ``` ``` -------------------------------- ### Draw a polyline in the viewer Source: https://context7.com/prismarinejs/prismarine-viewer/llms.txt Renders a 3D polyline connecting an array of Vec3 points. Uses a unique ID for updates or removal. Color defaults to red. ```javascript bot.once('spawn', () => { mineflayerViewer(bot, { port: 3000 }) // Draw a static diagonal line const { Vec3 } = require('vec3') bot.viewer.drawLine('myLine', [ new Vec3(0, 64, 0), new Vec3(10, 70, 10), new Vec3(20, 64, 20) ], 0xff00ff) // magenta // Overwrite the same line with updated points setTimeout(() => { bot.viewer.drawLine('myLine', [ new Vec3(0, 64, 0), new Vec3(5, 80, 5) ], 0x0000ff) // blue }, 5000) }) ``` -------------------------------- ### WorldView Class Source: https://github.com/prismarinejs/prismarine-viewer/blob/master/viewer/README.md WorldView represents the world from a player or camera's point of view. ```APIDOC ## WorldView(world, viewDistance, position, emitter) ### Description Constructs a WorldView instance. ### Parameters * world (object) - The prismarine-world object. * viewDistance (number) - The number of chunks to consider for rendering. * position (Vec3, optional) - The initial position of the camera. Defaults to new Vec3(0, 0, 0). * emitter (object, optional) - The event emitter to connect to. If null, it defaults to itself or a socket. ``` ```APIDOC ## WorldView.listenToBot(bot) ### Description Starts listening to events from a mineflayer bot. ### Parameters * bot (object) - The mineflayer bot instance. ``` ```APIDOC ## WorldView.removeListenersFromBot(bot) ### Description Stops listening to events from a mineflayer bot. ### Parameters * bot (object) - The mineflayer bot instance. ``` ```APIDOC ## WorldView.init(pos) ### Description Initializes the WorldView and starts emitting chunks from the specified position. ### Parameters * pos (object) - The starting position. ``` ```APIDOC ## WorldView.loadChunk(pos) ### Description Emits chunks at the specified position. ### Parameters * pos (object) - The position for which to load chunks. ``` ```APIDOC ## WorldView.unloadChunk(pos) ### Description Emits an event to unload chunks at the specified position. ### Parameters * pos (object) - The position of the chunks to unload. ``` ```APIDOC ## WorldView.updatePosition(pos) ### Description Updates the camera's position and emits corresponding events. ### Parameters * pos (object) - The new camera position. ``` -------------------------------- ### WorldView Class - World data bridge Source: https://context7.com/prismarinejs/prismarine-viewer/llms.txt Manages loaded chunks around a moving position and emits events for chunk loading/unloading, block updates, and entities. It can connect to a mineflayer bot or a Socket.IO socket. ```APIDOC ## WorldView Class - World data bridge between a world and a Viewer ### Description Manages which chunks are loaded around a moving position and emits `loadChunk` / `unloadChunk` / `blockUpdate` / `entity` events that `Viewer.listen()` consumes. Can connect directly to a mineflayer bot or to a Socket.IO socket (for client/server split architectures). ### Usage Example ```js const { WorldView } = require('prismarine-viewer').viewer const { Vec3 } = require('vec3') // Standalone usage: WorldView as its own emitter const worldView = new WorldView( world, // prismarine-world instance 6, // viewDistance in chunks new Vec3(0, 64, 0), // initial camera position null // emitter: null = use self; pass a socket.io socket for remote ) // Initialize: loads all chunks in view radius await worldView.init(new Vec3(0, 64, 0)) // Move the camera — unloads out-of-range chunks, loads new ones await worldView.updatePosition(new Vec3(16, 64, 0)) // Attach to a mineflayer bot for automatic chunk and entity sync worldView.listenToBot(bot) // Listen for block click raycasts worldView.on('blockClicked', (block, face, button) => { console.log(`Block clicked at ${block.position}, face ${face}, button ${button}`) }) // Detach from the bot (e.g. on socket disconnect) worldView.removeListenersFromBot(bot) ``` ``` -------------------------------- ### bot.viewer event: 'blockClicked' Source: https://context7.com/prismarinejs/prismarine-viewer/llms.txt Emitted whenever a user right-clicks or left-clicks a block in the browser viewport. Useful for click-to-move functionality. ```APIDOC ## `bot.viewer` event: `'blockClicked'` — React to block clicks in the browser The `bot.viewer` EventEmitter emits `'blockClicked'` whenever a user right-clicks or left-clicks a block in the browser viewport. Integrates naturally with `mineflayer-pathfinder` for click-to-move behavior. ### Parameters #### Event Parameters - **block** (object) - The clicked block object. - **face** (Vec3) - The face of the block that was clicked. - **button** (number) - The mouse button used (0 for left-click, 2 for right-click). ### Event Example ```javascript bot.viewer.on('blockClicked', (block, face, button) => { if (button !== 2) return // right-click only const target = block.position.offset(0, 1, 0) bot.pathfinder.setGoal(new GoalBlock(target.x, target.y, target.z)) console.log(`Navigating to ${target}`) }) ``` ```