"""Procedural mesh palm for Moonwater (replaces the 25-prim palms of gen_islet.py palm()). Run (Blender 5.2, headless): "C:/Program Files/Blender Foundation/Blender 5.2/blender.exe" -b -P palm_mesh.py -- \ --name palm_a --height 6.6 --lean 16 --fronds 9 --seed 1 [--out DIR] [--render] [--tex-dir DIR] Writes into --out (default: this script's folder): NAME.glb high LOD (upload this one; with the current uploadMesh it's the only file used) NAME_med.glb medium LOD } for the floater's "load from file" per LOD NAME_low.glb low LOD } NAME_lowest.glb lowest LOD } NAME_phys.glb physics: the trunk only, a bent 6-sided tube Every file (high included) carries two 1 mm anchor triangles at the corners of the union bbox of all LODs, so SL's fit-each-LOD-to-the-high-bbox can't stretch any of them. NAME_info.json tri counts, bbox, crown + base offsets from the bbox centre NAME_view*.png, NAME_lods.png with --render Geometry (Blender/region axes, metres): origin = trunk base at ground level, +Z up, the trunk leans toward +X. Trunk: tapering tube along a smooth bend (tilt grows with height like the prim palm's segments), 0.3 m buried below the origin, closed by a cone at the crown. Fronds: strips that rise and droop along an accelerating-droop curve, an inverted-V cross-section (leaflets hang off the rachis), slight twist and sideways drift; each strip has a flipped back copy because SL draws mesh faces single-sided. No coconuts (they stay prims for the falling-coconut script). Materials: slot 0 "bark" (SL face 0), slot 1 "frond" (SL face 1). UVs: bark wraps once around the trunk and repeats every 0.7 m up it (like the prims); frond U runs base->tip over the whole frond, V across its width, matching frond.png (rachis on the horizontal centre, base at the left). Claude Opus 5.5 (subagent for Tessel), 2026-10-14. """ import bpy import json import math import os import random import sys from mathutils import Matrix, Vector HERE = os.path.dirname(os.path.abspath(__file__)) def args(): a = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else [] opt = {"--name": "palm", "--height": "6.6", "--lean": "16", "--fronds": "9", "--seed": "1", "--out": HERE, "--tex-dir": os.path.dirname(HERE)} flags = set() i = 0 while i < len(a): if i + 1 < len(a) and not a[i + 1].startswith("--"): opt[a[i]] = a[i + 1] i += 2 else: flags.add(a[i]) i += 1 return opt, flags # Level-of-detail settings. Tri budget lives mostly in the fronds (each strip is drawn twice). # At this size (bbox radius 5-6 m) SL's streaming cost weights the LODs roughly high 2%, medium # 20-28%, low 66-70%, lowest 0-12% (li_estimate.py), so medium and low are kept lean. # ground: a ring at ground level (root flare); cap: cone over the crown; nfr: fronds kept (None = all). LODS = { "high": dict(sides=10, rings=14, ground=True, cap=True, fsegs=9, across=2, nfr=None), "med": dict(sides=4, rings=3, ground=False, cap=False, fsegs=2, across=2, nfr=None), "low": dict(sides=3, rings=2, ground=False, cap=False, fsegs=1, across=2, nfr=5), "lowest": dict(sides=3, rings=1, ground=False, cap=False, fsegs=1, across=1, nfr=3), } # Lower LODs with nfr set get a simplified crown: nfr evenly spaced fronds of a mid-rank shape (a # subset of the real fronds looked lopsided, and an erect young frond turned into a spike). SYNTH_RANK = 0.6 SYNTH_DROOP = (0, -45) # elevation along the synthetic fronds: their one-segment chords droop ~22 deg # (a real frond rises, then falls, so its chord ended level with the crown and read as a rotor) BURY = 0.3 # trunk continues this far below the origin, into the sand BARK_REPEAT = 0.7 # metres of trunk per vertical bark tile (the prims used seg/0.7 repeats) GOLDEN = 137.508 LEAF_V = (0.2, 0.8) # frond.png's leaflets fill V 0.23-0.77; the strip edges map just outside that def lerp(a, b, t): return a + (b - a) * t class Palm: def __init__(self, height, lean, fronds, seed): self.H, self.lean, self.n = height, lean, fronds r = random.Random(seed) # Trunk centreline: integrate the tilt profile finely, arc-length parametrised. self.fine = [] p = Vector((0, 0, 0)) N = 400 for i in range(N + 1): s = i / N t = math.radians(self.tilt(s)) self.fine.append((p.copy(), Vector((math.sin(t), 0, math.cos(t))))) p = p + Vector((math.sin(t), 0, math.cos(t))) * (height / N) self.crown = self.fine[-1][0] + self.fine[-1][1] * 0.12 top_tilt = self.tilt(1.0) # The crown leans with the trunk top, but only half as much: fronds respond to gravity. self.crown_rot = Matrix.Rotation(math.radians(top_tilt * 0.5), 3, "Y") # Frond parameters by rank: rank 0 = youngest/upper (more erect), 1 = oldest/lowest (hangs). self.fr = [] az0 = r.uniform(0, 360) lscale = (height / 6.6) ** 0.35 for j in range(fronds): rank = j / max(1, fronds - 1) self.fr.append(dict( rank=rank, az=az0 + j * GOLDEN + r.uniform(-8, 8), e0=lerp(62, 22, rank) + r.uniform(-6, 6), e1=lerp(-28, -78, rank) + r.uniform(-8, 8), L=lerp(3.1, 3.7, rank) * r.uniform(0.94, 1.06) * lscale, drift=r.uniform(-14, 14), twist=r.uniform(-30, 30), fold0=r.uniform(6, 14), fold1=r.uniform(28, 42), W=1.5 * r.uniform(0.92, 1.05), p=r.uniform(1.4, 1.9), )) def tilt(self, s): return self.lean * (0.35 + 0.65 * s ** 1.5) def trunk_at(self, s): """Centre, tangent at arc fraction s in [0, 1]; s < 0 extends straight below the base.""" if s <= 0: p0, t0 = self.fine[0] return p0 + t0 * (s * self.H), t0 f = s * (len(self.fine) - 1) i = min(int(f), len(self.fine) - 2) k = f - i (pa, ta), (pb, tb) = self.fine[i], self.fine[i + 1] return pa.lerp(pb, k), ta.lerp(tb, k).normalized() def radius(self, s): h = s * self.H # metres along the trunk from ground level r = 0.15 + 0.08 * (1 - max(0.0, s)) ** 1.3 r += 0.07 * math.exp(-max(0.0, h + BURY * 0.3) / 0.35) # root flare k = max(0.0, (s - 0.9) / 0.1) r += 0.035 * k * k * (3 - 2 * k) # crown swelling return r def frond_curve(self, f, steps=64): """Polyline of (point, tangent) from the crown along frond f, before the crown tilt.""" pts = [] p = Vector((0, 0, 0)) dl = f["L"] / steps for i in range(steps + 1): t = i / steps e = math.radians(f["e0"] + (f["e1"] - f["e0"]) * t ** f["p"]) h = math.radians(f["az"] + f["drift"] * t) d = Vector((math.cos(e) * math.cos(h), math.cos(e) * math.sin(h), math.sin(e))) pts.append((p.copy(), d, h)) p = p + d * dl return pts def build(palm, lod): """Returns verts, faces (lists of vertex indices), per-face UV lists, per-face material index.""" c = LODS[lod] V, F, UV, M = [], [], [], [] # --- trunk --- sides, rings = c["sides"], c["rings"] # ring stations: one at the buried bottom, then rings spaced along the trunk with more near the top stations = [-BURY / palm.H] + [(i / rings) ** 0.9 for i in range(0 if c["ground"] else 1, rings + 1)] base_idx = [] for s in stations: ctr, tan = palm.trunk_at(s) nrm = Vector((tan.z, 0, -tan.x)) # in the bend plane, perpendicular to the tangent bin_ = Vector((0, 1, 0)) r = palm.radius(s) base_idx.append(len(V)) for k in range(sides): a = 2 * math.pi * k / sides + math.pi / sides V.append(ctr + (nrm * math.cos(a) + bin_ * math.sin(a)) * r) vlen = [(s * palm.H) / BARK_REPEAT for s in stations] for i in range(len(stations) - 1): for k in range(sides): k2 = (k + 1) % sides a, b = base_idx[i] + k, base_idx[i] + k2 cc, d = base_idx[i + 1] + k2, base_idx[i + 1] + k F.append([a, b, cc, d]) u0, u1 = k / sides, (k + 1) / sides UV.append([(u0, vlen[i]), (u1, vlen[i]), (u1, vlen[i + 1]), (u0, vlen[i + 1])]) M.append(0) if c["cap"]: # crown cone cap tip = len(V) V.append(palm.crown.copy()) top = base_idx[-1] for k in range(sides): k2 = (k + 1) % sides F.append([top + k, top + k2, tip]) UV.append([(k / sides, vlen[-1]), ((k + 1) / sides, vlen[-1]), ((k + 0.5) / sides, vlen[-1] + 0.25)]) M.append(0) # --- fronds --- fronds = palm.fr if c["nfr"]: ref = palm.fr[min(palm.n - 1, round(SYNTH_RANK * (palm.n - 1)))] mean = {k: sum(f[k] for f in palm.fr) / palm.n for k in ("e0", "e1", "L", "W", "p", "fold0", "fold1")} fronds = [dict(mean, rank=SYNTH_RANK, az=ref["az"] + i * 360 / c["nfr"], drift=0, twist=0, e0=SYNTH_DROOP[0], e1=SYNTH_DROOP[1], p=1.0) for i in range(c["nfr"])] base = palm.crown - Vector((0, 0, 0.05)) for f in fronds: fine = palm.frond_curve(f) n = c["fsegs"] for side in (0, 1): # 0 = top face, 1 = flipped underside rows = [] for i in range(n + 1): t = i / n fi = t * (len(fine) - 1) i0 = min(int(fi), len(fine) - 2) k = fi - i0 p = fine[i0][0].lerp(fine[i0 + 1][0], k) d = fine[i0][1].lerp(fine[i0 + 1][1], k).normalized() h = lerp(fine[i0][2], fine[i0 + 1][2], k) S = Vector((-math.sin(h), math.cos(h), 0)) S = Matrix.Rotation(math.radians(f["twist"] * t), 3, d) @ S U = d.cross(S).normalized() w = f["W"] / 2 * (1.0 - 0.15 * t) if c["across"] == 2: fa = math.radians(lerp(f["fold0"], f["fold1"], t)) edge_l = p + S * (w * math.cos(fa)) - U * (w * math.sin(fa)) edge_r = p - S * (w * math.cos(fa)) - U * (w * math.sin(fa)) row = [edge_l, p, edge_r] vs = [LEAF_V[0], 0.5, LEAF_V[1]] else: fa = math.radians(lerp(f["fold0"], f["fold1"], t) * 0.5) row = [p + S * (w * math.cos(fa)) - U * (w * math.sin(fa)) * 0.5, p - S * (w * math.cos(fa)) - U * (w * math.sin(fa)) * 0.5] vs = list(LEAF_V) idx = [] for q in row: idx.append(len(V)) V.append(base + palm.crown_rot @ q) rows.append((idx, t, vs)) for i in range(n): (ra, ta, vs), (rb, tb, _) = rows[i], rows[i + 1] for k in range(len(ra) - 1): quad = [ra[k], ra[k + 1], rb[k + 1], rb[k]] uv = [(ta, vs[k]), (ta, vs[k + 1]), (tb, vs[k + 1]), (tb, vs[k])] if side == 1: quad.reverse() uv.reverse() F.append(quad) UV.append(uv) M.append(1) return V, F, UV, M def physics(palm): """Trunk only: a closed, bent 6-sided tube from just below ground to the crown.""" V, F = [], [] sides, segs = 6, 4 stations = [-0.1 / palm.H] + [i / segs for i in range(1, segs + 1)] for s in stations: ctr, tan = palm.trunk_at(min(s, 1.0)) nrm = Vector((tan.z, 0, -tan.x)) r = palm.radius(max(s, 0.08)) * 0.95 for k in range(sides): a = 2 * math.pi * k / sides V.append(ctr + (nrm * math.cos(a) + Vector((0, 1, 0)) * math.sin(a)) * r) for i in range(len(stations) - 1): for k in range(sides): k2 = (k + 1) % sides F.append([i * sides + k, i * sides + k2, (i + 1) * sides + k2, (i + 1) * sides + k]) F.append(list(reversed(range(sides)))) last = (len(stations) - 1) * sides F.append([last + k for k in range(sides)]) return V, F, [None] * len(F), [0] * len(F) def bbox(V): lo = Vector([min(v[i] for v in V) for i in range(3)]) hi = Vector([max(v[i] for v in V) for i in range(3)]) return lo, hi def add_anchors(V, F, UV, M, lo, hi, mat): """Two 1 mm triangles at the reference bbox corners so the uploader can't rescale this LOD.""" e = 0.001 for corner, sgn in ((lo, 1), (hi, -1)): i = len(V) V += [corner.copy(), corner + Vector((sgn * e, 0, 0)), corner + Vector((0, sgn * e, 0))] F.append([i, i + 1, i + 2] if sgn > 0 else [i, i + 2, i + 1]) UV.append([(0.5, 0.5)] * 3) M.append(mat) def tris(F): return sum(len(f) - 2 for f in F) def make_materials(tex_dir): mats = [] for name, img, alpha in (("bark", "bark.png", False), ("frond", "frond.png", True)): m = bpy.data.materials.get(name) or bpy.data.materials.new(name) m.use_nodes = True nt = m.node_tree bsdf = nt.nodes.get("Principled BSDF") bsdf.inputs["Roughness"].default_value = 0.85 path = os.path.join(tex_dir, img) if os.path.exists(path): tex = nt.nodes.new("ShaderNodeTexImage") tex.image = bpy.data.images.load(path, check_existing=True) nt.links.new(tex.outputs["Color"], bsdf.inputs["Base Color"]) if alpha: gt = nt.nodes.new("ShaderNodeMath") gt.operation = "GREATER_THAN" gt.inputs[1].default_value = 0.5 nt.links.new(tex.outputs["Alpha"], gt.inputs[0]) nt.links.new(gt.outputs[0], bsdf.inputs["Alpha"]) m.use_backface_culling = True # as SL draws it mats.append(m) return mats def make_object(name, V, F, UV, M, mats, uvs=True): me = bpy.data.meshes.new(name) me.from_pydata([tuple(v) for v in V], [], F) me.validate(clean_customdata=False) if uvs: uvl = me.uv_layers.new(name="UVMap") li = 0 for poly, uv in zip(me.polygons, UV): for k in range(poly.loop_total): uvl.data[poly.loop_start + k].uv = uv[k] for m in mats: me.materials.append(m) me.polygons.foreach_set("material_index", M) me.shade_smooth() ob = bpy.data.objects.new(name, me) bpy.context.scene.collection.objects.link(ob) return ob def export(ob, path): bpy.ops.object.select_all(action="DESELECT") ob.select_set(True) bpy.context.view_layer.objects.active = ob bpy.ops.export_scene.gltf(filepath=path, export_format="GLB", use_selection=True, export_apply=True, export_image_format="NONE", export_materials="EXPORT") def setup_render(scene): world = bpy.data.worlds.new("w") world.use_nodes = True world.node_tree.nodes["Background"].inputs["Color"].default_value = (0.55, 0.68, 0.85, 1) world.node_tree.nodes["Background"].inputs["Strength"].default_value = 0.9 scene.world = world sun = bpy.data.objects.new("sun", bpy.data.lights.new("sun", "SUN")) sun.data.energy = 3.0 sun.data.angle = math.radians(2) sun.rotation_euler = (math.radians(40), math.radians(10), math.radians(-35)) scene.collection.objects.link(sun) gm = bpy.data.materials.new("sand") gm.use_nodes = True gm.node_tree.nodes["Principled BSDF"].inputs["Base Color"].default_value = (0.42, 0.36, 0.26, 1) bpy.ops.mesh.primitive_circle_add(vertices=48, radius=60, fill_type="NGON", location=(0, 0, 0)) ground = bpy.context.active_object ground.data.materials.append(gm) cam = bpy.data.objects.new("cam", bpy.data.cameras.new("cam")) scene.collection.objects.link(cam) scene.camera = cam scene.render.engine = "BLENDER_EEVEE" try: scene.eevee.taa_render_samples = 32 except AttributeError: pass scene.render.resolution_x, scene.render.resolution_y = 640, 720 scene.view_settings.view_transform = "Standard" return cam def shoot(scene, cam, path, loc, target, lens=35): cam.location = loc cam.data.lens = lens d = Vector(target) - Vector(loc) cam.rotation_euler = d.to_track_quat("-Z", "Y").to_euler() scene.render.filepath = path bpy.ops.render.render(write_still=True) print("rendered", path) def main(): opt, flags = args() name, out = opt["--name"], opt["--out"] os.makedirs(out, exist_ok=True) palm = Palm(float(opt["--height"]), float(opt["--lean"]), int(opt["--fronds"]), int(opt["--seed"])) for ob in list(bpy.data.objects): bpy.data.objects.remove(ob) mats = make_materials(opt["--tex-dir"]) info = {"name": name, "height": palm.H, "lean": palm.lean, "fronds": palm.n, "seed": int(opt["--seed"]), "tris": {}} objs = {} built = {lod: build(palm, lod) for lod in ("high", "med", "low", "lowest")} # Every file gets the same bbox (the union over LODs), pinned by two 1 mm anchor triangles. boxes = [bbox(b[0]) for b in built.values()] ref = (Vector([min(b[0][i] for b in boxes) for i in range(3)]), Vector([max(b[1][i] for b in boxes) for i in range(3)])) for lod, (V, F, UV, M) in built.items(): add_anchors(V, F, UV, M, ref[0], ref[1], 1) info["tris"][lod] = tris(F) fname = name + ("" if lod == "high" else "_" + lod) ob = make_object(name, V, F, UV, M, mats) # same object name in every LOD file export(ob, os.path.join(out, fname + ".glb")) ob.name = ob.data.name = name + "_" + lod # free the plain name for the next file objs[lod] = ob V, F, UV, M = physics(palm) add_anchors(V, F, UV, M, ref[0], ref[1], 0) info["tris"]["physics"] = tris(F) ph = make_object(name, V, F, [[(0, 0)] * len(f) for f in F], M, mats[:1]) export(ph, os.path.join(out, name + "_phys.glb")) bpy.data.meshes.remove(ph.data) lo, hi = ref ctr = (lo + hi) / 2 r3 = lambda v: [round(x, 3) for x in v] info["bbox_min"], info["bbox_max"], info["bbox_size"] = r3(lo), r3(hi), r3(hi - lo) info["bbox_centre_from_origin"] = r3(ctr) info["ground_point_from_bbox_centre"] = r3(-ctr) info["crown_from_origin"] = r3(palm.crown) info["crown_from_bbox_centre"] = r3(palm.crown - ctr) info["radius_half_diagonal"] = round((hi - lo).length / 2, 3) with open(os.path.join(out, name + "_info.json"), "w") as fh: json.dump(info, fh, indent=1) print(json.dumps(info)) if "--render" in flags: scene = bpy.context.scene cam = setup_render(scene) for lod, ob in objs.items(): ob.hide_render = lod != "high" cz = palm.crown.z mid = (palm.crown.x * 0.5, 0, cz * 0.55) shoot(scene, cam, os.path.join(out, name + "_view1.png"), (mid[0], -15, 1.7), mid) shoot(scene, cam, os.path.join(out, name + "_view2.png"), (11, 9, cz + 3.0), (palm.crown.x * 0.7, 0, cz * 0.55)) shoot(scene, cam, os.path.join(out, name + "_view3.png"), (palm.crown.x - 4.5, -3.5, 1.6), (palm.crown.x, 0, cz - 0.4), lens=20) # LOD sheet: the four LODs side by side, seen across the lean for k, (lod, ob) in enumerate(objs.items()): ob.hide_render = False ob.location.x = k * 9.0 scene.render.resolution_x, scene.render.resolution_y = 1400, 520 cx = 13.5 + palm.crown.x * 0.5 shoot(scene, cam, os.path.join(out, name + "_lods.png"), (cx, -34, 3.0), (cx, 0, cz * 0.5), lens=40) main()