A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
tools(render-lab): small scenes with known answers, drawn by Blender and the engine from one glTF
yhh800b85c60eba
diff --git a/tools/render-lab/README.md b/tools/render-lab/README.mdnew file mode 100644index 000000000..1e519cad3--- /dev/null+++ b/tools/render-lab/README.md@@ -0,0 +1,21 @@+# Render lab++Small scenes with known answers, drawn by Blender (Cycles) and by the engine from the same glTF, the same camera, sun and sky. A sphere's+brightness is a formula and a shadow's edge is where a ray goes, so what the two renderers disagree about points at one formula.++Scenes are listed in `lab_specs.py`: `balls_sun`, `balls_env` (six spheres, dielectric and metal at roughness 0.15 / 0.45 / 0.9, under a sun+alone or a uniform white sky alone), `shadow`, `shadow_soft` (a floor, a box and a sphere, a hard sun and one of 3.4 degrees), `strands`+(cards of fine stripes seen small: a cut-out, an opaque one, a ramp).++```bash+B="/c/Program Files/Blender Foundation/Blender 5.2/blender.exe"; O=D:/estella/output/render-lab+"$B" --background --python tools/render-lab/build_lab.py -- balls $O/balls.glb # the scene, as a GLB+"$B" --background --python tools/render-lab/lab_ref.py -- balls_sun $O/balls.glb $O/ref_balls_sun.png+BACKEND=webgl2 bash tools/render-lab/run-lab.sh balls_sun $O/balls.glb # or BACKEND=webgpu (opens a window)+python tools/render-lab/lab_compare.py balls_sun $O/ref_balls_sun.png $O/engine_balls_sun.png $O/cmp_balls_sun.png+```++Blender renders with the Standard view transform and the engine with no output transform, so the two PNGs compare as they are. A Blender sun of+strength S lights a white diffuse surface to S / pi; the engine's sun of intensity I to I, so the lab gives Blender pi times the engine's intensity.+`sourceAngle` is in degrees in the engine and radians in Blender. Spheres stand three metres apart so one does not light another (the engine has+no bounce light by default; Blender has twelve bounces).diff --git a/tools/render-lab/build_lab.py b/tools/render-lab/build_lab.pynew file mode 100644index 000000000..54e46e63c--- /dev/null+++ b/tools/render-lab/build_lab.py@@ -0,0 +1,145 @@+"""Builds the geometry of one lab scene in Blender and exports it as a GLB both renderers then draw.+blender --background --python build_lab.py -- <lab> <out.glb>+"""+import json+import os+import struct+import sys++import bmesh+import bpy+import numpy as np++sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))+import lab_specs as S # noqa: E402+from lab_png import write_png # noqa: E402++lab, out = sys.argv[sys.argv.index('--') + 1:][:2]+bpy.ops.wm.read_factory_settings(use_empty=True)+g2b = S.to_blender+CUTOUTS = {}+++def principled(name, base, metallic=0.0, roughness=0.5, image=None, alpha_clip=None):+ m = bpy.data.materials.new(name)+ m.use_nodes = True+ bsdf = m.node_tree.nodes['Principled BSDF']+ bsdf.inputs['Base Color'].default_value = (*base, 1.0)+ bsdf.inputs['Metallic'].default_value = metallic+ bsdf.inputs['Roughness'].default_value = roughness+ if image is not None:+ tex = m.node_tree.nodes.new('ShaderNodeTexImage')+ tex.image = image+ tex.interpolation = 'Linear'+ m.node_tree.links.new(tex.outputs['Color'], bsdf.inputs['Base Color'])+ if alpha_clip is not None:+ m.node_tree.links.new(tex.outputs['Alpha'], bsdf.inputs['Alpha'])+ CUTOUTS[name] = alpha_clip+ return m+++def sphere(name, centre, radius, mat, segments=96, rings=64):+ bpy.ops.mesh.primitive_uv_sphere_add(segments=segments, ring_count=rings, radius=radius, location=g2b(centre))+ ob = bpy.context.active_object+ ob.name = name+ bpy.ops.object.shade_smooth()+ ob.data.materials.append(mat)+ return ob+++def box(name, centre, size, mat):+ bpy.ops.mesh.primitive_cube_add(size=1.0, location=g2b(centre))+ ob = bpy.context.active_object+ ob.name = name+ ob.scale = (size[0], size[2], size[1])+ bpy.ops.object.transform_apply(scale=True)+ ob.data.materials.append(mat)+ return ob+++def flat_face(name, pts_gltf, uvs, mat):+ """One quad from four glTF-space corners (listed counter-clockwise seen from the side it should face)."""+ me = bpy.data.meshes.new(name)+ bm = bmesh.new()+ verts = [bm.verts.new(g2b(p)) for p in pts_gltf]+ face = bm.faces.new(verts)+ layer = bm.loops.layers.uv.new('UVMap')+ for loop, (u, v) in zip(face.loops, uvs):+ loop[layer].uv = (u, v)+ bm.to_mesh(me)+ bm.free()+ ob = bpy.data.objects.new(name, me)+ bpy.context.scene.collection.objects.link(ob)+ ob.data.materials.append(mat)+ return ob+++def card(name, centre, width, height, mat):+ """A flat card facing -Z (the camera), `width` along glTF X and `height` along Y, uvs 0..1 with (0, 0) at the bottom left of the picture."""+ cx, cy, cz = centre+ hw, hh = width / 2, height / 2+ # Seen from -Z, +X is to the left: counter-clockwise from the picture's bottom left is bottom-left, bottom-right, top-right, top-left.+ pts = [(cx + hw, cy - hh, cz), (cx - hw, cy - hh, cz), (cx - hw, cy + hh, cz), (cx + hw, cy + hh, cz)]+ return flat_face(name, pts, ((0, 0), (1, 0), (1, 1), (0, 1)), mat)+++def load_png(rgba, name):+ path = os.path.join(os.path.dirname(os.path.abspath(out)), name + '.png')+ write_png(path, rgba)+ img = bpy.data.images.load(path)+ img.colorspace_settings.name = 'sRGB'+ img.pack()+ return img+++def stripes_image(name, size, period, duty, dark, bright, alpha_cut):+ """Vertical strands, `period` texels apart: bright in the middle of each, dark at its edge; with `alpha_cut` the gaps are clear."""+ x = np.arange(size)+ phase = (x % period) / period+ prof = 0.5 + 0.5 * np.cos(2 * np.pi * (phase - 0.5)) # 1 at the strand's centre, 0 at its edge+ col = dark + (bright - dark) * prof+ alpha = np.where(np.abs(phase - 0.5) < duty / 2, 1.0, 0.0) if alpha_cut else np.ones(size)+ row = np.stack([col, col, col, alpha], axis=1)+ return load_png(np.tile(row[None, :, :], (size, 1, 1)), name)+++def ramp_image(name, size):+ x = np.linspace(0.05, 0.95, size)+ row = np.stack([x, x, x, np.ones(size)], axis=1)+ return load_png(np.tile(row[None, :, :], (size, 1, 1)), name)+++if lab.startswith('balls'):+ for i, (centre, base, metal, rough) in enumerate(S.BALLS):+ sphere('ball%d' % i, centre, S.BALL_RADIUS, principled('m%d' % i, base, metal, rough))+elif lab.startswith('shadow'):+ # The floor faces +Y: counter-clockwise seen from above.+ flat_face('floor', [(-6, 0, -6), (-6, 0, 6), (6, 0, 6), (6, 0, -6)], ((0, 0), (0, 1), (1, 1), (1, 0)), principled('floor', (0.6, 0.6, 0.6), 0.0, 1.0))+ box('box', (-0.9, 0.5, 0.4), (1.0, 1.0, 1.0), principled('boxm', (0.8, 0.3, 0.25), 0.0, 0.8))+ sphere('ball', (1.1, 0.55, -0.3), 0.55, principled('ballm', (0.3, 0.55, 0.8), 0.0, 0.5))+elif lab == 'strands':+ n = 1024+ fine = stripes_image('fine', n, 3, 0.6, 0.15, 0.7, True)+ solid = stripes_image('solid', n, 3, 0.6, 0.15, 0.7, False)+ ramp = ramp_image('ramp', n)+ card('cut', (0.4, 0.0, 0.0), 0.25, 0.25, principled('cut', (1, 1, 1), 0.0, 1.0, fine, 0.5))+ card('opaque', (0.0, 0.0, 0.0), 0.25, 0.25, principled('opaque', (1, 1, 1), 0.0, 1.0, solid))+ card('ramp', (-0.4, 0.0, 0.0), 0.25, 0.25, principled('ramp', (1, 1, 1), 0.0, 1.0, ramp))++bpy.ops.export_scene.gltf(filepath=out, export_format='GLB', export_apply=True, export_yup=True)++# The exporter writes a linked alpha as BLEND; a cut-out is MASK with its cutoff, which is what the importer on either side then reads.+if CUTOUTS:+ data = open(out, 'rb').read()+ jlen = struct.unpack('<I', data[12:16])[0]+ doc = json.loads(data[20:20 + jlen])+ for m in doc['materials']:+ if m['name'] in CUTOUTS:+ m['alphaMode'] = 'MASK'+ m['alphaCutoff'] = CUTOUTS[m['name']]+ js = json.dumps(doc, separators=(',', ':')).encode()+ js += b' ' * ((4 - len(js) % 4) % 4)+ rest = data[20 + jlen:]+ total = 12 + 8 + len(js) + len(rest)+ open(out, 'wb').write(data[:8] + struct.pack('<I', total) + struct.pack('<I', len(js)) + data[16:20] + js + rest)+print('exported', out)diff --git a/tools/render-lab/edit_build.py b/tools/render-lab/edit_build.pynew file mode 100644index 000000000..ce2a2fff3--- /dev/null+++ b/tools/render-lab/edit_build.py@@ -0,0 +1,35 @@+p = 'D:/estella/tools/render-lab/build_lab.py'+s = open(p, encoding='utf8', newline='').read()+i = s.index("def finish(img, name):")+j = s.index("if lab.startswith('balls'):")+new = '''def load_png(rgba, name):+ path = os.path.join(os.path.dirname(os.path.abspath(out)), name + '.png')+ write_png(path, rgba)+ img = bpy.data.images.load(path)+ img.colorspace_settings.name = 'sRGB'+ img.pack()+ return img+++def stripes_image(name, size, period, duty, dark, bright, alpha_cut):+ """Vertical strands, `period` texels apart: bright in the middle of each, dark at its edge; with `alpha_cut` the gaps are clear."""+ x = np.arange(size)+ phase = (x % period) / period+ prof = 0.5 + 0.5 * np.cos(2 * np.pi * (phase - 0.5)) # 1 at the strand's centre, 0 at its edge+ col = dark + (bright - dark) * prof+ alpha = np.where(np.abs(phase - 0.5) < duty / 2, 1.0, 0.0) if alpha_cut else np.ones(size)+ row = np.stack([col, col, col, alpha], axis=1)+ return load_png(np.tile(row[None, :, :], (size, 1, 1)), name)+++def ramp_image(name, size):+ x = np.linspace(0.05, 0.95, size)+ row = np.stack([x, x, x, np.ones(size)], axis=1)+ return load_png(np.tile(row[None, :, :], (size, 1, 1)), name)+++'''+s = s[:i] + new + s[j:]+s = s.replace("import lab_specs as S # noqa: E402\n", "import lab_specs as S # noqa: E402\nfrom lab_png import write_png # noqa: E402\n", 1)+open(p, 'w', encoding='utf8', newline='').write(s)+print('ok')diff --git a/tools/render-lab/lab_compare.py b/tools/render-lab/lab_compare.pynew file mode 100644index 000000000..bb79b9d8e--- /dev/null+++ b/tools/render-lab/lab_compare.py@@ -0,0 +1,48 @@+"""Compares the engine's picture of a lab scene with Blender's, region by region, and writes a side-by-side.+python lab_compare.py <lab> <ref.png> <engine.png> [out.png]+For the ball scenes each sphere is read in three places: where the light faces it (diffuse), at its highlight, and at its rim (Fresnel).+"""+import os+import sys++import numpy as np+from PIL import Image, ImageDraw++sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))+import lab_specs as S # noqa: E402++lab, ref_path, eng_path = sys.argv[1:4]+spec = S.LABS[lab]+ref = np.array(Image.open(ref_path).convert('RGB')).astype(float)+eng = np.array(Image.open(eng_path).convert('RGB')).astype(float)+print('mean abs difference over the frame: %.2f / 255' % np.abs(ref - eng).mean())+++def disc(cx, cy, r):+ ys, xs = np.mgrid[0:S.SIZE[1], 0:S.SIZE[0]]+ return (xs - cx) ** 2 + (ys - cy) ** 2 <= r * r+++def report(name, mask):+ r, e = ref[mask].mean(0), eng[mask].mean(0)+ d = np.abs(ref[mask] - eng[mask]).mean()+ print('%-22s ref %5.1f %5.1f %5.1f engine %5.1f %5.1f %5.1f ratio %.3f %.3f %.3f mean|d| %.2f' % ((name,) + tuple(r) + tuple(e) + tuple(e / np.maximum(r, 0.5)) + (d,)))+++if lab.startswith('balls'):+ for i, (centre, base, metal, rough) in enumerate(S.BALLS):+ px, py, z = S.project(centre, spec['cam'])+ rpx = S.BALL_RADIUS / z / np.tan(np.radians(spec['cam'][2]) / 2) * S.SIZE[1] / 2+ report('ball%d %s r%.2f all' % (i, 'metal' if metal else 'diel', rough), disc(px, py, rpx * 0.97))+ report(' core', disc(px, py, rpx * 0.5))+ ring = disc(px, py, rpx * 0.97) & ~disc(px, py, rpx * 0.8)+ report(' rim', ring)+else:+ print('(whole frame only)')++side = np.concatenate([ref, eng, np.clip(np.abs(ref - eng) * 4, 0, 255)], axis=1).astype(np.uint8)+im = Image.fromarray(side)+d = ImageDraw.Draw(im)+for k, t in enumerate(('blender', 'engine', 'difference x4')):+ d.text((8 + k * S.SIZE[0], 6), t, fill=(255, 255, 0))+im.resize((im.width // 2, im.height // 2), Image.LANCZOS).save(sys.argv[4] if len(sys.argv) > 4 else eng_path.replace('.png', '_cmp.png'))diff --git a/tools/render-lab/lab_png.py b/tools/render-lab/lab_png.pynew file mode 100644index 000000000..0cf5892aa--- /dev/null+++ b/tools/render-lab/lab_png.py@@ -0,0 +1,19 @@+"""An 8-bit RGBA PNG written without any library: Blender will not save the pixels of an image made in a script."""+import struct+import zlib++import numpy as np+++def write_png(path, rgba):+ """`rgba` is an (h, w, 4) float array in 0..1."""+ h, w, _ = rgba.shape+ bytes8 = np.clip(np.round(rgba * 255.0), 0, 255).astype(np.uint8)+ raw = b''.join(b'\x00' + bytes8[y].tobytes() for y in range(h))++ def chunk(tag, data):+ return struct.pack('>I', len(data)) + tag + data + struct.pack('>I', zlib.crc32(tag + data) & 0xffffffff)++ with open(path, 'wb') as f:+ f.write(b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('>IIBBBBB', w, h, 8, 6, 0, 0, 0))+ + chunk(b'IDAT', zlib.compress(raw, 6)) + chunk(b'IEND', b''))diff --git a/tools/render-lab/lab_project.py b/tools/render-lab/lab_project.pynew file mode 100644index 000000000..69e693b7c--- /dev/null+++ b/tools/render-lab/lab_project.py@@ -0,0 +1,65 @@+"""The engine's side of a lab scene: a project holding the lab GLB, the camera, the sun and the sky of its spec.+python lab_project.py <projectDir> <lab> <scene.glb> (env BACKEND, EFFECTS (json), Q (json quality), EXTENT)+"""+import json+import math+import os+import shutil+import sys+import uuid++sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))+import lab_specs as S # noqa: E402++proj, lab, glb = sys.argv[1:4]+spec = S.LABS[lab]+os.makedirs(proj + '/assets/models/lab', exist_ok=True)+os.makedirs(proj + '/assets/env', exist_ok=True)+os.makedirs(proj + '/assets/scenes', exist_ok=True)+shutil.copy(glb, proj + '/assets/models/lab/lab.glb')+json.dump({'uuid': str(uuid.uuid4()), 'version': '2.0', 'type': 'model', 'importer': {}}, open(proj + '/assets/models/lab/lab.glb.meta', 'w'), indent=2)+json.dump({'formatVersion': '1', 'name': 'Lab', 'version': '0.1.0', 'tag': '3D', 'defaultScene': 'assets/scenes/lab.esscene',+ 'designResolution': {'width': S.SIZE[0], 'height': S.SIZE[1]}, 'spineVersion': 'none',+ 'features': {'rendering': {'backend': os.environ.get('BACKEND', 'webgl2'), 'colorSpace': 'linear', 'outputTransform': 'none',+ 'quality': dict({'mode': 'high'}, **json.loads(os.environ.get('Q', '{}')))}}},+ open(proj + '/project.esproject', 'w'), indent=2)++ambient = spec['ambient']+w, h = 64, 32+++def rgbe(v):+ if v <= 0:+ return bytes((0, 0, 0, 0))+ m, e = math.frexp(v)+ return bytes((int(m * 256),) * 3 + (e + 128,))+++with open(proj + '/assets/env/uniform.hdr', 'wb') as f:+ f.write(b'#?RADIANCE\nFORMAT=32-bit_rle_rgbe\n\n-Y %d +X %d\n' % (h, w))+ f.write(rgbe(max(ambient, 1e-6)) * (w * h))++pos, target, fov = spec['cam']+qw, qx, qy, qz = S.cam_quaternion(spec['cam'])+entities = [+ {'id': 0, 'name': 'Camera', 'parent': None, 'children': [], 'visible': True, 'components': [+ {'type': 'Transform', 'data': {'position': {'x': pos[0], 'y': pos[1], 'z': pos[2]}, 'rotation': {'w': qw, 'x': qx, 'y': qy, 'z': qz}}},+ {'type': 'Camera', 'data': {'projectionType': 0, 'fov': fov, 'nearPlane': 0.05, 'farPlane': 100.0, 'isActive': True, 'priority': 0, 'clearFlags': 3}}]},+]+if ambient > 0:+ entities.append({'id': 1, 'name': 'Sky', 'parent': None, 'children': [], 'visible': True, 'components': [+ {'type': 'Transform', 'data': {}},+ {'type': 'Light', 'data': {'type': 2, 'color': {'r': 1, 'g': 1, 'b': 1, 'a': 1}, 'intensity': 1.0, 'enabled': True,+ 'environment': 'assets/env/uniform.esenv', 'drawEnvironment': True}}]})+if spec['sun']:+ sw, sx, sy, sz = S.sun_quaternion(spec['sun']['dir'])+ entities.append({'id': 5, 'name': 'Sun', 'parent': None, 'children': [], 'visible': True, 'components': [+ {'type': 'Transform', 'data': {'rotation': {'w': sw, 'x': sx, 'y': sy, 'z': sz}}},+ {'type': 'Light', 'data': {'type': 1, 'color': {'r': 1, 'g': 1, 'b': 1, 'a': 1}, 'intensity': spec['sun']['intensity'], 'enabled': True,+ 'meshShadows': os.environ.get('SHADOW', '1') == '1', 'shadowExtent': float(os.environ.get('EXTENT', '0')), 'shadowStrength': 1.0,+ 'sourceAngle': spec['sun']['angle']}}]})+effects = json.loads(os.environ.get('EFFECTS', '[]'))+if effects:+ entities[0]['components'].append({'type': 'PostProcessVolume', 'data': {'isGlobal': True, 'weight': 1, 'priority': 0, 'effects': effects}})+json.dump({'version': 4, 'name': 'Lab', 'entities': entities}, open(proj + '/assets/scenes/lab.esscene', 'w'), indent=1)+print('project ready')diff --git a/tools/render-lab/lab_ref.py b/tools/render-lab/lab_ref.pynew file mode 100644index 000000000..8ec2c775f--- /dev/null+++ b/tools/render-lab/lab_ref.py@@ -0,0 +1,58 @@+"""The Blender (Cycles) picture of a lab scene, from the same GLB, camera, sun and sky the engine is given.+blender --background --python lab_ref.py -- <lab> <scene.glb> <out.png> (env SAMPLES, DENOISE=0 to turn the denoiser off)+"""+import math+import os+import sys++import bpy+from mathutils import Vector++sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))+import lab_specs as S # noqa: E402++lab, glb, out = sys.argv[sys.argv.index('--') + 1:][:3]+spec = S.LABS[lab]+bpy.ops.wm.read_factory_settings(use_empty=True)+bpy.ops.import_scene.gltf(filepath=glb)+scene = bpy.context.scene+scene.render.engine = 'CYCLES'+scene.cycles.samples = int(os.environ.get('SAMPLES', '128'))+scene.cycles.use_denoising = os.environ.get('DENOISE', '1') == '1'+scene.cycles.device = 'CPU'+scene.cycles.max_bounces = 12+scene.render.resolution_x, scene.render.resolution_y = S.SIZE+scene.view_settings.view_transform = 'Standard'+scene.view_settings.look = 'None'++world = bpy.data.worlds.new('W')+world.use_nodes = True+bg = world.node_tree.nodes['Background']+bg.inputs['Color'].default_value = (1, 1, 1, 1)+bg.inputs['Strength'].default_value = spec['ambient']+scene.world = world+# The sky shows behind the picture in the engine too (drawEnvironment), so the background is the sky.++pos, target, fov = spec['cam']+to_b = lambda v: Vector(S.to_blender(v))+cam_data = bpy.data.cameras.new('C')+cam_data.sensor_fit = 'VERTICAL'+cam_data.angle_y = math.radians(fov)+cam_data.clip_start, cam_data.clip_end = 0.05, 100+cam = bpy.data.objects.new('C', cam_data)+scene.collection.objects.link(cam)+cam.location = to_b(pos)+cam.rotation_euler = (to_b(target) - cam.location).to_track_quat('-Z', 'Y').to_euler()+scene.camera = cam++if spec['sun']:+ sun = bpy.data.lights.new('S', 'SUN')+ sun.energy = spec['sun']['intensity'] * S.SUN_STRENGTH_PER_INTENSITY+ sun.angle = math.radians(spec['sun']['angle'])+ ob = bpy.data.objects.new('S', sun)+ scene.collection.objects.link(ob)+ ob.rotation_euler = to_b(spec['sun']['dir']).to_track_quat('-Z', 'Y').to_euler()++scene.render.filepath = out+bpy.ops.render.render(write_still=True)+print('rendered', out)diff --git a/tools/render-lab/lab_specs.py b/tools/render-lab/lab_specs.pynew file mode 100644index 000000000..5d58385d3--- /dev/null+++ b/tools/render-lab/lab_specs.py@@ -0,0 +1,97 @@+"""The render lab: small scenes whose answer is known, drawn by Blender (Cycles) and by the engine from one glTF.++A scene here is a few primitives and one light, so every pixel has an explanation: a sphere's brightness is a formula, a shadow's edge is where+a ray goes, a stack of cards lets through a fraction of the light that can be written down. What the two renderers disagree about is a bug+in one of them, and the scene says which formula to look at, which a character never does.++Coordinates are glTF's (metres, +Y up, the camera looks along +Z); Blender's are (x, -z, y) of these.+"""+import math++SUN_STRENGTH_PER_INTENSITY = math.pi # Blender's sun in W/m^2 against the engine's: a white diffuse surface facing the sun shows `intensity` in the engine and S / pi in Blender.++CAM_BALLS = ((0.0, 0.0, -13.5), (0.0, 0.0, 0.0), 30.0)++LABS = {+ # Six spheres: a dielectric and a metal at three roughnesses, lit by a sun alone (no sky), which shows diffuse, the GGX lobe and Fresnel on their own.+ 'balls_sun': dict(cam=CAM_BALLS, sun=dict(dir=(0.5, -0.45, 0.74), intensity=1.0, angle=0.0), ambient=0.0),+ # The same six under a uniform white sky and no sun: the diffuse irradiance is exactly the albedo, and the specular is the split-sum environment term.+ 'balls_env': dict(cam=CAM_BALLS, sun=None, ambient=1.0),+ # A floor, a box and a sphere under a sun: the position and the edge of a shadow.+ 'shadow': dict(cam=((0.0, 3.4, -6.2), (0.0, 0.2, 0.0), 32.0), sun=dict(dir=(0.45, -0.7, 0.55), intensity=1.0, angle=0.0), ambient=0.0),+ 'shadow_soft': dict(cam=((0.0, 3.4, -6.2), (0.0, 0.2, 0.0), 32.0), sun=dict(dir=(0.45, -0.7, 0.55), intensity=1.0, angle=3.4), ambient=0.0),+ # Three cards of fine stripes seen from a distance that shrinks them below a texel a pixel: a cut-out card, an opaque one, and a smooth ramp.+ 'strands': dict(cam=((0.0, 0.0, -3.0), (0.0, 0.0, 0.0), 20.0), sun=None, ambient=1.0),+}++SIZE = (1280, 720)+++def to_blender(v):+ return (v[0], -v[2], v[1])+++def project(point, cam, size=SIZE):+ """Where a world point lands, in pixels, for a camera (position, target, vertical fov degrees) looking along its target."""+ pos, target, fov = cam+ f = [target[i] - pos[i] for i in range(3)]+ n = math.sqrt(sum(c * c for c in f))+ f = [c / n for c in f]+ right = [-f[2], 0.0, f[0]] # cross(f, up) with up = +Y+ rn = math.sqrt(sum(c * c for c in right))+ right = [c / rn for c in right]+ up = [right[1] * f[2] - right[2] * f[1], right[2] * f[0] - right[0] * f[2], right[0] * f[1] - right[1] * f[0]]+ d = [point[i] - pos[i] for i in range(3)]+ z = sum(d[i] * f[i] for i in range(3))+ x = sum(d[i] * right[i] for i in range(3))+ y = sum(d[i] * up[i] for i in range(3))+ t = math.tan(math.radians(fov) / 2)+ aspect = size[0] / size[1]+ px = (x / (z * t * aspect) * 0.5 + 0.5) * size[0]+ py = (0.5 - y / (z * t) * 0.5) * size[1]+ return px, py, z+++def cam_quaternion(cam):+ """The engine camera's rotation (it looks along its local -Z, up is +Y), as (w, x, y, z)."""+ pos, target, _ = cam+ f = [target[i] - pos[i] for i in range(3)]+ n = math.sqrt(sum(c * c for c in f))+ f = [c / n for c in f]+ right = [-f[2], 0.0, f[0]] # cross(f, +Y)+ rn = math.sqrt(sum(c * c for c in right))+ right = [c / rn for c in right]+ up = [right[1] * f[2] - right[2] * f[1], right[2] * f[0] - right[0] * f[2], right[0] * f[1] - right[1] * f[0]]+ back = [-c for c in f]+ m = [[right[0], up[0], back[0]], [right[1], up[1], back[1]], [right[2], up[2], back[2]]]+ tr = m[0][0] + m[1][1] + m[2][2]+ if tr > 0:+ s = math.sqrt(tr + 1.0) * 2+ return (0.25 * s, (m[2][1] - m[1][2]) / s, (m[0][2] - m[2][0]) / s, (m[1][0] - m[0][1]) / s)+ if m[0][0] > m[1][1] and m[0][0] > m[2][2]:+ s = math.sqrt(1.0 + m[0][0] - m[1][1] - m[2][2]) * 2+ return ((m[2][1] - m[1][2]) / s, 0.25 * s, (m[0][1] + m[1][0]) / s, (m[0][2] + m[2][0]) / s)+ if m[1][1] > m[2][2]:+ s = math.sqrt(1.0 + m[1][1] - m[0][0] - m[2][2]) * 2+ return ((m[0][2] - m[2][0]) / s, (m[0][1] + m[1][0]) / s, 0.25 * s, (m[1][2] + m[2][1]) / s)+ s = math.sqrt(1.0 + m[2][2] - m[0][0] - m[1][1]) * 2+ return ((m[1][0] - m[0][1]) / s, (m[0][2] + m[2][0]) / s, (m[1][2] + m[2][1]) / s, 0.25 * s)+++def sun_quaternion(d):+ """A light shines along its local -Z: the rotation that turns -Z onto direction d (shortest arc), as (w, x, y, z)."""+ a = (0.0, 0.0, -1.0)+ n0 = math.sqrt(sum(c * c for c in d))+ d = [c / n0 for c in d]+ cx, cy, cz = a[1] * d[2] - a[2] * d[1], a[2] * d[0] - a[0] * d[2], a[0] * d[1] - a[1] * d[0]+ w = 1 + (a[0] * d[0] + a[1] * d[1] + a[2] * d[2])+ n = math.sqrt(cx * cx + cy * cy + cz * cz + w * w)+ return (w / n, cx / n, cy / n, cz / n)+++# Spheres of `balls_*`: (centre, base colour, metallic, roughness). The top row is dielectric and the bottom a metal, left to right 0.15 / 0.45 / 0.9.+BALLS = []+for row, (y, base, metal) in enumerate(((1.4, (0.8, 0.8, 0.8), 0.0), (-1.4, (0.95, 0.64, 0.54), 1.0))):+ for col, rough in enumerate((0.15, 0.45, 0.9)):+ BALLS.append(((-3.0 + 3.0 * col, y, 0.0), base, metal, rough))+BALL_RADIUS = 0.5diff --git a/tools/render-lab/run-lab.sh b/tools/render-lab/run-lab.shnew file mode 100644index 000000000..1c058936a--- /dev/null+++ b/tools/render-lab/run-lab.sh@@ -0,0 +1,29 @@+#!/bin/bash+# The engine's picture of a lab scene: <out>/engine_<lab>.png.+# usage: run-lab.sh <lab> <scene.glb> [name] env: BACKEND (webgl2|webgpu) EFFECTS Q EXTENT OUT+set -e+HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -W)"+ROOT="$(cd "$HERE/../.." && pwd -W)"+OUT="${OUT:-$ROOT/output/render-lab}"+mkdir -p "$OUT"+LAB=$1; GLB=$2; NAME=${3:-$LAB}+P="$OUT/proj_$NAME"+rm -rf "$P" "$OUT/web_$NAME"+python "$HERE/lab_project.py" "$P" "$LAB" "$GLB" > /dev/null+cd "$ROOT"+node pipeline/bin/estella.mjs import-hdr "$P/assets/env/uniform.hdr" --project "$P" > /dev/null 2>&1+node pipeline/bin/estella.mjs import-model "$P/assets/models/lab/lab.glb" --project "$P" > /dev/null 2>&1+node tools/asset-meta.js "$P/assets" > /dev/null 2>&1+python - <<EOF+import json+P=r'$P'+u=json.load(open(P+'/assets/models/lab/lab.esprefab.meta'))['uuid']+sp=P+'/assets/scenes/lab.esscene'+s=json.load(open(sp))+s['entities'].append({'id':max(e['id'] for e in s['entities'])+1,'name':'Lab','parent':None,'prefab':'@uuid:'+u,'overrides':[],'added':[],'removed':[]})+json.dump(s,open(sp,'w'),indent=1)+EOF+node pipeline/bin/estella.mjs export "$P" --out "$OUT/web_$NAME" 2>&1 | grep -E '"ok"|error' | head -2+node "$HERE/shot.mjs" "$OUT" "$OUT/web_$NAME" "$NAME" 2>&1 | grep -E "error|ERROR|warn" | head -5 | cut -c1-200 || true+mv "$OUT/lab-$NAME.png" "$OUT/engine_$NAME.png"+echo "engine_$NAME.png written to $OUT"diff --git a/tools/render-lab/shot.mjs b/tools/render-lab/shot.mjsnew file mode 100644index 000000000..702080227--- /dev/null+++ b/tools/render-lab/shot.mjs@@ -0,0 +1,27 @@+import { pathToFileURL } from 'node:url';+import path from 'node:path';+const { chromium } = await import(pathToFileURL(path.resolve(import.meta.dirname, '../../node_modules/playwright/index.mjs')).href);+const { serveHost } = await import(pathToFileURL(path.resolve(import.meta.dirname, '../lib/staticServer.mjs')).href);+const out = process.argv[2];+const web = process.argv[3];+const view = process.argv[4] ?? 'front';+const server = await serveHost(path.resolve(web));+const gpu = process.env.BACKEND === 'webgpu';+const browser = await chromium.launch({ headless: !gpu && process.env.HEADED !== '1', args: gpu ? ['--enable-unsafe-webgpu', '--disable-gpu-sandbox', '--ignore-gpu-blocklist'] : ['--use-angle=d3d11', '--enable-webgl', '--ignore-gpu-blocklist', '--enable-unsafe-swiftshader'] });+const logs = [];+try {+ const page = await browser.newPage({ viewport: { width: Number(process.env.W || 1280), height: Number(process.env.H || 720) }, deviceScaleFactor: 1 });+ page.on('response', (r) => { if (r.status() >= 400) logs.push(r.status() + ' ' + r.url()); });+ page.on('pageerror', (e) => logs.push('pageerror ' + String(e)));+ page.on('console', (m) => { if (process.env.DEBUG_LOGS === '1' || m.type() === 'error' || m.type() === 'warning') logs.push(m.type() + ' ' + m.text().slice(0, 700)); });+ await page.goto(`http://127.0.0.1:${server.address().port}/${gpu ? "" : "?headless"}`, { waitUntil: 'load' });+ await page.waitForTimeout(12000);+ await page.screenshot({ path: out + `/lab-${view}.png`, timeout: 120000 }).catch((e) => logs.push('screenshot ' + String(e).slice(0, 160)));+ console.log('context:', await page.evaluate(() => { const c = document.querySelector('canvas'); return c ? (c.getContext('webgpu') ? 'webgpu' : c.getContext('webgl2') ? 'webgl2' : 'unknown') : 'no canvas'; }).catch((e) => String(e)));+ const facts = await page.evaluate(() => (window.__estellaCooked ? window.__estellaCooked.facts() : 'no hook')).catch((e) => String(e));+ console.log(JSON.stringify(facts).slice(0, 400));+} finally {+ await browser.close();+ server.close();+}+console.log(logs.slice(0, 60).join('\n'));