Files
Ornament-Generator-RNG/map/build_map.py
T
2026-11-16 23:50:40 +03:00

824 lines
41 KiB
Python

# Floating snow-island hub map: terrain + fenced player zones (no trees / installations yet).
# Run: blender -b --factory-startup --python build_map.py
# Units: 1 Blender unit = 1 Roblox stud (avatar ~5 studs tall).
import bpy, bmesh, math, os, random
from mathutils import Matrix, Vector, noise
OUT_DIR = r"C:\roblox\Ornament Generator RNG\map"
random.seed(11)
# ---------------------------------------------------------------- layout
ISLAND_R = 158.0 # island top radius (room for trees around the zones)
PLAZA_R = 60.0 # central plaza radius
PLAZA_INNER_R = 38.0 # inner tiled circle
ZONE_COUNT = 10
ZONE_RING_R = 112.0 # distance from centre to each zone centre (zones close to the plaza)
ZONE_A, ZONE_B, ZONE_CORNER = 21.0, 16.0, 7.0 # zone half-width (tangential), half-depth (radial), corner radius
GATE_HALF = 4.6 # half opening of the gate (between gate-post centres)
PATH_HALF = 5.0 # half width of the radial paths
POST_STEP = 6.2 # fence post spacing
POST_W, POST_H = 1.7, 6.0 # chunky square posts
RAIL_T, RAIL_H = 0.8, 1.0 # rail thickness / height
RAIL_Z = (2.0, 4.3) # rail centre heights
SNOW_RES = 0.11 # metaball polygonisation step for the fence snow (smaller = smoother)
SNOW_DECIMATE = 0.14 # keep this fraction of the snow triangles (smooth-shaded, stays soft)
def zone_frame(i):
th = math.radians(90 + i * 360.0 / ZONE_COUNT)
er = Vector((math.cos(th), math.sin(th), 0))
et = Vector((-math.sin(th), math.cos(th), 0))
return th, er, et, er * ZONE_RING_R
def zone_local(p, i):
_, er, et, c = zone_frame(i)
d = Vector((p.x, p.y, 0)) - c
return d.dot(et), d.dot(er)
def in_rounded_rect(u, v, a, b, r):
qx, qy = abs(u) - (a - r), abs(v) - (b - r)
return math.hypot(max(qx, 0), max(qy, 0)) + min(max(qx, qy), 0) - r <= 0
def flat_area(x, y, pad=4.0):
"""True where the ground must stay flat: plaza, paths and zones."""
r = math.hypot(x, y)
if r <= PLAZA_R + pad:
return True
for i in range(ZONE_COUNT):
u, v = zone_local(Vector((x, y, 0)), i)
if in_rounded_rect(u, v, ZONE_A + pad, ZONE_B + pad, ZONE_CORNER + pad):
return True
if abs(u) <= PATH_HALF + pad and -ZONE_B - pad <= v <= 0 and r <= ZONE_RING_R:
return True
th, er, et, c = zone_frame(i)
p = Vector((x, y, 0))
if abs(p.dot(et)) <= PATH_HALF + pad and 0 < p.dot(er) <= ZONE_RING_R - ZONE_B:
return True
return False
# ---------------------------------------------------------------- scene
def setup_scene():
sc = bpy.context.scene
for o in list(bpy.data.objects):
bpy.data.objects.remove(o, do_unlink=True)
for c in list(bpy.data.collections):
bpy.data.collections.remove(c)
cols = {}
for n in ("Terrain", "Fences", "Studio"):
cols[n] = bpy.data.collections.new(n)
sc.collection.children.link(cols[n])
return sc, cols
# ---------------------------------------------------------------- shaders
def new_mat(name):
m = bpy.data.materials.get(name) or bpy.data.materials.new(name)
try:
m.use_nodes = True
except Exception:
pass
m.node_tree.nodes.clear()
return m, m.node_tree.nodes, m.node_tree.links
def out(N, L, sock):
o = N.new("ShaderNodeOutputMaterial")
L.new(sock, o.inputs["Surface"])
def mat_snow():
m, N, L = new_mat("Snow")
tc = N.new("ShaderNodeTexCoord")
nz = N.new("ShaderNodeTexNoise"); nz.inputs["Scale"].default_value = 0.08; nz.inputs["Detail"].default_value = 6
L.new(tc.outputs["Object"], nz.inputs["Vector"])
ramp = N.new("ShaderNodeValToRGB")
ramp.color_ramp.elements[0].color = (0.84, 0.90, 1.0, 1) # faint cool shade in hollows
ramp.color_ramp.elements[1].color = (1.0, 1.0, 1.0, 1)
ramp.color_ramp.elements[0].position = 0.3
L.new(nz.outputs["Fac"], ramp.inputs["Fac"])
bs = N.new("ShaderNodeBsdfPrincipled")
L.new(ramp.outputs["Color"], bs.inputs["Base Color"])
bs.inputs["Roughness"].default_value = 0.55
if "Subsurface Weight" in bs.inputs:
bs.inputs["Subsurface Weight"].default_value = 0.15
bs.inputs["Subsurface Radius"].default_value = (0.4, 0.6, 1.0)
if "Coat Weight" in bs.inputs:
bs.inputs["Coat Weight"].default_value = 0.15
# fine sparkle bump
fine = N.new("ShaderNodeTexNoise"); fine.inputs["Scale"].default_value = 1.8
L.new(tc.outputs["Object"], fine.inputs["Vector"])
bump = N.new("ShaderNodeBump"); bump.inputs["Strength"].default_value = 0.25
L.new(fine.outputs["Fac"], bump.inputs["Height"])
L.new(bump.outputs["Normal"], bs.inputs["Normal"])
out(N, L, bs.outputs["BSDF"])
m.diffuse_color = (0.95, 0.97, 1, 1)
return m
def mat_snow_soft():
"""Fence snow: bright, soft subsurface look with tiny glints (like the reference snow caps)."""
m, N, L = new_mat("Snow_Soft")
tc = N.new("ShaderNodeTexCoord")
bs = N.new("ShaderNodeBsdfPrincipled")
nz = N.new("ShaderNodeTexNoise"); nz.inputs["Scale"].default_value = 1.2
L.new(tc.outputs["Object"], nz.inputs["Vector"])
ramp = N.new("ShaderNodeValToRGB")
# low-poly look: near-white flat colour, faint cool tint, no micro detail (the facets do the work)
ramp.color_ramp.elements[0].color = (0.90, 0.94, 1.0, 1)
ramp.color_ramp.elements[1].color = (1.0, 1.0, 1.0, 1)
L.new(nz.outputs["Fac"], ramp.inputs["Fac"])
L.new(ramp.outputs["Color"], bs.inputs["Base Color"])
bs.inputs["Roughness"].default_value = 0.6
if "Subsurface Weight" in bs.inputs:
bs.inputs["Subsurface Weight"].default_value = 0.08
bs.inputs["Subsurface Radius"].default_value = (0.7, 0.85, 1.0)
bs.inputs["Subsurface Scale"].default_value = 0.1
# a touch of self-light so shadowed facets stay white rather than grey-blue
bs.inputs["Emission Color"].default_value = (0.92, 0.95, 1.0, 1)
bs.inputs["Emission Strength"].default_value = 0.12
out(N, L, bs.outputs["BSDF"])
m.diffuse_color = (0.95, 0.97, 1, 1)
return m
def mat_rock():
m, N, L = new_mat("Cliff_Rock")
tc = N.new("ShaderNodeTexCoord")
wave = N.new("ShaderNodeTexWave"); wave.wave_type = "BANDS"; wave.bands_direction = "Z"
wave.inputs["Scale"].default_value = 0.035; wave.inputs["Distortion"].default_value = 6; wave.inputs["Detail"].default_value = 4
L.new(tc.outputs["Object"], wave.inputs["Vector"])
nz = N.new("ShaderNodeTexNoise"); nz.inputs["Scale"].default_value = 0.12; nz.inputs["Detail"].default_value = 8
L.new(tc.outputs["Object"], nz.inputs["Vector"])
mix = N.new("ShaderNodeMix"); mix.data_type = "FLOAT"; mix.inputs["Factor"].default_value = 0.5
L.new(wave.outputs["Fac"], mix.inputs["A"]); L.new(nz.outputs["Fac"], mix.inputs["B"])
ramp = N.new("ShaderNodeValToRGB")
ramp.color_ramp.elements[0].color = (0.10, 0.11, 0.16, 1)
ramp.color_ramp.elements[1].color = (0.42, 0.44, 0.55, 1)
L.new(mix.outputs["Result"], ramp.inputs["Fac"])
bs = N.new("ShaderNodeBsdfPrincipled")
L.new(ramp.outputs["Color"], bs.inputs["Base Color"])
bs.inputs["Roughness"].default_value = 0.85
bump = N.new("ShaderNodeBump"); bump.inputs["Strength"].default_value = 0.8
L.new(mix.outputs["Result"], bump.inputs["Height"])
L.new(bump.outputs["Normal"], bs.inputs["Normal"])
out(N, L, bs.outputs["BSDF"])
m.diffuse_color = (0.3, 0.32, 0.4, 1)
return m
def mat_tiles(name, c1, c2, mortar, scale, radial=False):
m, N, L = new_mat(name)
tc = N.new("ShaderNodeTexCoord")
vec = tc.outputs["Object"]
if radial: # polar coordinates -> rings of tiles around the plaza centre
sep = N.new("ShaderNodeSeparateXYZ"); L.new(vec, sep.inputs[0])
at = N.new("ShaderNodeMath"); at.operation = "ARCTAN2"
L.new(sep.outputs["Y"], at.inputs[0]); L.new(sep.outputs["X"], at.inputs[1])
ln = N.new("ShaderNodeVectorMath"); ln.operation = "LENGTH"; L.new(vec, ln.inputs[0])
sc_ = N.new("ShaderNodeMath"); sc_.operation = "MULTIPLY"; sc_.inputs[1].default_value = 6.0
L.new(at.outputs["Value"], sc_.inputs[0])
comb = N.new("ShaderNodeCombineXYZ")
L.new(sc_.outputs["Value"], comb.inputs["X"]); L.new(ln.outputs["Value"], comb.inputs["Y"])
vec = comb.outputs["Vector"]
br = N.new("ShaderNodeTexBrick")
br.inputs["Color1"].default_value = (*c1, 1); br.inputs["Color2"].default_value = (*c2, 1)
br.inputs["Mortar"].default_value = (*mortar, 1)
br.inputs["Scale"].default_value = scale
br.inputs["Mortar Size"].default_value = 0.025
br.inputs["Brick Width"].default_value = 0.5; br.inputs["Row Height"].default_value = 0.35
br.offset = 0.5
L.new(vec, br.inputs["Vector"])
nz = N.new("ShaderNodeTexNoise"); nz.inputs["Scale"].default_value = 0.4
L.new(tc.outputs["Object"], nz.inputs["Vector"])
snowmix = N.new("ShaderNodeMix"); snowmix.data_type = "RGBA"
pw = N.new("ShaderNodeMath"); pw.operation = "POWER"; pw.inputs[1].default_value = 6.0
L.new(nz.outputs["Fac"], pw.inputs[0])
L.new(pw.outputs["Value"], snowmix.inputs["Factor"])
L.new(br.outputs["Color"], snowmix.inputs["A"])
snowmix.inputs["B"].default_value = (0.92, 0.94, 1.0, 1) # light dusting of snow
bs = N.new("ShaderNodeBsdfPrincipled")
L.new(snowmix.outputs["Result"], bs.inputs["Base Color"])
bs.inputs["Roughness"].default_value = 0.7
bump = N.new("ShaderNodeBump"); bump.inputs["Strength"].default_value = 0.6
inv = N.new("ShaderNodeMath"); inv.operation = "SUBTRACT"; inv.inputs[0].default_value = 1.0
L.new(br.outputs["Fac"], inv.inputs[1]); L.new(inv.outputs["Value"], bump.inputs["Height"])
L.new(bump.outputs["Normal"], bs.inputs["Normal"])
out(N, L, bs.outputs["BSDF"])
m.diffuse_color = (*c1, 1)
return m
# stylised flat-colour wood (like the sample): warm tan boards with per-board tone, soft posterised
# light/dark patches along the board, sparse thin outlined grain lines, a few outlined knots.
WOOD_TOP = (0.74, 0.27, 0.09) # light orange at the top of a board
WOOD_BOTTOM = (0.36, 0.10, 0.03) # darker brown at the bottom
WOOD_LINE = (0.12, 0.025, 0.007) # thin dark grain lines / outlines
WOOD_KNOT = (0.16, 0.035, 0.01)
WOOD_HILITE = (0.90, 0.42, 0.18) # thin light edge next to grain lines
def mat_wood():
m, N, L = new_mat("Fence_Wood")
uvn = N.new("ShaderNodeUVMap"); uvn.uv_map = "UVMap"
sep = N.new("ShaderNodeSeparateXYZ"); L.new(uvn.outputs["UV"], sep.inputs[0])
def math_(op, a, b=None, val=None):
n = N.new("ShaderNodeMath"); n.operation = op
L.new(a, n.inputs[0])
if b is not None:
L.new(b, n.inputs[1])
elif val is not None:
n.inputs[1].default_value = val
return n.outputs["Value"]
def mix_col(fac, a, b):
n = N.new("ShaderNodeMix"); n.data_type = "RGBA"
L.new(fac, n.inputs["Factor"])
if isinstance(a, tuple):
n.inputs["A"].default_value = (*a, 1)
else:
L.new(a, n.inputs["A"])
if isinstance(b, tuple):
n.inputs["B"].default_value = (*b, 1)
else:
L.new(b, n.inputs["B"])
return n.outputs["Result"]
# inputs: per-face 0..1 coords, face size in studs, per-face seed
dn = N.new("ShaderNodeUVMap"); dn.uv_map = "FaceDims"
dsep = N.new("ShaderNodeSeparateXYZ"); L.new(dn.outputs["UV"], dsep.inputs[0])
sn = N.new("ShaderNodeUVMap"); sn.uv_map = "FaceSeed"
ssep = N.new("ShaderNodeSeparateXYZ"); L.new(sn.outputs["UV"], ssep.inputs[0])
U, V = sep.outputs["X"], sep.outputs["Y"]
Wd, Ln, S = dsep.outputs["X"], dsep.outputs["Y"], ssep.outputs["X"]
u_st = math_("MULTIPLY", U, Wd) # studs across the face
v_st = math_("MULTIPLY", V, Ln) # studs along the face
seed10 = math_("MULTIPLY", S, val=37.0)
# 1) one board per face: light at the top, darker toward the bottom in soft stepped bands
wob = N.new("ShaderNodeTexNoise"); wob.noise_dimensions = "2D"; wob.inputs["Scale"].default_value = 1.0
wv = N.new("ShaderNodeCombineXYZ")
L.new(math_("MULTIPLY", u_st, val=0.8), wv.inputs["X"]); L.new(math_("ADD", math_("MULTIPLY", v_st, val=0.5), seed10), wv.inputs["Y"])
L.new(wv.outputs["Vector"], wob.inputs["Vector"])
g = math_("ADD", V, math_("MULTIPLY", math_("SUBTRACT", wob.outputs["Fac"], val=0.5), val=0.18))
steps = math_("DIVIDE", math_("FLOOR", math_("MULTIPLY", g, val=7.0)), val=7.0) # posterised bands
grad = N.new("ShaderNodeValToRGB"); gcr = grad.color_ramp
gcr.elements[0].color = (*WOOD_BOTTOM, 1)
gcr.elements[1].color = (*WOOD_TOP, 1)
L.new(steps, grad.inputs["Fac"])
# slight per-face tone shift so neighbouring faces/boards differ
tone = math_("ADD", math_("MULTIPLY", S, val=0.25), val=0.88)
tn = N.new("ShaderNodeMix"); tn.data_type = "RGBA"; tn.blend_type = "MULTIPLY"; tn.inputs["Factor"].default_value = 1.0
tcomb = N.new("ShaderNodeCombineColor")
for ch in ("Red", "Green", "Blue"):
L.new(tone, tcomb.inputs[ch])
L.new(grad.outputs["Color"], tn.inputs["A"]); L.new(tcomb.outputs["Color"], tn.inputs["B"])
col = tn.outputs["Result"]
# darker strip along both long edges (bevelled-board look)
edge_d = math_("MULTIPLY", math_("MINIMUM", U, math_("SUBTRACT", math_("MULTIPLY", U, val=-1.0), val=-1.0)), Wd)
col = mix_col(math_("MULTIPLY", math_("LESS_THAN", edge_d, val=0.16), val=0.35), col, WOOD_BOTTOM)
# 2) 2-3 thin, partly-broken grain lines running along the board
gv = N.new("ShaderNodeCombineXYZ")
L.new(math_("ADD", u_st, seed10), gv.inputs["X"])
L.new(math_("MULTIPLY", v_st, val=0.07), gv.inputs["Y"])
wave = N.new("ShaderNodeTexWave"); wave.wave_type = "BANDS"; wave.bands_direction = "X"
wave.wave_profile = "SAW"
wave.inputs["Scale"].default_value = 1.4
wave.inputs["Distortion"].default_value = 1.6
wave.inputs["Detail"].default_value = 0.5
L.new(gv.outputs["Vector"], wave.inputs["Vector"])
brk = N.new("ShaderNodeTexNoise"); brk.noise_dimensions = "2D"; brk.inputs["Scale"].default_value = 1.0
bv = N.new("ShaderNodeCombineXYZ")
L.new(math_("MULTIPLY", u_st, val=2.0), bv.inputs["X"]); L.new(math_("ADD", math_("MULTIPLY", v_st, val=0.3), seed10), bv.inputs["Y"])
L.new(bv.outputs["Vector"], brk.inputs["Vector"])
keep = math_("GREATER_THAN", brk.outputs["Fac"], val=0.47)
away = math_("GREATER_THAN", edge_d, val=0.2) # no grain lines on the edge strips
line = math_("MULTIPLY", math_("MULTIPLY", math_("LESS_THAN", wave.outputs["Fac"], val=0.022), keep), away)
hi = math_("MULTIPLY", math_("MULTIPLY", math_("GREATER_THAN", wave.outputs["Fac"], val=0.022),
math_("LESS_THAN", wave.outputs["Fac"], val=0.045)), math_("MULTIPLY", keep, away))
col = mix_col(math_("MULTIPLY", hi, val=0.5), col, WOOD_HILITE)
col = mix_col(line, col, WOOD_LINE)
# 3) rare knots (outlined dark eye), only on some faces
kv = N.new("ShaderNodeCombineXYZ")
L.new(math_("MULTIPLY", u_st, val=1.2), kv.inputs["X"])
L.new(math_("ADD", math_("MULTIPLY", v_st, val=0.3), seed10), kv.inputs["Y"])
vor = N.new("ShaderNodeTexVoronoi"); vor.inputs["Scale"].default_value = 0.7
L.new(kv.outputs["Vector"], vor.inputs["Vector"])
sepc = N.new("ShaderNodeSeparateColor"); L.new(vor.outputs["Color"], sepc.inputs["Color"])
pick = math_("MULTIPLY", math_("GREATER_THAN", sepc.outputs["Red"], val=0.86), away)
d = vor.outputs["Distance"]
core = math_("MULTIPLY", math_("LESS_THAN", d, val=0.07), pick)
ring = math_("MULTIPLY", math_("MULTIPLY", math_("GREATER_THAN", d, val=0.095), math_("LESS_THAN", d, val=0.115)), pick)
col = mix_col(ring, col, WOOD_LINE)
col = mix_col(core, col, WOOD_KNOT)
# 4) thin dark outline on the long edges and the ends of every face
end_d = math_("MULTIPLY", math_("MINIMUM", V, math_("SUBTRACT", math_("MULTIPLY", V, val=-1.0), val=-1.0)), Ln)
outline = math_("MAXIMUM", math_("LESS_THAN", edge_d, val=0.045), math_("LESS_THAN", end_d, val=0.04))
col = mix_col(outline, col, WOOD_LINE)
bs = N.new("ShaderNodeBsdfPrincipled")
L.new(col, bs.inputs["Base Color"])
bs.inputs["Roughness"].default_value = 0.7
if "Specular IOR Level" in bs.inputs:
bs.inputs["Specular IOR Level"].default_value = 0.3
out(N, L, bs.outputs["BSDF"])
m.diffuse_color = (*WOOD_TOP, 1)
return m
def mat_simple(name, col, rough=0.5, emit=0.0, metal=0.0):
m, N, L = new_mat(name)
bs = N.new("ShaderNodeBsdfPrincipled")
bs.inputs["Base Color"].default_value = (*col, 1)
bs.inputs["Roughness"].default_value = rough
bs.inputs["Metallic"].default_value = metal
bs.inputs["Emission Color"].default_value = (*col, 1)
bs.inputs["Emission Strength"].default_value = emit
out(N, L, bs.outputs["BSDF"])
m.diffuse_color = (*col, 1)
return m
# ---------------------------------------------------------------- terrain
def build_island(coll, snow, rock):
SEG = 256
RINGS_TOP = 48
bm = bmesh.new()
def edge_r(a):
return ISLAND_R * (1.0 + 0.035 * noise.noise(Vector((math.cos(a) * 3, math.sin(a) * 3, 0.5)))
+ 0.015 * noise.noise(Vector((math.cos(a) * 11, math.sin(a) * 11, 2.0))))
angles = [2 * math.pi * k / SEG for k in range(SEG)]
er = [edge_r(a) for a in angles]
centre = bm.verts.new((0, 0, 0))
grid = []
for ri in range(1, RINGS_TOP + 1):
t = ri / RINGS_TOP
row = []
for k, a in enumerate(angles):
r = er[k] * t
x, y = r * math.cos(a), r * math.sin(a)
z = 0.0
if not flat_area(x, y):
z = 2.6 * max(0.0, noise.noise(Vector((x * 0.035, y * 0.035, 7.0)))) + 0.3
z *= min(1.0, (1 - t) * 6) # settle to 0 at the edge lip
if ri == RINGS_TOP:
z = 0.6 # snow lip slightly raised at the rim
row.append(bm.verts.new((x, y, z)))
grid.append(row)
for k in range(SEG):
bm.faces.new((centre, grid[0][k], grid[0][(k + 1) % SEG])).material_index = 0
for ri in range(RINGS_TOP - 1):
for k in range(SEG):
k2 = (k + 1) % SEG
bm.faces.new((grid[ri][k], grid[ri + 1][k], grid[ri + 1][k2], grid[ri][k2])).material_index = 0
# side: snow skirt with drips, then a jagged rocky cone
profile = [(1.012, -1.5, 0), (1.010, -4.0, 0), (0.995, -6.0, 1), (0.97, -14, 1), (0.93, -28, 1),
(0.86, -46, 1), (0.74, -66, 1), (0.57, -88, 1), (0.36, -110, 1), (0.16, -128, 1)]
prev = grid[-1]
for pi_, (f, z, mi) in enumerate(profile):
row = []
for k, a in enumerate(angles):
jag = 1.0
zz = z
if mi == 1:
jag += 0.06 * noise.noise(Vector((math.cos(a) * 6, math.sin(a) * 6, z * 0.05)))
jag += 0.03 * noise.noise(Vector((math.cos(a) * 25, math.sin(a) * 25, z * 0.2)))
else:
if pi_ == 1: # snow drips hanging over the cliff
zz -= 2.5 * max(0.0, noise.noise(Vector((math.cos(a) * 30, math.sin(a) * 30, 1.0))))
r = er[k] * f * jag
row.append(bm.verts.new((r * math.cos(a), r * math.sin(a), zz)))
for k in range(SEG):
k2 = (k + 1) % SEG
bm.faces.new((prev[k], row[k], row[k2], prev[k2])).material_index = mi
prev = row
tip = bm.verts.new((0, 0, -140))
for k in range(SEG):
bm.faces.new((prev[k], tip, prev[(k + 1) % SEG])).material_index = 1
bmesh.ops.recalc_face_normals(bm, faces=list(bm.faces))
me = bpy.data.meshes.new("Island")
bm.to_mesh(me); bm.free()
me.materials.append(snow); me.materials.append(rock)
for p in me.polygons:
p.use_smooth = True
ob = bpy.data.objects.new("Island", me)
coll.objects.link(ob)
return ob
def cylinder(name, coll, mat, r, z0, z1, seg=128):
bm = bmesh.new()
bmesh.ops.create_cone(bm, cap_ends=True, cap_tris=True, segments=seg, radius1=r, radius2=r, depth=z1 - z0,
matrix=Matrix.Translation((0, 0, (z0 + z1) / 2)))
me = bpy.data.meshes.new(name)
bm.to_mesh(me); bm.free()
me.materials.append(mat)
ob = bpy.data.objects.new(name, me)
bv = ob.modifiers.new("Bevel", "BEVEL"); bv.width = 0.15; bv.segments = 2; bv.limit_method = "ANGLE"
coll.objects.link(ob)
return ob
def build_plaza_and_paths(coll, tiles, tiles_inner, curb):
cylinder("Plaza_Border", coll, curb, PLAZA_R + 2.5, -0.5, 0.35)
cylinder("Plaza_Tiles", coll, tiles, PLAZA_R, -0.4, 0.45)
cylinder("Plaza_Inner_Ring", coll, curb, PLAZA_INNER_R + 1.2, -0.3, 0.5)
cylinder("Plaza_Inner_Tiles", coll, tiles_inner, PLAZA_INNER_R, -0.2, 0.55)
bm = bmesh.new()
def box(c, size, yaw, mi):
M = Matrix.Translation(c) @ Matrix.Rotation(yaw, 4, "Z") @ Matrix.Diagonal((size[0], size[1], size[2], 1))
ret = bmesh.ops.create_cube(bm, size=1.0, matrix=M)
for f in {f for v in ret["verts"] for f in v.link_faces}:
f.material_index = mi
for i in range(ZONE_COUNT):
th, er, et, c = zone_frame(i)
r0, r1 = PLAZA_R - 1.0, ZONE_RING_R - ZONE_B + 2.0
L_ = r1 - r0
mid = er * ((r0 + r1) / 2)
yaw = th
box(Vector((mid.x, mid.y, 0.15)), (L_, PATH_HALF * 2, 0.6), yaw, 0) # path tiles
for s in (-1, 1): # curbs
cp = mid + et * s * (PATH_HALF + 0.45)
box(Vector((cp.x, cp.y, 0.25)), (L_ - 3.0, 0.9, 0.8), yaw, 1)
me = bpy.data.meshes.new("Paths")
bm.to_mesh(me); bm.free()
me.materials.append(tiles); me.materials.append(curb)
ob = bpy.data.objects.new("Paths", me)
bv = ob.modifiers.new("Bevel", "BEVEL"); bv.width = 0.12; bv.segments = 2; bv.limit_method = "ANGLE"
coll.objects.link(ob)
# ---------------------------------------------------------------- fences
def zone_perimeter(a, b, r):
"""Dense CCW polyline of the rounded rectangle, from the right gate edge round to the left gate edge."""
pts = [Vector((GATE_HALF, -b))]
def arc(cx, cy, a0, a1, n=14):
for k in range(1, n + 1):
t = math.radians(a0 + (a1 - a0) * k / n)
pts.append(Vector((cx + r * math.cos(t), cy + r * math.sin(t))))
pts.append(Vector((a - r, -b)))
arc(a - r, -b + r, -90, 0)
pts.append(Vector((a, b - r)))
arc(a - r, b - r, 0, 90)
pts.append(Vector((-(a - r), b)))
arc(-(a - r), b - r, 90, 180)
pts.append(Vector((-a, -b + r)))
arc(-(a - r), -b + r, 180, 270)
pts.append(Vector((-GATE_HALF, -b)))
return pts
def resample(poly, step):
seglens = [(poly[i + 1] - poly[i]).length for i in range(len(poly) - 1)]
total = sum(seglens)
n = max(1, round(total / step))
out_, targets = [], [total * k / n for k in range(n + 1)]
acc, si = 0.0, 0
for t in targets:
while si < len(seglens) - 1 and acc + seglens[si] < t:
acc += seglens[si]; si += 1
f = 0.0 if seglens[si] == 0 else (t - acc) / seglens[si]
out_.append(poly[si].lerp(poly[si + 1], min(1.0, f)))
return out_
def uv_box(bm, uvl, center, size, yaw, mi=0, rot_y=0.0):
"""Box where EVERY FACE is its own board (like one side of a beam in the reference):
UVMap = 0..1 across (U) and along (V) the face; V runs along the box's long axis, V=1 at the top
FaceDims = (face width, face length) in studs
FaceSeed = (random seed per face, random)"""
uv, dims, seed = uvl
hs = [s / 2 for s in size]
R = Matrix.Rotation(yaw, 4, "Z") @ Matrix.Rotation(rot_y, 4, "Y")
verts = {}
for sx in (-1, 1):
for sy in (-1, 1):
for sz in (-1, 1):
verts[(sx, sy, sz)] = bm.verts.new(Vector(center) + R @ Vector((sx * hs[0], sy * hs[1], sz * hs[2])))
long_ax = max(range(3), key=lambda a: size[a])
for a in range(3):
for s in (-1, 1):
o = [k for k in range(3) if k != a]
keys = []
for cu, cv in ((-1, -1), (1, -1), (1, 1), (-1, 1)):
k = [0, 0, 0]; k[a] = s; k[o[0]] = cu; k[o[1]] = cv
keys.append(tuple(k))
f = bm.faces.new([verts[k] for k in keys])
f.material_index = mi
vax = long_ax if long_ax in o else max(o, key=lambda q: size[q])
uax = o[0] if o[1] == vax else o[1]
fs = (random.random(), random.random())
for lp, k in zip(f.loops, keys):
lp[uv].uv = ((k[uax] + 1) / 2, (k[vax] + 1) / 2)
lp[dims].uv = (size[uax], size[vax])
lp[seed].uv = fs
def finish_obj(name, bm, mats, coll, bevel, segs, angle=40):
bmesh.ops.recalc_face_normals(bm, faces=list(bm.faces))
me = bpy.data.meshes.new(name)
bm.to_mesh(me); bm.free()
for m in mats:
me.materials.append(m)
for p in me.polygons:
p.use_smooth = True
ob = bpy.data.objects.new(name, me)
bv = ob.modifiers.new("Bevel", "BEVEL")
bv.width, bv.segments, bv.limit_method = bevel, segs, "ANGLE"
bv.angle_limit = math.radians(angle)
bv.harden_normals = True
bv.use_clamp_overlap = True
coll.objects.link(ob)
return ob
def build_fence(i, coll, wood, snow, wire, bulb, bulb2):
th, er, et, c = zone_frame(i)
def W(u, v, z=0.0):
p = c + et * u + er * v
return Vector((p.x, p.y, z))
zone_name = "Zone_%02d" % (i + 1)
bw = bmesh.new() # wood
uvl = (bw.loops.layers.uv.new("UVMap"), bw.loops.layers.uv.new("FaceDims"), bw.loops.layers.uv.new("FaceSeed"))
bl = bmesh.new() # lights
# snow = metaballs: elements melt into each other -> soft, rounded caps with wavy, drooping edges
mb = bpy.data.metaballs.new(zone_name + "_SnowMB")
mb.resolution = mb.render_resolution = SNOW_RES
mb.threshold = 0.6
def melem(kind, co, radius, size=None, yaw=0.0, vertical=False, stiff=2.0):
e = mb.elements.new(type=kind)
e.co = co
e.radius = radius
e.stiffness = stiff
if size is not None:
e.size_x, e.size_y, e.size_z = size
q = Matrix.Rotation(yaw, 4, "Z").to_quaternion()
if vertical: # capsules run along local X; stand them up for drips
q = q @ Matrix.Rotation(math.radians(90), 4, "Y").to_quaternion()
e.rotation = q
return e
def drip(top_point, yaw, ln, r):
"""Hanging icicle-like drip: a vertical capsule ending in a rounder bead."""
melem("CAPSULE", top_point - Vector((0, 0, ln / 2)), r, size=(ln / 2, 1, 1), yaw=yaw, vertical=True)
melem("BALL", top_point - Vector((0, 0, ln)), r * 1.25)
def lbox(center, size, yaw, mi):
M = Matrix.Translation(center) @ Matrix.Rotation(yaw, 4, "Z") @ Matrix.Diagonal((size[0], size[1], size[2], 1))
ret = bmesh.ops.create_cube(bl, size=1.0, matrix=M)
for f in {f for v in ret["verts"] for f in v.link_faces}:
f.material_index = mi
def lbulb(center, r, mi):
M = Matrix.Translation(center) @ Matrix.Diagonal((r, r, r * 1.35, 1))
ret = bmesh.ops.create_icosphere(bl, subdivisions=2, radius=1.0, matrix=M)
for f in {f for v in ret["verts"] for f in v.link_faces}:
f.material_index = mi
def snow_cap(base, w, h, yaw):
"""Soft snow cap: rounded slab overhanging the post, a dome on top, a wavy drooping rim
made of melted beads, and a couple of drips."""
hw = w / 2
# chunky: thick overhanging slab + tall dome
melem("CUBE", base + Vector((0, 0, h + 0.45)), 0.75, size=(hw + 0.05, hw + 0.05, 0.28), yaw=yaw)
melem("ELLIPSOID", base + Vector((0, 0, h + 1.0)), 1.0, size=(hw * 0.95, hw * 0.95, 0.75), yaw=yaw)
rot = Matrix.Rotation(yaw, 4, "Z")
edge = hw + 0.45
for side in range(4):
n = rot @ Vector((math.cos(side * math.pi / 2), math.sin(side * math.pi / 2), 0))
t = Vector((-n.y, n.x, 0))
steps = 3
for s in range(steps + 1): # fat, wavy drooping rim
u = -edge + 2 * edge * s / steps
droop = random.uniform(0.0, 0.25)
melem("BALL", base + n * (edge - 0.05) + t * u + Vector((0, 0, h + 0.12 - droop)),
random.uniform(0.42, 0.55))
# flowing snow: 1-2 soft tongues sliding down the side, each ending in a long drip
for _ in range(random.choice((1, 1, 2))):
u = random.uniform(-hw * 0.8, hw * 0.8)
tl = random.uniform(0.45, 0.85) # tongue length
pt = base + n * (edge - 0.22) + t * u + Vector((0, 0, h - tl / 2 + 0.1))
melem("ELLIPSOID", pt, 1.0, size=(random.uniform(0.35, 0.5), 0.26, tl / 2 + 0.15),
yaw=yaw + side * math.pi / 2)
tip = base + n * (edge - 0.2) + t * (u + random.uniform(-0.15, 0.15)) + Vector((0, 0, h - tl + 0.15))
drip(tip, yaw, random.uniform(0.35, 1.1), random.uniform(0.17, 0.24))
for _ in range(random.choice((0, 1, 2))): # extra short drips along the rim
p = base + n * (edge - 0.1) + t * random.uniform(-hw, hw) + Vector((0, 0, h))
drip(p, yaw, random.uniform(0.3, 0.7), random.uniform(0.17, 0.23))
posts = resample(zone_perimeter(ZONE_A, ZONE_B, ZONE_CORNER), POST_STEP)
n_posts = len(posts)
GATE_W, GATE_POST_H = 2.4, 8.0
for k, p in enumerate(posts):
gate = k in (0, n_posts - 1)
prev_p, next_p = posts[max(k - 1, 0)], posts[min(k + 1, n_posts - 1)]
dl = W(next_p.x, next_p.y) - W(prev_p.x, prev_p.y)
yaw = th if gate else math.atan2(dl.y, dl.x)
base = W(p.x, p.y)
w, h = (GATE_W, GATE_POST_H) if gate else (POST_W, POST_H)
uv_box(bw, uvl, base + Vector((0, 0, h / 2)), (w, w, h), yaw)
uv_box(bw, uvl, base + Vector((0, 0, h - 0.25)), (w + 0.35, w + 0.35, 0.5), yaw) # chunky top collar
uv_box(bw, uvl, base + Vector((0, 0, 0.3)), (w + 0.3, w + 0.3, 0.6), yaw) # foot
if gate:
snow_cap(base, w + 0.35, h, yaw)
lbox(base + Vector((0, 0, h + 1.35)), (0.5, 0.5, 0.5), yaw, 0) # lantern stem
lbulb(base + Vector((0, 0, h + 2.05)), 0.62, 1) # glowing lantern
else:
snow_cap(base, w + 0.35, h, yaw)
for k in range(n_posts - 1):
a_, b_ = W(posts[k].x, posts[k].y), W(posts[k + 1].x, posts[k + 1].y)
d = b_ - a_
yaw = math.atan2(d.y, d.x)
mid = (a_ + b_) / 2
L_ = d.length - POST_W + 0.3
for z in RAIL_Z:
uv_box(bw, uvl, mid + Vector((0, 0, z)), (L_, RAIL_T, RAIL_H), yaw) # thick rails
top = RAIL_Z[1] + RAIL_H / 2
low = RAIL_Z[0] + RAIL_H / 2
tvec = d.normalized()
nvec = Vector((-tvec.y, tvec.x, 0))
# soft snow roll on the top rail: rounded slab + melted beads along both edges (wavy overhang)
# chunky roll: thick rounded slab + fat beads along both edges
melem("CUBE", mid + Vector((0, 0, top + 0.25)), 0.6, size=(L_ / 2 - 0.2, RAIL_T / 2 - 0.05, 0.16), yaw=yaw)
nb = max(3, int(L_ / 0.9))
for s_ in (-1, 1):
for bi in range(nb + 1):
u = -L_ / 2 + 0.3 + (L_ - 0.6) * bi / nb
droop = random.uniform(0.0, 0.2)
melem("BALL", mid + tvec * u + nvec * s_ * (RAIL_T / 2 + 0.12) + Vector((0, 0, top + 0.05 - droop)),
random.uniform(0.34, 0.46))
for _ in range(random.randint(2, 4)): # snow sliding over the rail edge + drips
s_ = random.choice((-1, 1))
u = random.uniform(-L_ / 2.6, L_ / 2.6)
tl = random.uniform(0.35, 0.7)
pt = mid + tvec * u + nvec * s_ * (RAIL_T / 2 + 0.1) + Vector((0, 0, top - tl / 2 + 0.1))
melem("ELLIPSOID", pt, 1.0, size=(random.uniform(0.35, 0.6), 0.22, tl / 2 + 0.12), yaw=yaw)
p = mid + tvec * (u + random.uniform(-0.2, 0.2)) + nvec * s_ * (RAIL_T / 2 + 0.12) + Vector((0, 0, top - tl + 0.1))
drip(p, yaw, random.uniform(0.3, 0.9), random.uniform(0.16, 0.22))
# lumpy snow on the lower rail
melem("CUBE", mid + Vector((0, 0, low + 0.12)), 0.42, size=(L_ / 2 - 0.5, RAIL_T / 2 - 0.12, 0.06), yaw=yaw)
for bi in range(nb):
u = -L_ / 2 + 0.6 + (L_ - 1.2) * (bi + 0.5) / nb
melem("BALL", mid + tvec * u + nvec * random.uniform(-0.15, 0.15) + Vector((0, 0, low + 0.15)),
random.uniform(0.26, 0.36))
# string lights on both faces of the fence, sagging between posts
for s_ in (-1, 1):
off = nvec * s_ * (RAIL_T / 2 + 0.55)
n = 6
prev = None
for si in range(n + 1):
t = si / n
p = a_.lerp(b_, t) + off + Vector((0, 0, POST_H - 0.75 - 0.75 * math.sin(math.pi * t)))
if prev is not None:
seg = p - prev
mid_w = (p + prev) / 2
M = (Matrix.Translation(mid_w) @ Matrix.Rotation(yaw, 4, "Z")
@ Matrix.Rotation(-math.atan2(seg.z, seg.xy.length), 4, "Y")
@ Matrix.Diagonal((seg.length, 0.09, 0.09, 1)))
bmesh.ops.create_cube(bl, size=1.0, matrix=M)
if 0 < si < n:
lbulb(p - Vector((0, 0, 0.42)), 0.24, 1 if si % 2 else 2)
prev = p
# double gate: arched plank leaves with cross rails + diagonal brace, swung open into the zone
leaf_w = GATE_HALF - GATE_W / 2 - 0.1
for side in (-1, 1):
hinge = W(side * (GATE_HALF - GATE_W / 2 - 0.05), -ZONE_B)
open_yaw = th + side * math.radians(5) # ~95 deg open
dir_ = Vector((math.cos(open_yaw), math.sin(open_yaw), 0))
n_pl = 4
pw = leaf_w / n_pl
for pk in range(n_pl):
off = pw * (pk + 0.5)
closed_u = leaf_w - off # distance from the gate centre when closed
h = 3.6 + 1.2 * math.cos(min(1.0, closed_u / GATE_HALF) * math.pi / 2)
uv_box(bw, uvl, hinge + dir_ * off + Vector((0, 0, 0.3 + h / 2)), (pw - 0.06, 0.4, h), open_yaw)
for z in (1.4, 3.3):
uv_box(bw, uvl, hinge + dir_ * (leaf_w / 2) + Vector((0, 0, z)), (leaf_w, 0.7, 0.55), open_yaw)
diag = math.atan2(1.9, leaf_w - 0.4)
uv_box(bw, uvl, hinge + dir_ * (leaf_w / 2) + Vector((0, 0, 2.35)),
(math.hypot(leaf_w - 0.4, 1.9), 0.6, 0.45), open_yaw, rot_y=diag) # Z-brace
wood_ob = finish_obj(zone_name + "_Fence", bw, [wood], coll, 0.12, 2)
# polygonise the metaball snow into a regular smooth mesh
mb_ob = bpy.data.objects.new(zone_name + "_SnowMB", mb)
coll.objects.link(mb_ob)
dg = bpy.context.evaluated_depsgraph_get()
dg.update()
sme = bpy.data.meshes.new_from_object(mb_ob.evaluated_get(dg))
bpy.data.objects.remove(mb_ob, do_unlink=True)
bpy.data.metaballs.remove(mb)
sme.name = zone_name + "_FenceSnow"
for p in sme.polygons:
p.use_smooth = True
sme.materials.clear()
sme.materials.append(snow)
snow_ob = bpy.data.objects.new(zone_name + "_FenceSnow", sme)
coll.objects.link(snow_ob)
# metaballs over-tessellate flat areas: bake a collapse-decimate into the mesh (keeps the soft shape)
dec = snow_ob.modifiers.new("Decimate", "DECIMATE")
dec.ratio = SNOW_DECIMATE
dg = bpy.context.evaluated_depsgraph_get()
dg.update()
light_me = bpy.data.meshes.new_from_object(snow_ob.evaluated_get(dg))
snow_ob.modifiers.clear()
old = snow_ob.data
snow_ob.data = light_me
light_me.name = zone_name + "_FenceSnow"
bpy.data.meshes.remove(old)
for p in light_me.polygons:
p.use_smooth = True # smooth, fluffy snow
lights_ob = finish_obj(zone_name + "_Lights", bl, [wire, bulb, bulb2], coll, 0.02, 1, angle=60)
return wood_ob, n_posts
# ---------------------------------------------------------------- studio
def setup_studio(sc, coll):
w = bpy.data.worlds.new("Sky")
try:
w.use_nodes = True
except Exception:
pass
N, L = w.node_tree.nodes, w.node_tree.links
N.clear()
tc = N.new("ShaderNodeTexCoord"); sep = N.new("ShaderNodeSeparateXYZ")
L.new(tc.outputs["Window"], sep.inputs[0])
ramp = N.new("ShaderNodeValToRGB")
ramp.color_ramp.elements[0].color = (0.32, 0.62, 1.0, 1)
ramp.color_ramp.elements[1].color = (0.10, 0.36, 0.92, 1)
L.new(sep.outputs["Y"], ramp.inputs["Fac"])
bg_cam = N.new("ShaderNodeBackground"); L.new(ramp.outputs["Color"], bg_cam.inputs["Color"])
bg_env = N.new("ShaderNodeBackground")
bg_env.inputs["Color"].default_value = (0.45, 0.62, 1.0, 1); bg_env.inputs["Strength"].default_value = 0.9
lp = N.new("ShaderNodeLightPath"); mix = N.new("ShaderNodeMixShader")
L.new(lp.outputs["Is Camera Ray"], mix.inputs["Fac"])
L.new(bg_env.outputs["Background"], mix.inputs[1]); L.new(bg_cam.outputs["Background"], mix.inputs[2])
L.new(mix.outputs["Shader"], N.new("ShaderNodeOutputWorld").inputs["Surface"])
sc.world = w
sun = bpy.data.objects.new("Sun", bpy.data.lights.new("Sun", "SUN"))
sun.data.energy = 3.2
sun.data.color = (1.0, 0.93, 0.82)
sun.data.angle = math.radians(4)
sun.rotation_euler = (math.radians(58), 0, math.radians(-40))
coll.objects.link(sun)
cam = bpy.data.objects.new("Map_Camera", bpy.data.cameras.new("Map_Camera"))
cam.data.lens = 35
cam.data.clip_end = 5000
target = Vector((0, 0, -32))
dist, el = 500.0, math.radians(36)
cam.location = target + Vector((0, -dist * math.cos(el), dist * math.sin(el)))
cam.rotation_euler = (target - cam.location).to_track_quat("-Z", "Y").to_euler()
coll.objects.link(cam)
sc.camera = cam
sc.render.engine = "BLENDER_EEVEE"
try:
sc.eevee.use_raytracing = True
except Exception:
pass
sc.render.resolution_x, sc.render.resolution_y = 1920, 1080
try:
sc.view_settings.view_transform = "AgX"
sc.view_settings.look = "AgX - Medium High Contrast"
except Exception:
pass
try:
tree = bpy.data.node_groups.new("Map_Compositor", "CompositorNodeTree")
sc.compositing_node_group = tree
rl, gl, go = tree.nodes.new("CompositorNodeRLayers"), tree.nodes.new("CompositorNodeGlare"), tree.nodes.new("NodeGroupOutput")
tree.interface.new_socket("Image", in_out="OUTPUT", socket_type="NodeSocketColor")
try:
gl.glare_type = "BLOOM"
except Exception:
if "Type" in gl.inputs:
gl.inputs["Type"].default_value = "Bloom"
for k, v in (("Threshold", 1.0), ("Strength", 0.4), ("Size", 0.4)):
if k in gl.inputs:
gl.inputs[k].default_value = v
tree.links.new(rl.outputs["Image"], gl.inputs["Image"])
tree.links.new(gl.outputs["Image"], go.inputs[0])
except Exception as ex:
print("bloom unavailable:", ex)
# ---------------------------------------------------------------- main
def main():
os.makedirs(OUT_DIR, exist_ok=True)
sc, cols = setup_scene()
snow, rock = mat_snow(), mat_rock()
snow_soft = mat_snow_soft()
tiles = mat_tiles("Path_Tiles", (0.30, 0.20, 0.13), (0.24, 0.155, 0.10), (0.11, 0.09, 0.08), 0.13)
tiles_inner = mat_tiles("Plaza_Tiles_Radial", (0.36, 0.25, 0.17), (0.29, 0.19, 0.13), (0.12, 0.10, 0.09), 0.16, radial=True)
curb = mat_simple("Stone_Curb", (0.15, 0.14, 0.16), 0.75)
wood = mat_wood()
wire = mat_simple("Light_Wire", (0.03, 0.04, 0.03), 0.6)
bulb = mat_simple("Light_Bulb", (1.0, 0.72, 0.30), 0.2, emit=14.0)
bulb2 = mat_simple("Light_Bulb_Gold", (1.0, 0.50, 0.12), 0.2, emit=12.0)
build_island(cols["Terrain"], snow, rock)
build_plaza_and_paths(cols["Terrain"], tiles, tiles_inner, curb)
posts = 0
for i in range(ZONE_COUNT):
_, n = build_fence(i, cols["Fences"], wood, snow_soft, wire, bulb, bulb2)
posts += n
setup_studio(sc, cols["Studio"])
sc.render.filepath = os.path.join(OUT_DIR, "map_preview.png")
bpy.ops.render.render(write_still=True)
# close-up of the bottom zone's gate to show fence detail and string lights
cam = sc.camera
_, er, et, c = zone_frame(7) # zone at 270 deg (front, nearest the camera)
gate = c - er * ZONE_B
tgt = Vector((gate.x, gate.y, 4.0)) + er * 6
cam.location = Vector((gate.x, gate.y, 0)) - er * 30 + et * 16 + Vector((0, 0, 13))
cam.rotation_euler = (tgt - cam.location).to_track_quat("-Z", "Y").to_euler()
sc.render.filepath = os.path.join(OUT_DIR, "map_closeup.png")
bpy.ops.render.render(write_still=True)
bpy.ops.wm.save_as_mainfile(filepath=os.path.join(OUT_DIR, "map_terrain.blend"))
tris = sum(sum(len(p.vertices) - 2 for p in o.data.polygons) for o in bpy.data.objects if o.type == "MESH")
return {"posts": posts, "tris_base": tris}
if __name__ == "__main__":
print("RESULT", main())