Mike0021 commited on
Commit
8b253ad
·
verified ·
1 Parent(s): 22a050c

Round 33: keep the caller's layer colours within 15 (CIELAB), tiles that redraw the layout give only fine texture, canal/bayou water words, /api/jobs refuses terrain bodies

Browse files
Files changed (4) hide show
  1. app/llms.txt +6 -3
  2. app/server.py +37 -6
  3. projtex/terrain.py +86 -25
  4. tests/smoke.py +3 -0
app/llms.txt CHANGED
@@ -205,9 +205,12 @@ Request (JSON; only the ground and a prompt are required):
205
  that differs from its close-up; forests and woods default to their tree crowns. If you place your own 3D trees,
206
  make the forest layer their floor: from_above "pine-needle forest floor, no tree crowns" and a brown colour (a
207
  green patch is painted as crowns); then no trees are painted anywhere. A layer's "color" [r, g, b] is kept:
208
- the colour map is turned to its hue (the image model drifts, e.g. red autumn leaves toward olive). Presets (when
209
- layers is omitted, chosen from the prompt's words): alpine, temperate, desert, arctic, winter, volcanic (GET /api
210
- lists them).
 
 
 
211
  - uv: planar (default: terrain.glb gets top-down UVs) | keep (the colour map is baked into your own UVs).
212
  - backend: qwen-turbo (default) | qwen-space | mock (free dry run). Cost: layers + 1 + tiles images (2048: about
213
  15 images, ~2 min of GPU quota and ~2-3 min in all; 4096: ~31 images).
 
205
  that differs from its close-up; forests and woods default to their tree crowns. If you place your own 3D trees,
206
  make the forest layer their floor: from_above "pine-needle forest floor, no tree crowns" and a brown colour (a
207
  green patch is painted as crowns); then no trees are painted anywhere. A layer's "color" [r, g, b] is kept:
208
+ the colour map is turned to its hue (the image model drifts, e.g. red autumn leaves toward olive) and a layer
209
+ painted far from it is moved to within 15 (CIELAB), listed in terrain.colours_pulled. Narrow features repeated
210
+ across a large ground (13 m stripes on 2.4 km) are smaller than the image model can follow: tiles that redraw
211
+ them give only their fine texture (terrain.tiles_off_layout), softer there; on a smaller ground (13 m stripes on
212
+ 700 m) they keep their detail. Presets (when layers is omitted, chosen from the prompt's words): alpine,
213
+ temperate, desert, arctic, winter, volcanic (GET /api lists them).
214
  - uv: planar (default: terrain.glb gets top-down UVs) | keep (the colour map is baked into your own UVs).
215
  - backend: qwen-turbo (default) | qwen-space | mock (free dry run). Cost: layers + 1 + tiles images (2048: about
216
  15 images, ~2 min of GPU quota and ~2-3 min in all; 4096: ~31 images).
app/server.py CHANGED
@@ -19,7 +19,7 @@ from typing import Any, Literal
19
  import requests
20
  from fastapi import FastAPI, File, Form, HTTPException, Request, Response, UploadFile
21
  from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, PlainTextResponse
22
- from pydantic import BaseModel, Field
23
  from starlette.concurrency import run_in_threadpool
24
 
25
  from .jobs import BACKENDS, MAX_FACES, MAX_MESH_BYTES, MAX_RUNNING, SAMPLE_INFO, TERRAIN_BACKENDS, Identity, JobError, \
@@ -85,6 +85,18 @@ def terrain_status(job, base: str, events: int = 12) -> dict:
85
  "why": "the image model painted water beyond your water_level (it enlarges small ponds and lakes); "
86
  "that ground was repainted with its layers' colours before the tiles. The model's own "
87
  "picture is files.overview_raw."}
 
 
 
 
 
 
 
 
 
 
 
 
88
  if st.get("covered", 1) < 0.97:
89
  warnings.append(f"{round((1 - st['covered']) * 100, 1)} % of the ground's top-down area has no upward "
90
  "surface (holes, or a mesh that is not +Y up): those parts were filled from their "
@@ -523,6 +535,22 @@ class TextureRequest(BaseModel):
523
  "generation. Kept in memory for this job only, never stored or "
524
  "logged. Alternatively send it as header X-HF-Token.")
525
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
526
 
527
  class TerrainPath(BaseModel):
528
  points: list[list[float]] = Field(..., description="[[x, z], ...] ground coordinates in metres (glTF/three.js "
@@ -549,9 +577,10 @@ class TerrainLayer(BaseModel):
549
  "natural patches (dirt patches in grass: 0.15)")
550
  breakup: float | None = Field(None, ge=0, le=1, description="How irregular the layer's edges are (default 0.5)")
551
  tile_m: float = Field(4.0, gt=0.2, le=50, description="Size in metres of one repeat of the detail texture")
552
- color: list[float] | None = Field(None, description="Optional [r, g, b] 0-255 the layer shows in the overview "
553
- "guide (default: its detail texture's mean colour); the "
554
- "colour map is turned to its hue")
 
555
  triplanar: bool | None = Field(None, description="Project the detail texture from the sides on steep slopes "
556
  "(default: layers whose rules start at 30 degrees or more)")
557
  from_above: str | None = Field(None, description="How the layer looks from high above in the colour map, if "
@@ -1057,9 +1086,11 @@ async def upload_mesh(request: Request, filename: str | None = None) -> dict:
1057
  "height_m": "<black-to-white height in metres>"},
1058
  "prompt": "<the place, e.g. an alpine valley in early summer>"}}]
1059
  return up
1060
- up["next"] = [{"do": "create the job", "method": "POST", "url": f"{base}/api/jobs",
 
1061
  "body": {"upload_id": up["upload_id"], "prompt": "<materials and colours>"}},
1062
- {"do": "or, if this is a terrain / the ground of a scene: create a terrain job", "method": "POST",
 
1063
  "url": f"{base}/api/terrain",
1064
  "body": {"upload_id": up["upload_id"], "prompt": "<the place, e.g. rolling farmland in summer>"}}]
1065
  return up
 
19
  import requests
20
  from fastapi import FastAPI, File, Form, HTTPException, Request, Response, UploadFile
21
  from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, PlainTextResponse
22
+ from pydantic import BaseModel, Field, model_validator
23
  from starlette.concurrency import run_in_threadpool
24
 
25
  from .jobs import BACKENDS, MAX_FACES, MAX_MESH_BYTES, MAX_RUNNING, SAMPLE_INFO, TERRAIN_BACKENDS, Identity, JobError, \
 
85
  "why": "the image model painted water beyond your water_level (it enlarges small ponds and lakes); "
86
  "that ground was repainted with its layers' colours before the tiles. The model's own "
87
  "picture is files.overview_raw."}
88
+ if st.get("colours_pulled"):
89
+ out["terrain"]["colours_pulled"] = {
90
+ "layers": st["colours_pulled"],
91
+ "why": "the image model painted these layers far from your color (their CIELAB distance from it is "
92
+ "shown; narrow stripes of strong colours are often lost in its picture of the whole ground): "
93
+ "the colour map was moved to within 15 of your color, lightness too, its texture kept"}
94
+ if st.get("tiles_off_layout"):
95
+ out["terrain"]["tiles_off_layout"] = {
96
+ "tiles": st["tiles_off_layout"],
97
+ "why": "these tiles of the colour map redrew the layout instead of refining it (narrow features "
98
+ "repeated across the ground, e.g. 13 m stripes on 1 km); only their finest texture was used, "
99
+ "so your layout is kept there but looks softer. A smaller ground per job keeps more detail."}
100
  if st.get("covered", 1) < 0.97:
101
  warnings.append(f"{round((1 - st['covered']) * 100, 1)} % of the ground's top-down area has no upward "
102
  "surface (holes, or a mesh that is not +Y up): those parts were filled from their "
 
535
  "generation. Kept in memory for this job only, never stored or "
536
  "logged. Alternatively send it as header X-HF-Token.")
537
 
538
+ @model_validator(mode="before")
539
+ @classmethod
540
+ def _not_a_terrain(cls, data):
541
+ """A terrain body sent here is refused, not run as an orbit job without its layers: a tester followed the
542
+ upload's first "next" (POST /api/jobs) with layers, water_level and macro_size, and waited 5 minutes for
543
+ an object texture of its polder (round 33)."""
544
+ found = [k for k in TERRAIN_ONLY if isinstance(data, dict) and k in data]
545
+ if found:
546
+ raise JobError(f"{', '.join(found)} {'is a terrain field' if len(found) == 1 else 'are terrain fields'}: "
547
+ "this endpoint textures objects", 400,
548
+ "send the same body to POST /api/terrain (ground layers and a top-down colour map)")
549
+ return data
550
+
551
+
552
+ TERRAIN_ONLY = ("layers", "water_level", "macro_size", "heightmap", "axes")
553
+
554
 
555
  class TerrainPath(BaseModel):
556
  points: list[list[float]] = Field(..., description="[[x, z], ...] ground coordinates in metres (glTF/three.js "
 
577
  "natural patches (dirt patches in grass: 0.15)")
578
  breakup: float | None = Field(None, ge=0, le=1, description="How irregular the layer's edges are (default 0.5)")
579
  tile_m: float = Field(4.0, gt=0.2, le=50, description="Size in metres of one repeat of the detail texture")
580
+ color: list[float] | None = Field(None, description="Optional [r, g, b] 0-255 (or 0-1) the layer shows in the "
581
+ "overview guide (default: its detail texture's mean colour); "
582
+ "the colour map is turned to its hue and kept within 15 "
583
+ "(CIELAB) of it")
584
  triplanar: bool | None = Field(None, description="Project the detail texture from the sides on steep slopes "
585
  "(default: layers whose rules start at 30 degrees or more)")
586
  from_above: str | None = Field(None, description="How the layer looks from high above in the colour map, if "
 
1086
  "height_m": "<black-to-white height in metres>"},
1087
  "prompt": "<the place, e.g. an alpine valley in early summer>"}}]
1088
  return up
1089
+ up["next"] = [{"do": "texture an object (a prop, building, vehicle, character)", "method": "POST",
1090
+ "url": f"{base}/api/jobs",
1091
  "body": {"upload_id": up["upload_id"], "prompt": "<materials and colours>"}},
1092
+ {"do": "or, if this is a terrain / the ground of a scene (with layers): create a terrain job",
1093
+ "method": "POST",
1094
  "url": f"{base}/api/terrain",
1095
  "body": {"upload_id": up["upload_id"], "prompt": "<the place, e.g. rolling farmland in summer>"}}]
1096
  return up
projtex/terrain.py CHANGED
@@ -304,7 +304,7 @@ def rule_warnings(layers: list[dict], prompt: str, st: dict) -> list[str]:
304
  "sea) use \"elevation\": [min_m, max_m] in the mesh's own heights (this ground: "
305
  f"{y0:.1f} to {y0 + relief:.1f})")
306
  for L in layers:
307
- lab = _lab(np.asarray(L.get("color") or [128] * 3, np.float32) / 255) if tree_floor(L) else None
308
  if lab is not None and np.hypot(lab[1], lab[2]) > 8 and 95 < np.degrees(np.arctan2(lab[2], lab[1])) < 200:
309
  out.append(f"layer {L['name']}: it is the ground under your own trees (it rules out tree crowns) but its "
310
  "color is green, and the image model paints a green patch seen from above as tree crowns: "
@@ -1054,19 +1054,22 @@ def _lab(rgb) -> np.ndarray:
1054
 
1055
 
1056
  def match_colours(img: np.ndarray, W: np.ndarray, layers: list[dict], keep: np.ndarray | None = None,
1057
- chroma: float = 0.5, cap: float = 15.0) -> np.ndarray:
1058
  """The colour map with each layer the caller gave a ``color`` turned toward that colour's hue (and half way to
1059
  its chroma, at most ``cap`` in a*b*), lightness and texture as painted. The image model drifts toward its idea
1060
  of the place: October leaf litter asked for in rust (126, 74, 38) came back olive brown, a* 19 -> 6, and red
1061
- blueberry scrub olive, hue 55 -> 94 degrees (round 32): the tester recoloured the materials by hand.
1062
- ``W`` and ``keep`` (0..1, where to change it: not the caller's water) are at the splat map's size; the shift is
1063
- measured there and resized to the image."""
 
 
 
1064
  import cv2
1065
 
1066
  S = W.shape[1]
1067
  lab = lambda a: cv2.cvtColor(np.clip(a, 0, 1).astype(np.float32), cv2.COLOR_RGB2LAB) # noqa: E731
1068
  small = lab(cv2.resize(img, (S, S), interpolation=cv2.INTER_AREA) if img.shape[0] != S else img)
1069
- shift = np.zeros((S, S, 2), np.float32)
1070
  inner = np.ones((S, S), bool) if keep is None else keep > 0.5
1071
  for i, L in enumerate(layers):
1072
  if not L.get("color"):
@@ -1074,20 +1077,28 @@ def match_colours(img: np.ndarray, W: np.ndarray, layers: list[dict], keep: np.n
1074
  m = cv2.erode(((W[i] > 0.7) & inner).astype(np.uint8), np.ones((5, 5), np.uint8)) > 0
1075
  if m.sum() < max(100, 1e-4 * m.size):
1076
  continue
1077
- ab = small[m][:, 1:].mean(0)
1078
- want = _lab(guide_colour(L))[1:]
1079
- c, wc = float(np.hypot(*ab)), float(np.hypot(*want))
 
1080
  tc = c + chroma * (wc - c)
1081
- target = want * tc / wc if wc > 3 else ab * tc / max(c, 1e-6) # a grey has no hue to turn to
1082
- d = target - ab
1083
- d *= min(1.0, cap / max(float(np.linalg.norm(d)), 1e-6))
 
 
 
 
 
 
 
1084
  shift += W[i][..., None] * d.astype(np.float32)
1085
  if keep is not None:
1086
  shift *= keep[..., None]
1087
  if not shift.any():
1088
  return img
1089
  out = lab(img)
1090
- out[..., 1:] += cv2.resize(shift, img.shape[1::-1], interpolation=cv2.INTER_LINEAR) if img.shape[0] != S else shift
1091
  return np.clip(cv2.cvtColor(out, cv2.COLOR_LAB2RGB), 0, 1)
1092
 
1093
 
@@ -1283,12 +1294,19 @@ def water_look(prompt: str) -> tuple[np.ndarray, str]:
1283
  """Colour and words for the water below ``water_level``: turquoise shallows for tropical seas, else dark."""
1284
  import re
1285
 
1286
- noun = next((n for p, n in ((r"\b(?:sea|ocean|coast|bay|lagoon|reef|island)", "the sea"), (r"\bpond", "the pond"),
1287
- (r"\b(?:lake|loch|tarn|reservoir)", "the lake")) if re.search(p, prompt or "", re.I)),
1288
- "the water")
1289
- if re.search(r"tropic|lagoon|turquoise|caribbean|reef|atoll", prompt or "", re.I):
1290
- return np.array([0.24, 0.55, 0.58], np.float32), f"clear turquoise shallow water of {noun}, calm"
1291
- return np.array([0.16, 0.24, 0.28], np.float32), f"open water of {noun}, calm and dark"
 
 
 
 
 
 
 
1292
 
1293
 
1294
  _WATER_LAYER = r"\b(?:water|rivers?|streams?|creeks?|brooks?|ponds?|lakes?|sea|ocean|canals?|pools?)\b"
@@ -1446,9 +1464,28 @@ def tile_layout(macro_size: int, tile: int = 1024, overlap: int = 256) -> dict:
1446
  return {"n": n, "stride": (macro_size - tile) / (n - 1), "tile": tile, "size": macro_size}
1447
 
1448
 
1449
- def merge_tiles(tiles: dict, layout: dict, overview: np.ndarray) -> np.ndarray:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1450
  """Blend overlapping tiles (raised-cosine windows), then take the low frequencies from the overview so tiles
1451
- that drifted in colour or brightness still agree with each other and with the whole."""
 
 
1452
  import cv2
1453
 
1454
  F, T, n, stride = layout["size"], layout["tile"], layout["n"], layout["stride"]
@@ -1458,17 +1495,37 @@ def merge_tiles(tiles: dict, layout: dict, overview: np.ndarray) -> np.ndarray:
1458
  r = np.minimum(np.arange(T) + 0.5, T - np.arange(T) - 0.5)
1459
  ramp = 0.5 - 0.5 * np.cos(np.pi * np.clip(r / max(ov, 1), 0, 1))
1460
  win = np.maximum(ramp[:, None] * ramp[None, :], 1e-4).astype(np.float32)[..., None]
 
 
 
1461
  for (i, j), t in tiles.items():
1462
  y0, x0 = int(round(i * stride)), int(round(j * stride))
 
 
 
1463
  acc[y0:y0 + T, x0:x0 + T] += t * win
1464
  wsum[y0:y0 + T, x0:x0 + T] += win
1465
  plain = acc / np.maximum(wsum, 1e-6)
1466
- del acc, wsum
1467
  up = cv2.resize(overview.astype(np.float32), (F, F), interpolation=cv2.INTER_CUBIC)
1468
  sig = F / overview.shape[0] * 3.0
1469
  out = cv2.GaussianBlur(up, (0, 0), sig)
1470
  out += plain
1471
  out -= cv2.GaussianBlur(plain, (0, 0), sig)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1472
  return np.clip(out, 0, 1)
1473
 
1474
 
@@ -1675,7 +1732,7 @@ class Terrain:
1675
 
1676
  def one(L):
1677
  seed = self._seed("layer:" + L["name"], new_seeds)
1678
- col = np.asarray(L["color"], np.float32) / 255 if L.get("color") else np.asarray(default_colour(L))
1679
  path = bool(L.get("paths"))
1680
  words = surface_words(L["prompt"]) if path else floor_words(L["prompt"]) if wooded(L) else L["prompt"]
1681
  if words != L["prompt"]:
@@ -1830,20 +1887,24 @@ class Terrain:
1830
 
1831
  ov = _load(self.root / "macro" / "overview.png")
1832
  lay = self.state.get("tiles") or tile_layout(int(self.prm.get("macro_size", 2048)))
 
1833
  if lay["n"] == 1:
1834
  macro = cv2.resize(ov, (lay["size"], lay["size"]), interpolation=cv2.INTER_CUBIC) \
1835
  if ov.shape[0] != lay["size"] else ov
1836
  else:
1837
  d = self.root / "macro" / "tiles"
1838
  tiles = {(i, j): _load(d / f"tile_{i}_{j}.png") for i in range(lay["n"]) for j in range(lay["n"])}
1839
- macro = merge_tiles(tiles, lay, ov)
 
1840
  F = macro.shape[0]
1841
  W = self.weights()
1842
  keep = None
1843
  if self.prm.get("water_level") is not None: # the water painted below the caller's plane stays water
1844
  H = resample(np.load(self.root / "mesh" / "height.npy").astype(np.float32), W.shape[1])
1845
  keep = cv2.GaussianBlur((H >= float(self.prm["water_level"])).astype(np.float32), (0, 0), 1)
1846
- macro = match_colours(macro, W, self.state["layers"], keep)
 
 
1847
  _save(self.root / "macro" / "macro.jpg", macro, quality=92)
1848
  self.state["macro_file"] = "macro/macro.jpg"
1849
  (x0, _), (x1, _) = self.bounds
 
304
  "sea) use \"elevation\": [min_m, max_m] in the mesh's own heights (this ground: "
305
  f"{y0:.1f} to {y0 + relief:.1f})")
306
  for L in layers:
307
+ lab = _lab(guide_colour(L)) if L.get("color") and tree_floor(L) else None
308
  if lab is not None and np.hypot(lab[1], lab[2]) > 8 and 95 < np.degrees(np.arctan2(lab[2], lab[1])) < 200:
309
  out.append(f"layer {L['name']}: it is the ground under your own trees (it rules out tree crowns) but its "
310
  "color is green, and the image model paints a green patch seen from above as tree crowns: "
 
1054
 
1055
 
1056
  def match_colours(img: np.ndarray, W: np.ndarray, layers: list[dict], keep: np.ndarray | None = None,
1057
+ chroma: float = 0.5, cap: float = 15.0, tol: float = 15.0, pulled: dict | None = None) -> np.ndarray:
1058
  """The colour map with each layer the caller gave a ``color`` turned toward that colour's hue (and half way to
1059
  its chroma, at most ``cap`` in a*b*), lightness and texture as painted. The image model drifts toward its idea
1060
  of the place: October leaf litter asked for in rust (126, 74, 38) came back olive brown, a* 19 -> 6, and red
1061
+ blueberry scrub olive, hue 55 -> 94 degrees (round 32): the tester recoloured the materials by hand. A layer
1062
+ still more than ``tol`` (CIELAB) from its colour after that is moved to ``tol`` from it, lightness too: the
1063
+ model painted 13 m red, yellow and pink tulip stripes, 8 px in its 1 MP picture of a 2.4 km polder, as
1064
+ grey-brown bulb rows, 61 to 72 away, at every seed and wording tried (round 33). ``pulled`` collects those
1065
+ layers' distances before. ``W`` and ``keep`` (0..1, where to change it: not the caller's water) are at the
1066
+ splat map's size; the shift is measured there and resized to the image."""
1067
  import cv2
1068
 
1069
  S = W.shape[1]
1070
  lab = lambda a: cv2.cvtColor(np.clip(a, 0, 1).astype(np.float32), cv2.COLOR_RGB2LAB) # noqa: E731
1071
  small = lab(cv2.resize(img, (S, S), interpolation=cv2.INTER_AREA) if img.shape[0] != S else img)
1072
+ shift = np.zeros((S, S, 3), np.float32)
1073
  inner = np.ones((S, S), bool) if keep is None else keep > 0.5
1074
  for i, L in enumerate(layers):
1075
  if not L.get("color"):
 
1077
  m = cv2.erode(((W[i] > 0.7) & inner).astype(np.uint8), np.ones((5, 5), np.uint8)) > 0
1078
  if m.sum() < max(100, 1e-4 * m.size):
1079
  continue
1080
+ cur = small[m].mean(0)
1081
+ want = _lab(guide_colour(L))
1082
+ ab = cur[1:]
1083
+ c, wc = float(np.hypot(*ab)), float(np.hypot(*want[1:]))
1084
  tc = c + chroma * (wc - c)
1085
+ target = want[1:] * tc / wc if wc > 3 else ab * tc / max(c, 1e-6) # a grey has no hue to turn to
1086
+ d = np.zeros(3, np.float32)
1087
+ d[1:] = target - ab
1088
+ d[1:] *= min(1.0, cap / max(float(np.linalg.norm(d[1:])), 1e-6))
1089
+ rest = want - (cur + d)
1090
+ far = float(np.linalg.norm(rest))
1091
+ if far > tol:
1092
+ d += rest * (1 - tol / far)
1093
+ if pulled is not None:
1094
+ pulled[L["name"]] = round(float(np.linalg.norm(want - cur)), 1)
1095
  shift += W[i][..., None] * d.astype(np.float32)
1096
  if keep is not None:
1097
  shift *= keep[..., None]
1098
  if not shift.any():
1099
  return img
1100
  out = lab(img)
1101
+ out += cv2.resize(shift, img.shape[1::-1], interpolation=cv2.INTER_LINEAR) if img.shape[0] != S else shift
1102
  return np.clip(cv2.cvtColor(out, cv2.COLOR_LAB2RGB), 0, 1)
1103
 
1104
 
 
1294
  """Colour and words for the water below ``water_level``: turquoise shallows for tropical seas, else dark."""
1295
  import re
1296
 
1297
+ # a sea dike, sea wall or sea level is not the sea, nor is a bayou a bay: "a canal beside a grassy sea dike"
1298
+ # and "a Louisiana bayou swamp" were both "the sea" (round 33)
1299
+ words = re.sub(r"\bsea[- ]?(?:dikes?|dykes?|walls?|level|grass|shells?|salt|birds?|gulls?)\b", "", prompt or "",
1300
+ flags=re.I)
1301
+ noun = next((n for p, n in ((r"\b(?:seas?|oceans?|coast\w*|bays?|lagoons?|reefs?|islands?|fjords?)\b", "the sea"), (r"\bpond", "the pond"),
1302
+ (r"\b(?:lake|loch|tarn|reservoir)", "the lake"), (r"\bcanal", "the canal"),
1303
+ (r"\b(?:river|stream|creek|brook)", "the river"),
1304
+ (r"\b(?:swamp|bayou|marsh)", "the swamp")) if re.search(p, words, re.I)),
1305
+ None)
1306
+ of = f" of {noun}" if noun else ""
1307
+ if re.search(r"tropic|lagoon|turquoise|caribbean|reef|atoll", words, re.I):
1308
+ return np.array([0.24, 0.55, 0.58], np.float32), f"clear turquoise shallow water{of}, calm"
1309
+ return np.array([0.16, 0.24, 0.28], np.float32), f"open water{of}, calm and dark"
1310
 
1311
 
1312
  _WATER_LAYER = r"\b(?:water|rivers?|streams?|creeks?|brooks?|ponds?|lakes?|sea|ocean|canals?|pools?)\b"
 
1464
  return {"n": n, "stride": (macro_size - tile) / (n - 1), "tile": tile, "size": macro_size}
1465
 
1466
 
1467
+ def layout_kept(tile: np.ndarray, crop: np.ndarray) -> float:
1468
+ """1 when a refined tile keeps the layout of its overview crop, 0 when it redrew it: the crop's structure 2 to
1469
+ 8 px across (its own pixels, CIELAB) the tile did not reproduce, energy x (1 - correlation), 2.5 -> 1, 4.5 ->
1470
+ 0. ``tile`` is resized to ``crop``. Measured (round 33): 13 m tulip stripes, 8 px in the overview, were redrawn
1471
+ as the model's own wider stripes in other places at every seed tried, 4 to 8; tiles of 14 earlier terrains
1472
+ (alpine, ski, farms, an island, a park, a bayou) at most 1.9, sharper or not."""
1473
+ import cv2
1474
+
1475
+ lab = lambda a: cv2.cvtColor(np.clip(a, 0, 1).astype(np.float32), cv2.COLOR_RGB2LAB) # noqa: E731
1476
+ band = lambda a: cv2.GaussianBlur(a, (0, 0), 2.0) - cv2.GaussianBlur(a, (0, 0), 8.0) # noqa: E731
1477
+ a = band(lab(crop))
1478
+ b = band(lab(cv2.resize(tile, crop.shape[1::-1], interpolation=cv2.INTER_AREA)))
1479
+ corr = float((a * b).sum() / np.sqrt((a * a).sum() * (b * b).sum() + 1e-9))
1480
+ lost = float(np.linalg.norm(a, axis=-1).mean()) * (1 - max(corr, 0.0))
1481
+ return float(np.clip((4.5 - lost) / 2.0, 0, 1))
1482
+
1483
+
1484
+ def merge_tiles(tiles: dict, layout: dict, overview: np.ndarray, off: list | None = None) -> np.ndarray:
1485
  """Blend overlapping tiles (raised-cosine windows), then take the low frequencies from the overview so tiles
1486
+ that drifted in colour or brightness still agree with each other and with the whole. A tile that redrew the
1487
+ layout (``layout_kept``) gives only its finest texture: its stripes mixed with the overview's made a rainbow
1488
+ of both (round 33). ``off`` collects the names of those tiles."""
1489
  import cv2
1490
 
1491
  F, T, n, stride = layout["size"], layout["tile"], layout["n"], layout["stride"]
 
1495
  r = np.minimum(np.arange(T) + 0.5, T - np.arange(T) - 0.5)
1496
  ramp = 0.5 - 0.5 * np.cos(np.pi * np.clip(r / max(ov, 1), 0, 1))
1497
  win = np.maximum(ramp[:, None] * ramp[None, :], 1e-4).astype(np.float32)[..., None]
1498
+ s = overview.shape[0] / F
1499
+ N = max(8, int(round(T * s)))
1500
+ kept = {}
1501
  for (i, j), t in tiles.items():
1502
  y0, x0 = int(round(i * stride)), int(round(j * stride))
1503
+ crop = cv2.warpAffine(overview.astype(np.float32), np.float32([[1, 0, -x0 * s], [0, 1, -y0 * s]]), (N, N),
1504
+ flags=cv2.INTER_LINEAR, borderMode=cv2.BORDER_REFLECT)
1505
+ kept[(i, j)] = layout_kept(t, crop)
1506
  acc[y0:y0 + T, x0:x0 + T] += t * win
1507
  wsum[y0:y0 + T, x0:x0 + T] += win
1508
  plain = acc / np.maximum(wsum, 1e-6)
1509
+ del acc
1510
  up = cv2.resize(overview.astype(np.float32), (F, F), interpolation=cv2.INTER_CUBIC)
1511
  sig = F / overview.shape[0] * 3.0
1512
  out = cv2.GaussianBlur(up, (0, 0), sig)
1513
  out += plain
1514
  out -= cv2.GaussianBlur(plain, (0, 0), sig)
1515
+ if min(kept.values(), default=1.0) < 1:
1516
+ if off is not None:
1517
+ off += [f"tile_{i}_{j}" for (i, j), k in sorted(kept.items()) if k < 0.5]
1518
+ k = np.zeros((F, F, 1), np.float32)
1519
+ for (i, j), kij in kept.items():
1520
+ y0, x0 = int(round(i * stride)), int(round(j * stride))
1521
+ k[y0:y0 + T, x0:x0 + T] += kij * win
1522
+ k /= np.maximum(wsum, 1e-6)
1523
+ fine = max(1.0, sig / 6) # the tile's flowers, stones and blades of grass, not its stripes or fields
1524
+ alt = cv2.GaussianBlur(up, (0, 0), fine)
1525
+ alt += plain
1526
+ alt -= cv2.GaussianBlur(plain, (0, 0), fine)
1527
+ out *= k
1528
+ out += alt * (1 - k)
1529
  return np.clip(out, 0, 1)
1530
 
1531
 
 
1732
 
1733
  def one(L):
1734
  seed = self._seed("layer:" + L["name"], new_seeds)
1735
+ col = guide_colour(L) if L.get("color") else np.asarray(default_colour(L))
1736
  path = bool(L.get("paths"))
1737
  words = surface_words(L["prompt"]) if path else floor_words(L["prompt"]) if wooded(L) else L["prompt"]
1738
  if words != L["prompt"]:
 
1887
 
1888
  ov = _load(self.root / "macro" / "overview.png")
1889
  lay = self.state.get("tiles") or tile_layout(int(self.prm.get("macro_size", 2048)))
1890
+ self.state["tiles_off_layout"] = []
1891
  if lay["n"] == 1:
1892
  macro = cv2.resize(ov, (lay["size"], lay["size"]), interpolation=cv2.INTER_CUBIC) \
1893
  if ov.shape[0] != lay["size"] else ov
1894
  else:
1895
  d = self.root / "macro" / "tiles"
1896
  tiles = {(i, j): _load(d / f"tile_{i}_{j}.png") for i in range(lay["n"]) for j in range(lay["n"])}
1897
+ macro = merge_tiles(tiles, lay, ov, self.state["tiles_off_layout"])
1898
+ del tiles
1899
  F = macro.shape[0]
1900
  W = self.weights()
1901
  keep = None
1902
  if self.prm.get("water_level") is not None: # the water painted below the caller's plane stays water
1903
  H = resample(np.load(self.root / "mesh" / "height.npy").astype(np.float32), W.shape[1])
1904
  keep = cv2.GaussianBlur((H >= float(self.prm["water_level"])).astype(np.float32), (0, 0), 1)
1905
+ pulled: dict = {}
1906
+ macro = match_colours(macro, W, self.state["layers"], keep, pulled=pulled)
1907
+ self.state["colours_pulled"] = pulled
1908
  _save(self.root / "macro" / "macro.jpg", macro, quality=92)
1909
  self.state["macro_file"] = "macro/macro.jpg"
1910
  (x0, _), (x1, _) = self.bounds
tests/smoke.py CHANGED
@@ -234,6 +234,9 @@ def terrain_checks(base: str, H: dict) -> None:
234
  {"name": "grass", "prompt": "short grass"},
235
  {"name": "rock", "prompt": "grey rock", "where": {"slope": [10, None]}},
236
  {"name": "road", "prompt": "packed gravel", "paths": [{"points": [[-300, 0], [300, 50]], "width": 8}]}]}
 
 
 
237
  r = requests.post(f"{base}/api/terrain", json=body, headers=H, timeout=60)
238
  check(r.status_code == 202 and r.json().get("kind") == "terrain", f"POST /api/terrain -> {r.status_code}")
239
  d = wait(base, r.json()["job_id"], H)
 
234
  {"name": "grass", "prompt": "short grass"},
235
  {"name": "rock", "prompt": "grey rock", "where": {"slope": [10, None]}},
236
  {"name": "road", "prompt": "packed gravel", "paths": [{"points": [[-300, 0], [300, 50]], "width": 8}]}]}
237
+ r = requests.post(f"{base}/api/jobs", json=body, headers=H, timeout=60) # the object endpoint refuses it
238
+ check(r.status_code == 400 and "/api/terrain" in (r.json().get("hint") or ""),
239
+ f"terrain body on POST /api/jobs -> {r.status_code} {r.json().get('error')}")
240
  r = requests.post(f"{base}/api/terrain", json=body, headers=H, timeout=60)
241
  check(r.status_code == 202 and r.json().get("kind") == "terrain", f"POST /api/terrain -> {r.status_code}")
242
  d = wait(base, r.json()["job_id"], H)