"""
Forge 3D — Python worker for Google Colab, Kaggle, or any machine.

It connects to your Forge 3D modeler, picks up generation jobs, builds 3D models
(GLB), uploads them, and drops them straight into the scene that asked for them.

    !pip -q install trimesh numpy requests fast_simplification
    !wget -q -O modeler_worker.py https://<your-forge3d-site>/py/modeler_worker.py
    import modeler_worker
    modeler_worker.run(key="mk_...", background=True)     # Colab: keeps running in the background
    modeler_worker.run(key="mk_...", max_hours=8.5)       # Kaggle "Save & Run All": blocks until time is up

No GPU needed. Every job runs on a plain CPU runtime; a GPU only makes the optional AI engines faster.

Job kinds
  procedural   game assets built with trimesh (CPU, seconds): rock, tree, pine, house, crate, barrel, ...
  text_to_3d   prompt -> mesh. engine "auto": CPU = words -> procedural asset (instant), falling back to
               SDXL-turbo -> TripoSR on CPU (minutes) for things it has no generator for; GPU = SDXL -> TripoSR
  image_to_3d  image -> mesh. engine "auto": CPU = "relief" (cut-out + inflate, seconds, vertex colours);
               GPU = TripoSR. Ask for engine "triposr" to run TripoSR on CPU too (slower, better backs)
  optimize     decimate a GLB/OBJ/STL to a target triangle count
  python       run your own Python that builds a trimesh mesh (only if allow_python=True)
  blender_ops  real Blender modifiers on any model: subdivide, bevel, boolean, remesh, decimate, solidify, UV unwrap…
  blender      run your own bpy script in headless Blender (only if allow_python=True)
  render           Blender Cycles path-traced image of the scene, up to 8K. On CPU it uses adaptive sampling,
                   the light tree and OpenImageDenoise (albedo + normal guided), so 64-128 samples look clean
  text_to_texture  seamless PBR texture (albedo + normal + roughness, AO baked). engine "auto": CPU = procedural
                   material synth (numpy, 1-3 s at 2K); GPU = SDXL-turbo. "procedural" / "sdxl" to force
  terrain_erosion  realistic hydraulic erosion of a terrain (CPU)
  voxelize         any model -> blocks (CPU)
"""
from __future__ import annotations

import io
import json
import math
import os
import platform
import socket
import sys
import threading
import time
import traceback
import re
import uuid

import numpy as np
import requests
import trimesh

__version__ = "2.0.0"

SUPABASE_URL = os.environ.get("FORGE3D_SUPABASE_URL", "https://fhbqxujlnqlmzvulrdxt.supabase.co")
SUPABASE_ANON = os.environ.get(
    "FORGE3D_SUPABASE_ANON",
    "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImZoYnF4dWpsbnFsbXp2dWxyZHh0Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3ODc2MTc0NDQsImV4cCI6MjEwMzE5MzQ0NH0.ThFmY_FXQlnaaI8GNLz9xSHATOacM9iOb8u0G0WFJ2w",
)
BUCKET = "modeler-assets"
YUP = trimesh.transformations.rotation_matrix(-math.pi / 2, [1, 0, 0])  # Z-up -> Y-up


class Cancelled(Exception):
    pass


# --------------------------------------------------------------------------- API

class Api:
    def __init__(self, key: str, url: str = SUPABASE_URL, anon: str = SUPABASE_ANON):
        self.key, self.url, self.anon = key, url.rstrip("/"), anon
        self.s = requests.Session()
        self.s.headers.update({"apikey": anon, "Authorization": f"Bearer {anon}"})

    def rpc(self, fn: str, **params):
        params = {"p_key": self.key, **params}
        for attempt in range(4):
            try:
                r = self.s.post(f"{self.url}/rest/v1/rpc/{fn}", json=params, timeout=40)
            except requests.RequestException as e:
                if attempt == 3:
                    raise
                time.sleep(2 * (attempt + 1))
                continue
            if r.status_code >= 500 and attempt < 3:
                time.sleep(2 * (attempt + 1))
                continue
            if not r.ok:
                try:
                    msg = r.json().get("message") or r.text
                except Exception:
                    msg = r.text
                raise RuntimeError(f"{fn}: {msg}")
            return r.json() if r.text else None

    def upload(self, path: str, data: bytes, content_type: str) -> str:
        r = self.s.post(
            f"{self.url}/storage/v1/object/{BUCKET}/{path}",
            data=data,
            headers={"Content-Type": content_type, "x-upsert": "false"},
            timeout=180,
        )
        if not r.ok:
            raise RuntimeError(f"upload failed ({r.status_code}): {r.text[:300]}")
        return f"{self.url}/storage/v1/object/public/{BUCKET}/{path}"


# --------------------------------------------------------------------------- mesh helpers

def srgb_to_linear(c):
    c = np.asarray(c, dtype=np.float64) / 255.0
    lin = np.where(c <= 0.04045, c / 12.92, ((c + 0.055) / 1.055) ** 2.4)
    return np.clip(lin * 255.0 + 0.5, 0, 255).astype(np.uint8)


def hex_rgb(h, default=(200, 200, 200)):
    try:
        h = str(h).lstrip("#")
        if len(h) == 3:
            h = "".join(ch * 2 for ch in h)
        return tuple(int(h[i:i + 2], 16) for i in (0, 2, 4))
    except Exception:
        return default


def shade(rgb, f):
    return tuple(int(np.clip(v * f, 0, 255)) for v in rgb)


def paint(mesh: trimesh.Trimesh, rgb, jitter: float = 0.0, rng=None):
    """Give every face a colour (optionally jittered per face for a hand-made low-poly look)."""
    rgb = np.array(rgb[:3], dtype=np.float64)
    n = len(mesh.faces)
    cols = np.tile(rgb, (n, 1))
    if jitter and n:
        rng = rng or np.random.default_rng(0)
        cols *= (1.0 + rng.uniform(-jitter, jitter, size=(n, 1)))
    fc = np.zeros((n, 4), dtype=np.uint8)
    fc[:, :3] = np.clip(cols, 0, 255).astype(np.uint8)
    fc[:, 3] = 255
    mesh.visual = trimesh.visual.ColorVisuals(mesh, face_colors=fc)
    return mesh


def finalize(parts, smooth: bool = False) -> trimesh.Trimesh:
    """Merge coloured parts into one game-ready mesh with per-vertex colours (GLB COLOR_0, linear)."""
    if isinstance(parts, trimesh.Trimesh):
        parts = [parts]
    parts = [p for p in parts if p is not None and len(p.faces)]
    for p in parts:
        if not isinstance(p.visual, trimesh.visual.ColorVisuals) or p.visual.kind is None:
            paint(p, (200, 200, 200))
    m = trimesh.util.concatenate(parts)
    fc = np.asarray(m.visual.face_colors).copy()
    if smooth:
        m.visual = trimesh.visual.ColorVisuals(m, face_colors=fc)
        vc = np.asarray(m.visual.vertex_colors).copy()
        vc[:, :3] = srgb_to_linear(vc[:, :3])
        m.visual = trimesh.visual.ColorVisuals(m, vertex_colors=vc)
        return m
    m.unmerge_vertices()  # flat shading + exact per-face colour
    vc = np.repeat(fc, 3, axis=0)
    vc[:, :3] = srgb_to_linear(vc[:, :3])
    m.visual = trimesh.visual.ColorVisuals(m, vertex_colors=vc)
    return m


def box(ext, pos, rgb, **kw):
    m = trimesh.creation.box(extents=ext)
    m.apply_translation(pos)
    return paint(m, rgb, **kw)


def cyl(r, h, pos, rgb, sections=16, **kw):
    m = trimesh.creation.cylinder(radius=r, height=h, sections=sections)
    m.apply_transform(YUP)
    m.apply_translation([pos[0], pos[1] + h / 2, pos[2]])
    return paint(m, rgb, **kw)


def cone(r, h, pos, rgb, sections=12, **kw):
    m = trimesh.creation.cone(radius=r, height=h, sections=sections)
    m.apply_transform(YUP)
    m.apply_translation(pos)
    return paint(m, rgb, **kw)


def ico(r, pos, rgb, sub=1, **kw):
    m = trimesh.creation.icosphere(subdivisions=sub, radius=r)
    m.apply_translation(pos)
    return paint(m, rgb, **kw)


def hull(points, rgb, **kw):
    return paint(trimesh.convex.convex_hull(np.asarray(points, dtype=float)), rgb, **kw)


def lumpy(mesh, rng, amount=0.25, waves=10):
    """Displace vertices along their normals with a sum of random waves (cheap 3D noise)."""
    v = mesh.vertices
    n = mesh.vertex_normals
    disp = np.zeros(len(v))
    for _ in range(waves):
        d = rng.normal(size=3)
        d /= np.linalg.norm(d)
        f = rng.uniform(1.0, 4.5)
        disp += rng.uniform(0.3, 1.0) / f * np.cos(v @ d * f * 2.2 + rng.uniform(0, 6.28))
    disp = disp / (np.abs(disp).max() + 1e-9)
    mesh.vertices = v + n * (disp * amount)[:, None]
    return mesh


def _hash2(ix, iy, seed):
    n = (ix.astype(np.uint64) * np.uint64(374761393) + iy.astype(np.uint64) * np.uint64(668265263)
         + np.uint64(seed) * np.uint64(1442695041)) & np.uint64(0xFFFFFFFF)
    n = ((n ^ (n >> np.uint64(13))) * np.uint64(1274126177)) & np.uint64(0xFFFFFFFF)
    return ((n ^ (n >> np.uint64(16))) & np.uint64(0xFFFF)).astype(np.float64) / 65535.0


def value_noise(x, y, seed):
    xi, yi = np.floor(x), np.floor(y)
    xf, yf = x - xi, y - yi
    xi = (xi.astype(np.int64) + (1 << 20)).astype(np.uint64)
    yi = (yi.astype(np.int64) + (1 << 20)).astype(np.uint64)
    u, v = xf * xf * (3 - 2 * xf), yf * yf * (3 - 2 * yf)
    a, b = _hash2(xi, yi, seed), _hash2(xi + np.uint64(1), yi, seed)
    c, d = _hash2(xi, yi + np.uint64(1), seed), _hash2(xi + np.uint64(1), yi + np.uint64(1), seed)
    return (a + (b - a) * u) * (1 - v) + (c + (d - c) * u) * v


def fbm(x, y, seed, octaves=5):
    total, amp, freq, norm = 0.0, 1.0, 1.0, 0.0
    for o in range(octaves):
        total = total + amp * value_noise(x * freq, y * freq, seed + o * 101)
        norm += amp
        amp *= 0.5
        freq *= 2.0
    return total / norm


def normalize(mesh, size=1.0, ground=True, center=True):
    """Scale so the largest dimension == size, centre on X/Z, sit on y=0."""
    b = mesh.bounds
    ext = float((b[1] - b[0]).max()) or 1.0
    mesh.apply_scale(size / ext)
    b = mesh.bounds
    off = np.zeros(3)
    if center:
        off[0] = -(b[0][0] + b[1][0]) / 2
        off[2] = -(b[0][2] + b[1][2]) / 2
    if ground:
        off[1] = -b[0][1]
    mesh.apply_translation(off)
    return mesh


# --------------------------------------------------------------------------- procedural generators
# Every generator: (rng, size, detail, color) -> list of coloured parts (Y-up, sitting on y=0, ~1 unit tall)

GENERATORS = {}


def generator(name):
    def deco(fn):
        GENERATORS[name] = fn
        return fn
    return deco


@generator("rock")
def g_rock(rng, detail=2, color=None, **_):
    base = color or (128, 124, 118)
    m = trimesh.creation.icosphere(subdivisions=min(1 + detail, 3), radius=0.5)
    lumpy(m, rng, amount=0.18, waves=12)
    m.apply_scale([rng.uniform(0.9, 1.3), rng.uniform(0.55, 0.85), rng.uniform(0.8, 1.15)])
    m.apply_translation([0, -m.bounds[0][1] - 0.04, 0])
    paint(m, base, jitter=0.12, rng=rng)
    return [m]


@generator("rocks")
def g_rocks(rng, detail=2, color=None, **_):
    parts = []
    for i in range(rng.integers(3, 7)):
        r = g_rock(rng, detail=detail, color=color)[0]
        s = rng.uniform(0.25, 0.6) if i else 0.7
        r.apply_scale(s)
        a, d = rng.uniform(0, 6.28), rng.uniform(0, 0.55) if i else 0
        r.apply_translation([math.cos(a) * d, 0, math.sin(a) * d])
        parts.append(r)
    return parts


@generator("tree")
def g_tree(rng, detail=2, color=None, **_):
    leaf = color or (88, 150, 72)
    trunk_h = rng.uniform(0.38, 0.5)
    parts = [cyl(0.055, trunk_h + 0.1, [0, 0, 0], (110, 78, 52), sections=6 + 2 * detail, jitter=0.08, rng=rng)]
    for _ in range(rng.integers(3, 6)):
        r = rng.uniform(0.17, 0.27)
        p = [rng.uniform(-0.13, 0.13), trunk_h + rng.uniform(0.05, 0.3), rng.uniform(-0.13, 0.13)]
        b = ico(r, p, shade(leaf, rng.uniform(0.85, 1.12)), sub=min(detail, 2), jitter=0.1, rng=rng)
        lumpy(b, rng, amount=0.035, waves=6)
        parts.append(b)
    return parts


@generator("pine")
def g_pine(rng, detail=2, color=None, **_):
    leaf = color or (52, 112, 76)
    parts = [cyl(0.05, 0.25, [0, 0, 0], (98, 70, 48), sections=6 + detail * 2)]
    tiers = 3 + detail
    y = 0.15
    for i in range(tiers):
        t = i / max(tiers - 1, 1)
        r = 0.36 * (1 - 0.65 * t)
        h = 0.36 * (1 - 0.35 * t)
        parts.append(cone(r, h, [0, y, 0], shade(leaf, 0.9 + 0.2 * t), sections=6 + 2 * detail, jitter=0.07, rng=rng))
        y += h * 0.55
    return parts


@generator("bush")
def g_bush(rng, detail=2, color=None, **_):
    leaf = color or (78, 140, 70)
    parts = []
    for _ in range(rng.integers(4, 8)):
        r = rng.uniform(0.14, 0.24)
        p = [rng.uniform(-0.22, 0.22), r * 0.8, rng.uniform(-0.22, 0.22)]
        b = ico(r, p, shade(leaf, rng.uniform(0.85, 1.1)), sub=min(detail, 2), jitter=0.1, rng=rng)
        lumpy(b, rng, amount=0.03, waves=5)
        parts.append(b)
    if rng.random() < 0.5:
        for _ in range(rng.integers(3, 7)):
            a = rng.uniform(0, 6.28)
            parts.append(ico(0.025, [math.cos(a) * 0.25, rng.uniform(0.15, 0.35), math.sin(a) * 0.25], (220, 70, 80), sub=0))
    return parts


@generator("mushroom")
def g_mushroom(rng, detail=2, color=None, **_):
    cap = color or (200, 50, 45)
    stem_h = rng.uniform(0.35, 0.5)
    parts = [cyl(0.08, stem_h, [0, 0, 0], (235, 225, 205), sections=8 + 2 * detail)]
    c = trimesh.creation.icosphere(subdivisions=min(detail + 1, 3), radius=0.3)
    c.vertices[:, 1] = np.maximum(c.vertices[:, 1], -0.02) * 0.75
    c.apply_translation([0, stem_h, 0])
    parts.append(paint(c, cap, jitter=0.05, rng=rng))
    for _ in range(rng.integers(4, 9)):
        th, ph = rng.uniform(0, 6.28), rng.uniform(0.2, 1.1)
        p = [0.3 * math.sin(ph) * math.cos(th), stem_h + 0.3 * math.cos(ph) * 0.75, 0.3 * math.sin(ph) * math.sin(th)]
        parts.append(ico(0.035, p, (245, 242, 235), sub=0))
    return parts


@generator("terrain")
def g_terrain(rng, detail=2, color=None, height=0.22, **_):
    res = [24, 48, 96][min(detail, 3) - 1]
    seed = int(rng.integers(1 << 30))
    xs = np.linspace(-0.5, 0.5, res + 1)
    X, Z = np.meshgrid(xs, xs)
    H = fbm(X * 3.0 + 10, Z * 3.0 + 10, seed, octaves=5)
    H = (H - H.min()) / (np.ptp(H) + 1e-9)
    H = H ** 1.6 * float(height)
    verts = np.stack([X.ravel(), H.ravel(), Z.ravel()], axis=1)
    faces = []
    for i in range(res):
        for j in range(res):
            a = i * (res + 1) + j
            b, c, d = a + 1, a + res + 1, a + res + 2
            faces += [[a, c, b], [b, c, d]]
    m = trimesh.Trimesh(verts, np.array(faces), process=False)
    fh = m.triangles_center[:, 1] / max(float(height), 1e-6)
    slope = 1 - np.abs(m.face_normals[:, 1])
    grass = np.array(color or (96, 150, 78), dtype=float)
    cols = np.zeros((len(fh), 3))
    for i, (h, s) in enumerate(zip(fh, slope)):
        if h < 0.08:
            c = (196, 182, 132)
        elif s > 0.45 or h > 0.72:
            c = (120, 116, 110) if h < 0.88 else (236, 238, 242)
        else:
            c = tuple(grass * (0.9 + 0.25 * h))
        cols[i] = c
    cols *= rng.uniform(0.94, 1.06, size=(len(cols), 1))
    fc = np.zeros((len(cols), 4), dtype=np.uint8)
    fc[:, :3] = np.clip(cols, 0, 255)
    fc[:, 3] = 255
    m.visual = trimesh.visual.ColorVisuals(m, face_colors=fc)
    skirt = box([1, 0.04, 1], [0, -0.02, 0], (92, 74, 56))
    return [m, skirt]


@generator("house")
def g_house(rng, detail=2, color=None, **_):
    wall = color or tuple(int(v) for v in rng.choice([(226, 214, 190), (210, 180, 150), (190, 200, 210), (232, 228, 220)]))
    roof = tuple(int(v) for v in rng.choice([(150, 60, 50), (70, 80, 100), (110, 75, 55)]))
    w, d, h = rng.uniform(0.8, 1.0), rng.uniform(0.6, 0.8), rng.uniform(0.45, 0.6)
    rh = rng.uniform(0.3, 0.42)
    parts = [box([w, h, d], [0, h / 2, 0], wall, jitter=0.03, rng=rng)]
    o = 0.06
    pts = [[-w / 2 - o, h, -d / 2 - o], [w / 2 + o, h, -d / 2 - o], [-w / 2 - o, h, d / 2 + o], [w / 2 + o, h, d / 2 + o],
           [-w / 2 - o, h + rh, 0], [w / 2 + o, h + rh, 0]]
    parts.append(hull(pts, roof, jitter=0.05, rng=rng))
    parts.append(box([0.16, 0.28, 0.02], [0, 0.14, d / 2 + 0.005], (100, 66, 42)))
    for sx in (-1, 1):
        parts.append(box([0.14, 0.14, 0.02], [sx * w * 0.3, h * 0.6, d / 2 + 0.005], (150, 200, 230)))
        parts.append(box([0.02, 0.14, 0.14], [sx * (w / 2 + 0.005), h * 0.6, 0], (150, 200, 230)))
    parts.append(box([0.1, 0.25, 0.1], [w * 0.25, h + rh * 0.7, -d * 0.15], (130, 110, 100)))
    return parts


@generator("tower")
def g_tower(rng, detail=2, color=None, **_):
    stone = color or (150, 146, 138)
    secs = 8 + 4 * detail
    r, h = 0.28, 0.85
    parts = [cyl(r, h, [0, 0, 0], stone, sections=secs, jitter=0.06, rng=rng),
             cyl(r + 0.04, 0.06, [0, h, 0], shade(stone, 0.9), sections=secs)]
    n = 8
    for i in range(n):
        a = i / n * 2 * math.pi
        parts.append(box([0.08, 0.09, 0.08], [math.cos(a) * (r + 0.01), h + 0.1, math.sin(a) * (r + 0.01)], shade(stone, 0.95)))
    if rng.random() < 0.6:
        parts.append(cone(r + 0.06, 0.4, [0, h + 0.06, 0], (130, 50, 45), sections=secs))
    parts.append(box([0.12, 0.2, 0.05], [0, 0.1, r - 0.01], (80, 56, 38)))
    for y in (0.4, 0.62):
        a = rng.uniform(0, 6.28)
        parts.append(box([0.04, 0.1, 0.04], [math.cos(a) * r, y, math.sin(a) * r], (40, 40, 45)))
    return parts


@generator("crate")
def g_crate(rng, detail=2, color=None, **_):
    wood = color or (176, 122, 62)
    dark = shade(wood, 0.7)
    s, t = 1.0, 0.08
    parts = [box([s - 0.02, s - 0.02, s - 0.02], [0, s / 2, 0], wood, jitter=0.05, rng=rng)]
    for a in (-1, 1):
        for b in (-1, 1):
            parts.append(box([s, t, t], [0, s / 2 + a * (s / 2 - t / 2), b * (s / 2 - t / 2)], dark))
            parts.append(box([t, s, t], [a * (s / 2 - t / 2), s / 2, b * (s / 2 - t / 2)], dark))
            parts.append(box([t, t, s], [a * (s / 2 - t / 2), s / 2 + b * (s / 2 - t / 2), 0], dark))
    if detail >= 2:
        diag = trimesh.creation.box(extents=[s * 1.25, t * 0.8, 0.02])
        diag.apply_transform(trimesh.transformations.rotation_matrix(math.pi / 4, [0, 0, 1]))
        for z in (s / 2 + 0.005, -s / 2 - 0.005):
            dd = diag.copy()
            dd.apply_translation([0, s / 2, z])
            dd.vertices[:, 0] = np.clip(dd.vertices[:, 0], -s / 2 + t, s / 2 - t)
            dd.vertices[:, 1] = np.clip(dd.vertices[:, 1], t, s - t)
            parts.append(paint(dd, dark))
    return parts


@generator("barrel")
def g_barrel(rng, detail=2, color=None, **_):
    wood = color or (150, 98, 54)
    n = 8 + 4 * detail
    zs = np.linspace(0, 1.0, 9)
    prof = np.stack([0.32 + 0.07 * np.sin(zs * math.pi), zs], axis=1)
    prof = np.vstack([[0, 0], prof, [0, 1.0]])
    m = trimesh.creation.revolve(prof, sections=n)
    m.apply_transform(YUP)
    parts = [paint(m, wood, jitter=0.06, rng=rng)]
    for z in (0.12, 0.88, 0.5 if detail >= 2 else None):
        if z is None:
            continue
        rr = 0.32 + 0.07 * math.sin(z * math.pi)
        ring = trimesh.creation.annulus(r_min=rr - 0.01, r_max=rr + 0.012, height=0.045, sections=n)
        ring.apply_transform(YUP)
        ring.apply_translation([0, z, 0])
        parts.append(paint(ring, (70, 70, 76)))
    return parts


@generator("chest")
def g_chest(rng, detail=2, color=None, **_):
    wood = color or (140, 86, 44)
    gold = (214, 172, 64)
    w, d, h = 1.0, 0.62, 0.45
    parts = [box([w, h, d], [0, h / 2, 0], wood, jitter=0.05, rng=rng)]
    lid = trimesh.creation.cylinder(radius=d / 2, height=w, sections=6 + 4 * detail)
    lid.apply_transform(trimesh.transformations.rotation_matrix(math.pi / 2, [0, 1, 0]))
    lid.vertices[:, 1] = np.maximum(lid.vertices[:, 1], 0)
    lid.apply_scale([1, 0.7, 1])
    lid.apply_translation([0, h, 0])
    parts.append(paint(lid, shade(wood, 1.08), jitter=0.05, rng=rng))
    for x in (-w * 0.33, w * 0.33):
        parts.append(box([0.06, h + 0.01, d + 0.02], [x, h / 2, 0], gold))
        band = trimesh.creation.cylinder(radius=d / 2 + 0.012, height=0.06, sections=6 + 4 * detail)
        band.apply_transform(trimesh.transformations.rotation_matrix(math.pi / 2, [0, 1, 0]))
        band.vertices[:, 1] = np.maximum(band.vertices[:, 1], 0)
        band.apply_scale([1, 0.7, 1])
        band.apply_translation([x, h, 0])
        parts.append(paint(band, gold))
    parts.append(box([0.1, 0.13, 0.03], [0, h - 0.02, d / 2 + 0.012], gold))
    return parts


@generator("fence")
def g_fence(rng, detail=2, color=None, length=3, **_):
    wood = color or (160, 120, 80)
    length = int(max(1, min(int(length or 3), 12)))
    parts = []
    for i in range(length + 1):
        x = i - length / 2
        ph = 0.9 + rng.uniform(-0.04, 0.04)
        parts.append(box([0.1, ph, 0.1], [x, ph / 2, 0], shade(wood, rng.uniform(0.85, 1.0))))
        parts.append(hull([[x - 0.05, ph, -0.05], [x + 0.05, ph, -0.05], [x - 0.05, ph, 0.05], [x + 0.05, ph, 0.05], [x, ph + 0.07, 0]], shade(wood, 0.8)))
    for y in (0.3, 0.65):
        parts.append(box([length + 0.05, 0.08, 0.05], [0, y, 0.06], wood, jitter=0.05, rng=rng))
    return parts


@generator("wall")
def g_wall(rng, detail=2, color=None, length=3, **_):
    stone = color or (150, 146, 138)
    length = float(max(1, min(float(length or 3), 12)))
    rows, h = 4 + detail, 1.0
    rh = h / rows
    parts = []
    for r in range(rows):
        x = -length / 2 + (rng.uniform(0, 0.25) if r % 2 else 0)
        while x < length / 2 - 0.05:
            w = min(rng.uniform(0.3, 0.55), length / 2 - x)
            b = box([w - 0.02, rh - 0.02, 0.35 + rng.uniform(-0.03, 0.03)], [x + w / 2, r * rh + rh / 2, rng.uniform(-0.015, 0.015)],
                    shade(stone, rng.uniform(0.82, 1.1)))
            parts.append(b)
            x += w
    parts.append(box([length, 0.06, 0.4], [0, h + 0.03, 0], shade(stone, 0.9)))
    return parts


@generator("column")
def g_column(rng, detail=2, color=None, **_):
    marble = color or (232, 228, 218)
    secs = 8 + 4 * detail
    parts = [box([0.5, 0.08, 0.5], [0, 0.04, 0], shade(marble, 0.95)),
             cyl(0.2, 0.06, [0, 0.08, 0], marble, sections=secs),
             cyl(0.16, 1.6, [0, 0.14, 0], marble, sections=secs, jitter=0.02, rng=rng),
             cyl(0.2, 0.06, [0, 1.74, 0], marble, sections=secs),
             box([0.5, 0.1, 0.5], [0, 1.85, 0], shade(marble, 0.95))]
    return parts


@generator("crystal")
def g_crystal(rng, detail=2, color=None, **_):
    base = color or tuple(int(v) for v in rng.choice([(120, 200, 255), (200, 120, 255), (120, 255, 190), (255, 120, 170)]))
    parts = [g_rock(rng, detail=1, color=(90, 88, 96))[0]]
    parts[0].apply_scale([0.7, 0.35, 0.7])
    for i in range(rng.integers(4, 8)):
        r = rng.uniform(0.05, 0.11)
        h = rng.uniform(0.35, 0.9) if i else 1.0
        ang = [i * 2 * math.pi / 6 for i in range(6)]
        pts = [[r * math.cos(a), 0, r * math.sin(a)] for a in ang] + [[r * math.cos(a), h * 0.8, r * math.sin(a)] for a in ang] + [[0, h, 0]]
        c = trimesh.convex.convex_hull(np.array(pts))
        tilt = rng.uniform(0, 0.6) if i else 0.05
        c.apply_transform(trimesh.transformations.rotation_matrix(tilt, [math.cos(i * 1.7), 0, math.sin(i * 1.7)]))
        c.apply_translation([rng.uniform(-0.15, 0.15), 0.05, rng.uniform(-0.15, 0.15)])
        parts.append(paint(c, shade(base, rng.uniform(0.8, 1.15)), jitter=0.1, rng=rng))
    return parts


@generator("sword")
def g_sword(rng, detail=2, color=None, **_):
    steel = color or (205, 212, 222)
    L = rng.uniform(0.68, 0.78)
    g = 0.24
    w, t = 0.06, 0.012
    blade = [[-w / 2, g, 0], [w / 2, g, 0], [0, g, t], [0, g, -t],
             [-w / 2 * 0.85, g + L * 0.85, 0], [w / 2 * 0.85, g + L * 0.85, 0], [0, g + L * 0.85, t], [0, g + L * 0.85, -t], [0, g + L, 0]]
    parts = [hull(blade, steel)]
    parts.append(box([0.26, 0.04, 0.05], [0, g - 0.01, 0], (190, 150, 60)))
    parts.append(cyl(0.022, 0.18, [0, 0.05, 0], (90, 50, 35), sections=8 + 2 * detail))
    parts.append(ico(0.04, [0, 0.04, 0], (190, 150, 60), sub=1))
    return parts


@generator("lamp_post")
def g_lamp(rng, detail=2, color=None, **_):
    metal = color or (52, 56, 62)
    secs = 8 + 2 * detail
    parts = [cyl(0.1, 0.08, [0, 0, 0], metal, sections=secs),
             cyl(0.035, 1.6, [0, 0.08, 0], metal, sections=secs),
             box([0.32, 0.03, 0.03], [0.14, 1.62, 0], metal),
             box([0.16, 0.2, 0.16], [0.28, 1.5, 0], (255, 214, 120)),
             hull([[0.19, 1.6, -0.09], [0.37, 1.6, -0.09], [0.19, 1.6, 0.09], [0.37, 1.6, 0.09], [0.28, 1.68, 0]], metal)]
    return parts


GENERATOR_INFO = {
    "rock": "single boulder", "rocks": "cluster of rocks", "tree": "round leafy tree", "pine": "conifer",
    "bush": "bush (sometimes with berries)", "mushroom": "toadstool", "terrain": "terrain tile with sand/grass/rock/snow (param height)",
    "house": "small house", "tower": "castle tower", "crate": "wooden crate", "barrel": "barrel", "chest": "treasure chest",
    "fence": "fence (param length = sections)", "wall": "stone wall (param length)", "column": "classical column",
    "crystal": "crystal cluster", "sword": "sword (standing on its pommel)", "lamp_post": "street lamp",
}


def build_procedural(params: dict) -> trimesh.Trimesh:
    name = params.get("generator", "rock")
    if name not in GENERATORS:
        raise ValueError(f"unknown generator '{name}'. Options: {', '.join(sorted(GENERATORS))}")
    seed = int(params.get("seed", 0) or 0)
    rng = np.random.default_rng(seed)
    detail = int(max(1, min(int(params.get("detail", 2) or 2), 3)))
    color = hex_rgb(params["color"]) if params.get("color") else None
    extra = {k: v for k, v in params.items() if k in ("length", "height")}
    parts = GENERATORS[name](rng, detail=detail, color=color, **extra)
    m = finalize(parts)
    size = float(params.get("size", 1) or 1)
    if name in ("fence", "wall"):
        m.apply_scale(size)
        b = m.bounds
        m.apply_translation([0, -b[0][1], 0])
    else:
        normalize(m, size=size)
    return m


# --------------------------------------------------------------------------- AI engines (GPU)

ENGINES = {"text": {}, "image": {}}
_pipes = {}


def register_engine(kind: str, name: str, fn):
    """Plug in your own model. fn(params: dict, progress: callable) -> trimesh.Trimesh (Y-up)."""
    assert kind in ("text", "image")
    ENGINES[kind][name] = fn


def _gpu_name():
    try:
        import torch
        if torch.cuda.is_available():
            return torch.cuda.get_device_name(0)
    except Exception:
        pass
    return None


def _has_gpu_hw():
    """A GPU Blender could use, even without torch installed."""
    if _gpu_name():
        return True
    import shutil, subprocess
    if shutil.which("nvidia-smi"):
        try:
            return subprocess.run(["nvidia-smi", "-L"], capture_output=True, timeout=10).returncode == 0
        except Exception:
            return False
    return False


def _device():
    """'cuda' when a GPU is present, otherwise 'cpu' — every AI engine runs on either."""
    return "cuda" if _gpu_name() else "cpu"


def _dtype():
    import torch
    return torch.float16 if _device() == "cuda" else torch.float32


def _cpu_threads():
    try:
        import torch
        torch.set_num_threads(max(1, os.cpu_count() or 1))
    except Exception:
        pass


def _shap_e_mesh_to_trimesh(out_mesh):
    v = out_mesh.verts.detach().cpu().numpy()
    f = out_mesh.faces.detach().cpu().numpy()
    ch = out_mesh.vertex_channels
    cols = np.stack([ch[c].detach().cpu().float().numpy() for c in "RGB"], axis=1)
    rgb = np.clip(cols * 255.0, 0, 255).astype(np.uint8)
    vc = np.concatenate([srgb_to_linear(rgb), np.full((len(rgb), 1), 255, np.uint8)], axis=1)
    m = trimesh.Trimesh(v, f, vertex_colors=vc, process=False)
    m.apply_transform(YUP)
    return m


def _shap_e_text(params, progress):
    import torch
    from diffusers import ShapEPipeline
    if "shap-e" not in _pipes:
        progress("loading Shap-E (first run downloads ~2.5 GB)")
        _pipes["shap-e"] = ShapEPipeline.from_pretrained("openai/shap-e", torch_dtype=_dtype(), variant="fp16").to(_device())
    pipe = _pipes["shap-e"]
    progress("generating mesh")
    gen = torch.Generator(_device()).manual_seed(int(params.get("seed", 0) or 0))
    out = pipe(params["prompt"], guidance_scale=float(params.get("guidance", 15.0)),
               num_inference_steps=int(params.get("steps", 64 if _device() == "cuda" else 32)), frame_size=256, output_type="mesh", generator=gen)
    return _shap_e_mesh_to_trimesh(out.images[0])


def _shap_e_image(params, progress):
    import torch
    from diffusers import ShapEImg2ImgPipeline
    from diffusers.utils import load_image
    if "shap-e-img" not in _pipes:
        progress("loading Shap-E img2img (first run downloads ~2.5 GB)")
        _pipes["shap-e-img"] = ShapEImg2ImgPipeline.from_pretrained("openai/shap-e-img2img", torch_dtype=_dtype(), variant="fp16").to(_device())
    pipe = _pipes["shap-e-img"]
    progress("downloading image")
    img = load_image(params["image_url"]).convert("RGB").resize((256, 256))
    try:  # remove the background if rembg is installed — much better results
        from rembg import remove
        progress("removing background")
        rgba = remove(img)
        bg = __import__("PIL.Image", fromlist=["Image"]).new("RGB", rgba.size, (255, 255, 255))
        bg.paste(rgba, mask=rgba.split()[3])
        img = bg
    except Exception:
        pass
    progress("generating mesh")
    gen = torch.Generator(_device()).manual_seed(int(params.get("seed", 0) or 0))
    out = pipe(img, guidance_scale=float(params.get("guidance", 3.0)), num_inference_steps=int(params.get("steps", 64 if _device() == "cuda" else 32)),
               frame_size=256, output_type="mesh", generator=gen)
    return _shap_e_mesh_to_trimesh(out.images[0])


register_engine("text", "shap-e", _shap_e_text)
register_engine("image", "shap-e", _shap_e_image)


def _ai_available():
    """True when torch + diffusers are installed (GPU or not — the engines run on CPU too)."""
    try:
        import torch  # noqa: F401
        import diffusers  # noqa: F401
        return True
    except Exception:
        return False


def install_ai_deps(quiet=True):
    """pip-install diffusers & friends (optional; works on CPU or GPU runtimes)."""
    import subprocess
    pkgs = ["diffusers>=0.27", "transformers", "accelerate", "rembg[gpu]" if _gpu_name() else "rembg"]
    subprocess.run([sys.executable, "-m", "pip", "install", *(["-q"] if quiet else []), *pkgs], check=False)


# --------------------------------------------------------------------------- mesh post-processing

def decimate(mesh: trimesh.Trimesh, target_faces: int) -> trimesh.Trimesh:
    target_faces = int(max(100, target_faces))
    if len(mesh.faces) <= target_faces:
        return mesh
    try:
        return mesh.simplify_quadric_decimation(face_count=target_faces)
    except TypeError:
        return mesh.simplify_quadric_decimation(target_faces)
    except Exception as e:
        raise RuntimeError(f"decimation failed ({e}). Run: pip install fast_simplification") from e


def to_single_mesh(obj) -> trimesh.Trimesh:
    if isinstance(obj, trimesh.Trimesh):
        return obj
    if isinstance(obj, trimesh.Scene):
        return obj.to_geometry() if hasattr(obj, "to_geometry") else obj.dump(concatenate=True)
    if isinstance(obj, (list, tuple)):
        return finalize(list(obj))
    raise TypeError("result must be a trimesh.Trimesh, a list of meshes, or a trimesh.Scene")


def export_glb(mesh) -> bytes:
    if isinstance(mesh, trimesh.Scene):
        return mesh.export(file_type="glb")
    return trimesh.Scene(mesh).export(file_type="glb")


# --------------------------------------------------------------------------- no-GPU engines (CPU, numpy)
# Everything here runs on a plain CPU runtime (free Colab/Kaggle CPU, a laptop, a VPS) in seconds:
#   procedural_texture  prompt -> seamless PBR maps (albedo, normal, roughness, AO baked in)
#   relief_from_image   photo -> inflated, vertex-coloured 3D model (silhouette + shading depth)
#   parts_from_text     prompt -> the best matching procedural generator, coloured and sized from the words

def _per_noise(res, freq, rng):
    """Seamless (periodic) value noise in [0,1] with smooth cubic interpolation."""
    freq = max(1, int(freq))
    g = rng.random((freq, freq))
    t = np.arange(res) * freq / res
    i0 = np.floor(t).astype(int); f = t - i0; i1 = (i0 + 1) % freq; i0 %= freq
    f = f * f * (3 - 2 * f)
    a = g[i0][:, i0]; b = g[i0][:, i1]; c = g[i1][:, i0]; d = g[i1][:, i1]
    fx = f[None, :]; fy = f[:, None]
    return (a * (1 - fx) + b * fx) * (1 - fy) + (c * (1 - fx) + d * fx) * fy


def _per_fbm(res, freq, rng, octaves=5, gain=0.5, ridged=False):
    s = np.zeros((res, res)); amp, norm = 1.0, 0.0
    for o in range(octaves):
        n = _per_noise(res, freq * 2 ** o, rng)
        if ridged:
            n = 1 - np.abs(n * 2 - 1)
        s += amp * n; norm += amp; amp *= gain
    return s / norm


def _warp(field, res, rng, amount=0.05, freq=4):
    """Domain-warp a periodic field (keeps it seamless)."""
    if amount <= 0:
        return field
    dx = (_per_fbm(res, freq, rng, 3) - 0.5) * amount * res
    dy = (_per_fbm(res, freq, rng, 3) - 0.5) * amount * res
    yy, xx = np.mgrid[0:res, 0:res]
    return field[((yy + dy).astype(int)) % res, ((xx + dx).astype(int)) % res]


def _per_cells(res, cells, rng, jitter=1.0):
    """Seamless Worley noise: returns (F1, F2, cell id) in cell units."""
    from scipy.spatial import cKDTree
    cells = max(1, int(cells))
    gy, gx = np.mgrid[0:cells, 0:cells]
    pts = np.stack([gx.ravel() + 0.5 + (rng.random(cells * cells) - 0.5) * jitter,
                    gy.ravel() + 0.5 + (rng.random(cells * cells) - 0.5) * jitter], 1) % cells
    tree = cKDTree(pts, boxsize=cells)
    yy, xx = np.mgrid[0:res, 0:res] * (cells / res)
    d, i = tree.query(np.stack([xx.ravel(), yy.ravel()], 1), k=2, workers=-1)
    return d[:, 0].reshape(res, res), d[:, 1].reshape(res, res), i[:, 0].reshape(res, res)


def _blur_wrap(a, sigma):
    from scipy.ndimage import gaussian_filter
    return gaussian_filter(a, sigma, mode="wrap")


def _lerp_col(c1, c2, t):
    c1 = np.asarray(c1, float) / 255; c2 = np.asarray(c2, float) / 255
    t = np.clip(t, 0, 1)[..., None]
    return c1 * (1 - t) + c2 * t


_TEX_COLORS = {
    "red": (170, 40, 34), "crimson": (140, 20, 40), "orange": (210, 110, 40), "yellow": (210, 180, 60), "gold": (200, 160, 60),
    "green": (60, 130, 60), "lime": (130, 190, 60), "teal": (40, 130, 130), "blue": (50, 90, 170), "navy": (30, 40, 90),
    "cyan": (60, 170, 200), "purple": (110, 60, 150), "violet": (130, 80, 180), "pink": (220, 120, 160), "magenta": (190, 50, 140),
    "brown": (110, 70, 40), "tan": (180, 150, 110), "beige": (210, 195, 165), "white": (235, 235, 230), "grey": (128, 128, 128),
    "gray": (128, 128, 128), "black": (28, 28, 30), "silver": (190, 192, 196), "copper": (180, 100, 60), "bronze": (150, 100, 50),
}


def _tex_recipe(kind, res, rng):
    """Returns albedo (HxWx3, 0..1), height (0..1), roughness (0..1), metal (0..1), normal strength."""
    R = res
    if kind == "brick":
        rows, cols = 12, 6
        yy, xx = np.mgrid[0:R, 0:R] / R
        rv = yy * rows; row = np.floor(rv).astype(int)
        cv = xx * cols + (row % 2) * 0.5; cl = np.floor(cv).astype(int)
        fy, fx = rv - row, cv - cl
        edge = np.minimum(np.minimum(fy, 1 - fy) * 3.2, np.minimum(fx, 1 - fx) * 6.4)
        n = _per_fbm(R, 16, rng, 5)
        bevel = np.clip(edge / 0.09, 0, 1) ** 0.6
        tint = rng.random((rows, cols + 1))[row % rows, cl % (cols + 1)]
        brick = _lerp_col((118, 46, 32), (176, 92, 62), tint * 0.6 + n * 0.5)
        mortar = _lerp_col((150, 145, 135), (190, 186, 176), n)
        m = (bevel > 0.02)[..., None]
        alb = np.where(m, brick, mortar)
        h = bevel * (0.85 + n * 0.15)
        return alb, h, np.where(bevel > 0.02, 0.8 + n * 0.15, 0.95), 0.0, 6
    if kind in ("stone", "cobblestone", "tiles"):
        cells = {"stone": 7, "cobblestone": 10, "tiles": 8}[kind]
        if kind == "tiles":
            yy, xx = np.mgrid[0:R, 0:R] * (cells / R)
            fx, fy = xx % 1, yy % 1
            edge = np.minimum(np.minimum(fx, 1 - fx), np.minimum(fy, 1 - fy)) * 2
            cid = (np.floor(xx) + np.floor(yy) * cells).astype(int)
        else:
            f1, f2, cid = _per_cells(R, cells, rng, 0.9)
            edge = f2 - f1
        n = _per_fbm(R, 12, rng, 6, 0.55)
        tint = rng.random(cells * cells + 1)[cid % (cells * cells + 1)]
        bevel = np.clip(edge / (0.06 if kind == "tiles" else 0.18), 0, 1) ** (0.5 if kind == "tiles" else 0.8)
        dome = bevel * (0.7 + 0.3 * n)
        base = (120, 116, 108), (176, 170, 160)
        if kind == "tiles":
            base = (200, 198, 192), (232, 230, 226)
        alb = _lerp_col(*base, tint * 0.6 + n * 0.5)
        grout = _lerp_col((70, 66, 60), (110, 104, 96), n)
        m = (bevel > 0.04)[..., None]
        return np.where(m, alb, grout), dome, np.where(bevel > 0.04, (0.35 if kind == "tiles" else 0.78) + n * 0.15, 0.95), 0.0, 5
    if kind in ("wood", "planks"):
        n = _per_fbm(R, 4, rng, 5, 0.5)
        yy, xx = np.mgrid[0:R, 0:R] / R
        boards = 6 if kind == "planks" else 1
        bid = np.floor(xx * boards).astype(int)
        off = rng.random(boards + 1)[bid]
        streak = _blur_wrap(rng.random((R, R)), (R / 16, 0.6))
        streak = (streak - streak.min()) / max(1e-6, np.ptp(streak))
        rings = 0.5 + 0.5 * np.sin(xx * np.pi * 2 * boards * 5 + _warp(n, R, rng, 0.08) * 9 + off * 20)
        grain = np.clip(streak * 0.55 + rings ** 2 * 0.45, 0, 1)
        alb = _lerp_col((86, 50, 26), (182, 126, 74), 0.2 + grain * 0.6 + (off - 0.5) * 0.35)
        h = 0.55 + (grain - 0.5) * 0.25
        if kind == "planks":
            fx = (xx * boards) % 1
            fy = (yy + off * 3) % 1
            seam = np.clip(np.minimum(fx, 1 - fx) * R / boards * 0.5, 0, 1) * np.clip(np.minimum(fy, 1 - fy) * R * 0.25, 0, 1)
            h *= seam; alb *= (0.45 + 0.55 * seam)[..., None]
        return alb, h, 0.55 + grain * 0.2, 0.0, 2
    if kind == "bark":
        n = _per_fbm(R, 6, rng, 6, 0.6, ridged=True)
        yy, xx = np.mgrid[0:R, 0:R] / R
        stretch = _per_fbm(R, 3, rng, 3)
        h = _warp(n, R, rng, 0.04, 3) * 0.7 + 0.3 * (0.5 + 0.5 * np.sin(xx * np.pi * 2 * 14 + stretch * 8))
        return _lerp_col((48, 34, 24), (122, 96, 72), h), h, 0.92, 0.0, 8
    if kind in ("metal", "steel", "chrome"):
        line = rng.random(R)[:, None] * np.ones((1, R))
        line = _blur_wrap(line, (0.4, 30))
        n = _per_fbm(R, 8, rng, 4)
        v = 0.62 + line * 0.18 + n * 0.08 if kind != "chrome" else 0.85 + n * 0.08
        alb = np.repeat(v[..., None], 3, 2) * np.array([0.98, 0.99, 1.02])
        return alb, line * 0.4 + n * 0.1, (0.28 if kind != "chrome" else 0.06) + line * 0.15, 1.0, 0.6
    if kind == "rust":
        n = _per_fbm(R, 6, rng, 6, 0.6)
        spots = _warp(_per_fbm(R, 4, rng, 5, 0.55), R, rng, 0.08)
        rusty = np.clip((spots - 0.42) * 4, 0, 1)
        metal = _lerp_col((120, 122, 126), (160, 162, 168), n)
        rcol = _lerp_col((90, 38, 16), (178, 92, 40), n * 1.2 - 0.1)
        alb = metal * (1 - rusty[..., None]) + rcol * rusty[..., None]
        return alb, rusty * 0.6 + n * 0.4, 0.35 + rusty * 0.6, 1 - rusty, 3
    if kind in ("concrete", "asphalt", "plaster"):
        n = _per_fbm(R, 6, rng, 7, 0.58)
        pores = (_per_noise(R, 96, rng) > 0.82).astype(float)
        cfg = {"concrete": ((110, 108, 104), (170, 168, 162)), "asphalt": ((40, 40, 42), (88, 88, 90)), "plaster": ((200, 196, 188), (236, 232, 224))}[kind]
        alb = _lerp_col(*cfg, n) * (1 - pores[..., None] * 0.15)
        return alb, n - pores * 0.2, 0.85 + n * 0.1, 0.0, 2
    if kind in ("grass", "moss"):
        n = _per_fbm(R, 8, rng, 6, 0.55)
        blades = _per_fbm(R, 128, rng, 2, 0.6)
        cfg = ((40, 72, 22), (110, 140, 48)) if kind == "grass" else ((44, 70, 24), (96, 128, 46))
        alb = _lerp_col(*cfg, n * 0.7 + blades * 0.5 - 0.1)
        return alb, blades * 0.6 + n * 0.4, 0.92, 0.0, 3
    if kind in ("dirt", "mud", "gravel"):
        n = _per_fbm(R, 8, rng, 6, 0.55)
        if kind == "gravel":
            f1, f2, cid = _per_cells(R, 40, rng)
            peb = np.clip(1 - f1 * 1.6, 0, 1) ** 0.6
            tint = rng.random(1601)[cid % 1601]
            alb = _lerp_col((96, 90, 84), (176, 168, 156), tint * 0.7 + n * 0.3) * (0.5 + 0.5 * peb[..., None])
            return alb, peb, 0.85, 0.0, 6
        cfg = ((70, 50, 34), (130, 100, 70)) if kind == "dirt" else ((40, 30, 20), (84, 64, 44))
        peb = (_per_fbm(R, 40, rng, 3) > 0.66).astype(float)
        alb = _lerp_col(*cfg, n + peb * 0.15)
        return alb, n * 0.7 + peb * 0.3, (0.95 if kind == "dirt" else 0.35 + n * 0.3), 0.0, 3
    if kind == "sand":
        n = _per_fbm(R, 8, rng, 5)
        yy, xx = np.mgrid[0:R, 0:R] / R
        rip = 0.5 + 0.5 * np.sin(xx * np.pi * 2 * 14 + _per_fbm(R, 3, rng, 3) * 8)
        return _lerp_col((190, 160, 112), (230, 206, 160), n * 0.7 + rip * 0.3), rip * 0.5 + n * 0.5, 0.95, 0.0, 2
    if kind == "snow":
        n = _per_fbm(R, 6, rng, 6)
        sp = (_per_noise(R, 200, rng) > 0.94).astype(float)
        alb = np.repeat((0.86 + n * 0.12)[..., None], 3, 2) * np.array([0.96, 0.98, 1.0]) + sp[..., None] * 0.05
        return alb, n, 0.55 + n * 0.25 - sp * 0.3, 0.0, 1.5
    if kind == "rock":
        n = _warp(_per_fbm(R, 5, rng, 7, 0.58), R, rng, 0.06)
        cr = _per_fbm(R, 6, rng, 5, 0.6, ridged=True)
        strata = 0.5 + 0.5 * np.sin(np.mgrid[0:R, 0:R][0] / R * np.pi * 2 * 6 + n * 6)
        h = n * 0.6 + cr * 0.3 + strata * 0.1
        return _lerp_col((78, 74, 70), (156, 150, 140), h * 1.1 - 0.1), h, 0.88, 0.0, 6
    if kind == "marble":
        n = _warp(_per_fbm(R, 3, rng, 6, 0.55), R, rng, 0.15, 2)
        vein = np.abs(np.sin(n * np.pi * 7)) ** 0.15
        alb = _lerp_col((96, 94, 92), (236, 234, 230), vein)
        return alb, np.full((R, R), 0.5), 0.12 + (1 - vein) * 0.1, 0.0, 0.2
    if kind == "lava":
        f1, f2, _ = _per_cells(R, 8, rng)
        n = _per_fbm(R, 6, rng, 6)
        crack = np.clip(1 - (f2 - f1) * 6, 0, 1) ** 2
        alb = _lerp_col((22, 16, 14), (66, 40, 30), n) * (1 - crack[..., None]) + _lerp_col((255, 90, 10), (255, 220, 90), n)[...] * crack[..., None]
        return alb, (1 - crack) * (0.6 + n * 0.4), 0.9 - crack * 0.5, 0.0, 4
    if kind == "ice":
        f1, f2, _ = _per_cells(R, 6, rng)
        n = _per_fbm(R, 6, rng, 6)
        crack = np.clip(1 - (f2 - f1) * 14, 0, 1)
        return _lerp_col((150, 196, 228), (226, 242, 252), n + crack * 0.3), 1 - crack * 0.4, 0.06 + crack * 0.3, 0.0, 1
    if kind == "leather":
        f1, f2, _ = _per_cells(R, 48, rng)
        n = _per_fbm(R, 10, rng, 4)
        h = np.clip((f2 - f1) * 3, 0, 1) ** 0.5
        return _lerp_col((70, 40, 22), (130, 80, 46), n * 0.6 + h * 0.4), h, 0.55 + n * 0.2, 0.0, 2.5
    if kind == "fabric":
        yy, xx = np.mgrid[0:R, 0:R] / R
        w = 96
        warp_t = 0.5 + 0.5 * np.sin(xx * np.pi * 2 * w); weft = 0.5 + 0.5 * np.sin(yy * np.pi * 2 * w)
        over = ((np.floor(xx * w) + np.floor(yy * w)) % 2).astype(float)
        h = over * warp_t + (1 - over) * weft
        n = _per_fbm(R, 16, rng, 3)
        return _lerp_col((150, 150, 150), (210, 210, 210), h * 0.6 + n * 0.4), h, 0.95, 0.0, 2
    if kind == "scales":
        yy, xx = np.mgrid[0:R, 0:R] / R
        rows = 16; rv = yy * rows; row = np.floor(rv)
        cv = xx * rows / 2 + (row % 2) * 0.5; fx = cv % 1 - 0.5; fy = rv % 1
        d = np.sqrt(fx ** 2 + (fy * 0.9) ** 2)
        h = np.clip(1 - d * 1.6, 0, 1) ** 0.5
        n = _per_fbm(R, 8, rng, 4)
        return _lerp_col((40, 70, 40), (120, 160, 80), h * 0.6 + n * 0.4), h, 0.35 + (1 - h) * 0.4, 0.0, 4
    if kind == "carbon":
        yy, xx = np.mgrid[0:R, 0:R] / R
        c = 24; u, v = xx * c, yy * c; tw = ((np.floor(u) + np.floor(v)) % 2) == 0
        f = np.where(tw, u % 1, v % 1); h = 0.5 + 0.5 * np.sin(f * np.pi)
        return np.repeat((0.06 + h * 0.12)[..., None], 3, 2), h, 0.3, 0.3, 1.5
    # fallback: generic noisy surface
    n = _per_fbm(R, 6, rng, 6)
    return _lerp_col((100, 100, 100), (180, 180, 180), n), n, 0.7, 0.0, 2


_TEX_WORDS = [  # (keywords, recipe) — first match wins, so put specific words first
    (("cobble",), "cobblestone"), (("brick",), "brick"), (("tile", "ceramic", "bathroom"), "tiles"),
    (("plank", "floorboard", "deck", "parquet"), "planks"), (("bark", "trunk"), "bark"), (("wood", "timber", "oak", "pine"), "wood"),
    (("rust", "corrod"), "rust"), (("chrome", "mirror"), "chrome"), (("metal", "steel", "iron", "alumin", "brushed"), "metal"),
    (("asphalt", "tarmac", "road"), "asphalt"), (("plaster", "stucco"), "plaster"), (("concrete", "cement"), "concrete"),
    (("moss",), "moss"), (("grass", "lawn", "turf"), "grass"), (("gravel", "pebble"), "gravel"), (("mud", "swamp"), "mud"),
    (("dirt", "soil", "earth"), "dirt"), (("sand", "desert", "beach", "dune"), "sand"), (("snow", "frost"), "snow"),
    (("marble",), "marble"), (("lava", "magma"), "lava"), (("ice", "frozen", "glacier"), "ice"),
    (("leather", "hide"), "leather"), (("fabric", "cloth", "canvas", "denim", "wool", "carpet"), "fabric"),
    (("scale", "dragon", "reptile", "snake"), "scales"), (("carbon",), "carbon"),
    (("stone", "slate", "flagstone", "castle", "dungeon"), "stone"), (("rock", "cliff", "granite", "boulder"), "rock"),
]


def texture_kind(prompt):
    p = (prompt or "").lower()
    for words, kind in _TEX_WORDS:
        if any(w in p for w in words):
            return kind
    return "concrete"


def procedural_texture(prompt, resolution=1024, seed=0):
    """Seamless PBR texture from a description, numpy only. Returns PIL images {map, normal, rough}."""
    from PIL import Image
    res = int(min(4096, max(128, resolution)))
    import zlib
    rng = np.random.default_rng(int(seed or 0) * 7919 + zlib.crc32((prompt or "").encode()))
    p = (prompt or "").lower()
    kind = texture_kind(p)
    alb, h, rough, metal, ns = _tex_recipe(kind, res, rng)
    h = np.asarray(h, float); rough = np.broadcast_to(np.asarray(rough, float), h.shape).copy()
    for word, rgb in _TEX_COLORS.items():
        if word in p.split() or f"{word}-" in p or f"{word}ish" in p:
            lum = alb.mean(axis=2, keepdims=True)
            tinted = alb * 0.25 + (lum / max(1e-3, lum.mean())) * (np.asarray(rgb) / 255.0) * 0.75
            wmask = np.clip(h * 4, 0, 1)[..., None]  # keep mortar / grout their own colour
            alb = alb * (1 - wmask) + tinted * wmask
            break
    # modifiers from the words
    if any(w in p for w in ("moss", "mossy", "overgrown")) and kind not in ("moss", "grass"):
        cav = np.clip((_blur_wrap(h, res / 64) - h) * 14 + (_per_fbm(res, 5, rng, 5) - 0.5) * 2.5 + (h < 0.15) * 0.6, 0, 1)
        alb = alb * (1 - cav[..., None]) + _lerp_col((48, 80, 28), (92, 124, 44), _per_fbm(res, 40, rng, 3)) * cav[..., None]
        rough = np.maximum(rough, cav * 0.95)
    if any(w in p for w in ("dirty", "grime", "weathered", "old", "worn", "aged", "grunge")):
        g = _warp(_per_fbm(res, 4, rng, 5), res, rng, 0.1)
        alb = alb * (0.72 + 0.28 * g[..., None]); rough = np.clip(rough + (1 - g) * 0.15, 0, 1)
    if any(w in p for w in ("crack", "broken", "damaged")):
        f1, f2, _ = _per_cells(res, 5, rng)
        crack = np.clip(1 - (f2 - f1) * 30, 0, 1) * (_per_fbm(res, 3, rng, 3) > 0.45)
        h = h - crack * 0.5; alb = alb * (1 - crack[..., None] * 0.7)
    if any(w in p for w in ("wet", "rain", "puddle", "glossy", "polished", "shiny")):
        rough = rough * 0.35
        alb = alb * 0.85
    # ambient occlusion from the height field gives the flat albedo real depth
    ao = np.clip(1 - np.maximum(0, _blur_wrap(h, max(1.0, res / 128)) - h) * 3.0, 0.45, 1)
    alb = np.clip(alb * ao[..., None], 0, 1)
    # tangent-space normal map (OpenGL convention, like three.js)
    k = ns * res / 512.0
    gx = (np.roll(h, -1, 1) - np.roll(h, 1, 1)) * k
    gy = (np.roll(h, -1, 0) - np.roll(h, 1, 0)) * k
    nrm = np.stack([-gx, gy, np.ones_like(h)], -1)
    nrm /= np.linalg.norm(nrm, axis=-1, keepdims=True)
    to8 = lambda a: (np.clip(a, 0, 1) * 255 + 0.5).astype(np.uint8)
    out = {"map": Image.fromarray(to8(alb)), "normal": Image.fromarray(to8(nrm * 0.5 + 0.5)),
           "rough": Image.fromarray(to8(rough))}
    if np.ndim(metal) or float(metal) > 0:
        out["metal"] = Image.fromarray(to8(np.broadcast_to(np.asarray(metal, float), h.shape)))
    return kind, out


def _object_mask(img):
    """Foreground mask for a photo of one object: alpha, rembg, or the border colour."""
    from scipy import ndimage
    a = np.asarray(img.convert("RGBA"), dtype=np.float64) / 255.0
    if a[..., 3].min() < 0.9:
        mask = a[..., 3] > 0.5
    else:
        mask = None
        try:
            from rembg import remove
            r = np.asarray(remove(img.convert("RGB")).convert("RGBA"))[..., 3]
            mask = r > 127
        except Exception:
            pass
        if mask is None or mask.mean() < 0.01:
            rgb = a[..., :3]
            border = np.concatenate([rgb[0], rgb[-1], rgb[:, 0], rgb[:, -1]])
            bg = np.median(border, axis=0)
            spread = np.percentile(np.linalg.norm(border - bg, axis=1), 90)
            mask = np.linalg.norm(rgb - bg, axis=2) > max(0.08, spread * 1.6)
    mask = ndimage.binary_opening(mask, iterations=1)
    mask = ndimage.binary_fill_holes(mask)
    lab, n = ndimage.label(mask)
    if n > 1:
        sizes = ndimage.sum(mask, lab, range(1, n + 1))
        mask = lab == (1 + int(np.argmax(sizes)))
    return mask


def relief_arrays(img, size=1.0, max_side=200, thickness=0.35, detail=0.25, back=0.8):
    """Photo -> closed 'inflated' mesh. Returns vertices (Y-up), faces, vertex colours (uint8 RGBA)."""
    from scipy import ndimage
    w, h0 = img.size
    s = max_side / max(w, h0)
    if s < 1:
        img = img.resize((max(8, int(w * s)), max(8, int(h0 * s))))
    mask = _object_mask(img)
    if mask.sum() < 30:
        raise ValueError("couldn't find an object in the image — use a photo of one object on a plain background")
    rgb = np.asarray(img.convert("RGB"), dtype=np.float64) / 255.0
    H, W = mask.shape
    dt = ndimage.distance_transform_edt(mask)
    R = max(1.0, dt.max())
    d = np.clip(dt / R, 0, 1)
    z = np.sqrt(np.clip(1 - (1 - d) ** 2, 0, 1)) * thickness * R  # round 'balloon' profile, in pixels
    lum = ndimage.gaussian_filter(rgb.mean(axis=2), 1.0)
    z += (lum - lum[mask].mean()) * detail * R * d  # shading adds surface detail
    z = ndimage.gaussian_filter(z, 0.8) * mask
    inside = np.pad(mask, 1)
    edge = mask & ~(inside[:-2, 1:-1] & inside[2:, 1:-1] & inside[1:-1, :-2] & inside[1:-1, 2:])
    z[edge] = 0
    # vertices: front for every masked pixel, back only for interior pixels (edge pixels are shared)
    fid = -np.ones((H, W), int); bid = -np.ones((H, W), int)
    ys, xs = np.nonzero(mask)
    fid[ys, xs] = np.arange(len(ys))
    iy, ix = np.nonzero(mask & ~edge)
    bid[iy, ix] = len(ys) + np.arange(len(iy))
    bid[edge] = fid[edge]
    V = np.concatenate([np.stack([xs, -ys, z[ys, xs]], 1), np.stack([ix, -iy, -z[iy, ix] * back], 1)]).astype(np.float64)
    C = np.concatenate([rgb[ys, xs], rgb[iy, ix] * 0.92])
    # quads where all 4 corners are inside
    q = mask[:-1, :-1] & mask[:-1, 1:] & mask[1:, :-1] & mask[1:, 1:]
    qy, qx = np.nonzero(q)
    def quads(ids, flip):
        a, b, c, dd = ids[qy, qx], ids[qy, qx + 1], ids[qy + 1, qx], ids[qy + 1, qx + 1]
        t1 = np.stack([a, c, b], 1); t2 = np.stack([b, c, dd], 1)
        f = np.concatenate([t1, t2])
        return f[:, ::-1] if flip else f
    F = np.concatenate([quads(fid, False), quads(bid, True)])
    F = F[(F[:, 0] != F[:, 1]) & (F[:, 1] != F[:, 2]) & (F[:, 0] != F[:, 2])]
    # scale: tallest side -> size, sit on the ground, centred
    V[:, 0] -= (xs.min() + xs.max()) / 2
    V[:, 1] -= -ys.max()
    span = max(xs.max() - xs.min(), ys.max() - ys.min(), 1)
    V *= size / span
    lin = np.where(C <= 0.04045, C / 12.92, ((C + 0.055) / 1.055) ** 2.4)
    VC = np.concatenate([(lin * 255).astype(np.uint8), np.full((len(C), 1), 255, np.uint8)], 1)
    return V, F.astype(np.int64), VC


# text -> 3D on CPU: words -> procedural generator
_PART_WORDS = [  # checked in order: built things first so "stone wall" is a wall, not a rock
    (("chest", "treasure", "loot"), "chest"), (("crate", "box", "cargo", "container"), "crate"),
    (("barrel", "keg", "cask", "drum"), "barrel"), (("fence", "railing"), "fence"), (("wall", "rampart"), "wall"),
    (("column", "pillar"), "column"), (("tower", "castle", "keep", "turret"), "tower"),
    (("house", "cabin", "cottage", "hut", "home", "shack"), "house"),
    (("sword", "blade", "katana", "sabre", "saber"), "sword"),
    (("lamp", "streetlight", "street light", "lantern", "light post"), "lamp_post"),
    (("crystal", "gem", "ore", "quartz", "amethyst"), "crystal"),
    (("boulders", "rocks", "stones", "rubble"), "rocks"), (("rock", "boulder", "stone", "pebble"), "rock"),
    (("pine", "fir", "spruce", "conifer", "christmas tree", "evergreen"), "pine"), (("tree", "oak", "maple", "birch"), "tree"),
    (("bush", "shrub", "hedge"), "bush"), (("mushroom", "toadstool", "fungus"), "mushroom"),
    (("terrain", "landscape", "island", "hill", "mountain"), "terrain"),
]


def parts_match(prompt):
    import re
    p = (prompt or "").lower()
    for words, gen in _PART_WORDS:
        if any(re.search(r"\b" + re.escape(w), p) for w in words):
            return gen
    return None


def relief_mesh(params, progress):
    """image_to_3d without a GPU: cut the object out of the photo and inflate it into a closed, coloured mesh."""
    from PIL import Image
    progress("downloading image")
    r = requests.get(params["image_url"], timeout=120); r.raise_for_status()
    img = Image.open(io.BytesIO(r.content))
    progress("cutting out the object and inflating it (CPU)")
    detail = {"low": 120, "medium": 200, "high": 320}.get(str(params.get("quality", "medium")), 200)
    V, F, C = relief_arrays(img, size=1.0, max_side=detail, thickness=float(params.get("thickness", 0.35)),
                            detail=float(params.get("relief", 0.25)))
    m = trimesh.Trimesh(V, F, vertex_colors=C, process=False)
    try:
        trimesh.smoothing.filter_taubin(m, iterations=6)
    except Exception:
        pass
    return m


def parts_text(params, progress):
    """text_to_3d without a GPU: pick the procedural generator the words describe, coloured from the words."""
    gen = parts_match(params.get("prompt"))
    if not gen:
        raise LookupError("no procedural generator for that description")
    p = (params.get("prompt") or "").lower()
    color = next((("#%02x%02x%02x" % rgb) for w, rgb in _TEX_COLORS.items() if re.search(r"\b" + w + r"\b", p)), None)
    detail = 3 if any(w in p for w in ("detailed", "high poly", "realistic", "hd")) else 1 if any(w in p for w in ("low poly", "lowpoly", "simple")) else 2
    import zlib
    seed = int(params.get("seed") or zlib.crc32(p.encode()) % 100000)
    progress(f"building a {gen.replace('_', ' ')} from your words (CPU)")
    return build_procedural({"generator": gen, "seed": seed, "detail": detail, **({"color": color} if color else {}),
                             "size": params.get("size", 1) or 1})


def _text_auto(params, progress):
    try:
        return parts_text(params, progress)
    except LookupError:
        pass
    if _ai_available():
        if _device() == "cpu":
            progress("no instant generator matches — running SDXL-turbo → TripoSR on CPU (a few minutes)")
        return _with_fallback(_sdxl_triposr_text, _shap_e_text)(params, progress)
    known = ", ".join(sorted({g for _, g in _PART_WORDS}))
    raise ValueError(f"On a CPU worker without AI libraries, text → 3D understands: {known}. "
                     "Run modeler_worker.setup(ai=True) to add SDXL → TripoSR (works on CPU, slower), "
                     "or use Add → Design a car / Blob / Character in the editor.")


def _image_auto(params, progress):
    if _device() == "cuda" and _ai_available():
        return _with_fallback(_triposr_image, relief_mesh)(params, progress)
    return relief_mesh(params, progress)


# --------------------------------------------------------------------------- GPU / heavy jobs
# render           Blender Cycles path tracing of the editor's scene (GLB) up to 8K
# text_to_texture  SDXL-turbo seamless PBR texture (albedo + normal + roughness)
# terrain_erosion  hydraulic erosion of a terrain heightfield (numpy, CPU is fine)
# voxelize         turn any model into blocks (trimesh)

BLENDER_URL = "https://download.blender.org/release/Blender4.2/blender-4.2.3-linux-x64.tar.xz"
BLENDER_DIR = os.path.expanduser("~/forge3d_blender")


def _blender_bin():
    for root, _, files in os.walk(BLENDER_DIR) if os.path.isdir(BLENDER_DIR) else []:
        if "blender" in files and os.access(os.path.join(root, "blender"), os.X_OK):
            return os.path.join(root, "blender")
    return None


def install_blender(progress=print):
    """Download Blender 4.2 LTS (portable, ~350 MB) for Cycles renders. Done once per runtime."""
    b = _blender_bin()
    if b:
        return b
    import subprocess, tarfile
    os.makedirs(BLENDER_DIR, exist_ok=True)
    tar = os.path.join(BLENDER_DIR, "blender.tar.xz")
    progress("downloading Blender 4.2 LTS (one time, ~350 MB)")
    with requests.get(BLENDER_URL, stream=True, timeout=600) as r:
        r.raise_for_status()
        with open(tar, "wb") as f:
            for chunk in r.iter_content(1 << 20):
                f.write(chunk)
    progress("unpacking Blender")
    subprocess.run(["tar", "-xf", tar, "-C", BLENDER_DIR], check=True)
    os.remove(tar)
    # libs Blender needs on minimal images
    subprocess.run("apt-get -qq install -y libxi6 libxxf86vm1 libxfixes3 libxrender1 libgl1 libxkbcommon0 libsm6 >/dev/null 2>&1", shell=True)
    return _blender_bin()


_BLENDER_SCRIPT = r'''
import bpy, json, math, sys, os
from mathutils import Vector
a = json.loads(open(sys.argv[sys.argv.index("--") + 1]).read())
bpy.ops.wm.read_factory_settings(use_empty=True)
bpy.ops.import_scene.gltf(filepath=a["glb"])
sc = bpy.context.scene
sc.render.engine = "CYCLES"
prefs = bpy.context.preferences.addons["cycles"].preferences
dev = "NONE"
for kind in ("OPTIX", "CUDA", "HIP", "METAL"):
    try:
        prefs.compute_device_type = kind; prefs.get_devices()
        if any(d.type == kind for d in prefs.devices):
            dev = kind; break
    except Exception:
        pass
for d in prefs.devices: d.use = True
sc.cycles.device = "GPU" if dev != "NONE" else "CPU"
cpu = dev == "NONE"
sc.cycles.samples = int(a["samples"]); sc.cycles.use_denoising = True
try: sc.cycles.denoiser = "OPTIX" if dev == "OPTIX" else "OPENIMAGEDENOISE"
except Exception: pass
# clean images from few samples: adaptive sampling + guided denoise (albedo + normal) — what makes CPU renders viable
sc.cycles.use_adaptive_sampling = True
sc.cycles.adaptive_threshold = float(a.get("noise_threshold", 0.03 if cpu else 0.01))
try:
    sc.cycles.denoising_input_passes = "RGB_ALBEDO_NORMAL"; sc.cycles.denoising_prefilter = "ACCURATE"
except Exception: pass
try: sc.cycles.use_light_tree = True
except Exception: pass
try: sc.cycles.use_guiding = cpu  # path guiding is CPU-only in Cycles and cuts noise in indirect light
except Exception: pass
if a.get("time_limit"): sc.cycles.time_limit = float(a["time_limit"])
sc.render.threads_mode = "AUTO"; sc.render.use_persistent_data = True
sc.cycles.max_bounces = 8 if cpu else 12; sc.cycles.diffuse_bounces = 3 if cpu else 4; sc.cycles.glossy_bounces = 4
sc.cycles.transmission_bounces = 8; sc.cycles.caustics_reflective = False; sc.cycles.caustics_refractive = False
sc.cycles.blur_glossy = 1.0 if cpu else 0.0; sc.cycles.sample_clamp_indirect = 10.0
if cpu and a.get("cpu_scale", 1) < 1:
    sc.render.resolution_percentage = int(a["cpu_scale"] * 100)
sc.render.resolution_x, sc.render.resolution_y = int(a["width"]), int(a["height"])
sc.render.image_settings.file_format = "PNG"
sc.view_settings.view_transform = "AgX"
sc.view_settings.look = "AgX - Punchy" if a.get("style") in ("photoreal", "cinematic", "stylized") else "None"
sc.view_settings.exposure = math.log2(max(0.05, float(a.get("exposure", 1))))
# three.js is Y-up: (x, y, z) -> Blender (x, -z, y)
B = lambda v: Vector((v[0], -v[2], v[1]))
cam_d = bpy.data.cameras.new("cam"); cam = bpy.data.objects.new("cam", cam_d); sc.collection.objects.link(cam); sc.camera = cam
c = a["camera"]; cam.location = B(c["position"])
d = B(c["target"]) - cam.location; cam.rotation_euler = d.to_track_quat("-Z", "Y").to_euler()
aspect = a["width"] / a["height"]; vfov = math.radians(c.get("fov", 55))
cam_d.sensor_fit = "VERTICAL"; cam_d.angle_y = vfov; cam_d.clip_end = 20000
cam_d.dof.use_dof = a.get("style") == "cinematic"; cam_d.dof.focus_distance = d.length; cam_d.dof.aperture_fstop = 2.8
# world: Poly Haven HDRI if given, else physical Nishita sky that matches the editor's sun
w = bpy.data.worlds.new("w"); sc.world = w; w.use_nodes = True; nt = w.node_tree; bg = nt.nodes["Background"]
sun_dir = B(a["sun"]).normalized()
if a.get("hdri_path"):
    env = nt.nodes.new("ShaderNodeTexEnvironment"); env.image = bpy.data.images.load(a["hdri_path"])
    mp = nt.nodes.new("ShaderNodeMapping"); tc = nt.nodes.new("ShaderNodeTexCoord")
    mp.inputs["Rotation"].default_value[2] = -math.radians(a.get("hdri_rotation", 0))
    nt.links.new(tc.outputs["Generated"], mp.inputs["Vector"]); nt.links.new(mp.outputs["Vector"], env.inputs["Vector"]); nt.links.new(env.outputs["Color"], bg.inputs["Color"])
else:
    sky = nt.nodes.new("ShaderNodeTexSky"); sky.sky_type = "NISHITA"
    sky.sun_elevation = max(-0.1, math.asin(max(-1, min(1, sun_dir.z))))
    sky.sun_rotation = math.atan2(sun_dir.x, sun_dir.y)
    sky.air_density = 1.0; sky.dust_density = 1.0 + (3 if a.get("weather") in ("cloudy", "overcast", "fog") else 0)
    nt.links.new(sky.outputs["Color"], bg.inputs["Color"]); bg.inputs["Strength"].default_value = 0.35 if sun_dir.z > 0 else 0.02
    sun_d = bpy.data.lights.new("sun", "SUN"); sun_d.energy = 4.5 if sun_dir.z > 0 else 0.05; sun_d.angle = math.radians(0.6)
    sun = bpy.data.objects.new("sun", sun_d); sc.collection.objects.link(sun)
    sun.rotation_euler = (-sun_dir).to_track_quat("-Z", "Y").to_euler()
# a ground plane where the editor draws its default ground
if a.get("ground", "grass") != "none":
    bpy.ops.mesh.primitive_plane_add(size=6000, location=(0, 0, -0.02))
    g = bpy.context.active_object; m = bpy.data.materials.new("ground"); m.use_nodes = True
    col = {"grass": (0.09, 0.16, 0.05), "asphalt": (0.05, 0.05, 0.055), "concrete": (0.28, 0.28, 0.27), "sand": (0.45, 0.36, 0.22), "dirt": (0.16, 0.11, 0.07), "snow": (0.8, 0.82, 0.85)}.get(a.get("ground"), (0.2, 0.2, 0.2))
    bsdf = m.node_tree.nodes["Principled BSDF"]; bsdf.inputs["Base Color"].default_value = (*col, 1); bsdf.inputs["Roughness"].default_value = 0.9
    g.data.materials.append(m)
sc.render.filepath = a["out"]
bpy.ops.render.render(write_still=True)

print("FORGE3D_DEVICE", dev)
'''


def render_job(api, job, progress):
    import subprocess, tempfile
    p = job["params"]
    blender = install_blender(progress)
    if not blender:
        raise RuntimeError("Blender install failed")
    tmp = tempfile.mkdtemp(prefix="forge3d_render_")
    progress("downloading scene")
    glb = os.path.join(tmp, "scene.glb")
    r = requests.get(p["scene_url"], timeout=300); r.raise_for_status()
    open(glb, "wb").write(r.content)
    hdri_path = None
    if p.get("hdri"):
        res = "4k" if int(p.get("width", 1920)) > 2000 else "2k"
        progress(f"downloading HDRI {p['hdri']} ({res})")
        u = f"https://dl.polyhaven.org/file/ph-assets/HDRIs/hdr/{res}/{p['hdri']}_{res}.hdr"
        rr = requests.get(u, timeout=300)
        if rr.ok:
            hdri_path = os.path.join(tmp, "sky.hdr"); open(hdri_path, "wb").write(rr.content)
    out = os.path.join(tmp, "render.png")
    args = {"glb": glb, "out": out, "width": min(7680, int(p.get("width", 1920))), "height": min(4320, int(p.get("height", 1080))),
            "samples": min(4096, int(p.get("samples", 256))), "camera": p["camera"], "sun": p.get("sun", [0.3, 0.8, 0.4]),
            "hdri_path": hdri_path, "hdri_rotation": p.get("hdri_rotation", 0), "exposure": p.get("exposure", 1),
            "style": p.get("style", "photoreal"), "weather": p.get("weather", "clear"), "ground": p.get("ground", "grass")}
    cpu = not _has_gpu_hw()
    if p.get("time_limit"):
        args["time_limit"] = float(p["time_limit"])
    if cpu:
        # no GPU: adaptive sampling + guided OpenImageDenoise make ~1/4 of the samples look clean; big frames are
        # path traced at half size and upscaled after the denoise, and a time limit guarantees the job finishes.
        args["samples"] = int(p.get("cpu_samples") or max(24, min(256, args["samples"] // 4)))
        big = args["width"] * args["height"] > 1920 * 1080 * 1.2
        args["cpu_scale"] = float(p.get("cpu_scale") or (0.5 if big else 1.0))
        args["time_limit"] = float(p.get("time_limit") or 1800)
        args["noise_threshold"] = float(p.get("noise_threshold") or 0.03)
    aj = os.path.join(tmp, "args.json"); json.dump(args, open(aj, "w"))
    sp = os.path.join(tmp, "render.py"); open(sp, "w").write(_BLENDER_SCRIPT)
    scale = args.get("cpu_scale", 1)
    progress(f"path tracing {int(args['width'] * scale)}×{int(args['height'] * scale)} @ {args['samples']} samples on "
             + ("CPU (denoised" + (", upscaled" if scale < 1 else "") + f", ≤{int(args['time_limit'] // 60)} min)" if cpu else "GPU"))
    proc = subprocess.Popen([blender, "-b", "--factory-startup", "-P", sp, "--", aj], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
    last = time.time(); log = []
    for line in proc.stdout:
        log.append(line); log = log[-40:]
        if "Sample" in line and time.time() - last > 4:
            last = time.time(); progress(line.strip()[-120:])
    if proc.wait() != 0 or not os.path.exists(out):
        raise RuntimeError("Blender failed:\n" + "".join(log[-15:]))
    if scale < 1:
        from PIL import Image, ImageFilter
        progress(f"upscaling to {args['width']}×{args['height']}")
        im = Image.open(out).convert("RGB").resize((args["width"], args["height"]), Image.LANCZOS)
        im.filter(ImageFilter.UnsharpMask(radius=1.2, percent=60, threshold=2)).save(out, "PNG")
    data = open(out, "rb").read()
    progress(f"uploading {len(data) / 1e6:.1f} MB")
    url = api.upload(f"images/render-{job['id']}.png", data, "image/png")
    device = next((l.split()[-1] for l in log if "FORGE3D_DEVICE" in l), "?")
    return {"image_url": url, "width": args["width"], "height": args["height"], "samples": args["samples"], "device": device,
            **({"cpu_scale": scale} if scale < 1 else {})}


# --------------------------------------------------------------------------- real Blender jobs (CPU is fine)
# blender_ops  a declarative modifier stack run by headless Blender on a model (or a fresh primitive) — no user code
# blender      a bpy script (only with allow_python=True); whatever is left in the scene is exported as GLB
# Both speak Forge coordinates (Y up, metres, degrees); the script converts to Blender's Z-up and back on export.

_BLENDER_EDIT_SCRIPT = r"""
import bpy, bmesh, json, math, sys, os
from mathutils import Vector, Euler, Matrix
a = json.loads(open(sys.argv[sys.argv.index("--") + 1]).read())
bpy.ops.wm.read_factory_settings(use_empty=True)
C = Matrix(((1, 0, 0), (0, 0, -1), (0, 1, 0)))           # Forge (x, y, z) -> Blender (x, -z, y)
F = lambda v: Vector((v[0], -v[2], v[1]))
AX = {"x": "X", "y": "Z", "z": "Y"}
AXI = {"x": 0, "y": 2, "z": 1}
rad = math.radians
def frot(deg):                                           # Forge XYZ degrees -> Blender euler
    return (C @ Euler([rad(x) for x in deg], "ZYX").to_matrix() @ C.transposed()).to_euler()
def lin(h, default=(0.8, 0.8, 0.8)):
    try:
        h = h.lstrip("#"); c = [int(h[i:i + 2], 16) / 255 for i in (0, 2, 4)]
        return tuple(x / 12.92 if x <= 0.04045 else ((x + 0.055) / 1.055) ** 2.4 for x in c)
    except Exception:
        return default
def clamp(v, lo, hi): return max(lo, min(hi, v))
def meshes(): return [o for o in bpy.context.scene.objects if o.type == "MESH"]
def activate(o):
    if bpy.context.object and bpy.context.object.mode != "OBJECT": bpy.ops.object.mode_set(mode="OBJECT")
    bpy.ops.object.select_all(action="DESELECT"); o.select_set(True); bpy.context.view_layer.objects.active = o
def tris(o): return sum(len(p.vertices) - 2 for p in o.data.polygons)
def load(path):
    e = path.rsplit(".", 1)[-1].lower()
    before = set(bpy.context.scene.objects)
    if e == "obj": bpy.ops.wm.obj_import(filepath=path)
    elif e == "stl": bpy.ops.wm.stl_import(filepath=path)
    elif e == "ply": bpy.ops.wm.ply_import(filepath=path)
    elif e == "fbx": bpy.ops.import_scene.fbx(filepath=path)
    else: bpy.ops.import_scene.gltf(filepath=path)
    return [o for o in bpy.context.scene.objects if o not in before]
def join(objs):
    # one mesh object with transforms applied, so modifiers and booleans act on the whole model
    for o in objs:
        if o.type in ("CURVE", "FONT", "SURFACE", "META"):
            activate(o); bpy.ops.object.convert(target="MESH")
    ms = [o for o in objs if o.type == "MESH"]
    if not ms: raise RuntimeError("the model has no mesh")
    for o in ms:
        if o.data.users > 1: o.data = o.data.copy()
    activate(ms[0])
    for o in ms: o.select_set(True)
    if len(ms) > 1: bpy.ops.object.join()
    o = bpy.context.view_layer.objects.active
    bpy.ops.object.parent_clear(type="CLEAR_KEEP_TRANSFORM")
    bpy.ops.object.transform_apply(location=True, rotation=True, scale=True)
    for x in objs:
        try:
            if x != o and x.name in bpy.data.objects: bpy.data.objects.remove(x, do_unlink=True)
        except ReferenceError: pass
    return o
def prim(s):
    k = s.get("primitive", "cube"); P = bpy.ops.mesh; seg = int(clamp(s.get("segments", 48), 3, 256))
    if k == "cube": P.primitive_cube_add(size=1)
    elif k == "uv_sphere": P.primitive_uv_sphere_add(radius=0.5, segments=seg, ring_count=max(3, seg // 2))
    elif k == "ico_sphere": P.primitive_ico_sphere_add(radius=0.5, subdivisions=int(clamp(s.get("subdivisions", 3), 1, 6)))
    elif k == "cylinder": P.primitive_cylinder_add(radius=0.5, depth=1, vertices=seg)
    elif k == "cone": P.primitive_cone_add(radius1=0.5, radius2=float(s.get("top_radius", 0)) * 0.5, depth=1, vertices=seg)
    elif k == "torus": P.primitive_torus_add(major_radius=0.375, minor_radius=float(clamp(s.get("tube", 0.125), 0.01, 0.37)), major_segments=seg, minor_segments=max(6, seg // 3))
    elif k == "plane": P.primitive_plane_add(size=1)
    elif k == "grid": n = int(clamp(s.get("subdivisions", 10), 1, 400)); P.primitive_grid_add(size=1, x_subdivisions=n, y_subdivisions=n)
    elif k == "monkey": P.primitive_monkey_add(size=1)
    elif k == "text":
        bpy.ops.object.text_add(); t = bpy.context.object; t.data.body = str(s.get("text", "FORGE"))[:200]
        t.data.extrude = float(clamp(s.get("extrude", 0.1), 0, 5)); t.data.bevel_depth = float(clamp(s.get("bevel", 0.01), 0, 0.5))
        t.data.align_x = "CENTER"; t.rotation_euler = (rad(90), 0, 0)   # stand the text up, facing Forge +Z
        bpy.ops.object.convert(target="MESH"); bpy.ops.object.transform_apply(rotation=True)
    else: raise RuntimeError("unknown primitive " + str(k))
    o = bpy.context.object
    sz = s.get("size") or [1, 1, 1]
    o.scale = (sz[0], sz[2], sz[1]); o.rotation_euler = frot(s.get("rotation") or [0, 0, 0]); o.location = F(s.get("position") or [0, 0, 0])
    if k not in ("cube", "plane", "grid", "text"): bpy.ops.object.shade_smooth()
    if s.get("color"): material(o, s)
    bpy.ops.object.transform_apply(location=True, rotation=True, scale=True)
    return o
def mod(o, typ, **kw):
    m = o.modifiers.new(typ.lower(), typ)
    for k, v in kw.items(): setattr(m, k, v)
    activate(o); bpy.ops.object.modifier_apply(modifier=m.name)
def edit(o, fn):
    activate(o); bpy.ops.object.mode_set(mode="EDIT"); bpy.ops.mesh.select_all(action="SELECT")
    try: fn()
    finally: bpy.ops.object.mode_set(mode="OBJECT")
def material(o, s):
    m = bpy.data.materials.new(str(s.get("name", "Material"))[:60]); m.use_nodes = True
    b = m.node_tree.nodes["Principled BSDF"]
    def put(names, v):
        for n in names:
            if n in b.inputs: b.inputs[n].default_value = v; return
    put(["Base Color"], (*lin(s.get("color", "#cccccc")), 1))
    put(["Metallic"], float(clamp(s.get("metallic", s.get("metalness", 0)), 0, 1)))
    put(["Roughness"], float(clamp(s.get("roughness", 0.5), 0, 1)))
    if s.get("emission"):
        put(["Emission Color", "Emission"], (*lin(s["emission"]), 1)); put(["Emission Strength"], float(clamp(s.get("emission_strength", 1), 0, 1000)))
    if s.get("transmission") is not None: put(["Transmission Weight", "Transmission"], float(clamp(s["transmission"], 0, 1)))
    if s.get("alpha") is not None and s["alpha"] < 1:
        put(["Alpha"], float(clamp(s["alpha"], 0, 1)))
        try: m.blend_method = "BLEND"
        except Exception: pass
    o.data.materials.clear(); o.data.materials.append(m)
TEX = {"clouds": "CLOUDS", "voronoi": "VORONOI", "musgrave": "MUSGRAVE", "marble": "MARBLE", "wood": "WOOD", "stucci": "STUCCI", "noise": "NOISE", "distorted": "DISTORTED_NOISE"}
def size_of(o): return max(o.dimensions) or 1.0

def run(o, s):
    k = s["op"]; ax = s.get("axis") or "y"
    if k == "subdivide":
        lv = int(clamp(s.get("levels", 1), 1, 5))
        while lv > 1 and len(o.data.polygons) * 4 ** lv > 2500000: lv -= 1
        mod(o, "SUBSURF", levels=lv, subdivision_type="SIMPLE" if s.get("simple") else "CATMULL_CLARK")
    elif k == "bevel":
        mod(o, "BEVEL", width=float(clamp(s.get("width", 0.02), 0.0001, 100)), segments=int(clamp(s.get("segments", 2), 1, 12)), limit_method="ANGLE", angle_limit=rad(clamp(s.get("angle", 30), 1, 180)))
    elif k == "decimate":
        if s.get("planar"): mod(o, "DECIMATE", decimate_type="DISSOLVE", angle_limit=rad(clamp(s.get("angle", 5), 0.1, 90)))
        else:
            r = s.get("ratio")
            if r is None: r = float(s.get("target_faces", 5000)) / max(1, tris(o))
            mod(o, "DECIMATE", ratio=float(clamp(r, 0.001, 1)))
    elif k == "remesh":
        mode = str(s.get("mode", "voxel")).upper()
        if mode == "VOXEL": mod(o, "REMESH", mode="VOXEL", voxel_size=float(max(s.get("voxel_size", size_of(o) / 80), size_of(o) / 400)), use_smooth_shade=bool(s.get("smooth", True)))
        else: mod(o, "REMESH", mode=mode if mode in ("BLOCKS", "SMOOTH", "SHARP") else "SHARP", octree_depth=int(clamp(s.get("octree_depth", 6), 1, 9)), use_smooth_shade=bool(s.get("smooth", mode != "BLOCKS")))
    elif k == "solidify": mod(o, "SOLIDIFY", thickness=float(clamp(s.get("thickness", 0.05), -100, 100)), offset=float(clamp(s.get("offset", -1), -1, 1)))
    elif k == "mirror":
        use = [False] * 3; use[AXI[ax if s.get("axis") else "x"]] = True
        mod(o, "MIRROR", use_axis=use, use_bisect_axis=use if s.get("bisect") else [False] * 3, use_bisect_flip_axis=use if s.get("flip") else [False] * 3, use_clip=True, merge_threshold=float(s.get("merge", 0.001)))
    elif k == "array":
        n = int(clamp(s.get("count", 3), 1, 500))
        if s.get("relative"): mod(o, "ARRAY", count=n, use_relative_offset=True, relative_offset_displace=F(s.get("offset") or [1, 0, 0]))
        else: mod(o, "ARRAY", count=n, use_relative_offset=False, use_constant_offset=True, constant_offset_displace=F(s.get("offset") or [size_of(o) * 1.1, 0, 0]))
    elif k == "boolean":
        cutter = join(load(s["with_path"])) if s.get("with_path") else prim(s.get("with") or {})
        mod(o, "BOOLEAN", operation=s.get("operation", "difference").upper(), object=cutter, solver="EXACT")
        bpy.data.objects.remove(cutter, do_unlink=True)
    elif k == "displace":
        t = bpy.data.textures.new("forge_displace", type=TEX.get(str(s.get("kind", "clouds")).lower(), "CLOUDS"))
        try: t.noise_scale = float(clamp(s.get("scale", size_of(o) / 4), 0.0001, 1000))
        except Exception: pass
        mod(o, "DISPLACE", texture=t, strength=float(clamp(s.get("strength", size_of(o) / 20), -1000, 1000)), mid_level=float(s.get("mid_level", 0.5)), texture_coords="GLOBAL")
    elif k == "smooth":
        if s.get("laplacian"): mod(o, "LAPLACIANSMOOTH", lambda_factor=float(clamp(s.get("factor", 1), 0, 1000)), iterations=int(clamp(s.get("iterations", 2), 1, 100)))
        else: mod(o, "SMOOTH", factor=float(clamp(s.get("factor", 0.5), 0, 2)), iterations=int(clamp(s.get("iterations", 5), 1, 200)))
    elif k == "deform":
        m = str(s.get("method", "twist")).upper(); m = m if m in ("TWIST", "BEND", "TAPER", "STRETCH") else "TWIST"
        kw = {"angle": rad(s.get("angle", 45))} if m in ("TWIST", "BEND") else {"factor": float(clamp(s.get("factor", 0.5), -10, 10))}
        mod(o, "SIMPLE_DEFORM", deform_method=m, deform_axis=AX[ax], **kw)
    elif k == "wireframe": mod(o, "WIREFRAME", thickness=float(clamp(s.get("thickness", 0.02), 0.0001, 100)), use_replace=not s.get("keep"))
    elif k == "screw": mod(o, "SCREW", angle=rad(s.get("angle", 360)), steps=int(clamp(s.get("steps", 32), 2, 512)), render_steps=int(clamp(s.get("steps", 32), 2, 512)), screw_offset=float(s.get("offset", 0) if not isinstance(s.get("offset"), list) else 0), axis=AX[ax])
    elif k == "weld": mod(o, "WELD", merge_threshold=float(clamp(s.get("distance", 0.001), 0, 100)))
    elif k == "triangulate": mod(o, "TRIANGULATE")
    elif k == "edge_split": mod(o, "EDGE_SPLIT", split_angle=rad(clamp(s.get("angle", 30), 0, 180)))
    elif k == "cast":
        c = str(s.get("shape", "sphere")).upper(); mod(o, "CAST", cast_type=c if c in ("SPHERE", "CYLINDER", "CUBOID") else "SPHERE", factor=float(clamp(s.get("factor", 0.5), -10, 10)))
    elif k == "shade_smooth":
        activate(o)
        if s.get("angle") is not None and hasattr(bpy.ops.object, "shade_smooth_by_angle"): bpy.ops.object.shade_smooth_by_angle(angle=rad(clamp(s["angle"], 0, 180)))
        else: bpy.ops.object.shade_smooth()
    elif k == "shade_flat": activate(o); bpy.ops.object.shade_flat()
    elif k == "uv_unwrap":
        m = str(s.get("method", "smart")).lower()
        def go():
            if m == "cube": bpy.ops.uv.cube_project(cube_size=float(s.get("size", 1)))
            elif m == "sphere": bpy.ops.uv.sphere_project(direction="ALIGN_TO_OBJECT")
            elif m == "cylinder": bpy.ops.uv.cylinder_project(direction="ALIGN_TO_OBJECT")
            else: bpy.ops.uv.smart_project(angle_limit=rad(clamp(s.get("angle", 66), 1, 89)), island_margin=float(clamp(s.get("margin", 0.02), 0, 0.5)))
        edit(o, go)
    elif k == "recalc_normals": edit(o, lambda: bpy.ops.mesh.normals_make_consistent(inside=bool(s.get("inside"))))
    elif k == "fill_holes": edit(o, lambda: bpy.ops.mesh.fill_holes(sides=int(clamp(s.get("sides", 0), 0, 1000))))
    elif k == "convex_hull": edit(o, lambda: bpy.ops.mesh.convex_hull())
    elif k == "limited_dissolve": edit(o, lambda: bpy.ops.mesh.dissolve_limited(angle_limit=rad(clamp(s.get("angle", 5), 0.1, 180))))
    elif k == "material": material(o, s)
    elif k == "transform":
        activate(o)
        if s.get("scale"): o.scale = (s["scale"][0], s["scale"][2], s["scale"][1])
        if s.get("rotate"): o.rotation_euler = frot(s["rotate"])
        if s.get("translate"): o.location = F(s["translate"])
        bpy.ops.object.transform_apply(location=True, rotation=True, scale=True)
    elif k == "origin":
        bb = [o.matrix_world @ Vector(c) for c in o.bound_box]; lo = Vector([min(v[i] for v in bb) for i in range(3)]); hi = Vector([max(v[i] for v in bb) for i in range(3)])
        c = (lo + hi) / 2; d = Vector((c.x, c.y, lo.z if str(s.get("to", "bottom")) == "bottom" else c.z))
        o.data.transform(Matrix.Translation(-(o.matrix_world.inverted() @ d))); o.data.update()
    else: raise RuntimeError("unknown op " + str(k))

done = []
if a.get("code_path"):
    if a.get("model"): load(a["model"])
    g = {"bpy": bpy, "bmesh": bmesh, "math": math, "Vector": Vector, "Euler": Euler, "Matrix": Matrix, "params": a.get("params") or {},
         "forge_to_blender": F, "__name__": "__forge3d__"}
    exec(compile(open(a["code_path"]).read(), "<forge3d blender job>", "exec"), g)
    if bpy.context.object and bpy.context.object.mode != "OBJECT": bpy.ops.object.mode_set(mode="OBJECT")
    for o in list(bpy.context.scene.objects):
        if o.type in ("CURVE", "FONT", "SURFACE", "META"):
            activate(o); bpy.ops.object.convert(target="MESH")
    out = meshes()
    if not out: raise RuntimeError("the script left no mesh in the scene — add or keep at least one mesh object")
else:
    o = join(load(a["model"])) if a.get("model") else prim(a.get("start") or {})
    for i, s in enumerate(a.get("ops") or []):
        before = tris(o)
        try: run(o, s)
        except Exception as e: raise RuntimeError("op %d (%s) failed: %s" % (i + 1, s.get("op"), e))
        done.append({"op": s["op"], "triangles": tris(o)}); print("FORGE3D_STEP %d/%d %s: %d -> %d triangles" % (i + 1, len(a["ops"]), s["op"], before, tris(o)), flush=True)
        if tris(o) > 4000000: raise RuntimeError("op %d (%s) produced over 4 million triangles — lower the levels / count" % (i + 1, s.get("op")))
        if not len(o.data.polygons) and s["op"] != "wireframe": raise RuntimeError("op %d (%s) left an empty mesh" % (i + 1, s.get("op")))
    out = [o]
dg = bpy.context.evaluated_depsgraph_get(); lo = [1e18] * 3; hi = [-1e18] * 3; nt = nv = 0
for o in out:
    e = o.evaluated_get(dg); me = e.to_mesh(); nt += sum(len(p.vertices) - 2 for p in me.polygons); nv += len(me.vertices)
    for v in me.vertices:
        w = e.matrix_world @ v.co; f = (w.x, w.z, -w.y)
        for i in range(3): lo[i] = min(lo[i], f[i]); hi[i] = max(hi[i], f[i])
    e.to_mesh_clear()
bpy.ops.export_scene.gltf(filepath=a["out"], export_format="GLB", export_apply=True)
print("FORGE3D_STATS " + json.dumps({"faces": nt, "vertices": nv, "objects": len(out), "bounds": [[round(x, 4) for x in lo], [round(x, 4) for x in hi]], "steps": done, "blender": bpy.app.version_string}), flush=True)
"""

_MODEL_EXTS = ("glb", "gltf", "obj", "stl", "ply", "fbx")


def _fetch_model(url, folder, stem):
    if not str(url).startswith("https://"):
        raise ValueError("model url must be https")
    ext = url.split("?")[0].rsplit(".", 1)[-1].lower()
    ext = ext if ext in _MODEL_EXTS else "glb"
    r = requests.get(url, timeout=300)
    r.raise_for_status()
    if len(r.content) > 300e6:
        raise ValueError("model is over 300 MB")
    path = os.path.join(folder, f"{stem}.{ext}")
    open(path, "wb").write(r.content)
    return path


def blender_edit(job, progress, script=False):
    """Run the modifier stack (or the user's bpy script) in headless Blender. Returns (glb bytes, stats)."""
    import subprocess, tempfile
    p = job.get("params") or {}
    blender = install_blender(progress)
    if not blender:
        raise RuntimeError("Blender install failed")
    tmp = tempfile.mkdtemp(prefix="forge3d_blender_")
    args = {"out": os.path.join(tmp, "out.glb"), "params": p.get("params") if isinstance(p.get("params"), dict) else {}}
    if p.get("url"):
        progress("downloading model")
        args["model"] = _fetch_model(p["url"], tmp, "model")
    if script:
        args["code_path"] = os.path.join(tmp, "user_script.py")
        open(args["code_path"], "w").write(str(p.get("code", "")))
    else:
        if not args.get("model"):
            args["start"] = p.get("start") if isinstance(p.get("start"), dict) else {"primitive": "cube"}
        ops = []
        for i, op in enumerate(p.get("ops") or []):
            op = dict(op)
            if op.get("op") == "boolean" and op.get("with_url"):
                op["with_path"] = _fetch_model(op["with_url"], tmp, f"cutter{i}")
            ops.append(op)
        args["ops"] = ops
    aj = os.path.join(tmp, "args.json"); json.dump(args, open(aj, "w"))
    sp = os.path.join(tmp, "edit.py"); open(sp, "w").write(_BLENDER_EDIT_SCRIPT)
    limit = float(min(3600, max(30, p.get("time_limit") or 900)))
    progress("running your bpy script in Blender" if script else f"Blender: {len(args.get('ops') or [])} step(s)")
    proc = subprocess.Popen([blender, "-b", "--factory-startup", "--python-exit-code", "1", "-P", sp, "--", aj],
                            stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, cwd=tmp)
    timer = threading.Timer(limit, proc.kill); timer.start()
    log, stats = [], None
    try:
        for line in proc.stdout:
            log.append(line); log = log[-60:]
            if line.startswith("FORGE3D_STEP"):
                progress(line[len("FORGE3D_STEP"):].strip()[:200])
            elif line.startswith("FORGE3D_STATS"):
                stats = json.loads(line[len("FORGE3D_STATS"):])
        code = proc.wait()
    finally:
        timer.cancel()
    if code != 0 or stats is None or not os.path.exists(args["out"]):
        tail = "".join(l for l in log if not l.startswith(("Blender ", "Read prefs", "Info:")))[-1500:]
        raise RuntimeError(("Blender timed out after %d s" % limit if code in (-9, 137) else "Blender failed") + ":\n" + tail)
    return open(args["out"], "rb").read(), stats


def _seamless(pipe):
    import torch
    for model in (pipe.unet, pipe.vae):
        for m in model.modules():
            if isinstance(m, torch.nn.Conv2d):
                m.padding_mode = "circular"


def text_to_texture(api, job, progress):
    p = job["params"]
    engine = str(p.get("engine") or "auto").lower()
    if engine in ("sdxl", "ai") or (engine == "auto" and _device() == "cuda" and _ai_available()):
        try:
            return _sdxl_texture(api, job, progress)
        except Exception as e:
            if engine != "auto":
                raise
            progress(f"SDXL unavailable ({type(e).__name__}); using the procedural material synth")
    res = int(min(4096, p.get("resolution", 1024)))
    progress(f"synthesizing a seamless {res}px PBR material (CPU)")
    kind, maps = procedural_texture(p["prompt"], res, p.get("seed", 0))
    return _apply_texture(api, job, p, maps, progress, kind)


def _apply_texture(api, job, p, maps, progress, kind=None):
    progress("uploading maps")
    urls = {}
    for k, im in maps.items():
        b = io.BytesIO(); im.save(b, "PNG", optimize=False)
        urls[k] = api.upload(f"images/tex-{job['id']}-{k}.png", b.getvalue(), "image/png")
    target = p.get("apply_to")
    if target and job.get("scene_id"):
        tm = {**urls, "repeat": float(p.get("repeat", 1)), "prompt": p["prompt"][:80]}
        if target == "__ground":
            _merge_params(api, job["scene_id"], "__env", {"groundMaps": tm})
        else:
            api.rpc("modeler_apply_ops", p_id=job["scene_id"], p_by="worker", p_ops=[{"op": "update", "id": target, "set": {"texMaps": tm}}])
    return {"image_url": urls["map"], **urls, "applied_to": target, **({"material": kind} if kind else {})}


def _sdxl_texture(api, job, progress):
    import torch
    from diffusers import AutoPipelineForText2Image
    from PIL import Image, ImageFilter
    p = job["params"]
    if "sdxl-turbo" not in _pipes:
        progress("loading SDXL-turbo (first run downloads ~7 GB)")
        pipe = AutoPipelineForText2Image.from_pretrained("stabilityai/sdxl-turbo", torch_dtype=_dtype(), variant="fp16").to(_device())
        _seamless(pipe); _pipes["sdxl-turbo"] = pipe
    pipe = _pipes["sdxl-turbo"]
    progress("painting a seamless texture" + (" on CPU (about a minute)" if _device() == "cpu" else ""))
    prompt = f"{p['prompt']}, seamless tileable texture, flat lay, top-down photograph, even lighting, no shadows, high detail, 8k"
    gen = torch.Generator(_device()).manual_seed(int(p.get("seed", 0) or 0))
    side = 1024 if _device() == "cuda" else 512  # CPU: paint at 512, upscale below
    img = pipe(prompt=prompt, num_inference_steps=4, guidance_scale=0.0, width=side, height=side, generator=gen).images[0]
    res = int(p.get("resolution", 1024))
    if res != img.size[0]:
        img = img.resize((res, res), Image.LANCZOS)
    progress("deriving normal and roughness maps")
    g = np.asarray(img.convert("L"), dtype=np.float32) / 255.0
    gx = (np.roll(g, -1, 1) - np.roll(g, 1, 1)) * 2.5; gy = (np.roll(g, -1, 0) - np.roll(g, 1, 0)) * 2.5
    n = np.stack([-gx, gy, np.ones_like(g)], -1); n /= np.linalg.norm(n, axis=-1, keepdims=True)
    normal = Image.fromarray(((n * 0.5 + 0.5) * 255).astype(np.uint8))
    rough = Image.fromarray((np.clip(0.55 + (0.5 - g) * 0.6, 0.05, 1) * 255).astype(np.uint8)).filter(ImageFilter.GaussianBlur(1))
    return _apply_texture(api, job, p, {"map": img, "normal": normal, "rough": rough}, progress)


def _merge_params(api, scene_id, obj_id, patch):
    s = api.rpc("modeler_get_scene", p_id=scene_id, p_since_version=None)
    o = next((x for x in (s or {}).get("objects", []) if x.get("id") == obj_id), None)
    if not o:
        if obj_id == "__env":
            api.rpc("modeler_apply_ops", p_id=scene_id, p_by="worker", p_ops=[{"op": "add", "object": {"id": "__env", "type": "env", "name": "Scene settings", "params": patch}}])
            return
        raise RuntimeError(f"object {obj_id} not found")
    api.rpc("modeler_apply_ops", p_id=scene_id, p_by="worker", p_ops=[{"op": "update", "id": obj_id, "set": {"params": {**(o.get("params") or {}), **patch}}}])


def erode(h, iterations=80000, seed=0, inertia=0.05, capacity=4.0, deposition=0.3, erosion=0.3, evaporation=0.015, radius=2, progress=None):
    """Particle-based hydraulic erosion (Beyer / Lague style) on a 2D heightfield in metres."""
    rng = np.random.default_rng(seed); n = h.shape[0]; h = h.astype(np.float64).copy()
    def grad(px, py):
        x, y = int(px), int(py); u, v = px - x, py - y
        a, b, c, d = h[y, x], h[y, x + 1], h[y + 1, x], h[y + 1, x + 1]
        return (b - a) * (1 - v) + (d - c) * v, (c - a) * (1 - u) + (d - b) * u, a * (1 - u) * (1 - v) + b * u * (1 - v) + c * (1 - u) * v + d * u * v
    offs = [(dx, dy, max(0.0, radius - math.hypot(dx, dy))) for dx in range(-radius, radius + 1) for dy in range(-radius, radius + 1)]
    wsum = sum(w for *_, w in offs); offs = [(dx, dy, w / wsum) for dx, dy, w in offs if w > 0]
    for it in range(iterations):
        if progress and it % 20000 == 0:
            progress(f"eroding… {it * 100 // iterations}%")
        px, py = rng.uniform(1, n - 2), rng.uniform(1, n - 2); dx = dy = 0.0; speed, water, sed = 1.0, 1.0, 0.0
        for _ in range(48):
            gx, gy, hgt = grad(px, py)
            dx = dx * inertia - gx * (1 - inertia); dy = dy * inertia - gy * (1 - inertia)
            l = math.hypot(dx, dy)
            if l < 1e-9: break
            dx /= l; dy /= l; ox, oy = px, py; px += dx; py += dy
            if px < 1 or py < 1 or px >= n - 2 or py >= n - 2: break
            nh = grad(px, py)[2]; dh = nh - hgt
            cap = max(-dh, 0.01) * speed * water * capacity
            ix, iy = int(ox), int(oy); u, v = ox - ix, oy - iy
            if sed > cap or dh > 0:
                amt = min(dh, sed) if dh > 0 else (sed - cap) * deposition
                sed -= amt
                h[iy, ix] += amt * (1 - u) * (1 - v); h[iy, ix + 1] += amt * u * (1 - v); h[iy + 1, ix] += amt * (1 - u) * v; h[iy + 1, ix + 1] += amt * u * v
            else:
                amt = min((cap - sed) * erosion, -dh); sed += amt
                for ddx, ddy, w in offs:
                    xx, yy = ix + ddx, iy + ddy
                    if 0 <= xx < n and 0 <= yy < n: h[yy, xx] -= amt * w
            speed = math.sqrt(max(0.0, speed * speed + dh * -9.81 * 0.1)); water *= (1 - evaporation)
    return h


def terrain_erosion(api, job, progress):
    import base64
    p = job["params"]; n = int(p["n"])
    raw = np.frombuffer(base64.b64decode(p["heights"]), dtype=np.int16).astype(np.float64) / 100.0
    if raw.size != n * n:
        raise ValueError("heights size does not match n")
    cell = float(p.get("size", 240)) / (n - 1)
    h = erode(raw.reshape(n, n) / cell, iterations=int(min(400000, p.get("iterations", 120000) * float(p.get("strength", 1)))), seed=int(p.get("seed", 0) or 0), progress=progress) * cell
    out = base64.b64encode(np.clip(np.round(h * 100), -32768, 32767).astype(np.int16).tobytes()).decode()
    if job.get("scene_id") and p.get("object_id"):
        progress("updating the terrain")
        _merge_params(api, job["scene_id"], p["object_id"], {"heights": out})
    return {"object_id": p.get("object_id"), "n": n, "min": float(h.min()), "max": float(h.max())}


def voxelize_mesh(url, pitch, progress):
    progress("downloading model")
    r = requests.get(url, timeout=120); r.raise_for_status()
    ext = url.split("?")[0].rsplit(".", 1)[-1].lower()
    mesh = to_single_mesh(trimesh.load(io.BytesIO(r.content), file_type=ext if ext in ("glb", "gltf", "obj", "stl", "ply") else "glb"))
    pitch = max(float(pitch), max(mesh.extents) / 160.0)
    progress(f"voxelizing at {pitch:.3f} m")
    vox = mesh.voxelized(pitch).fill()
    boxes = vox.as_boxes()
    try:  # carry the model's colours onto the blocks
        cols = mesh.visual.to_color().vertex_colors if mesh.visual is not None else None
        if cols is not None and len(cols):
            centers = vox.points
            from scipy.spatial import cKDTree
            idx = cKDTree(mesh.vertices).query(centers)[1]
            per_box = cols[idx]
            boxes.visual.face_colors = np.repeat(per_box, 12, axis=0)
    except Exception:
        pass
    return boxes


TRIPOSR_DIR = os.path.expanduser("~/forge3d_triposr")


def _triposr(progress):
    if "triposr" in _pipes:
        return _pipes["triposr"]
    import subprocess
    if not os.path.isdir(TRIPOSR_DIR):
        progress("installing TripoSR (one time)")
        subprocess.run(["git", "clone", "-q", "https://github.com/VAST-AI-Research/TripoSR", TRIPOSR_DIR], check=True)
        subprocess.run([sys.executable, "-m", "pip", "install", "-q", "omegaconf", "einops", "huggingface-hub", "transformers", "git+https://github.com/tatsy/torchmcubes.git"], check=True)
    sys.path.insert(0, TRIPOSR_DIR)
    from tsr.system import TSR
    progress("loading TripoSR")
    model = TSR.from_pretrained("stabilityai/TripoSR", config_name="config.yaml", weight_name="model.ckpt")
    model.renderer.set_chunk_size(8192 if _device() == "cuda" else 2048); model.to(_device()); _cpu_threads()
    _pipes["triposr"] = model
    return model


def _image_to_mesh_triposr(img, progress):
    import torch
    from PIL import Image
    model = _triposr(progress)
    try:
        from rembg import remove
        progress("removing background")
        img = remove(img.convert("RGB"))
    except Exception:
        img = img.convert("RGBA")
    # centre on grey like TripoSR expects
    bg = Image.new("RGBA", img.size, (127, 127, 127, 255)); bg.alpha_composite(img); img = bg.convert("RGB")
    progress("reconstructing 3D")
    with torch.no_grad():
        codes = model([img], device=_device())
        m = model.extract_mesh(codes, True, resolution=256)[0]
    m.apply_transform(trimesh.transformations.rotation_matrix(-math.pi / 2, [1, 0, 0]))
    return m


def _sdxl_triposr_text(params, progress):
    import torch
    from diffusers import AutoPipelineForText2Image
    if "sdxl-turbo-plain" not in _pipes:
        progress("loading SDXL-turbo")
        _pipes["sdxl-turbo-plain"] = AutoPipelineForText2Image.from_pretrained("stabilityai/sdxl-turbo", torch_dtype=_dtype(), variant="fp16").to(_device())
    progress("drawing a reference image")
    gen = torch.Generator(_device()).manual_seed(int(params.get("seed", 0) or 0))
    img = _pipes["sdxl-turbo-plain"](prompt=f"{params['prompt']}, single object, centered, full view, plain white background, studio lighting, 3d game asset",
                                     num_inference_steps=4, guidance_scale=0.0, width=512, height=512, generator=gen).images[0]
    return _image_to_mesh_triposr(img, progress)


def _triposr_image(params, progress):
    from diffusers.utils import load_image
    progress("downloading image")
    return _image_to_mesh_triposr(load_image(params["image_url"]), progress)


def _with_fallback(primary, fallback):
    def run(params, progress):
        try:
            return primary(params, progress)
        except Exception as e:
            progress(f"best engine unavailable ({type(e).__name__}: {str(e)[:80]}); falling back")
            return fallback(params, progress)
    return run


register_engine("text", "sdxl_triposr", _with_fallback(_sdxl_triposr_text, _shap_e_text))
register_engine("image", "triposr", _with_fallback(_triposr_image, _shap_e_image))
register_engine("text", "parts", parts_text)
register_engine("text", "auto", _text_auto)
register_engine("image", "relief", relief_mesh)
register_engine("image", "auto", _image_auto)
ENGINES["text"]["shap_e"] = ENGINES["text"]["shap-e"]
ENGINES["image"]["shap_e"] = ENGINES["image"]["shap-e"]


def setup(gpu_jobs=True, blender=True, quiet=True, ai=None):
    """One-time install. Works on CPU-only runtimes: numpy/scipy engines + Blender (Cycles renders on CPU).
    ai=None installs diffusers (SDXL / TripoSR / Shap-E) only when a GPU is present; ai=True installs them on CPU
    too (they then run on CPU — minutes instead of seconds); ai=False never."""
    import subprocess
    subprocess.run([sys.executable, "-m", "pip", "install", *(["-q"] if quiet else []), "trimesh", "numpy", "requests", "fast_simplification", "scipy", "pillow"], check=False)
    if ai or (ai is None and gpu_jobs and _gpu_name()):
        install_ai_deps(quiet)
    if blender:
        try:
            install_blender()
        except Exception as e:
            print("[forge3d] Blender install failed (renders disabled):", e)
    print("[forge3d] setup done · GPU:", _gpu_name() or "none (CPU mode — every job still works)", "· Blender:", bool(_blender_bin()),
          "· AI libs:", _ai_available())


# --------------------------------------------------------------------------- worker

def _detect_platform():
    if "google.colab" in sys.modules or os.environ.get("COLAB_RELEASE_TAG"):
        return "colab"
    if os.environ.get("KAGGLE_KERNEL_RUN_TYPE") or os.path.exists("/kaggle"):
        return "kaggle"
    return platform.system().lower()


class Worker:
    def __init__(self, key, name=None, allow_python=False, kinds=None, poll=3.0, verbose=True):
        self.api = Api(key)
        self.platform = _detect_platform()
        self.gpu = _gpu_name()
        self.name = name or f"{self.platform}-{socket.gethostname()[:8]}-{uuid.uuid4().hex[:4]}"
        self.allow_python = allow_python
        self.poll = poll
        self.verbose = verbose
        self._stop = threading.Event()
        self.threads = []
        self.done = 0
        # every kind works on CPU; a GPU (or installed AI libs) just upgrades the engines behind them
        caps = ["procedural", "optimize", "terrain_erosion", "voxelize", "text_to_3d", "image_to_3d", "text_to_texture"]
        if _blender_bin() or os.environ.get("FORGE3D_CPU_RENDER") or sys.platform.startswith("linux"):
            caps.append("render")  # Blender is fetched on the first render job if it isn't installed yet
            caps.append("blender_ops")  # real Blender modifiers (declarative, no user code)
        if allow_python:
            caps.append("python")
            if "render" in caps:
                caps.append("blender")  # the user's own bpy script
        self.kinds = [k for k in caps if not kinds or k in kinds]

    def log(self, *a):
        if self.verbose:
            print(time.strftime("%H:%M:%S"), "[forge3d]", *a, flush=True)

    # heartbeat ------------------------------------------------------------
    def _heartbeat_loop(self):
        while not self._stop.is_set():
            try:
                self.api.rpc("modeler_heartbeat", p_id=self.name, p_platform=self.platform, p_gpu=self.gpu or "none",
                             p_caps=self.kinds)
            except Exception as e:
                self.log("heartbeat failed:", e)
            self._stop.wait(20)

    # job helpers ----------------------------------------------------------
    def _progress(self, job, msg):
        r = self.api.rpc("modeler_update_job", p_id=job["id"], p_worker=self.name, p_progress=str(msg)[:300])
        if r is None:
            raise Cancelled()
        self.log(f"  {job['kind']} {job['id'][:8]}: {msg}")

    def _deliver(self, job, mesh, name, source):
        progress = lambda m: self._progress(job, m)
        mesh = to_single_mesh(mesh)
        progress(f"exporting GLB ({len(mesh.faces):,} triangles)")
        return self._deliver_glb(job, export_glb(mesh), name, source,
                                 {"faces": int(len(mesh.faces)), "vertices": int(len(mesh.vertices)),
                                  "bounds": np.asarray(mesh.bounds).round(4).tolist()})

    def _deliver_glb(self, job, data, name, source, stats):
        """Upload a finished GLB and put it in the scene: a new mesh object, or swap an existing one (replace + object_id)."""
        p = job.get("params") or {}
        url = self.api.upload(f"models/{job['id']}.glb", data, "model/gltf-binary")
        result = {"url": url, **stats, "bytes": len(data)}
        scene_id = job.get("scene_id")
        if scene_id and p.get("add_to_scene", True):
            if job["kind"] in ("optimize", "blender_ops", "blender") and p.get("replace") and p.get("object_id"):
                self.api.rpc("modeler_apply_ops", p_id=scene_id, p_by=self.name,
                             p_ops=[{"op": "update", "id": p["object_id"], "set": {
                                 "url": url, "source": source,
                                 # a basic shape rebuilt at its real size becomes a mesh at scale 1
                                 **({"type": "mesh", "scale": [1, 1, 1]} if p.get("convert") else {})}}])
                result["object_id"] = p["object_id"]
            else:
                obj = {"type": "mesh", "name": name[:60], "url": url, "position": p.get("position") or [0, 0, 0],
                       "rotation": p.get("rotation") or [0, 0, 0], "scale": p.get("scale") or [1, 1, 1], "source": source}
                r = self.api.rpc("modeler_apply_ops", p_id=scene_id, p_by=self.name, p_ops=[{"op": "add", "object": obj}])
                result["object_id"] = (r.get("added_ids") or [None])[0]
        return result

    def handle(self, job):
        kind, p = job["kind"], job.get("params") or {}
        progress = lambda m: self._progress(job, m)
        if kind == "procedural":
            progress(f"building {p.get('generator', 'rock')}")
            mesh = build_procedural(p)
            gname = p.get("generator", "rock").replace("_", " ").title()
            return self._deliver(job, mesh, p.get("name") or gname,
                                 {"kind": "procedural", "generator": p.get("generator"), "seed": p.get("seed")})
        if kind in ("text_to_3d", "image_to_3d"):
            which = "text" if kind == "text_to_3d" else "image"
            engine = p.get("engine") or "auto"
            if engine not in ENGINES[which]:
                raise ValueError(f"unknown {which} engine '{engine}'. Registered: {list(ENGINES[which])}")
            if which == "text" and not p.get("prompt"):
                raise ValueError("text_to_3d needs params.prompt")
            if which == "image" and not p.get("image_url"):
                raise ValueError("image_to_3d needs params.image_url")
            mesh = to_single_mesh(ENGINES[which][engine](p, progress))
            if len(mesh.faces) > int(p.get("max_faces", 30000)):
                progress("simplifying for games")
                try:
                    mesh = decimate(mesh, int(p.get("max_faces", 30000)))
                except Exception as e:
                    self.log("  (skipped decimation:", e, ")")
            normalize(mesh, size=float(p.get("size", 1) or 1))
            name = (p.get("prompt") or "Image model")[:60]
            return self._deliver(job, mesh, name, {"kind": kind, "engine": engine, "prompt": p.get("prompt")})
        if kind == "optimize":
            url = p.get("url")
            if not url:
                raise ValueError("optimize needs params.url (the model to simplify)")
            progress("downloading model")
            r = requests.get(url, timeout=120)
            r.raise_for_status()
            ext = url.split("?")[0].rsplit(".", 1)[-1].lower()
            loaded = trimesh.load(io.BytesIO(r.content), file_type=ext if ext in ("glb", "gltf", "obj", "stl", "ply") else "glb")
            mesh = to_single_mesh(loaded)
            before = len(mesh.faces)
            progress(f"decimating {before:,} -> {int(p.get('target_faces', 5000)):,} triangles")
            mesh = decimate(mesh, int(p.get("target_faces", 5000)))
            res = self._deliver(job, mesh, f"Optimized ({len(mesh.faces):,})",
                                {"kind": "optimize", "from_faces": before, "from_url": url})
            res["from_faces"] = before
            return res
        if kind == "render":
            return render_job(self.api, job, progress)
        if kind == "text_to_texture":
            return text_to_texture(self.api, job, progress)
        if kind == "terrain_erosion":
            return terrain_erosion(self.api, job, progress)
        if kind == "voxelize":
            boxes = voxelize_mesh(p["url"], p.get("pitch", 0.1), progress)
            return self._deliver(job, boxes, p.get("name") or "Voxels", {"kind": "voxelize", "pitch": p.get("pitch")})
        if kind == "blender_ops":
            data, stats = blender_edit(job, progress)
            names = [o.get("op") for o in p.get("ops") or []]
            return self._deliver_glb(job, data, p.get("name") or ("Blender: " + ", ".join(names[:4]) if names else "Blender model"),
                                     {"kind": "blender_ops", "ops": names, "from_url": p.get("url")}, stats)
        if kind == "blender":
            if not self.allow_python:
                raise PermissionError("this worker was started without allow_python=True (bpy scripts are your own code)")
            data, stats = blender_edit(job, progress, script=True)
            return self._deliver_glb(job, data, p.get("name") or "Blender model", {"kind": "blender"}, stats)
        if kind == "python":
            if not self.allow_python:
                raise PermissionError("this worker was started without allow_python=True")
            progress("running your Python")
            ns = {"trimesh": trimesh, "np": np, "math": math, "params": p, "gen": GENERATORS, "finalize": finalize,
                  "paint": paint, "box": box, "cyl": cyl, "cone": cone, "ico": ico, "hull": hull, "lumpy": lumpy,
                  "normalize": normalize, "progress": progress, "result": None}
            exec(compile(p.get("code", ""), f"<job {job['id'][:8]}>", "exec"), ns)
            if ns.get("result") is None:
                raise ValueError("your code must set `result` to a mesh, a list of meshes, or a trimesh.Scene")
            return self._deliver(job, ns["result"], p.get("name") or "Python model", {"kind": "python"})
        raise ValueError(f"unsupported job kind {kind}")

    # main loop ------------------------------------------------------------
    def _loop(self, max_hours=None):
        deadline = time.time() + max_hours * 3600 if max_hours else None
        idle_note = 0
        while not self._stop.is_set():
            if deadline and time.time() > deadline:
                self.log("max_hours reached, stopping")
                break
            try:
                job = self.api.rpc("modeler_claim_job", p_worker=self.name, p_kinds=self.kinds)
            except Exception as e:
                self.log("claim failed:", e)
                self._stop.wait(10)
                continue
            if not job or not job.get("id"):
                idle_note += 1
                if idle_note % 100 == 1:
                    self.log("waiting for jobs…")
                self._stop.wait(self.poll)
                continue
            idle_note = 0
            t0 = time.time()
            if not isinstance(job.get("params"), dict):
                job["params"] = {}
            self.log(f"job {job['id'][:8]} {job['kind']} {json.dumps(job.get('params') or {})[:120]}")
            try:
                result = self.handle(job)
                result["seconds"] = round(time.time() - t0, 1)
                self.api.rpc("modeler_update_job", p_id=job["id"], p_worker=self.name, p_status="done",
                             p_progress=f"done in {result['seconds']}s", p_result=result)
                self.done += 1
                self.log(f"  done in {result['seconds']}s -> {result.get('url')}")
            except Cancelled:
                self.log("  cancelled")
            except Exception as e:
                tb = traceback.format_exc(limit=3)
                self.log("  failed:", e)
                try:
                    self.api.rpc("modeler_update_job", p_id=job["id"], p_worker=self.name, p_status="error",
                                 p_progress="failed", p_error=f"{type(e).__name__}: {e}\n{tb[-1200:]}")
                except Exception:
                    pass
        self._stop.set()

    def start(self, background=True, max_hours=None):
        if not self.api.rpc("modeler_check_key"):
            raise SystemExit("Forge 3D: invalid access key")
        self.log(f"worker '{self.name}' online · {self.platform} · GPU: {self.gpu or 'none'} · jobs: {', '.join(self.kinds)}")
        if not self.gpu:
            self.log("no GPU — that's fine: textures, image → 3D (relief), text → 3D (procedural) and Cycles renders "
                     "(denoised) all run on CPU." + ("" if _ai_available() else " setup(ai=True) adds SDXL/TripoSR on CPU."))
        hb = threading.Thread(target=self._heartbeat_loop, daemon=True, name="forge3d-heartbeat")
        hb.start()
        self.threads.append(hb)
        if background:
            t = threading.Thread(target=self._loop, kwargs={"max_hours": max_hours}, daemon=True, name="forge3d-worker")
            t.start()
            self.threads.append(t)
            self.log("running in the background — keep this runtime open. Call .stop() to stop.")
            return self
        try:
            self._loop(max_hours=max_hours)
        except KeyboardInterrupt:
            self.log("stopped")
        finally:
            self._stop.set()
        return self

    def stop(self):
        self._stop.set()
        self.log("stopping…")


_current = None


def run(key=None, background=False, allow_python=False, max_hours=None, name=None, kinds=None, poll=3.0, verbose=True,
        install_ai=True, api=None):
    """Start a worker. key = your Forge 3D access key (or set FORGE3D_KEY).
    On a GPU runtime, the text/image->3D libraries are installed automatically (install_ai=False to skip)."""
    global _current
    key = key or os.environ.get("FORGE3D_KEY")
    if not key:
        raise SystemExit("Forge 3D: pass key='mk_...' or set FORGE3D_KEY")
    if install_ai and _gpu_name() and not _ai_available():
        print("[forge3d] GPU found — installing diffusers for text/image → 3D (one time, ~1 min)…", flush=True)
        install_ai_deps()
        import importlib
        importlib.invalidate_caches()
    if _current and not _current._stop.is_set():
        _current.stop()
        time.sleep(0.5)
    _current = Worker(key, name=name, allow_python=allow_python, kinds=kinds, poll=poll, verbose=verbose)
    return _current.start(background=background, max_hours=max_hours)


def preview(generator="rock", seed=0, **params):
    """Build a procedural asset locally (no server) — handy for testing generators in a notebook."""
    return build_procedural({"generator": generator, "seed": seed, **params})


if __name__ == "__main__":
    import argparse
    ap = argparse.ArgumentParser(description="Forge 3D worker")
    ap.add_argument("--key", default=os.environ.get("FORGE3D_KEY"))
    ap.add_argument("--allow-python", action="store_true")
    ap.add_argument("--max-hours", type=float)
    ap.add_argument("--name")
    a = ap.parse_args()
    run(key=a.key, background=False, allow_python=a.allow_python, max_hours=a.max_hours, name=a.name)
