Improve minimap, switch to block palette, update faster
This commit is contained in:
1 parent
8c75502966
commit
9be381c2de
6 files changed
+166
-38
No files matched your search
@@ -1,3 +1,4 @@
|
|||||||
|
import base64
|
||||||
import importlib
|
import importlib
|
||||||
import json
|
import json
|
||||||
import os
|
import os
|
||||||
@@ -174,24 +175,47 @@ def api_global():
|
|||||||
return response
|
return response
|
||||||
|
|
||||||
|
|
||||||
def _minimap_surface_cell(chunks, x, z):
|
def _minimap_surface_cell(chunks, x, z, section_cache=None):
|
||||||
"""Return the uppermost solid/water block in a loaded world column."""
|
"""Return the uppermost solid/water block in a loaded world column."""
|
||||||
from mosfet.info import blocks
|
from mosfet.info import blocks
|
||||||
|
|
||||||
chunk_x, chunk_z = floor(x / 16), floor(z / 16)
|
chunk_x, chunk_z = floor(x / 16), floor(z / 16)
|
||||||
chunk = chunks.chunks.get((chunk_x, chunk_z))
|
key = (chunk_x, chunk_z)
|
||||||
|
chunk = chunks.chunks.get(key)
|
||||||
if chunk is None:
|
if chunk is None:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
if section_cache is not None and key in section_cache:
|
||||||
|
sections = section_cache[key]
|
||||||
|
else:
|
||||||
|
sections = sorted(chunk.sections.items(), reverse=True)
|
||||||
|
if section_cache is not None:
|
||||||
|
section_cache[key] = sections
|
||||||
|
|
||||||
local_x, local_z = x - chunk_x * 16, z - chunk_z * 16
|
local_x, local_z = x - chunk_x * 16, z - chunk_z * 16
|
||||||
min_y = getattr(chunks, 'min_y', -64)
|
min_y = getattr(chunks, 'min_y', -64)
|
||||||
for section_y in sorted(chunk.sections, reverse=True):
|
for section_y, section in sections:
|
||||||
if section_y * 16 + 15 < min_y:
|
section_base = section_y * 16
|
||||||
|
if section_base + 15 < min_y:
|
||||||
continue
|
continue
|
||||||
section = chunk.sections[section_y]
|
|
||||||
if section.get('non_empty_blocks') == 0:
|
if section.get('non_empty_blocks') == 0:
|
||||||
continue
|
continue
|
||||||
for y in range(section_y * 16 + 15, max(min_y, section_y * 16) - 1, -1):
|
|
||||||
|
section_blocks = section.get('blocks')
|
||||||
|
if section_blocks is not None and hasattr(section_blocks, 'get'):
|
||||||
|
min_local_y = max(0, min_y - section_base)
|
||||||
|
for local_y in range(15, min_local_y - 1, -1):
|
||||||
|
index = ((local_y * 16 + local_z) * 16 + local_x)
|
||||||
|
state_id = section_blocks.get(index)
|
||||||
|
y = section_base + local_y
|
||||||
|
if state_id is None or state_id == blocks.AIR:
|
||||||
|
continue
|
||||||
|
if (state_id in blocks.NON_SOLID_IDS and
|
||||||
|
state_id not in blocks.WATER_IDS):
|
||||||
|
continue
|
||||||
|
return {'block': blocks.BLOCKS.get(state_id, 'unknown'), 'y': y}
|
||||||
|
else:
|
||||||
|
for y in range(section_base + 15, max(min_y, section_base) - 1, -1):
|
||||||
state_id = chunk.get_block_at(local_x, y, local_z)
|
state_id = chunk.get_block_at(local_x, y, local_z)
|
||||||
if state_id is None or state_id == blocks.AIR:
|
if state_id is None or state_id == blocks.AIR:
|
||||||
continue
|
continue
|
||||||
@@ -208,13 +232,13 @@ def api_minimap():
|
|||||||
chunks = g.get('chunks')
|
chunks = g.get('chunks')
|
||||||
if (not g.get('connected') or position is None or position is False or
|
if (not g.get('connected') or position is None or position is False or
|
||||||
chunks is None or not hasattr(chunks, 'chunks')):
|
chunks is None or not hasattr(chunks, 'chunks')):
|
||||||
return jsonify(ready=False, cells=[])
|
return jsonify(ready=False, palette=[], cell_bits=8, cells_b64='')
|
||||||
|
|
||||||
try:
|
try:
|
||||||
radius = int(request.args.get('radius', 12))
|
radius = int(request.args.get('radius', 12))
|
||||||
except (TypeError, ValueError):
|
except (TypeError, ValueError):
|
||||||
radius = 12
|
radius = 12
|
||||||
radius = max(4, min(32, radius))
|
radius = max(4, min(36, radius))
|
||||||
try:
|
try:
|
||||||
radius_x = int(request.args.get('radius_x', radius))
|
radius_x = int(request.args.get('radius_x', radius))
|
||||||
except (TypeError, ValueError):
|
except (TypeError, ValueError):
|
||||||
@@ -224,23 +248,42 @@ def api_minimap():
|
|||||||
except (TypeError, ValueError):
|
except (TypeError, ValueError):
|
||||||
radius_z = radius
|
radius_z = radius
|
||||||
radius_x = max(4, min(48, radius_x))
|
radius_x = max(4, min(48, radius_x))
|
||||||
radius_z = max(4, min(32, radius_z))
|
radius_z = max(4, min(36, radius_z))
|
||||||
center_x, center_z = floor(position.x), floor(position.z)
|
center_x, center_z = floor(position.x), floor(position.z)
|
||||||
center_y = floor(position.y)
|
center_y = floor(position.y)
|
||||||
|
section_cache = {}
|
||||||
|
palette = []
|
||||||
|
palette_indices = {}
|
||||||
|
cell_indices = []
|
||||||
lock = getattr(chunks, 'lock', None)
|
lock = getattr(chunks, 'lock', None)
|
||||||
if lock is not None:
|
if lock is not None:
|
||||||
lock.acquire()
|
lock.acquire()
|
||||||
try:
|
try:
|
||||||
cells = [
|
for dz in range(-radius_z, radius_z + 1):
|
||||||
[_minimap_surface_cell(chunks, center_x + dx, center_z + dz)
|
for dx in range(-radius_x, radius_x + 1):
|
||||||
for dx in range(-radius_x, radius_x + 1)]
|
cell = _minimap_surface_cell(
|
||||||
for dz in range(-radius_z, radius_z + 1)
|
chunks, center_x + dx, center_z + dz, section_cache)
|
||||||
]
|
if cell is None:
|
||||||
|
cell_indices.append(0)
|
||||||
|
else:
|
||||||
|
name = cell['block']
|
||||||
|
palette_index = palette_indices.get(name)
|
||||||
|
if palette_index is None:
|
||||||
|
palette_index = len(palette) + 1
|
||||||
|
palette_indices[name] = palette_index
|
||||||
|
palette.append(name)
|
||||||
|
cell_indices.append(palette_index)
|
||||||
finally:
|
finally:
|
||||||
if lock is not None:
|
if lock is not None:
|
||||||
lock.release()
|
lock.release()
|
||||||
|
|
||||||
ready = any(cell is not None for row in cells for cell in row)
|
ready = bool(palette)
|
||||||
|
cell_bits = 8 if len(palette) <= 255 else 16
|
||||||
|
if cell_bits == 8:
|
||||||
|
cell_data = bytes(cell_indices)
|
||||||
|
else:
|
||||||
|
cell_data = b''.join(index.to_bytes(2, 'little')
|
||||||
|
for index in cell_indices)
|
||||||
path_nodes = []
|
path_nodes = []
|
||||||
for node in (g.get('path') or ())[:512]:
|
for node in (g.get('path') or ())[:512]:
|
||||||
try:
|
try:
|
||||||
@@ -252,16 +295,21 @@ def api_minimap():
|
|||||||
continue
|
continue
|
||||||
path_nodes.append({'x': path_x, 'z': path_z})
|
path_nodes.append({'x': path_x, 'z': path_z})
|
||||||
|
|
||||||
return jsonify(
|
response_data = {
|
||||||
ready=ready,
|
'ready': ready,
|
||||||
center={'x': center_x, 'y': center_y, 'z': center_z},
|
'center': {'x': center_x, 'y': center_y, 'z': center_z},
|
||||||
yaw=float(g.get('yaw', 0.0) or 0.0),
|
'yaw': float(g.get('yaw', 0.0) or 0.0),
|
||||||
radius=radius,
|
'radius': radius,
|
||||||
radius_x=radius_x,
|
'radius_x': radius_x,
|
||||||
radius_z=radius_z,
|
'radius_z': radius_z,
|
||||||
cells=cells if ready else [],
|
'path': path_nodes,
|
||||||
path=path_nodes,
|
}
|
||||||
|
response_data.update(
|
||||||
|
palette=palette,
|
||||||
|
cell_bits=cell_bits,
|
||||||
|
cells_b64=base64.b64encode(cell_data).decode('ascii'),
|
||||||
)
|
)
|
||||||
|
return jsonify(response_data)
|
||||||
|
|
||||||
|
|
||||||
@app.route('/api/items')
|
@app.route('/api/items')
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import base64
|
||||||
import importlib.util
|
import importlib.util
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
import threading
|
import threading
|
||||||
@@ -126,9 +127,65 @@ class TestWebInventoryAPI(unittest.TestCase):
|
|||||||
])
|
])
|
||||||
self.assertEqual(data['radius_x'], 6)
|
self.assertEqual(data['radius_x'], 6)
|
||||||
self.assertEqual(data['radius_z'], 4)
|
self.assertEqual(data['radius_z'], 4)
|
||||||
self.assertEqual(len(data['cells']), 9)
|
self.assertEqual(data['palette'], ['grass_block'])
|
||||||
self.assertEqual(len(data['cells'][0]), 13)
|
indices = base64.b64decode(data['cells_b64'])
|
||||||
self.assertEqual(data['cells'][4][6], {'block': 'grass_block', 'y': 5})
|
self.assertEqual(len(indices), 9 * 13)
|
||||||
|
self.assertEqual(indices[4 * 13 + 6], 1)
|
||||||
|
self.assertNotIn('cells', data)
|
||||||
|
|
||||||
|
def test_minimap_returns_palette_encoded_surface_grid(self):
|
||||||
|
grass = blocks.MCD_BLOCKS['grass_block']['minStateId']
|
||||||
|
target_index = ((5 * 16 + 1) * 16 + 1)
|
||||||
|
|
||||||
|
class FakePalette:
|
||||||
|
def get(self, index):
|
||||||
|
return grass if index == target_index else blocks.AIR
|
||||||
|
|
||||||
|
class FakeChunk:
|
||||||
|
sections = {0: {
|
||||||
|
'non_empty_blocks': 1,
|
||||||
|
'blocks': FakePalette(),
|
||||||
|
}}
|
||||||
|
|
||||||
|
def get_block_at(self, *_args):
|
||||||
|
raise AssertionError('palette lookup should avoid per-block API')
|
||||||
|
|
||||||
|
class FakeChunks:
|
||||||
|
min_y = 0
|
||||||
|
chunks = {(0, 0): FakeChunk()}
|
||||||
|
|
||||||
|
self.g.connected = True
|
||||||
|
self.g.chunks = FakeChunks()
|
||||||
|
self.g.pos = Munch(x=1.5, y=6.0, z=1.5)
|
||||||
|
|
||||||
|
response = self.client.get(
|
||||||
|
'/api/minimap?radius=4&radius_x=4&radius_z=4')
|
||||||
|
|
||||||
|
self.assertEqual(response.status_code, 200)
|
||||||
|
data = response.get_json()
|
||||||
|
self.assertTrue(data['ready'])
|
||||||
|
self.assertEqual(data['palette'], ['grass_block'])
|
||||||
|
self.assertNotIn('cells', data)
|
||||||
|
indices = base64.b64decode(data['cells_b64'])
|
||||||
|
self.assertEqual(len(indices), 9 * 9)
|
||||||
|
self.assertEqual(indices[4 * 9 + 4], 1)
|
||||||
|
|
||||||
|
def test_minimap_api_allows_three_additional_zoom_out_levels(self):
|
||||||
|
class EmptyChunks:
|
||||||
|
chunks = {}
|
||||||
|
|
||||||
|
self.g.connected = True
|
||||||
|
self.g.chunks = EmptyChunks()
|
||||||
|
self.g.pos = Munch(x=0.0, y=64.0, z=0.0)
|
||||||
|
|
||||||
|
response = self.client.get(
|
||||||
|
'/api/minimap?radius=36&radius_x=48&radius_z=36')
|
||||||
|
|
||||||
|
self.assertEqual(response.status_code, 200)
|
||||||
|
data = response.get_json()
|
||||||
|
self.assertEqual(data['radius'], 36)
|
||||||
|
self.assertEqual(data['radius_x'], 48)
|
||||||
|
self.assertEqual(data['radius_z'], 36)
|
||||||
|
|
||||||
def test_global_api_exposes_world_time_ticks(self):
|
def test_global_api_exposes_world_time_ticks(self):
|
||||||
self.g.time = 12345.5
|
self.g.time = 12345.5
|
||||||
|
|||||||
@@ -81,7 +81,7 @@
|
|||||||
<div class="minimap-controls" aria-label="Minimap controls">
|
<div class="minimap-controls" aria-label="Minimap controls">
|
||||||
<button id="minimap-zoom-out" type="button" aria-label="Zoom out" title="Zoom out">−</button>
|
<button id="minimap-zoom-out" type="button" aria-label="Zoom out" title="Zoom out">−</button>
|
||||||
<button id="minimap-zoom-in" type="button" aria-label="Zoom in" title="Zoom in">+</button>
|
<button id="minimap-zoom-in" type="button" aria-label="Zoom in" title="Zoom in">+</button>
|
||||||
<button id="minimap-north-lock" type="button" aria-label="Lock north to the top" aria-pressed="false" title="Lock north to the top">N ↑</button>
|
<button id="minimap-north-lock" type="button" aria-label="Rotate with the bot" aria-pressed="true" title="Rotate with the bot">N ↑</button>
|
||||||
<button id="minimap-size" type="button" aria-label="Enlarge minimap" aria-pressed="false" title="Enlarge minimap">⤢</button>
|
<button id="minimap-size" type="button" aria-label="Enlarge minimap" aria-pressed="false" title="Enlarge minimap">⤢</button>
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
|||||||
@@ -81,7 +81,7 @@
|
|||||||
<div class="minimap-controls" aria-label="Minimap controls">
|
<div class="minimap-controls" aria-label="Minimap controls">
|
||||||
<button id="minimap-zoom-out" type="button" aria-label="Zoom out" title="Zoom out">−</button>
|
<button id="minimap-zoom-out" type="button" aria-label="Zoom out" title="Zoom out">−</button>
|
||||||
<button id="minimap-zoom-in" type="button" aria-label="Zoom in" title="Zoom in">+</button>
|
<button id="minimap-zoom-in" type="button" aria-label="Zoom in" title="Zoom in">+</button>
|
||||||
<button id="minimap-north-lock" type="button" aria-label="Lock north to the top" aria-pressed="false" title="Lock north to the top">N ↑</button>
|
<button id="minimap-north-lock" type="button" aria-label="Rotate with the bot" aria-pressed="true" title="Rotate with the bot">N ↑</button>
|
||||||
<button id="minimap-size" type="button" aria-label="Enlarge minimap" aria-pressed="false" title="Enlarge minimap">⤢</button>
|
<button id="minimap-size" type="button" aria-label="Enlarge minimap" aria-pressed="false" title="Enlarge minimap">⤢</button>
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
|||||||
@@ -2,9 +2,9 @@
|
|||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
const POLL_MS = 1000;
|
const POLL_MS = 1000;
|
||||||
const MINIMAP_POLL_MS = 2000;
|
const MINIMAP_POLL_MS = 250;
|
||||||
const MINIMAP_MIN_RADIUS = 4;
|
const MINIMAP_MIN_RADIUS = 4;
|
||||||
const MINIMAP_MAX_RADIUS = 24;
|
const MINIMAP_MAX_RADIUS = 36;
|
||||||
const MINIMAP_ZOOM_STEP = 4;
|
const MINIMAP_ZOOM_STEP = 4;
|
||||||
const $ = (id) => document.getElementById(id);
|
const $ = (id) => document.getElementById(id);
|
||||||
let itemNames = {};
|
let itemNames = {};
|
||||||
@@ -15,7 +15,7 @@
|
|||||||
let menuAnchor = null;
|
let menuAnchor = null;
|
||||||
let toastTimer = null;
|
let toastTimer = null;
|
||||||
let minimapRadius = 12;
|
let minimapRadius = 12;
|
||||||
let minimapNorthLocked = false;
|
let minimapNorthLocked = true;
|
||||||
let minimapLarge = false;
|
let minimapLarge = false;
|
||||||
let minimapRequestPending = false;
|
let minimapRequestPending = false;
|
||||||
let lastMinimapData = null;
|
let lastMinimapData = null;
|
||||||
@@ -100,6 +100,27 @@
|
|||||||
return '#7a806f';
|
return '#7a806f';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function decodeMinimapPalette(data) {
|
||||||
|
if (typeof data?.cells_b64 !== 'string' || !Array.isArray(data.palette)) {
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
const binary = atob(data.cells_b64);
|
||||||
|
const bits = Number(data.cell_bits) === 16 ? 16 : 8;
|
||||||
|
if (bits === 8) {
|
||||||
|
data.cellIndices = Uint8Array.from(binary, (character) =>
|
||||||
|
character.charCodeAt(0));
|
||||||
|
} else {
|
||||||
|
const indices = new Uint16Array(binary.length / 2);
|
||||||
|
for (let index = 0; index < indices.length; index++) {
|
||||||
|
indices[index] = binary.charCodeAt(index * 2) |
|
||||||
|
(binary.charCodeAt(index * 2 + 1) << 8);
|
||||||
|
}
|
||||||
|
data.cellIndices = indices;
|
||||||
|
}
|
||||||
|
data.paletteColors = data.palette.map(minimapBlockColor);
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
function drawMinimap(data = lastMinimapData) {
|
function drawMinimap(data = lastMinimapData) {
|
||||||
const canvas = $('minimap-canvas');
|
const canvas = $('minimap-canvas');
|
||||||
if (!canvas) return;
|
if (!canvas) return;
|
||||||
@@ -112,7 +133,7 @@
|
|||||||
context.fillStyle = '#111411';
|
context.fillStyle = '#111411';
|
||||||
context.fillRect(0, 0, width, height);
|
context.fillRect(0, 0, width, height);
|
||||||
|
|
||||||
if (!data?.ready || !Array.isArray(data.cells)) {
|
if (!data?.ready || !data.cellIndices || !Array.isArray(data.paletteColors)) {
|
||||||
$('minimap-caption').textContent = 'Waiting for loaded terrain';
|
$('minimap-caption').textContent = 'Waiting for loaded terrain';
|
||||||
updateMinimapControls();
|
updateMinimapControls();
|
||||||
return;
|
return;
|
||||||
@@ -131,10 +152,12 @@
|
|||||||
const rasterContext = raster.getContext('2d');
|
const rasterContext = raster.getContext('2d');
|
||||||
const rasterPixels = rasterContext.createImageData(columns, rows);
|
const rasterPixels = rasterContext.createImageData(columns, rows);
|
||||||
for (let rowIndex = 0; rowIndex < rows; rowIndex++) {
|
for (let rowIndex = 0; rowIndex < rows; rowIndex++) {
|
||||||
const row = data.cells[rowIndex] || [];
|
|
||||||
for (let columnIndex = 0; columnIndex < columns; columnIndex++) {
|
for (let columnIndex = 0; columnIndex < columns; columnIndex++) {
|
||||||
const surface = row[columnIndex];
|
const flatIndex = rowIndex * columns + columnIndex;
|
||||||
const color = surface ? minimapBlockColor(surface.block) : '#171b17';
|
const paletteIndex = data.cellIndices[flatIndex];
|
||||||
|
const color = paletteIndex
|
||||||
|
? data.paletteColors[paletteIndex - 1]
|
||||||
|
: '#171b17';
|
||||||
const value = Number.parseInt(color.slice(1), 16);
|
const value = Number.parseInt(color.slice(1), 16);
|
||||||
const pixel = (rowIndex * columns + columnIndex) * 4;
|
const pixel = (rowIndex * columns + columnIndex) * 4;
|
||||||
rasterPixels.data[pixel] = value >> 16;
|
rasterPixels.data[pixel] = value >> 16;
|
||||||
@@ -698,7 +721,7 @@
|
|||||||
{cache: 'no-store'},
|
{cache: 'no-store'},
|
||||||
);
|
);
|
||||||
if (!response.ok) throw new Error(`API ${response.status}`);
|
if (!response.ok) throw new Error(`API ${response.status}`);
|
||||||
const data = await response.json();
|
const data = decodeMinimapPalette(await response.json());
|
||||||
const currentRadii = minimapRadii();
|
const currentRadii = minimapRadii();
|
||||||
if (requestedRadius !== minimapRadius ||
|
if (requestedRadius !== minimapRadius ||
|
||||||
requestKey !== `${currentRadii.x}:${currentRadii.z}` ||
|
requestKey !== `${currentRadii.x}:${currentRadii.z}` ||
|
||||||
|
|||||||
@@ -81,7 +81,7 @@
|
|||||||
<div class="minimap-controls" aria-label="Minimap controls">
|
<div class="minimap-controls" aria-label="Minimap controls">
|
||||||
<button id="minimap-zoom-out" type="button" aria-label="Zoom out" title="Zoom out">−</button>
|
<button id="minimap-zoom-out" type="button" aria-label="Zoom out" title="Zoom out">−</button>
|
||||||
<button id="minimap-zoom-in" type="button" aria-label="Zoom in" title="Zoom in">+</button>
|
<button id="minimap-zoom-in" type="button" aria-label="Zoom in" title="Zoom in">+</button>
|
||||||
<button id="minimap-north-lock" type="button" aria-label="Lock north to the top" aria-pressed="false" title="Lock north to the top">N ↑</button>
|
<button id="minimap-north-lock" type="button" aria-label="Rotate with the bot" aria-pressed="true" title="Rotate with the bot">N ↑</button>
|
||||||
<button id="minimap-size" type="button" aria-label="Enlarge minimap" aria-pressed="false" title="Enlarge minimap">⤢</button>
|
<button id="minimap-size" type="button" aria-label="Enlarge minimap" aria-pressed="false" title="Enlarge minimap">⤢</button>
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
|||||||
Reference in new issue
Block a user