Spaces:
Running on Zero

File size: 2,377 Bytes
c8f167d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
"""How frames travel to the page (the live demo's window format, pwm-live-drop livedrop/encode.py): a 16-byte header
(magic b"PWMW", version, flags, frame count, first frame, point count; little endian), then the particles of every object
on the table [frames, points, 3]: the first frame as uint16 in the table's BOX, then each frame's change from the one
before as int16 (flags bit 1), on a grid 2^shift coarser (flags bits 4-7; shift 3 = 0.2 mm). For the Space the bytes
are deflated (resting objects send zeros, which deflate all but removes) and sent as base64 text.
"""
import base64
import struct
import zlib

import numpy as np

MAGIC = b"PWMW"
VERSION = 1
HEADER = struct.Struct("<4sBBHII")            # magic, version, flags, n_frames, first_frame, n_points
LEVELS = 65535
DELTAS_FLAG = 2
SHIFT = 3
BOX = np.array([[-0.85, -0.85, -0.05], [0.85, 0.85, 1.0]])    # metres, the model's frame


def quantize(frames, box=BOX):
    lo, hi = box
    return np.clip(np.round((np.asarray(frames, np.float64) - lo) / (hi - lo) * LEVELS), 0, LEVELS).astype(np.int32)


def dequantize(q, box=BOX):
    lo, hi = box
    return lo + np.asarray(q, np.float64) / LEVELS * (hi - lo)


def window_message(frames, first_frame, shift=SHIFT):
    """frames [L, N, 3] metres -> bytes."""
    q = quantize(frames) >> shift
    L, N, _ = q.shape
    body = q[:1].astype("<u2").tobytes() + np.diff(q, axis=0).astype("<i2").tobytes()
    return HEADER.pack(MAGIC, VERSION, DELTAS_FLAG | (shift << 4), L, int(first_frame), N) + body


def frames_text(frames, first_frame):
    """frames [L, N, 3] -> base64 of the deflated window message."""
    return base64.b64encode(zlib.compress(window_message(frames, first_frame), 6)).decode()


def read_window(message):
    magic, version, flags, L, first, N = HEADER.unpack_from(message, 0)
    if magic != MAGIC or version != VERSION:
        raise ValueError("not a window message")
    raw = np.frombuffer(message, dtype="<u2", offset=HEADER.size, count=L * N * 3).reshape(L, N, 3)
    shift = (flags >> 4) & 15
    d = raw.view("<i2").astype(np.int32)
    c = np.concatenate([raw[:1].astype(np.int32), d[1:]]).cumsum(axis=0)
    q = ((c << shift) + ((1 << shift) >> 1)).clip(0, LEVELS)
    return dict(first_frame=first, frames=dequantize(q), points=N)


def read_frames_text(text):
    return read_window(zlib.decompress(base64.b64decode(text)))