webcomic-background-mcp 3.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,6 @@
1
+ """webcomic-background-mcp: comic-panel backgrounds on a local ComfyUI, as an MCP server.
2
+
3
+ The modules in this folder import each other by plain name, so they run
4
+ unchanged from a clone (`python server.py`). Installed from PyPI they are the
5
+ webcomic_background_mcp package, and server.py puts this folder on sys.path itself.
6
+ """
@@ -0,0 +1,11 @@
1
+ """Where this server keeps its own data: next to the code in a clone, in the home folder when installed.
2
+
3
+ requirements.txt ships with the repo but not in the package, so its presence tells a cloned server from one
4
+ installed by pip or uvx. An installed copy lives inside the Python environment, which an upgrade replaces, so
5
+ the world bible and the output go to ~/webcomic-background-mcp/ instead.
6
+ """
7
+ import os
8
+
9
+ BASE = os.path.dirname(os.path.abspath(__file__))
10
+ IN_REPO = os.path.isfile(os.path.join(BASE, "requirements.txt"))
11
+ HOME = BASE if IN_REPO else os.path.join(os.path.expanduser("~"), "webcomic-background-mcp")
@@ -0,0 +1,366 @@
1
+ """
2
+ citygen.py — procedural 3D gothic city, rendered headless to a ControlNet sketch.
3
+
4
+ The "Metropolis mode" of the background generator: builds a seeded, reproducible
5
+ 3D city (street canyon converging on a landmark cathedral, layered skyline) and
6
+ renders a flat-gray *lineart pass* with a tiny software rasterizer — no GPU, no
7
+ browser, no 3D engine. The render is only a composition skeleton: its Canny edge
8
+ map drives ControlNet, and the checkpoint paints all the beauty on top.
9
+
10
+ Because the city is deterministic per seed, the same city can be re-rendered
11
+ from any camera for structurally consistent giant panels (and, later, camera
12
+ paths for animation).
13
+
14
+ Pipeline: build_city(seed) -> render_lineart(camera) -> sketch (Canny)
15
+ """
16
+
17
+ import math
18
+ import os
19
+
20
+ import numpy as np
21
+ import cv2
22
+
23
+
24
+ # ---------------------------------------------------------------- RNG (LCG) --
25
+ class _Rng:
26
+ """Deterministic park-miller LCG so a city is reproducible per seed."""
27
+ def __init__(self, seed: int):
28
+ self.s = (int(seed) % 2147483647) or 42
29
+
30
+ def rand(self) -> float:
31
+ self.s = (self.s * 16807) % 2147483647
32
+ return (self.s - 1) / 2147483646
33
+
34
+ def rr(self, a, b):
35
+ return a + self.rand() * (b - a)
36
+
37
+ def ri(self, a, b):
38
+ return int(self.rr(a, b + 1))
39
+
40
+
41
+ # ------------------------------------------------------------------ geometry --
42
+ def _box(cx, base_y, cz, w, h, d):
43
+ """Axis-aligned box: verts (8,3) + quad faces."""
44
+ x0, x1 = cx - w / 2, cx + w / 2
45
+ y0, y1 = base_y, base_y + h
46
+ z0, z1 = cz - d / 2, cz + d / 2
47
+ v = np.array([[x0,y0,z0],[x1,y0,z0],[x1,y0,z1],[x0,y0,z1],
48
+ [x0,y1,z0],[x1,y1,z0],[x1,y1,z1],[x0,y1,z1]], dtype=np.float64)
49
+ f = [(0,1,5,4),(1,2,6,5),(2,3,7,6),(3,0,4,7),(4,5,6,7),(0,3,2,1)]
50
+ return v, f
51
+
52
+
53
+ def _pyramid(cx, base_y, cz, w, h, d):
54
+ """4-sided spire/roof: rectangular base + apex."""
55
+ x0, x1 = cx - w / 2, cx + w / 2
56
+ z0, z1 = cz - d / 2, cz + d / 2
57
+ v = np.array([[x0,base_y,z0],[x1,base_y,z0],[x1,base_y,z1],[x0,base_y,z1],
58
+ [cx,base_y+h,cz]], dtype=np.float64)
59
+ f = [(0,1,4),(1,2,4),(2,3,4),(3,0,4),(0,3,2,1)]
60
+ return v, f
61
+
62
+
63
+ class _Mesh:
64
+ __slots__ = ("v", "f", "gray")
65
+ def __init__(self, v, f, gray):
66
+ self.v, self.f, self.gray = v, f, gray
67
+
68
+
69
+ def _gray(i: int) -> int:
70
+ """Distinct flat gray per mesh -> silhouette edges everywhere, no shading."""
71
+ g = 0.15 + 0.65 * ((i * 2654435761) % 97) / 97
72
+ return int(g * 255)
73
+
74
+
75
+ # ---------------------------------------------------------------- city model --
76
+ def build_city(seed: int = 40001):
77
+ """Procedural city: flanked avenue -> landmark cathedral -> far skyline.
78
+ Returns a list of _Mesh. Same seed = same city, forever."""
79
+ meshes = []
80
+ add = _adder(meshes)
81
+ rng = _Rng(seed)
82
+ _district_old_city(rng, add, (0.0, 0.0))
83
+ return meshes
84
+
85
+
86
+ def _adder(meshes):
87
+ """Appender that assigns each mesh its distinct flat gray."""
88
+ def add(v, f):
89
+ meshes.append(_Mesh(v, f, _gray(len(meshes))))
90
+ return add
91
+
92
+
93
+ def _building(rng, add, x, z, tier):
94
+ w, d = rng.rr(8, 22), rng.rr(8, 22)
95
+ h = rng.rr(14, 42) * (1 + tier * 0.55) # taller tiers = taller mass
96
+ add(*_box(x, 0, z, w, h, d))
97
+ add(*_pyramid(x, h, z, w * 0.72, rng.rr(4, 9), d * 0.72)) # gabled roof
98
+ for _ in range(rng.ri(0, 2)): # chimneys
99
+ add(*_box(x + rng.rr(-w/3, w/3), h, z + rng.rr(-d/3, d/3),
100
+ 1.2, rng.rr(3, 6), 1.2))
101
+ if rng.rand() < 0.30: # side tower
102
+ tw, th = rng.rr(3, 6), h * rng.rr(1.25, 1.8)
103
+ tx, tz = x + w/2 + tw/2 - 1, z + rng.rr(-d/3, d/3)
104
+ add(*_box(tx, 0, tz, tw, th, tw))
105
+ add(*_pyramid(tx, th, tz, tw * 0.8, rng.rr(8, 16), tw * 0.8))
106
+
107
+
108
+ def _cathedral(rng, add, x, z, s):
109
+ add(*_box(x, 0, z, 26*s, 46*s, 60*s)) # nave
110
+ add(*_box(x, 46*s, z, 27*s, 8*s, 62*s)) # roof block
111
+ for sx in (-11*s, 11*s): # twin towers
112
+ add(*_box(x+sx, 0, z+34*s, 9*s, 78*s, 9*s))
113
+ add(*_pyramid(x+sx, 78*s, z+34*s, 8.5*s, 30*s, 8.5*s))
114
+ add(*_pyramid(x, 46*s, z-6*s, 6*s, 38*s, 6*s)) # fleche
115
+
116
+
117
+ # ------------------------------------------------------------ district types --
118
+ def _district_old_city(rng, add, origin, rows=26, landmark=True):
119
+ """The founding layout: flanked avenue converging on a cathedral + far skyline."""
120
+ ox, oz = origin
121
+ AVE = 26
122
+ for row in range(rows):
123
+ z = oz - 30 - row * 26 + rng.rr(-4, 4)
124
+ tier = 0 if row < 6 else 1 if row < 14 else 2
125
+ for side in (-1, 1):
126
+ off = AVE/2 + rng.rr(4, 10)
127
+ for _ in range(2 if tier == 0 else 3):
128
+ _building(rng, add, ox + side * (off + rng.rr(0, 6)), z, tier)
129
+ off += rng.rr(16, 30)
130
+ if landmark:
131
+ _cathedral(rng, add, ox + 6, oz - 560, 2.1)
132
+ for _ in range(70): # far skyline
133
+ _building(rng, add, ox + rng.rr(-500, 500), oz + rng.rr(-620, -900), 2)
134
+
135
+
136
+ def _district_block(rng, add, origin, size=(220, 220), tier=0, density=1.0,
137
+ landmark=False):
138
+ """A rectangular fill of buildings — the growable unit (neighborhood/district).
139
+ origin is the block's near corner; buildings fill [-size] in z, [+size] in x."""
140
+ ox, oz = origin
141
+ w, d = size
142
+ step = 34 / max(0.25, density)
143
+ for gz in np.arange(oz - d, oz, step):
144
+ for gx in np.arange(ox, ox + w, step):
145
+ if rng.rand() < 0.85 * density:
146
+ _building(rng, add, gx + rng.rr(-6, 6), gz + rng.rr(-6, 6), tier)
147
+ if landmark:
148
+ _cathedral(rng, add, ox + w/2, oz - d/2, rng.rr(1.3, 1.9))
149
+
150
+
151
+ DISTRICT_TYPES = {"old_city": _district_old_city, "block": _district_block}
152
+
153
+
154
+ def build_from_plan(plan: dict):
155
+ """Assemble the whole persistent city from its plan (the editable master file).
156
+
157
+ The plan is the World Builder's growable 3D model: a JSON list of districts,
158
+ each with its own seed, position and parameters. Appending a district grows
159
+ the city; every earlier district re-renders identically because each has its
160
+ own RNG stream. Returns a list of _Mesh."""
161
+ meshes = []
162
+ add = _adder(meshes)
163
+ for d in plan.get("districts", []):
164
+ kind = d.get("type", "block")
165
+ if kind not in DISTRICT_TYPES:
166
+ raise ValueError(f"unknown district type '{kind}'; options: {', '.join(DISTRICT_TYPES)}")
167
+ rng = _Rng(d.get("seed", 1))
168
+ origin = tuple(d.get("origin", (0, 0)))
169
+ if kind == "old_city":
170
+ _district_old_city(rng, add, origin,
171
+ rows=int(d.get("rows", 26)),
172
+ landmark=bool(d.get("landmark", True)))
173
+ else:
174
+ _district_block(rng, add, origin,
175
+ size=tuple(d.get("size", (220, 220))),
176
+ tier=int(d.get("tier", 0)),
177
+ density=float(d.get("density", 1.0)),
178
+ landmark=bool(d.get("landmark", False)))
179
+ return meshes
180
+
181
+
182
+ def plan_centroid(plan: dict, focus: str | None = None):
183
+ """A point worth looking at: a named district's center, or the plan centroid."""
184
+ ds = plan.get("districts", [])
185
+ if not ds:
186
+ return (0.0, -400.0)
187
+ if focus:
188
+ for d in ds:
189
+ if d.get("id") == focus:
190
+ ox, oz = d.get("origin", (0, 0))
191
+ if d.get("type", "block") == "old_city":
192
+ return (ox, oz - 400.0) # mid-avenue, toward the cathedral
193
+ w, dd = d.get("size", (220, 220))
194
+ return (ox + w / 2, oz - dd / 2)
195
+ raise ValueError(f"no district with id '{focus}' in the plan")
196
+ pts = []
197
+ for d in ds:
198
+ ox, oz = d.get("origin", (0, 0))
199
+ pts.append((ox, oz - 300.0))
200
+ return (sum(p[0] for p in pts) / len(pts), sum(p[1] for p in pts) / len(pts))
201
+
202
+
203
+ # ------------------------------------------------------------------- cameras --
204
+ CAMERAS = {
205
+ "street": {"pos": (0, 9, 30), "look": (0, 26, -560), "fov": 58},
206
+ "vista": {"pos": (-90, 70, -40), "look": (6, 40, -560), "fov": 50},
207
+ "high": {"pos": (0, 150, 120), "look": (0, 20, -500), "fov": 48},
208
+ "canyon": {"pos": (26, 5, -120), "look": (-40, 60, -420), "fov": 65},
209
+ }
210
+
211
+ # Preset geometry expressed relative to a focus point, so the same four shot
212
+ # types work anywhere in a growing city: (pos - look) delta, look height, fov.
213
+ _CAM_REL = {
214
+ "street": {"delta": (0, -17, 590), "look_y": 26, "fov": 58},
215
+ "vista": {"delta": (-96, 30, 520), "look_y": 40, "fov": 50},
216
+ "high": {"delta": (0, 130, 620), "look_y": 20, "fov": 48},
217
+ "canyon": {"delta": (66, -55, 300), "look_y": 60, "fov": 65},
218
+ }
219
+
220
+
221
+ def camera_for(preset: str, focus) -> dict:
222
+ """Build an absolute camera from a relative preset aimed at `focus` (x, z)."""
223
+ if preset not in _CAM_REL:
224
+ raise ValueError(f"unknown camera '{preset}'; options: {', '.join(_CAM_REL)}")
225
+ c = _CAM_REL[preset]
226
+ fx, fz = focus
227
+ look = (fx, c["look_y"], fz)
228
+ d = c["delta"]
229
+ return {"pos": (fx + d[0], c["look_y"] + d[1], fz + d[2]),
230
+ "look": look, "fov": c["fov"]}
231
+
232
+
233
+ # ---------------------------------------------------------------- rasterizer --
234
+ # One world unit ≈ 0.37 m (buildings are 14-42 units ≈ 4-12 stories), so a
235
+ # standing adult is ~4.6 units tall. Used by the character anchor.
236
+ HUMAN_HEIGHT = 4.6
237
+
238
+
239
+ def _resolve_cam(camera):
240
+ return CAMERAS[camera] if isinstance(camera, str) else camera
241
+
242
+
243
+ def _cam_basis(cam, width, height):
244
+ pos = np.array(cam["pos"], dtype=np.float64)
245
+ look = np.array(cam["look"], dtype=np.float64)
246
+ fwd = look - pos
247
+ fwd /= np.linalg.norm(fwd)
248
+ right = np.cross(fwd, np.array([0.0, 1.0, 0.0]))
249
+ right /= np.linalg.norm(right)
250
+ up = np.cross(right, fwd)
251
+ focal = (height / 2) / math.tan(math.radians(cam["fov"]) / 2)
252
+ return pos, right, up, fwd, focal
253
+
254
+
255
+ def _ground(pos):
256
+ """Ground plane quad, ending just before the camera so it never straddles near."""
257
+ gz = pos[2] - 2
258
+ gv = np.array([[-1500, 0, gz], [1500, 0, gz],
259
+ [1500, 0, -1500], [-1500, 0, -1500]], dtype=np.float64)
260
+ return gv, [(0, 1, 2, 3)]
261
+
262
+
263
+ def _rasterize(draw, cam, width, height, near, background):
264
+ """Painter's-algorithm flat fill: draw = [(verts, faces, value), ...]."""
265
+ pos, right, up, fwd, focal = _cam_basis(cam, width, height)
266
+ img = np.full((height, width), background, dtype=np.uint8)
267
+ faces = [] # (mean_depth, pts2d, value)
268
+ for verts, flist, val in draw:
269
+ rel = verts - pos
270
+ vc = np.stack([rel @ right, rel @ up, rel @ fwd], axis=1) # camera space
271
+ for face in flist:
272
+ fv = vc[list(face)]
273
+ if np.any(fv[:, 2] < near): # crude near-clip: drop the face
274
+ continue
275
+ sx = width / 2 + focal * fv[:, 0] / fv[:, 2]
276
+ sy = height / 2 - focal * fv[:, 1] / fv[:, 2]
277
+ if (np.all(sx < 0) or np.all(sx >= width) or
278
+ np.all(sy < 0) or np.all(sy >= height)):
279
+ continue
280
+ pts = np.stack([sx, sy], axis=1).astype(np.int32)
281
+ faces.append((float(fv[:, 2].mean()), pts, val))
282
+ faces.sort(key=lambda t: -t[0]) # painter: far -> near
283
+ for _, pts, val in faces:
284
+ cv2.fillConvexPoly(img, pts, int(val))
285
+ return img
286
+
287
+
288
+ def render_lineart(meshes, camera="vista", width=1344, height=732,
289
+ near=0.5) -> np.ndarray:
290
+ """Flat-gray painter's-algorithm render on white — the lineart pass.
291
+ Good enough for Canny; not a beauty render (SD supplies the beauty)."""
292
+ cam = _resolve_cam(camera)
293
+ gv, gf = _ground(np.array(cam["pos"], dtype=np.float64))
294
+ draw = [(gv, gf, 110)] + [(m.v, m.f, m.gray) for m in meshes]
295
+ return _rasterize(draw, cam, width, height, near, 255)
296
+
297
+
298
+ def render_anchor(meshes, camera, anchor_x, anchor_z, width=1344, height=732,
299
+ anchor_height=HUMAN_HEIGHT, near=0.5):
300
+ """Character placement anchor: a human-scale box at (anchor_x, anchor_z),
301
+ rendered through the same camera WITH occlusion by the city.
302
+
303
+ Returns (mask, info): mask is a uint8 image — white where the character
304
+ stands, black elsewhere (buildings in front of the spot occlude it); info
305
+ reports the anchor's on-screen bounding box and pixel height so the artist
306
+ knows exactly how large to draw the character and where the feet sit."""
307
+ cam = _resolve_cam(camera)
308
+ av, af = _box(anchor_x, 0, anchor_z,
309
+ anchor_height * 0.35, anchor_height, anchor_height * 0.22)
310
+ gv, gf = _ground(np.array(cam["pos"], dtype=np.float64))
311
+ draw = ([(gv, gf, 0)] + [(m.v, m.f, 0) for m in meshes] + [(av, af, 255)])
312
+ mask = _rasterize(draw, cam, width, height, near, 0)
313
+
314
+ # unoccluded screen bbox of the anchor (where the character *would* be)
315
+ pos, right, up, fwd, focal = _cam_basis(cam, width, height)
316
+ rel = av - pos
317
+ vc = np.stack([rel @ right, rel @ up, rel @ fwd], axis=1)
318
+ info = None
319
+ if np.all(vc[:, 2] >= near):
320
+ sx = width / 2 + focal * vc[:, 0] / vc[:, 2]
321
+ sy = height / 2 - focal * vc[:, 1] / vc[:, 2]
322
+ info = {"bbox": (float(sx.min()), float(sy.min()),
323
+ float(sx.max()), float(sy.max())),
324
+ "height_px": float(sy.max() - sy.min()),
325
+ "feet_y_px": float(sy.max()),
326
+ "visible": bool(mask.max() > 0)}
327
+ return mask, info
328
+
329
+
330
+ # ------------------------------------------------------------------ pipeline --
331
+ def city_sketch(out_dir: str, city_seed: int = 40001, camera: str = "vista",
332
+ width: int = 1344, height: int = 732,
333
+ low: int = 60, high: int = 140,
334
+ meshes=None, tag: str | None = None) -> tuple[str, str]:
335
+ """Build city -> render lineart -> Canny sketch. Returns (sketch, lineart).
336
+ Pass `meshes` (e.g. from build_from_plan) to render a persistent plan city
337
+ instead of the one-shot seeded city."""
338
+ if isinstance(camera, str) and camera not in CAMERAS:
339
+ raise ValueError(f"unknown camera '{camera}'; options: {', '.join(CAMERAS)}")
340
+ os.makedirs(out_dir, exist_ok=True)
341
+ if meshes is None:
342
+ meshes = build_city(city_seed)
343
+ lineart = render_lineart(meshes, camera, width, height)
344
+
345
+ cam_name = camera if isinstance(camera, str) else "custom"
346
+ stem = tag or f"city_{city_seed}"
347
+ line_path = os.path.join(out_dir, f"{stem}_{cam_name}_lineart.png")
348
+ cv2.imwrite(line_path, lineart)
349
+
350
+ blurred = cv2.GaussianBlur(lineart, (3, 3), 0)
351
+ edges = cv2.Canny(blurred, low, high)
352
+ sketch_path = os.path.join(out_dir, f"{stem}_{cam_name}_sketch.png")
353
+ cv2.imwrite(sketch_path, edges)
354
+ return sketch_path, line_path
355
+
356
+
357
+ if __name__ == "__main__":
358
+ import argparse
359
+ ap = argparse.ArgumentParser()
360
+ ap.add_argument("--seed", type=int, default=40001)
361
+ ap.add_argument("--camera", default="vista", choices=list(CAMERAS))
362
+ ap.add_argument("--out", default="output/city")
363
+ a = ap.parse_args()
364
+ s, l = city_sketch(a.out, a.seed, a.camera)
365
+ print("sketch: ", s)
366
+ print("lineart:", l)