import json import math import os import numpy as np from PIL import Image ROOT = '/home/tahinli/Documents/Code/Rust/courier' GFX = os.path.join(ROOT, 'assets', 'gfx') MANIFEST = os.path.join(ROOT, 'tools', 'manifest') OUTLINE_RGB = np.array([27, 20, 32], float) _U = np.uint64 _MASK64 = (1 << 64) - 1 _MATS = [None] P = { 'grass': [(40, 62, 48), (62, 92, 56), (88, 118, 68), (120, 146, 84)], 'grass_dry': [(70, 62, 40), (104, 92, 52), (136, 122, 70), (166, 150, 96)], 'dirt': [(52, 40, 34), (84, 64, 48), (116, 92, 66), (146, 120, 88)], 'mud': [(40, 34, 32), (64, 54, 46), (90, 76, 62), (118, 100, 80)], 'cobble': [(54, 56, 62), (84, 84, 88), (114, 112, 112), (142, 136, 128)], 'stone': [(86, 88, 96), (122, 120, 118), (156, 150, 140), (186, 178, 164)], 'stone_dark': [(38, 38, 44), (62, 60, 64), (90, 86, 84), (118, 110, 104)], 'brick': [(92, 38, 34), (124, 54, 44), (152, 78, 58), (178, 108, 76)], 'brick_dark': [(56, 28, 30), (80, 40, 38), (106, 56, 48), (130, 76, 62)], 'plaster': [(176, 166, 150), (198, 190, 172), (218, 210, 190), (232, 226, 206)], 'thatch': [(110, 84, 44), (146, 114, 58), (178, 146, 80), (204, 176, 108)], 'wood': [(70, 46, 32), (104, 70, 44), (136, 98, 62), (164, 124, 80)], 'wood_dark': [(42, 30, 26), (62, 44, 36), (86, 62, 46), (110, 82, 58)], 'slate': [(56, 62, 72), (78, 84, 96), (102, 108, 118), (126, 128, 136)], 'coal': [(20, 20, 24), (36, 36, 42), (54, 52, 58), (74, 70, 74)], 'water': [(30, 56, 72), (44, 80, 100), (64, 108, 126), (92, 138, 150)], 'foliage': [(34, 66, 46), (52, 94, 60), (76, 122, 72), (104, 148, 88)], 'foliage_dark': [(26, 46, 40), (38, 66, 52), (54, 90, 62), (74, 112, 76)], 'bark': [(44, 34, 30), (64, 50, 40), (88, 70, 54), (114, 92, 70)], 'skin': [(120, 78, 62), (164, 112, 88), (200, 146, 116), (224, 176, 144)], 'hair_brown': [(44, 30, 24), (70, 48, 34), (98, 70, 46), (124, 94, 64)], 'hair_black': [(18, 16, 20), (30, 28, 34), (46, 44, 50), (64, 62, 68)], 'hair_gray': [(90, 88, 94), (124, 122, 126), (156, 154, 156), (186, 184, 184)], 'cloth_brown': [(60, 40, 30), (88, 60, 42), (118, 84, 58), (146, 108, 76)], 'cloth_navy': [(24, 32, 52), (36, 48, 74), (54, 70, 100), (78, 96, 128)], 'cloth_green': [(30, 48, 38), (44, 70, 54), (64, 96, 74), (90, 122, 96)], 'cloth_wine': [(54, 22, 32), (82, 34, 44), (110, 52, 60), (138, 76, 80)], 'cloth_gray': [(56, 58, 66), (84, 86, 94), (112, 114, 120), (140, 142, 146)], 'cloth_black': [(18, 18, 24), (30, 30, 38), (46, 46, 54), (66, 64, 72)], 'cloth_cream': [(150, 136, 112), (180, 168, 140), (206, 196, 168), (226, 218, 192)], 'leather': [(36, 24, 20), (60, 40, 30), (90, 62, 44), (118, 86, 60)], 'metal': [(44, 50, 58), (74, 82, 92), (108, 116, 124), (146, 152, 158)], 'brass': [(92, 70, 34), (128, 100, 50), (164, 136, 72), (198, 170, 100)], 'window': [(214, 156, 64), (240, 196, 96), (252, 224, 140)], 'canvas': [(120, 106, 84), (152, 138, 110), (180, 168, 140), (206, 196, 166)], 'fire': [(160, 48, 24), (220, 96, 32), (246, 160, 48), (255, 220, 110)], } def mat(ramp, pattern=None, emissive=False): assert 3 <= len(ramp) <= 6 _MATS.append((np.array(ramp, np.int64), pattern, bool(emissive))) return len(_MATS) - 1 def hash3(cx, cy, cz, seed=0): h = np.asarray(cx, np.int64).astype(_U) * _U(0x9E3779B97F4A7C15) h ^= np.asarray(cy, np.int64).astype(_U) * _U(0xC2B2AE3D27D4EB4F) h ^= np.asarray(cz, np.int64).astype(_U) * _U(0x165667B19E3779F9) h ^= _U((seed * 0x27D4EB2F165667C5) & _MASK64) h ^= h >> _U(31) h *= _U(0xBF58476D1CE4E5B9) h ^= h >> _U(29) h *= _U(0x94D049BB133111EB) h ^= h >> _U(32) return (h >> _U(11)).astype(np.float64) / 9007199254740992.0 def noise(amount=1, seed=0): def f(cx, cy, cz, face): return np.floor(hash3(cx, cy, cz, seed) * (2 * amount + 1)).astype(np.int64) - amount return f def rows(h=4): def f(cx, cy, cz, face): return np.where(np.asarray(cz) % h == 0, -1, 0) return f def bricks(h=4, w=12): def f(cx, cy, cz, face): cx, cy, cz, face = (np.asarray(a, np.int64) for a in (cx, cy, cz, face)) along = np.where(face == 1, cx, cy) course = cz // h off = along + (course & 1) * (w // 2) mortar = (cz % h == 0) | (off % w == 0) var = np.floor(hash3(off // w, course, face, 5) * 3).astype(np.int64) - 1 return np.where(mortar, 1, var) return f def planks(w=6, axis=2): def f(cx, cy, cz, face): c = [np.asarray(a, np.int64) for a in (cx, cy, cz)] face = np.asarray(face, np.int64) s = np.zeros(c[0].shape, np.int64) for fa in range(3): k = [i for i in range(3) if i not in (axis, fa)][0] s = np.where(face == fa, c[k], s) var = np.floor(hash3(s // w, face, axis, 9) * 3).astype(np.int64) - 1 return np.where(s % w == 0, -1, var) return f class Model: def __init__(self, sx, sy, sz): self.v = np.zeros((sx, sy, sz), np.uint8) def _fill(self, lo, hi, fn, m): sl = [] for a in range(3): i0 = max(0, math.floor(lo[a]) - 1) i1 = min(self.v.shape[a], math.ceil(hi[a]) + 1) if i1 <= i0: return sl.append(slice(i0, i1)) X, Y, Z = [np.arange(s.start, s.stop) + 0.5 for s in sl] mask = fn(X[:, None, None], Y[None, :, None], Z[None, None, :]) sub = self.v[sl[0], sl[1], sl[2]] sub[np.broadcast_to(mask, sub.shape)] = m def box(self, x0, y0, z0, x1, y1, z1, m): def fn(X, Y, Z): return (X >= x0) & (X <= x1) & (Y >= y0) & (Y <= y1) & (Z >= z0) & (Z <= z1) self._fill((x0, y0, z0), (x1, y1, z1), fn, m) def obox(self, cx, cy, cz, hx, hy, hz, yaw, m): c, s = math.cos(yaw), math.sin(yaw) R = math.hypot(hx, hy) def fn(X, Y, Z): dx = X - cx dy = Y - cy lx = dx * c + dy * s ly = dy * c - dx * s return (np.abs(lx) <= hx) & (np.abs(ly) <= hy) & (np.abs(Z - cz) <= hz) self._fill((cx - R, cy - R, cz - hz), (cx + R, cy + R, cz + hz), fn, m) def ellipsoid(self, cx, cy, cz, rx, ry, rz, m): def fn(X, Y, Z): return ((X - cx) / rx) ** 2 + ((Y - cy) / ry) ** 2 + ((Z - cz) / rz) ** 2 <= 1 self._fill((cx - rx, cy - ry, cz - rz), (cx + rx, cy + ry, cz + rz), fn, m) def capsule(self, a, b, r, m): a = np.asarray(a, float) ab = np.asarray(b, float) - a L2 = max(float(ab @ ab), 1e-12) def fn(X, Y, Z): px, py, pz = X - a[0], Y - a[1], Z - a[2] t = np.clip((px * ab[0] + py * ab[1] + pz * ab[2]) / L2, 0, 1) dx, dy, dz = px - t * ab[0], py - t * ab[1], pz - t * ab[2] return dx * dx + dy * dy + dz * dz <= r * r lo = np.minimum(a, a + ab) - r hi = np.maximum(a, a + ab) + r self._fill(lo, hi, fn, m) def cylinder(self, a, b, r, m): a = np.asarray(a, float) ab = np.asarray(b, float) - a L = float(np.linalg.norm(ab)) u = ab / max(L, 1e-12) def fn(X, Y, Z): px, py, pz = X - a[0], Y - a[1], Z - a[2] along = px * u[0] + py * u[1] + pz * u[2] d2 = px * px + py * py + pz * pz - along * along return (along >= 0) & (along <= L) & (d2 <= r * r) lo = np.minimum(a, a + ab) - r hi = np.maximum(a, a + ab) + r self._fill(lo, hi, fn, m) def gable(self, x0, y0, x1, y1, z0, z1, axis, m, overhang=0): o = overhang if axis == 'x': a0, a1, b0, b1, ca, cb = x0, x1, y0, y1, 0, 1 else: a0, a1, b0, b1, ca, cb = y0, y1, x0, x1, 1, 0 bc = (b0 + b1) / 2 hw = (b1 - b0) / 2 def fn(X, Y, Z): pos = (X, Y) A = pos[ca] B = pos[cb] d = np.abs(B - bc) / hw h = z0 + (z1 - z0) * (1 - np.minimum(d, 1)) return (A >= a0 - o) & (A <= a1 + o) & (d <= 1 + o / hw) & (Z >= z0) & (Z <= h) self._fill((x0 - o, y0 - o, z0), (x1 + o, y1 + o, z1), fn, m) def paint(self, fn, m): ix, iy, iz = np.nonzero(self.v) sel = np.broadcast_to(fn(ix + 0.5, iy + 0.5, iz + 0.5), ix.shape) self.v[ix[sel], iy[sel], iz[sel]] = m def render(model, outline=True, edges=True): v = model.v sx, sy, sz = v.shape W = sx + sy H = int(math.ceil((sx + sy) / 2 + sz)) U, V = np.meshgrid(np.arange(W) - sy + 0.5, np.arange(H) - sz + 0.5) bounds = np.stack([2 * sx - U, 2 * sy + U, 2 * (sz + V)]) face = np.argmin(bounds, axis=0).reshape(-1) s0 = bounds.min(axis=0) lo = np.maximum(np.maximum(-U, U), 2 * V) idx = np.flatnonzero((s0 >= lo).reshape(-1)) P0 = np.stack([(s0 + U) / 2, (s0 - U) / 2, s0 / 2 - V], -1).reshape(-1, 3) p = P0[idx] f = face[idx] dims = np.array(v.shape) hit_mat = np.zeros(H * W, np.uint8) hit_face = np.zeros(H * W, np.int64) hit_cell = np.zeros((H * W, 3), np.int64) for _ in range(4 * (sx + sy + sz) + 8): if not idx.size: break c = np.floor(p - 1e-6).astype(np.int64) inside = (c >= 0).all(1) cc = np.clip(c, 0, dims - 1) mt = v[cc[:, 0], cc[:, 1], cc[:, 2]] occ = inside & (mt > 0) hi_ = idx[occ] hit_mat[hi_] = mt[occ] hit_face[hi_] = f[occ] hit_cell[hi_] = c[occ] go = inside & ~occ idx, p, c = idx[go], p[go], c[go] d = p - c t = d.min(1) f = d.argmin(1) p = p - t[:, None] M = (hit_mat > 0).reshape(H, W) mat_img = hit_mat.reshape(H, W) face_img = hit_face.reshape(H, W) cell_img = hit_cell.reshape(H, W, 3) D = cell_img.sum(2) Mr = np.zeros_like(M) Mb = np.zeros_like(M) Dr = np.zeros_like(D) Db = np.zeros_like(D) Mr[:, :-1] = M[:, 1:] Dr[:, :-1] = D[:, 1:] Mb[:-1, :] = M[1:, :] Db[:-1, :] = D[1:, :] edge = M & (~Mr | (np.abs(D - Dr) > 4) | ~Mb | (np.abs(D - Db) > 4)) shade = np.zeros((H, W), np.int64) emis = np.zeros((H, W), bool) glass = np.zeros((H, W), bool) lens = np.zeros((H, W), np.int64) rgb = np.zeros((H, W, 3)) mids = np.unique(mat_img[M]) for mid in mids: ramp, pat, em = _MATS[mid] sel = mat_img == mid fa = face_img[sel] L = len(ramp) base = np.where(fa == 2, L - 2, np.where(fa == 1, L - 3, L - 4)) if pat is not None: cl = cell_img[sel] base = base + pat(cl[:, 0], cl[:, 1], cl[:, 2], fa) shade[sel] = base emis[sel] = em glass[sel] = em and len(ramp) == len(P['window']) and bool(np.all(ramp == np.array(P['window']))) lens[sel] = L shade = shade - (edge if edges else 0) for mid in mids: ramp = _MATS[mid][0] sel = mat_img == mid idx_ = np.clip(shade[sel], 0, len(ramp) - 1) rgb[sel] = ramp[idx_] Hc, Wc = H + 2, W + 2 img = np.zeros((Hc, Wc, 4), np.uint8) img[1:-1, 1:-1, :3] = np.round(rgb).astype(np.uint8) img[1:-1, 1:-1, 3] = M * 255 if outline: A = img[..., 3] > 0 col = img[..., :3].astype(float) out = np.zeros_like(col) got = np.zeros((Hc, Wc), bool) for dy, dx in ((1, 0), (-1, 0), (0, 1), (0, -1)): nA = np.roll(A, (dy, dx), (0, 1)) nC = np.roll(col, (dy, dx), (0, 1)) take = nA & ~A & ~got out[take] = 0.35 * nC[take] + 0.65 * OUTLINE_RGB got |= take img[got, :3] = np.round(out[got]).astype(np.uint8) img[got, 3] = 255 em_img = None E = np.zeros((Hc, Wc), bool) E[1:-1, 1:-1] = emis & M ys, xs = np.nonzero(img[..., 3]) x0, x1 = max(int(xs.min()) - 1, 0), min(int(xs.max()) + 2, Wc) y0, y1 = max(int(ys.min()) - 1, 0), min(int(ys.max()) + 2, Hc) if E.any(): em = np.zeros_like(img) em[E] = img[E] em_img = Image.fromarray(em[y0:y1, x0:x1]) G = np.zeros((Hc, Wc), bool) G[1:-1, 1:-1] = glass & M img[G, :3] = np.round(img[G, :3] * 0.22 + np.array([34, 40, 52]) * 0.78).astype(np.uint8) origin = (sy + 1 - x0, sz + 1 - y0) return Image.fromarray(img[y0:y1, x0:x1]), em_img, origin def project(x, y, z, origin): return origin[0] + (x - y), origin[1] + (x + y) / 2 - z def smoke_offset(px, py, origin): return ((px - origin[0]) * 2, -(py - origin[1]) * 2) def save(name, img, origin, foot=(1, 1), smoke=(), cell=None, grid=None, emissive=None, group='misc'): os.makedirs(GFX, exist_ok=True) os.makedirs(MANIFEST, exist_ok=True) img.save(os.path.join(GFX, name + '.png')) if emissive is not None: emissive.save(os.path.join(GFX, name + '_e.png')) path = os.path.join(MANIFEST, group + '.json') data = {} if os.path.exists(path): with open(path) as fh: data = json.load(fh) data[name] = { 'size': list(img.size), 'origin': [int(origin[0]), int(origin[1])], 'foot': list(foot), 'smoke': [list(s) for s in smoke], 'cell': list(cell) if cell is not None else None, 'grid': list(grid) if grid is not None else None, 'glow': emissive is not None, } with open(path, 'w') as fh: json.dump(data, fh, indent=2) def atlas(frames_rows): frames = [fr for row in frames_rows for fr in row] L = max(o[0] for _, o in frames) T = max(o[1] for _, o in frames) R = max(img.size[0] - o[0] for img, o in frames) B = max(img.size[1] - o[1] for img, o in frames) cw, ch = L + R, T + B cols = max(len(r) for r in frames_rows) rows_n = len(frames_rows) out = Image.new('RGBA', (cols * cw, rows_n * ch), (0, 0, 0, 0)) for j, row in enumerate(frames_rows): for i, (img, o) in enumerate(row): out.paste(img, (i * cw + L - o[0], j * ch + T - o[1])) return out, (cw, ch), (cols, rows_n), (L, T)