File size: 4,327 Bytes
06b3545
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
"""Top-down PIL renderer for the 2D CLEVRER-lite world.

Sphere  -> shaded disc with a specular highlight
Cube    -> rotated square with beveled edges
Cylinder-> ring (dark side + lighter top face), as seen from above
Metal   -> brighter material with a strong specular; rubber is matte.
"""

import numpy as np
from PIL import Image, ImageDraw

from . import config

_LIGHT = np.array([-0.6, -0.8])   # light comes from top-left


def _shade(rgb, factor):
    return tuple(int(min(255, max(0, c * factor))) for c in rgb)


def _background(size):
    top = np.array([128.0, 128.0, 133.0])
    bot = np.array([100.0, 100.0, 106.0])
    rows = np.linspace(0.0, 1.0, size)[:, None]
    grad = top[None, :] * (1.0 - rows) + bot[None, :] * rows      # (size, 3)
    arr = np.repeat(grad[:, None, :], size, axis=1)               # (size, size, 3)
    return arr.astype(np.uint8)


def render(bodies, size: int = 128, half: float = config.WORLD_HALF) -> np.ndarray:
    """Render a list of Body objects into an (size, size, 3) uint8 array."""
    ss = 2                                   # 2x supersampling for anti-aliasing
    S = size * ss
    scale = S / (2.0 * half)

    def to_px(p):
        return (p[0] + half) * scale, (half - p[1]) * scale  # flip y: +y is "behind"

    img = Image.fromarray(_background(S), "RGB")

    # ---- soft ground shadows (drawn on an RGBA overlay) ----
    shadow = Image.new("RGBA", (S, S), (0, 0, 0, 0))
    sd = ImageDraw.Draw(shadow)
    off = 0.05 * scale
    for b in bodies:
        cx, cy = to_px(b.pos)
        r = b.radius * scale
        sd.ellipse([cx - r + off, cy - r + off * 0.5, cx + r + off, cy + r + off * 0.5],
                   fill=(15, 15, 20, 60))
    img = Image.alpha_composite(img.convert("RGBA"), shadow).convert("RGB")

    d = ImageDraw.Draw(img)
    spec = Image.new("RGBA", (S, S), (0, 0, 0, 0))
    spd = ImageDraw.Draw(spec)

    for b in sorted(bodies, key=lambda x: -x.radius):
        base = np.array(config.COLORS[b.color], dtype=float)
        if b.material == "metal":
            base = np.clip(base * 1.25 + 28, 0, 255)
        base = tuple(int(c) for c in base)
        cx, cy = to_px(b.pos)
        r = b.radius * scale

        if b.shape == "sphere":
            d.ellipse([cx - r, cy - r, cx + r, cy + r], fill=_shade(base, 0.72))
            d.ellipse([cx - 0.92 * r, cy - 0.92 * r, cx + 0.92 * r, cy + 0.92 * r],
                      fill=base)
            hi_a = 210 if b.material == "metal" else 90
            spd.ellipse([cx - 0.45 * r, cy - 0.55 * r, cx - 0.05 * r, cy - 0.15 * r],
                        fill=(255, 255, 255, hi_a))

        elif b.shape == "cube":
            hs = r * 0.88                       # half side s.t. area ~ circle
            ang = b.angle
            ca, sa = np.cos(ang), np.sin(ang)
            corners = []
            for dx, dy in ((-1, -1), (1, -1), (1, 1), (-1, 1)):
                corners.append((cx + hs * (dx * ca - dy * sa),
                                cy + hs * (dx * sa + dy * ca)))
            d.polygon(corners, fill=base)
            # bevel: edges facing the light are bright, others dark
            for k in range(4):
                a_, b_ = corners[k], corners[(k + 1) % 4]
                ex, ey = b_[0] - a_[0], b_[1] - a_[1]
                ln = np.hypot(ex, ey) + 1e-9
                nx, ny = -ey / ln, ex / ln       # outward normal (polygon is CCW on screen)
                if nx * _LIGHT[0] + ny * _LIGHT[1] < 0:
                    col = _shade(base, 1.45 if b.material == "metal" else 1.22)
                else:
                    col = _shade(base, 0.55)
                d.line([a_, b_], fill=col, width=max(2, int(0.06 * r)))

        else:  # cylinder seen from above: dark rim + lighter top face
            d.ellipse([cx - r, cy - r, cx + r, cy + r], fill=_shade(base, 0.62))
            d.ellipse([cx - 0.78 * r, cy - 0.78 * r, cx + 0.78 * r, cy + 0.78 * r],
                      fill=base)
            spd.ellipse([cx - 0.5 * r, cy - 0.55 * r, cx - 0.1 * r, cy - 0.2 * r],
                        fill=(255, 255, 255, 200 if b.material == "metal" else 70))

    img = Image.alpha_composite(img.convert("RGBA"), spec).convert("RGB")

    # downsample for anti-aliasing
    img = img.resize((size, size), Image.LANCZOS)
    return np.asarray(img, dtype=np.uint8)