Files
airdef/tools/web_remote/terrain.py
T

113 lines
4.5 KiB
Python

"""Bounded, asynchronous terrain tile cache for the web remote."""
from collections import OrderedDict, deque
import struct
import threading
import time
import zlib
_TILE_SIDE = 128
_RGBA_BYTES = _TILE_SIDE * _TILE_SIDE * 4
_SAMPLES = _TILE_SIDE * _TILE_SIDE
def _chunk(kind, data):
body = kind + data
return struct.pack('>I', len(data)) + body + struct.pack('>I', zlib.crc32(body) & 0xffffffff)
def _png(rgba):
"""Encode a tile as a standard unfiltered RGBA PNG."""
stride = _TILE_SIDE * 4
rows = b''.join(b'\0' + rgba[offset:offset + stride]
for offset in range(0, _RGBA_BYTES, stride))
header = struct.pack('>IIBBBBB', _TILE_SIDE, _TILE_SIDE, 8, 6, 0, 0, 0)
return (b'\x89PNG\r\n\x1a\n' + _chunk(b'IHDR', header) +
_chunk(b'IDAT', zlib.compress(rows)) + _chunk(b'IEND', b''))
class TerrainTiles:
"""Nonblocking tile lookup; call work from the bridge's rate-limited worker.
``get(session, x, z, step)`` returns a PNG and sample count, or None. ``work(session,
transport)`` processes at most one queued tile, returning True if one was
attempted. The transport receives (x, z, step) and returns a mapping with
an RGBA hex string and the number of known samples. Failed requests can be
retried on a later lookup; stale cached tiles remain available.
"""
def __init__(self, *, max_tiles=128, max_queue=64, complete_ttl=300,
partial_ttl=10, empty_ttl=3):
if max_tiles < 1 or max_queue < 1:
raise ValueError('cache and queue limits must be positive')
self.max_tiles, self.max_queue = max_tiles, max_queue
self.complete_ttl, self.partial_ttl, self.empty_ttl = complete_ttl, partial_ttl, empty_ttl
self._lock = threading.Lock()
self._session = object()
self._generation = 0
self._cache = OrderedDict()
self._queue = deque()
self._pending = set()
self._inflight = set()
def _activate(self, session):
# Called under the lock. The generation also invalidates work already
# outside the lock when a new game session arrives.
if session != self._session:
self._session = session
self._generation += 1
self._cache.clear()
self._queue.clear()
self._pending.clear()
self._inflight.clear()
def get(self, session, x, z, step):
key = (x, z, step)
with self._lock:
self._activate(session)
item = self._cache.get(key)
if item is not None:
self._cache.move_to_end(key)
if (item is None or time.monotonic() >= item[2]):
if key not in self._pending and key not in self._inflight and len(self._queue) < self.max_queue:
self._queue.append(key)
self._pending.add(key)
return item[:2] if item is not None else None
def work(self, session, transport):
with self._lock:
self._activate(session)
if not self._queue:
return False
key = self._queue.popleft()
self._pending.remove(key)
self._inflight.add(key)
generation = self._generation
try:
result = transport(*key)
rgba = bytes.fromhex(result['rgba'])
known = result['known']
if len(rgba) != _RGBA_BYTES or not isinstance(known, int) or not 0 <= known <= _SAMPLES:
raise ValueError('invalid terrain tile')
png = _png(rgba) if known else b""
ttl = self.empty_ttl if known == 0 else self.complete_ttl if known == _SAMPLES else self.partial_ttl
except (OSError, ValueError, TypeError, KeyError, zlib.error):
# Transport, malformed data and encoding failures must not kill the
# bridge worker. A future lookup can retry, retaining stale data.
with self._lock:
if generation == self._generation:
self._inflight.discard(key)
item = self._cache.get(key)
if item is not None:
self._cache[key] = (*item[:2], time.monotonic() + self.empty_ttl)
return True
with self._lock:
if generation == self._generation:
self._inflight.discard(key)
self._cache[key] = (png, known, time.monotonic() + ttl)
self._cache.move_to_end(key)
while len(self._cache) > self.max_tiles:
self._cache.popitem(last=False)
return True