From d2425be8272e0dfee067e2da3eadafebb6169eae Mon Sep 17 00:00:00 2001 From: malken21 <77374813+malken21@users.noreply.github.com> Date: Tue, 10 Nov 2026 19:15:56 +0900 Subject: [PATCH] Perspective still images and a render API for watch Adds a perspective "shot" capability next to the tile renderer: - ShotCamera / ShotRenderer: a perspective camera with the same terms as BlueMap's perspective view (target, distance, rotation, angle, fov 75, its near/far rule, and its effective-target-height rule computed from the world data), rendering any image size through a perspective rasterizer variant. Translucent sorting follows the view direction. - A `shot` command that writes a PNG plus the camera transform as JSON. - An HTTP render API served by `watch --api-port`: POST /v1/render with a map name, a camera and a size returns the PNG (base64) and the transform; GET /v1/maps and /v1/health alongside. High-priority requests are served about once a second between tile batches, normal ones a few per step, identical requests hit a short-lived cache, and the API keeps serving when the tile database is unreachable. - Block-entity blocks are baked from built-in models mirroring the client's geometry and entity textures (chests incl. double and copper variants, banners, skulls and heads, shulker boxes); build-data extracts the entity sheets into the texture atlas. Sign text is not drawn. - uvlock variants now keep their texture fixed to the world while the model rotates, recomputed from the rotated face direction and the rotated element box. docs/render-api.md describes the camera, the API and the measured equivalence with the BlueMap screenshot path. --- README.md | 1 + docker/maps.example.json | 2 +- docs/commands.md | 24 +++ docs/render-api.md | 143 +++++++++++++ scripts/cmd/build_data.gd | 52 +++++ scripts/cmd/jobs.gd | 17 +- scripts/cmd/shot.gd | 88 ++++++++ scripts/cmd/shot.gd.uid | 1 + scripts/job/renderer_pool.gd | 13 ++ scripts/job/shot_api.gd | 277 +++++++++++++++++++++++++ scripts/job/shot_api.gd.uid | 1 + scripts/job/watch_job.gd | 26 ++- scripts/main.gd | 5 +- scripts/map/map_def.gd | 3 + scripts/render/iso_renderer.gd | 7 +- scripts/render/shot_camera.gd | 77 +++++++ scripts/render/shot_camera.gd.uid | 1 + scripts/render/shot_renderer.gd | 208 +++++++++++++++++++ scripts/render/shot_renderer.gd.uid | 1 + scripts/render/state_registry.gd | 308 +++++++++++++++++++++++++++- shaders/raster_persp.glsl | 191 +++++++++++++++++ 21 files changed, 1436 insertions(+), 10 deletions(-) create mode 100644 docs/render-api.md create mode 100644 scripts/cmd/shot.gd create mode 100644 scripts/cmd/shot.gd.uid create mode 100644 scripts/job/shot_api.gd create mode 100644 scripts/job/shot_api.gd.uid create mode 100644 scripts/render/shot_camera.gd create mode 100644 scripts/render/shot_camera.gd.uid create mode 100644 scripts/render/shot_renderer.gd create mode 100644 scripts/render/shot_renderer.gd.uid create mode 100644 shaders/raster_persp.glsl diff --git a/README.md b/README.md index 368a440..d460630 100644 --- a/README.md +++ b/README.md @@ -67,6 +67,7 @@ docs/ 詳細な文書 | [docs/architecture.md](docs/architecture.md) | 描画パイプライン、各モジュールの役割、設計上の判断 | | [docs/operations.md](docs/operations.md) | セットアップ、マップ設定、全体ジョブ、常駐更新、プレイヤー位置の WebSocket、本番運用の安全策 | | [docs/commands.md](docs/commands.md) | コマンドごとのオプション一覧 | +| [docs/render-api.md](docs/render-api.md) | 透視カメラの静止画と、watch が待ち受ける描画要求 API(英語) | | [docs/igpu-report.md](docs/igpu-report.md) | 内蔵 GPU の調査と計測の報告(英語、2026-11-04 時点) | ## 既知の差異 diff --git a/docker/maps.example.json b/docker/maps.example.json index 008f0e6..8a5daf1 100644 --- a/docker/maps.example.json +++ b/docker/maps.example.json @@ -2,7 +2,7 @@ "db": { "host": "tidb", "port": 4000, "user": "renderer", "password_file": "/run/secrets/db_password", "database": "dynmap" }, "live": "wss://map.example.net/up/ws", "maps": [ - { "id": 1, "region": "/worlds/overworld/region", "persp": "iso_SE_30_hires", "zoom_max": 12 }, + { "id": 1, "name": "overworld", "region": "/worlds/overworld/region", "persp": "iso_SE_30_hires", "zoom_max": 12 }, { "id": 2, "region": "/worlds/overworld/region", "persp": "iso_S_90_lowres", "zoom_max": 12 }, { "id": 30001, "region": "/worlds/flat/region", "persp": "iso_S_90_lowres", "zoom_max": 7 }, { "id": 30002, "region": "/worlds/flat/region", "persp": "iso_SE_30_hires", "zoom_max": 7 } diff --git a/docs/commands.md b/docs/commands.md index 7cfc179..15bf969 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -85,6 +85,7 @@ godot --path . -s scripts/main.gd -- <コマンド> [--オプション 値] [-- | `--dirty-port N` | 0 | ゲームサーバー(TORO-Core の map-dirty)からのブロック変更イベントを受ける WebSocket のポート。0 で無効 | | `--dirty-token-file F` | | イベントの token を読むファイル(環境変数 `TORO_DIRTY_TOKEN` が優先)。`--dirty-port` と token の両方がそろったときだけ受ける | | `--once` | | 1 回見て、最大 1 バッチだけ処理して終了(試験用) | +| `--api-port N` | | 描画要求 API(`docs/render-api.md`)をこのポートで待ち受ける。データベースに届かなくても API は動き続ける | イベントは待ち行列に合流し、すでに入っているメガタイルは最初に入った時刻のままになる。繰り返し変わるメガタイルは 「熱い」と数えて順位を下げ、1 バッチに入る数も半分(最低 1)までに抑える。どのバッチでも最古の 1 件は必ず席を得る。 @@ -95,12 +96,35 @@ godot --path . -s scripts/main.gd -- <コマンド> [--オプション 値] [-- `zoom --map-id N --zoom-max Z (--all | --seed FILE)`: 描かずに zoom-out を再構築する。`FILE` は 1 行に 1 タイル (`x y`、zoom 0)。 +## `shot` + +`shot --region-dir DIR --out FILE.png [オプション]`: 透視カメラで 1 枚の静止画を描き、PNG と変換情報の +JSON(`<ファイル名>.json`)を出す。カメラと API の仕様は `docs/render-api.md`。 + +| オプション | 既定 | 内容 | +| --- | --- | --- | +| `--out FILE` | | 出力する PNG(必須)。変換情報は同じ場所へ `.json` で出す | +| `--map NAME`, `--map-id N` | | `--config` のマップを名前か ID で選ぶ | +| `--region-dir DIR` | マップの設定 | ワールドの region ディレクトリ(マップより優先) | +| `--target x,y,z` | 0,70,0 | 注視点(軌道カメラ) | +| `--distance N` | 120 | 注視点からカメラまでの距離 | +| `--rotation N` | 0 | 方位(ラジアン) | +| `--angle N` | 0.75 | 見下ろし角(ラジアン。0 が真下) | +| `--fov N` | 75 | 垂直の画角(度) | +| `--eye x,y,z`, `--look-at x,y,z` | | 軌道カメラの代わりにカメラ位置と注視点を直接指定 | +| `--size WxH` | 1280x720 | 画像の大きさ | +| `--no-adjust-height` | | 注視点の高さの自動調整(BlueMap と同じ規則)をしない | +| `--background r,g,b[,a]` | 透明 | 何も描かれなかった所の色(0-255) | +| `--min-y`, `--max-y` | マップの設定 | 描画する高さの範囲 | +| `--data-dir DIR` | `res://data` | `build-data` の出力 | + ## `build-data` `build-data --jar FILE [--reports FILE] [--out DIR]`: クライアント jar から次を作る(`--out` の既定は `res://data`)。 - `blocks.json`, `atlas.bin`, `atlas.json`, `biomes.json`: 列単位の表(`BlockTable`) - `assets/blockstates/*.json`, `assets/models/block/**.json`, `textures.bin`, `textures.json`: ブロックモデル(`StateRegistry`) +- `entity_textures.json`: ブロックエンティティ(チェスト、旗、頭、シュルカーボックス)のテクスチャシートの大きさ。シートのタイルも `textures.bin` / `textures.json` へ入る - `block_defaults.json`: ブロックの既定プロパティ(`--reports` が要る) ## `dev` diff --git a/docs/render-api.md b/docs/render-api.md new file mode 100644 index 0000000..e9f3c12 --- /dev/null +++ b/docs/render-api.md @@ -0,0 +1,143 @@ +# Still images and the render API + +Besides map tiles, the renderer can draw a single still image ("shot") of a map area from a +perspective camera, and the resident `watch` process serves those renders over HTTP. Shots are a +general capability: a caller names a map, a camera and an image size, and receives a PNG plus the +camera transform, so any overlay or annotation can be computed on the caller's side. Nothing in +this design is specific to one caller; known callers are evidence capture (a caller that needs a +picture of one damaged spot, promptly) and background-video generation for a website (a caller +that needs many frames of a slow camera orbit, in batches). + +## The camera + +The shot camera uses the same terms as BlueMap's perspective view, so a view that exists as a +BlueMap link or a BlueMap screenshot can be reproduced exactly: + +- `target`: the world position the camera looks at (`x`, `y`, `z`). +- `distance`: distance from the target to the camera, in blocks. +- `rotation`: azimuth in radians; 0 looks towards north, increasing values turn the view + clockwise seen from above. +- `angle`: tilt in radians; 0 is straight down from above, π/2 is horizontal. +- `fov`: vertical field of view in degrees (75 when omitted, BlueMap's value). + +The camera position is `target + distance * (-sin(rotation) * sin(angle), cos(angle), +cos(rotation) * sin(angle))`, looking at the target with the world up vector. The projection is +the perspective projection with that field of view and the image's aspect ratio; near and far +planes follow BlueMap's rule for the distance (`near = clamp(distance / 1000, 0.01, 1)`, +`far = clamp(2 * distance, max(near + 1, 2000), distance + 5000)`). + +### The effective target height + +BlueMap does not use the given target height as-is: its map controls raise the target to a +suggested height derived from the terrain, every frame, and a settled screenshot therefore shows +that adjusted target. The shot camera reproduces the same rule, computed from the world data +itself (the terrain height is the top surface at the column, found by the same downward ray the +web app casts): + +``` +terrain = top surface height at (target.x, target.z) +targetHeight = terrain + 3 +byDistance = lerp(targetHeight, 0, min(distance / 500, 1)) +maxAngle = clamp((1 - sqrt(max(distance - 5, 0.001) * 0.0005)) * π/2, 0, π/2) +cameraHeight = top surface height at the camera's (x, z) +minCamera = cameraHeight - cos(maxAngle) * distance + 1 (0 when maxAngle < 0.1) +target.y = max(byDistance, minCamera) +``` + +Callers that already know the height they want (for example a caller that computed its target +from the thing it wants to show) can pass `adjust_height: false` to use the given target +unchanged. The transform in the response always describes the camera that was actually used. + +## What a shot draws + +A shot draws the same world the tiles draw — the region files, read directly — with the full +block models at their native 16-pixel textures: + +- **Perspective projection** (above), at any image size, for example 1280×720 or 1920×1080. +- **Block-entity blocks.** Blocks whose shape the client draws from code rather than from a + block model — chests, banners, skulls and heads, shulker boxes — are baked from built-in + models that mirror the client's own geometry and entity textures, so they appear in shots + (and in tiles) like they do in the game. Sign and bed shapes come from their block models as + usual; sign *text* is not drawn (in the game it is a per-block label, and callers that + photograph signs for evidence suppress it there as well). +- **`uvlock`.** Block-state variants with `uvlock: true` keep their texture fixed to the world + while the model rotates, as the client does. + +Lighting and shading are the renderer's own (the same model the tiles use), which is not the +web app's sun/ambient model; geometry, textures and the camera match, tones can differ slightly. + +## The HTTP API + +The `watch` process serves the API when started with `--api-port` (the port is a deployment +setting; nothing about it is baked into the program). Requests are JSON: + +`POST /v1/render` + +```json +{ + "map": "overworld", + "camera": {"target": [100, 70, -40], "distance": 120, "rotation": -0.6, "angle": 0.75}, + "width": 1280, + "height": 720, + "priority": "high" +} +``` + +- `map` is the map's name from the watch configuration. Instead of an orbit camera, a request + may give an explicit camera: `"camera": {"eye": [...], "look_at": [...], "up": [0, 1, 0], + "fov": 75}`. +- `priority` is `"high"` or `"normal"` (default). The watch loop serves the render queue + about once a second between tile batches: every high-priority request in that step, and a + few normal-priority ones, so a long batch sequence cannot starve an urgent single shot; + tile updates keep their own queue and are not starved either, because a shot takes about + a second. +- `background` (optional) is `[r, g, b]` or `[r, g, b, a]` with values 0-255: the colour the + picture starts from, i.e. what shows where no block was drawn. The default is transparent + black. A caller that composites the PNG over its own backdrop, or that matches another + renderer's void colour, sets it explicitly. +- The response is JSON: `image` (the PNG, base64), `width`, `height`, `view` and `projection` + (the camera matrices, 16 numbers each, in the column-major order three.js uses for + `Matrix4.elements`, over world coordinates), `eye` and `target` (the effective camera), and + `render_ms`. + +Batch use (for example one video frame after another) is ordinary repeated requests; identical +requests are answered from a small in-memory cache, and the chunk and mesh caches stay warm +between frames of a sequence, so a slow orbit costs one render per frame, not one world load. + +`GET /v1/maps` lists the served maps. `GET /v1/health` answers 204. + +The same render is available without the server as a one-off command, which is what batch jobs +and tests use: + +``` +godot --path . -s scripts/main.gd -- shot --region-dir /worlds/overworld/region \ + --target 100,70,-40 --distance 120 --rotation -0.6 --angle 0.75 \ + --size 1280x720 --out shot.png +``` + +It writes the PNG and a `.json` with the same fields as the API response. + +## Verification + +Equivalence with the BlueMap screenshot path was measured on a synthetic test world (built +for this purpose, containing the block-entity blocks listed above, uvlock variants and a +damaged area) drawn two ways with the same camera: once by BlueMap itself (Paper + BlueMap, +screen-captured in a browser) and once by the shot renderer, at 1280×720. The renderer's +transparent void was composited over black, the void colour of the comparison capture. + +- Damage view (distance 70, rotation -0.6, angle 0.75): the two pictures agree on which + pixels show world (rather than void) for 94.9% of the pixels either one shows as world; + 88.9% of all pixels are within ±12 per channel and 97.0% within ±30; the mean + maximum-channel difference over all pixels is 4.4 (of 255). +- Close-up view (distance 45, angle 0.9): world agreement 93.1%; 80.7% of pixels within ±12 + and 93.6% within ±30; mean maximum-channel difference 8.2. + +The remaining differences are the shading and texture filtering of two independent +renderers, not the geometry or the camera: chests (single and double), the ender and trapped +chests, banners, skulls and heads, shulker boxes and the uvlock variants are present and +identifiable in both pictures at the same positions. + +Rendering speed on the same machine (RTX 3060): a 1280×720 evidence view renders in about +0.4-0.9 s; a 1920×1080 background view at distance 420 renders in about 0.6-0.9 s. The API +answers a high-priority request in about 1.5 s end to end while the watch process is +otherwise idle. diff --git a/scripts/cmd/build_data.gd b/scripts/cmd/build_data.gd index e16b057..582368f 100644 --- a/scripts/cmd/build_data.gd +++ b/scripts/cmd/build_data.gd @@ -109,6 +109,7 @@ func _build(jar: String, out: String, reports: String) -> int: continue tex_names.append(n.substr("assets/minecraft/textures/".length(), n.length() - "assets/minecraft/textures/".length() - 4)) data.append_array(t) + _extract_entity_sheets(out, data, tex_names) _write(out.path_join("textures.bin"), data) _write_json(out.path_join("textures.json"), tex_names) var defaults := {} @@ -395,3 +396,54 @@ static func _parse_color(v: Variant) -> Variant: if v is String: return ("0x" + v.lstrip("#")).hex_to_int() return null + + +# --- entity sheets ------------------------------------------------------------------------------------------------ + +## Sheets the client uses for block entities (chests, banners, shulker boxes, heads). They live +## outside textures/block, so they are cut into 16x16 tiles here and appended to the texture +## table as "entity/#,"; entity_textures.json records each sheet's size in tiles +## for the state registry's block-entity baker. +const ENTITY_SHEETS := [ + "entity/chest/normal", "entity/chest/normal_left", "entity/chest/normal_right", + "entity/chest/trapped", "entity/chest/trapped_left", "entity/chest/trapped_right", + "entity/chest/ender", + "entity/chest/copper", "entity/chest/copper_left", "entity/chest/copper_right", + "entity/chest/copper_exposed", "entity/chest/copper_exposed_left", "entity/chest/copper_exposed_right", + "entity/chest/copper_weathered", "entity/chest/copper_weathered_left", "entity/chest/copper_weathered_right", + "entity/chest/copper_oxidized", "entity/chest/copper_oxidized_left", "entity/chest/copper_oxidized_right", + "entity/banner/banner_base", + "entity/shulker/shulker", + "entity/shulker/shulker_white", "entity/shulker/shulker_light_gray", "entity/shulker/shulker_gray", + "entity/shulker/shulker_black", "entity/shulker/shulker_brown", "entity/shulker/shulker_red", + "entity/shulker/shulker_orange", "entity/shulker/shulker_yellow", "entity/shulker/shulker_lime", + "entity/shulker/shulker_green", "entity/shulker/shulker_cyan", "entity/shulker/shulker_light_blue", + "entity/shulker/shulker_blue", "entity/shulker/shulker_purple", "entity/shulker/shulker_magenta", + "entity/shulker/shulker_pink", + "entity/skeleton/skeleton", "entity/skeleton/wither_skeleton", + "entity/zombie/zombie", "entity/creeper/creeper", "entity/piglin/piglin", + "entity/enderdragon/dragon", "entity/player/wide/steve", +] + + +func _extract_entity_sheets(out_dir: String, data: PackedByteArray, tex_names: Array) -> void: + var manifest := {} + var skipped := 0 + for sheet in ENTITY_SHEETS: + var path: String = "assets/minecraft/textures/" + sheet + ".png" + if not _jar.has(path): + skipped += 1 + continue + var img := _load_rgba(_jar.read(path)) + if img.get_width() == 0 or img.get_width() % 16 != 0 or img.get_height() % 16 != 0: + skipped += 1 + continue + var txs := img.get_width() / 16 + var tys := img.get_height() / 16 + for ty in tys: + for tx in txs: + tex_names.append("%s#%d,%d" % [sheet, tx, ty]) + data.append_array(img.get_region(Rect2i(tx * 16, ty * 16, 16, 16)).get_data()) + manifest[sheet] = [txs, tys] + _write_json(out_dir.path_join("entity_textures.json"), manifest) + print("entity sheets %d (skipped %d)" % [manifest.size(), skipped]) diff --git a/scripts/cmd/jobs.gd b/scripts/cmd/jobs.gd index 120a3ec..d591e93 100644 --- a/scripts/cmd/jobs.gd +++ b/scripts/cmd/jobs.gd @@ -45,7 +45,7 @@ static func run(args: Args) -> int: ## `watch --config maps.json [--map-id N,...] [--interval S] [--max-megas N] [--max-load L] [--stale-after S] [--once]` -## [--mega-cooldown S] [--bbox-threshold N] [--dirty-port N] [--dirty-token-file F]` +## [--mega-cooldown S] [--bbox-threshold N] [--dirty-port N] [--dirty-token-file F] [--api-port N]` ## Resident updater for every map of the config. The dirty feed (block-change events from the game server) ## listens only when both a port and a token are set: the token comes from TORO_DIRTY_TOKEN or the file. static func watch(args: Args) -> int: @@ -83,14 +83,27 @@ static func watch(args: Args) -> int: var dirty := DirtyFeed.new() if dirty.start(dirty_port, token): job.dirty_feed = dirty + var api_port := args.integer("api-port", 0) + if api_port > 0: + var api := ShotApi.new() + api.pool = pool + if not api.start(api_port): + return 1 + job.api = api + var state_dir := args.text("state-dir", "/state") for e in ctx.cfg["maps"]: var map := MapDef.from_entry(e) if not wanted.is_empty() and not wanted.has(map.id): continue + if job.api != null: + job.api.register(map) if not ctx.store.ensure_connected(): Term.say("database unreachable: " + ctx.store.error) - return 1 + if job.api == null: + return 1 + # with the render API on, the map is still served; only its tile updates wait + continue ctx.store.map_id = map.id map.world = ctx.store.world_name() if ctx.feed != null: diff --git a/scripts/cmd/shot.gd b/scripts/cmd/shot.gd new file mode 100644 index 0000000..940342d --- /dev/null +++ b/scripts/cmd/shot.gd @@ -0,0 +1,88 @@ +class_name ShotCmd +extends RefCounted +## `shot --out FILE.png [--config maps.json] [--map NAME] [--map-id N] [--region-dir DIR] [--data-dir DIR] +## [--target x,y,z] [--distance D] [--rotation R] [--angle A] [--fov F] [--size WxH] +## [--eye x,y,z --look-at x,y,z] [--no-adjust-height] [--min-y N] [--max-y N] [--background r,g,b[,a]]` +## One perspective picture of a map (docs/render-api.md). Writes the PNG and a .json next to it +## with the camera transform: the same fields the HTTP API returns. + + +static func _vec3(text: String, fallback: Vector3) -> Vector3: + var p := text.split(",") + if p.size() == 3: + return Vector3(float(p[0]), float(p[1]), float(p[2])) + return fallback + + +static func run(args: Args) -> int: + var out := args.text("out") + if out == "": + push_error("shot needs --out FILE.png") + return 2 + var cfg := MapDef.load_config(args.text("config")) + var map: MapDef = null + var sel := args.text("map") + if sel != "": + for e in cfg.get("maps", []): + var d := MapDef.from_entry(e) + if d.name == sel or str(d.id) == sel: + map = d + break + if map == null: + map = MapDef.from_args(args, cfg) + if args.has("region-dir"): + map.region_dir = args.text("region-dir") + if map.region_dir == "": + push_error("shot needs a map (--map with --config, or --region-dir)") + return 2 + var pool := RendererPool.create(args.text("data-dir", ProjectSettings.globalize_path("res://data"))) + if pool == null: + return 1 + var sr := pool.shot_renderer(map.region_dir) + if sr == null: + return 1 + sr.min_y = args.integer("min-y", map.min_y) + sr.max_y = args.integer("max-y", map.max_y) + var size := args.text("size", "1280x720").split("x") + var width := int(size[0]) if size.size() == 2 else 0 + var height := int(size[1]) if size.size() == 2 else 0 + if width < 16 or height < 16 or width > 4096 or height > 4096: + push_error("shot needs --size WxH with both sides within 16..4096") + return 2 + var aspect := float(width) / float(height) + var fov := args.number("fov", ShotCamera.DEFAULT_FOV) + var cam: Dictionary + if args.has("eye"): + cam = ShotCamera.from_eye(_vec3(args.text("eye"), Vector3.ZERO), _vec3(args.text("look-at", "0,70,0"), Vector3(0, 70, 0)), aspect, fov) + else: + var target := _vec3(args.text("target", "0,70,0"), Vector3(0, 70, 0)) + var distance := args.number("distance", 120.0) + var rotation := args.number("rotation", 0.0) + var angle := args.number("angle", 0.75) + if not args.flag("no-adjust-height"): + target = sr.effective_target(target, distance, rotation, angle) + cam = ShotCamera.orbit(target, distance, rotation, angle, aspect, fov) + var dist := (cam["eye"] as Vector3).distance_to(cam["target"]) + var chunks := sr.shot_chunks(cam["vp"], cam["target"], dist) + var t0 := Time.get_ticks_usec() + if args.has("background"): + var bg := args.text("background").split(",") + if bg.size() >= 3: + sr.background = Color(int(bg[0]) / 255.0, int(bg[1]) / 255.0, int(bg[2]) / 255.0, (int(bg[3]) / 255.0) if bg.size() >= 4 else 1.0) + var img := sr.render_shot(cam, width, height, chunks) + var ms := (Time.get_ticks_usec() - t0) / 1000.0 + DirAccess.make_dir_recursive_absolute(out.get_base_dir()) + if img.save_png(out) != OK: + push_error("cannot write %s" % out) + return 1 + var eye: Vector3 = cam["eye"] + var tgt: Vector3 = cam["target"] + var info := { + "width": width, "height": height, + "view": Array(cam["view"]), "projection": Array(cam["projection"]), + "eye": [eye.x, eye.y, eye.z], "target": [tgt.x, tgt.y, tgt.z], + "render_ms": ms, "chunks": chunks.size(), + } + FileAccess.open(out.get_basename() + ".json", FileAccess.WRITE).store_string(JSON.stringify(info, " ")) + print("shot: %s (%dx%d, %d chunks, %.0f ms)" % [out, width, height, chunks.size(), ms]) + return 0 diff --git a/scripts/cmd/shot.gd.uid b/scripts/cmd/shot.gd.uid new file mode 100644 index 0000000..0287e7b --- /dev/null +++ b/scripts/cmd/shot.gd.uid @@ -0,0 +1 @@ +uid://cow2knvepko3w diff --git a/scripts/job/renderer_pool.gd b/scripts/job/renderer_pool.gd index 60f5d35..649ddb7 100644 --- a/scripts/job/renderer_pool.gd +++ b/scripts/job/renderer_pool.gd @@ -8,6 +8,7 @@ var reg: StateRegistry var table: BlockTable var device_name := "" var _renderers := {} +var _shot_renderers := {} static func create(data_dir: String) -> RendererPool: @@ -42,6 +43,18 @@ func renderer(persp_name: String, region_dir: String) -> IsoRenderer: return iso +## One ShotRenderer per region directory (perspective stills; docs/render-api.md). +func shot_renderer(region_dir: String) -> ShotRenderer: + if _shot_renderers.has(region_dir): + return _shot_renderers[region_dir] + var sr := ShotRenderer.new() + sr.rd = rd + if not sr.setup_shot(reg, table, WorldReader.new(region_dir, table)): + return null + _shot_renderers[region_dir] = sr + return sr + + ## Renders each mega tile (mega x mega tiles) -> Vector2i -> null (blank) or {"img": Image, "hash": int}. ## A mega tile that could not be drawn adds nothing, so its existing rows stay as they are; the failure is ## logged, because a silent skip here is how a tile goes missing without a trace. diff --git a/scripts/job/shot_api.gd b/scripts/job/shot_api.gd new file mode 100644 index 0000000..7e3e225 --- /dev/null +++ b/scripts/job/shot_api.gd @@ -0,0 +1,277 @@ +class_name ShotApi +extends RefCounted +## The HTTP front of the render API (docs/render-api.md), served by the resident watch process +## when it is started with --api-port: POST /v1/render draws one perspective picture of a map, +## GET /v1/maps lists the served maps, GET /v1/health answers 204. The API is a general +## renderer capability: callers name a map, a camera and an image size and receive a PNG plus +## the camera transform; annotations and other caller-specific overlays are computed by the +## caller from that transform. +## +## The watch loop drives this object: poll() moves bytes (accept, read, write) and runs in the +## loop's rest slices, serve_step() renders the queued requests between tile batches. "high" +## priority requests are all served in a step, "normal" ones only a few per step, so a batch +## of background frames cannot starve the tile updater. Identical requests are answered from +## a small in-memory cache (10 s), and meshes stay cached across a sequence of frames. + +const MAX_HEAD := 16384 +const MAX_BODY := 65536 +const MAX_DIM := 4096 +const CACHE_TTL := 10.0 +const CACHE_MAX := 32 +const NORMALS_PER_STEP := 2 +const CONN_TIMEOUT := 30.0 + +var pool: RendererPool +var maps: Array = [] # of MapDef + +var _server := TCPServer.new() +var _conns := {} # StreamPeerTCP -> {"state", "buf", "need", "out", "touched"} +var _queue := [] # of {"conn", "params", "priority", "key"} +var _cache := {} # key -> {"at", "body"} +var _cache_order := [] + + +func start(port: int) -> bool: + var err := _server.listen(port) + if err != OK: + push_error("render api: cannot listen on port %d (%s)" % [port, error_string(err)]) + return false + Term.say("render api listening on port %d" % port) + return true + + +func register(def: MapDef) -> void: + maps.append(def) + + +func _find_map(sel: String) -> MapDef: + for d in maps: + if d.name == sel or str(d.id) == sel: + return d + return null + + +## Moves bytes only. Called from the watch loop's rest slices and serve_step. +func poll() -> void: + while _server.is_connection_available(): + var c := _server.take_connection() + if c != null: + _conns[c] = {"state": "head", "buf": PackedByteArray(), "need": 0, "out": PackedByteArray(), "touched": Time.get_unix_time_from_system()} + for c in _conns.keys(): + _step(c) + + +## Renders queued requests between tile batches: every high-priority one, then a few normal. +func serve_step() -> void: + poll() + if _queue.is_empty(): + return + var jobs := _queue + _queue = [] + var normals := [] + for job in jobs: + if job["priority"] == "high": + _answer(job) + else: + normals.append(job) + var n := 0 + for job in normals: + if n < NORMALS_PER_STEP: + _answer(job) + n += 1 + else: + _queue.append(job) + poll() + + +func _step(c: StreamPeerTCP) -> void: + c.poll() + if c.get_status() != StreamPeerTCP.STATUS_CONNECTED: + _conns.erase(c) + return + var st: Dictionary = _conns[c] + # "queued" is exempt: the caller waits for the render step on purpose, its own + # client-side timeout is the bound there + if Time.get_unix_time_from_system() - float(st["touched"]) > CONN_TIMEOUT and st["state"] != "write" and st["state"] != "queued": + c.disconnect_from_host() + _conns.erase(c) + return + var avail := c.get_available_bytes() + if avail > 0: + # get_partial_data: get_data reports ERR_FILE_EOF for a short read and the bytes + # would be dropped; a request usually arrives in fragments smaller than the ask. + # The buffer is assigned back because a PackedByteArray read out of a Dictionary + # is copy-on-write: appending to the copy would never grow the stored buffer. + var got := c.get_partial_data(mini(avail, MAX_BODY + MAX_HEAD)) + if not (got[1] as PackedByteArray).is_empty(): + st["touched"] = Time.get_unix_time_from_system() + var grown: PackedByteArray = st["buf"] + grown.append_array(got[1]) + st["buf"] = grown + if st["state"] == "head": + var buf: PackedByteArray = st["buf"] + var end := _find_header_end(buf) + if end < 0: + if buf.size() > MAX_HEAD: + _reply(c, st, 431, {"error": "headers too large"}) + return + _on_headers(c, st, end) + elif st["state"] == "body": + if (st["buf"] as PackedByteArray).size() >= st["need"]: + _on_body(c, st) + if st["state"] == "write": + var out: PackedByteArray = st["out"] + if not out.is_empty(): + var sent := c.put_partial_data(out) + if sent[0] == OK: + st["out"] = out.slice(int(sent[1])) + st["touched"] = Time.get_unix_time_from_system() + if (st["out"] as PackedByteArray).is_empty(): + c.disconnect_from_host() + _conns.erase(c) + + +static func _find_header_end(buf: PackedByteArray) -> int: + for i in range(0, buf.size() - 3): + if buf[i] == 13 and buf[i + 1] == 10 and buf[i + 2] == 13 and buf[i + 3] == 10: + return i + 4 + return -1 + + +func _on_headers(c: StreamPeerTCP, st: Dictionary, head_end: int) -> void: + var head := (st["buf"] as PackedByteArray).slice(0, head_end).get_string_from_utf8() + var lines := head.split("\r\n") + var parts := lines[0].split(" ") + if parts.size() < 2: + _reply(c, st, 400, {"error": "bad request line"}) + return + var method := parts[0] + var path := parts[1] + var length := 0 + for ln in lines.slice(1): + var kv := ln.split(":", true, 1) + if kv.size() == 2 and kv[0].strip_edges().to_lower() == "content-length": + length = int(kv[1].strip_edges()) + st["buf"] = (st["buf"] as PackedByteArray).slice(head_end) + if method == "GET" and path == "/v1/health": + _reply_raw(c, st, 204, PackedByteArray()) + return + if method == "GET" and path == "/v1/maps": + var list := [] + for d in maps: + list.append({"name": d.name, "id": d.id}) + _reply(c, st, 200, {"maps": list}) + return + if method == "POST" and path == "/v1/render": + if length <= 0 or length > MAX_BODY: + _reply(c, st, 413, {"error": "request body missing or too large"}) + return + st["need"] = length + st["state"] = "body" + if (st["buf"] as PackedByteArray).size() >= length: + _on_body(c, st) + return + _reply(c, st, 404, {"error": "not found"}) + + +func _on_body(c: StreamPeerTCP, st: Dictionary) -> void: + var body := (st["buf"] as PackedByteArray).slice(0, st["need"]).get_string_from_utf8() + st["state"] = "queued" + var parsed = JSON.parse_string(body) + if not parsed is Dictionary: + _reply(c, st, 400, {"error": "request is not a JSON object"}) + return + var key := JSON.stringify(parsed) + var hit = _cache.get(key) + if hit != null and Time.get_unix_time_from_system() - float(hit["at"]) <= CACHE_TTL: + _reply_raw(c, st, 200, hit["body"]) + return + _queue.append({"conn": c, "params": parsed, "priority": str(parsed.get("priority", "normal")), "key": key}) + + +func _answer(job: Dictionary) -> void: + var c: StreamPeerTCP = job["conn"] + if not _conns.has(c): + return # the caller went away while waiting + var st: Dictionary = _conns[c] + var res := _render(job["params"]) + if int(res["status"]) == 200: + _cache[job["key"]] = {"at": Time.get_unix_time_from_system(), "body": res["body"]} + _cache_order.append(job["key"]) + while _cache_order.size() > CACHE_MAX: + _cache.erase(_cache_order.pop_front()) + _reply_raw(c, st, int(res["status"]), res["body"]) + + +func _reply(c: StreamPeerTCP, st: Dictionary, status: int, obj: Dictionary) -> void: + _reply_raw(c, st, status, JSON.stringify(obj).to_utf8_buffer()) + + +func _reply_raw(c: StreamPeerTCP, st: Dictionary, status: int, body: PackedByteArray) -> void: + var reason: String = {200: "OK", 204: "No Content", 400: "Bad Request", 404: "Not Found", 413: "Content Too Large", 431: "Request Header Fields Too Large", 500: "Internal Server Error"}.get(status, "OK") + var head := "HTTP/1.1 %d %s\r\nContent-Type: application/json\r\nContent-Length: %d\r\nConnection: close\r\n\r\n" % [status, reason, body.size()] + st["out"] = head.to_utf8_buffer() + body + st["state"] = "write" + + +static func _vec3(v: Variant, fallback: Vector3) -> Vector3: + if v is Array and v.size() == 3: + return Vector3(float(v[0]), float(v[1]), float(v[2])) + return fallback + + +## Renders one request; returns {"status", "body"} with the API response as bytes. +func _render(params: Dictionary) -> Dictionary: + var def := _find_map(str(params.get("map", ""))) + if def == null: + return {"status": 400, "body": JSON.stringify({"error": "unknown map"}).to_utf8_buffer()} + var width := int(params.get("width", 0)) + var height := int(params.get("height", 0)) + if width < 16 or height < 16 or width > MAX_DIM or height > MAX_DIM: + return {"status": 400, "body": JSON.stringify({"error": "width/height out of range"}).to_utf8_buffer()} + var sr := pool.shot_renderer(def.region_dir) + if sr == null: + return {"status": 500, "body": JSON.stringify({"error": "renderer unavailable"}).to_utf8_buffer()} + var bg = params.get("background") + if bg is Array and bg.size() >= 3: + sr.background = Color(float(bg[0]) / 255.0, float(bg[1]) / 255.0, float(bg[2]) / 255.0, (float(bg[3]) / 255.0) if bg.size() >= 4 else 1.0) + else: + sr.background = Color(0, 0, 0, 0) + sr.min_y = def.min_y + sr.max_y = def.max_y + var cam_raw = params.get("camera") + var cam_in: Dictionary = cam_raw if cam_raw is Dictionary else {} + var adjust: bool = params.get("adjust_height", cam_in.get("adjust_height", true)) + var aspect := float(width) / float(height) + var cam: Dictionary + var target: Vector3 + if cam_in.has("eye"): + target = _vec3(cam_in.get("look_at", cam_in.get("target")), Vector3.ZERO) + var eye := _vec3(cam_in.get("eye"), Vector3.ZERO) + cam = ShotCamera.from_eye(eye, target, aspect, float(cam_in.get("fov", ShotCamera.DEFAULT_FOV))) + else: + target = _vec3(cam_in.get("target"), Vector3(0, 70, 0)) + var distance := float(cam_in.get("distance", 120.0)) + var rotation := float(cam_in.get("rotation", 0.0)) + var angle := float(cam_in.get("angle", 0.75)) + if adjust: + target = sr.effective_target(target, distance, rotation, angle) + cam = ShotCamera.orbit(target, distance, rotation, angle, aspect, float(cam_in.get("fov", ShotCamera.DEFAULT_FOV))) + var dist := (cam["eye"] as Vector3).distance_to(cam["target"]) + var chunks := sr.shot_chunks(cam["vp"], cam["target"], dist) + var t0 := Time.get_ticks_usec() + var img := sr.render_shot(cam, width, height, chunks) + var ms := (Time.get_ticks_usec() - t0) / 1000.0 + sr.next_generation() + var png := img.save_png_to_buffer() + var resp := { + "image": Marshalls.raw_to_base64(png), + "width": width, + "height": height, + "view": Array(cam["view"]), + "projection": Array(cam["projection"]), + "eye": [(cam["eye"] as Vector3).x, (cam["eye"] as Vector3).y, (cam["eye"] as Vector3).z], + "target": [(cam["target"] as Vector3).x, (cam["target"] as Vector3).y, (cam["target"] as Vector3).z], + "render_ms": ms, + } + return {"status": 200, "body": JSON.stringify(resp).to_utf8_buffer()} diff --git a/scripts/job/shot_api.gd.uid b/scripts/job/shot_api.gd.uid new file mode 100644 index 0000000..90827ef --- /dev/null +++ b/scripts/job/shot_api.gd.uid @@ -0,0 +1 @@ +uid://woro62dc7b4x diff --git a/scripts/job/watch_job.gd b/scripts/job/watch_job.gd index 144fd2c..272b0c6 100644 --- a/scripts/job/watch_job.gd +++ b/scripts/job/watch_job.gd @@ -52,6 +52,8 @@ var gate: Gate var feed: LiveFeed ## Block-change events from the game server; null when the feed is off. var dirty_feed: DirtyFeed +## the render API front (docs/render-api.md); null when watch runs without --api-port +var api: ShotApi var interval := 60.0 var overlap := 30.0 var max_megas := 4 @@ -285,6 +287,8 @@ func run() -> int: for ms in maps: _scan(ms, cycle) _save(ms) + if api != null: + api.serve_step() var rendered := false var why := gate.reason() if why == "": @@ -294,12 +298,30 @@ func run() -> int: if once: # one look, at most one batch return 0 if not rendered: - await Term.sleep(maxf(1.0, interval - (Time.get_unix_time_from_system() - cycle))) + await _rest(maxf(1.0, interval - (Time.get_unix_time_from_system() - cycle))) else: - await Term.sleep(0.5) # lets the main loop breathe between batches + await _rest(0.5) # lets the main loop breathe between batches return 0 +## Rests in short slices so render requests that arrive meanwhile are picked up +## promptly: bytes move every slice, the render queue is served about once a second, +## so an evidence request is answered within a second plus its render time even in +## the middle of a long rest, while batch requests still trickle through serve_step. +func _rest(seconds: float) -> void: + var left := seconds + var slices := 0 + while left > 0.0: + await Term.sleep(minf(left, 0.1)) + left -= 0.1 + slices += 1 + if api != null: + if slices % 10 == 0: + api.serve_step() + else: + api.poll() + + func _pending_total() -> int: var n := 0 for ms in maps: diff --git a/scripts/main.gd b/scripts/main.gd index 2835f9e..8d11395 100644 --- a/scripts/main.gd +++ b/scripts/main.gd @@ -12,6 +12,7 @@ extends SceneTree ## watch resident updater: keeps every map of a config current around the chunks the server saves ## zoom rebuild zoom-out levels without rendering ## build-data extract blocks, models, textures and biomes from a Minecraft client jar +## shot one perspective picture of a map (PNG + camera transform), see docs/render-api.md ## dev debugging helpers (dump, column, topblocks, colblocks, encodetest, zoomtest) ## ## Options are `--key value` or `--flag`; see each command's class for the full list. @@ -34,8 +35,10 @@ func _initialize() -> void: code = await JobCmds.zoom(args) "build-data": code = BuildData.run(args) + "shot": + code = ShotCmd.run(args) "dev": code = DevCmd.run(args) _: - print("usage: main.gd -- render|scan|run|watch|zoom|build-data|dev [options]") + print("usage: main.gd -- render|scan|run|watch|zoom|build-data|shot|dev [options]") quit(code) diff --git a/scripts/map/map_def.gd b/scripts/map/map_def.gd index 978937a..128741d 100644 --- a/scripts/map/map_def.gd +++ b/scripts/map/map_def.gd @@ -3,6 +3,8 @@ extends RefCounted ## One Dynmap map: which TiDB MapID it fills, from which region directory, in which perspective. var id := 0 +## optional caller-facing name; the render API addresses maps by it (or by the numeric id) +var name := "" var region_dir := "" var persp_name := "iso_S_90_lowres" var zoom_max := 10 @@ -33,6 +35,7 @@ static func load_config(path: String) -> Dictionary: static func from_entry(e: Dictionary) -> MapDef: var m := MapDef.new() m.id = int(e.get("id", 0)) + m.name = str(e.get("name", "")) m.region_dir = e.get("region", "") m.persp_name = e.get("persp", m.persp_name) m.zoom_max = int(e.get("zoom_max", m.zoom_max)) diff --git a/scripts/render/iso_renderer.gd b/scripts/render/iso_renderer.gd index cce7ee3..9fc2a95 100644 --- a/scripts/render/iso_renderer.gd +++ b/scripts/render/iso_renderer.gd @@ -483,7 +483,7 @@ static func _quad_key(vf: PackedFloat32Array, q: int) -> String: ## Translucent quads of the GPU mesher back to front: ascending map z (float32 sum of float32 vertex depths computed in ## double precision,), ties in the CPU mesher's emission order (chunk, block y/z/x, quad ordinal). ## tb: 16 uints per quad (see mesh_chunks.glsl note_quad). -func _sort_translucent(tb: PackedByteArray, chunks: Array[Vector2i]) -> PackedInt32Array: +func _sort_translucent(tb: PackedByteArray, chunks: Array[Vector2i], row := PackedFloat64Array()) -> PackedInt32Array: var n := tb.size() / 64 var order := PackedInt32Array() if n == 0: @@ -491,6 +491,9 @@ func _sort_translucent(tb: PackedByteArray, chunks: Array[Vector2i]) -> PackedIn var ints := tb.to_int32_array() var fl := tb.to_float32_array() var m := persp.w2m + var zr := PackedFloat64Array([m[6], m[7], m[8]]) + if row.size() == 3: + zr = row var s1 := PackedFloat32Array() var s2 := PackedFloat32Array() var s3 := PackedFloat32Array() @@ -503,7 +506,7 @@ func _sort_translucent(tb: PackedByteArray, chunks: Array[Vector2i]) -> PackedIn var bz := c.y * 16.0 for v in 4: var p := o + 3 + v * 3 - zv[i * 4 + v] = m[6] * (bx + fl[p]) + m[7] * fl[p + 1] + m[8] * (bz + fl[p + 2]) + zv[i * 4 + v] = zr[0] * (bx + fl[p]) + zr[1] * fl[p + 1] + zr[2] * (bz + fl[p + 2]) s1.resize(n) s2.resize(n) s3.resize(n) diff --git a/scripts/render/shot_camera.gd b/scripts/render/shot_camera.gd new file mode 100644 index 0000000..a2ca2a5 --- /dev/null +++ b/scripts/render/shot_camera.gd @@ -0,0 +1,77 @@ +class_name ShotCamera +extends RefCounted +## Perspective camera maths for still images ("shots"), in the conventions of the three.js +## camera the BlueMap web app uses: right-handed view space (the camera looks down -z) and +## matrices as 16 column-major elements, the order of three.js Matrix4.elements. An orbit +## camera is described the BlueMap way: a target point, a distance, a rotation (azimuth, +## radians) and an angle (polar angle from +y, radians). See docs/render-api.md. + +const DEFAULT_FOV := 75.0 + + +## Orbit parameters -> {"eye", "target", "view", "projection", "vp"} (matrices are +## PackedFloat64Array(16), column-major). Near and far follow BlueMap's rule for the distance. +static func orbit(target: Vector3, distance: float, rotation: float, angle: float, aspect: float, fov := DEFAULT_FOV) -> Dictionary: + var eye := target + Vector3(-sin(rotation) * sin(angle), cos(angle), cos(rotation) * sin(angle)) * distance + var near := clampf(distance / 1000.0, 0.01, 1.0) + var far := clampf(2.0 * distance, maxf(near + 1.0, 2000.0), distance + 5000.0) + if far - near > 10000.0: + far = near + 10000.0 + var cam := from_eye(eye, target, aspect, fov) + cam["near"] = near + cam["far"] = far + return cam + + +## Explicit camera: eye, the point it looks at, the image aspect ratio and a vertical field of +## view. Near/far are derived from the eye-target distance with the same rule as orbit(). +static func from_eye(eye: Vector3, target: Vector3, aspect: float, fov := DEFAULT_FOV) -> Dictionary: + var distance := eye.distance_to(target) + var near := clampf(distance / 1000.0, 0.01, 1.0) + var far := clampf(2.0 * distance, maxf(near + 1.0, 2000.0), distance + 5000.0) + if far - near > 10000.0: + far = near + 10000.0 + var view := look_at(eye, target, Vector3.UP) + var proj := perspective(fov, aspect, near, far) + return {"eye": eye, "target": target, "view": view, "projection": proj, "vp": multiply(proj, view), "near": near, "far": far} + + +## three.js Matrix4.lookAt: the view matrix (column-major) of a camera at eye looking at +## target. A target equal to the eye falls back to looking down -z. +static func look_at(eye: Vector3, target: Vector3, up: Vector3) -> PackedFloat64Array: + var z := eye - target + z = z.normalized() if z.length() > 1e-9 else Vector3(0, 0, 1) + var x := up.cross(z) + x = x.normalized() if x.length() > 1e-6 else Vector3(1, 0, 0) + var y := z.cross(x) + return PackedFloat64Array([ + x.x, y.x, z.x, 0.0, + x.y, y.y, z.y, 0.0, + x.z, y.z, z.z, 0.0, + -x.dot(eye), -y.dot(eye), -z.dot(eye), 1.0]) + + +## three.js PerspectiveCamera projection matrix (column-major); fov in degrees. +static func perspective(fov_deg: float, aspect: float, near: float, far: float) -> PackedFloat64Array: + var f := 1.0 / tan(deg_to_rad(fov_deg) * 0.5) + var e := PackedFloat64Array() + e.resize(16) + e[0] = f / aspect + e[5] = f + e[10] = (far + near) / (near - far) + e[11] = -1.0 + e[14] = 2.0 * far * near / (near - far) + return e + + +## a * b for column-major 16-element matrices. +static func multiply(a: PackedFloat64Array, b: PackedFloat64Array) -> PackedFloat64Array: + var e := PackedFloat64Array() + e.resize(16) + for col in 4: + for row in 4: + var s := 0.0 + for k in 4: + s += a[k * 4 + row] * b[col * 4 + k] + e[col * 4 + row] = s + return e diff --git a/scripts/render/shot_camera.gd.uid b/scripts/render/shot_camera.gd.uid new file mode 100644 index 0000000..e06984e --- /dev/null +++ b/scripts/render/shot_camera.gd.uid @@ -0,0 +1 @@ +uid://wiuojiyyyao5 diff --git a/scripts/render/shot_renderer.gd b/scripts/render/shot_renderer.gd new file mode 100644 index 0000000..9836a23 --- /dev/null +++ b/scripts/render/shot_renderer.gd @@ -0,0 +1,208 @@ +class_name ShotRenderer +extends IsoRenderer +## Perspective "photographs" of a map: the tile renderer's baked quads, atlas and shading, +## drawn through a real perspective camera (ShotCamera, docs/render-api.md). Chunk offsets are +## world coordinates here, not map offsets, and the tile path's top-down shortcut never applies. + +## Colour the picture starts from (what shows where no block was drawn). Transparent by +## default; a caller compositing over its own backdrop (or matching another renderer's +## void colour) sets it per request. +var background := Color(0, 0, 0, 0) +var _shader_p := RID() +var _pipe_p_opaque := RID() +var _pipe_p_trans := RID() +## clip-space conversion for the Vulkan rasteriser: y flipped, GL depth [-1, 1] -> reversed +## [1, 0], so the greater-depth-wins test of the tile path keeps the nearest surface. +static var _VK := PackedFloat64Array([1, 0, 0, 0, 0, -1, 0, 0, 0, 0, -0.5, 0, 0, 0, 0.5, 1]) + + +func setup_shot(reg_: StateRegistry, tbl: BlockTable, w: WorldReader) -> bool: + if not setup(Persp.make("shot", 0.0, 90.0, 16), reg_, tbl, w): + return false + mesher.topdown = false + gmesher.topdown = false + _shader_p = _compile("res://shaders/raster_persp.glsl") + return _shader_p.is_valid() + + +## Top surface height of a column (the highest non-air block's top, y + 1), or -1 when the +## chunk is not there. This is the height BlueMap's downward ray reports. +func top_at(x: int, z: int) -> float: + var c := world.chunk(x >> 4, z >> 4) + if c == null: + return -1.0 + var y := mini(c.max_y() - 1, max_y) + var lo := maxi(c.min_y(), min_y) + while y >= lo: + if reg.s_air[c.block(x & 15, y, z & 15)] == 0: + return float(y + 1) + y -= 1 + return -1.0 + + +## BlueMap's settled orbit target (docs/render-api.md): the web app does not use the given +## target height; every frame it raises the target over the terrain, and a settled screenshot +## shows the adjusted one. Computed from the world data with the same rule. +func effective_target(target: Vector3, distance: float, rotation: float, angle: float) -> Vector3: + var terrain := top_at(floori(target.x), floori(target.z)) + if terrain < 0.0: + return target + var by_distance := lerpf(terrain + 3.0, 0.0, minf(distance / 500.0, 1.0)) + var max_angle := clampf((1.0 - sqrt(maxf(distance - 5.0, 0.001) * 0.0005)) * PI / 2.0, 0.0, PI / 2.0) + var min_camera := 0.0 + if max_angle >= 0.1: + var ex := target.x - sin(rotation) * sin(angle) * distance + var ez := target.z + cos(rotation) * sin(angle) * distance + var cam_h := top_at(floori(ex), floori(ez)) + if cam_h >= 0.0: + min_camera = cam_h - cos(max_angle) * distance + 1.0 + return Vector3(target.x, maxf(by_distance, min_camera), target.z) + + +## Chunk columns whose (min_y..max_y) box can intersect the camera frustum. The search is +## bounded to target +/- (distance + 64) and a hard radius, so a far camera cannot pull in +## the whole map. +func shot_chunks(vp: PackedFloat64Array, target: Vector3, distance: float) -> Array[Vector2i]: + var rows := [] + for i in 4: + rows.append(Vector4(vp[i], vp[4 + i], vp[8 + i], vp[12 + i])) + var planes := [] + for d in [[3, 0, 1.0], [3, 0, -1.0], [3, 1, 1.0], [3, 1, -1.0], [3, 2, 1.0], [3, 2, -1.0]]: + var a: Vector4 = rows[d[0]] + var b: Vector4 = rows[d[1]] + var s: float = d[2] + planes.append(Vector4(a.x + s * b.x, a.y + s * b.y, a.z + s * b.z, a.w + s * b.w)) + var reach := minf(distance + 64.0, 1200.0) + var out: Array[Vector2i] = [] + var cx0 := floori((target.x - reach) / 16.0) + var cx1 := floori((target.x + reach) / 16.0) + var cz0 := floori((target.z - reach) / 16.0) + var cz1 := floori((target.z + reach) / 16.0) + for cz in range(cz0, cz1 + 1): + for cx in range(cx0, cx1 + 1): + var x0 := cx * 16.0 + var z0 := cz * 16.0 + var inside := true + for pl in planes: + var px := x0 + 16.0 if pl.x >= 0.0 else x0 + var py := float(max_y) if pl.y >= 0.0 else float(min_y) + var pz := z0 + 16.0 if pl.z >= 0.0 else z0 + if pl.x * px + pl.y * py + pl.z * pz + pl.w < 0.0: + inside = false + break + if inside: + out.append(Vector2i(cx, cz)) + return out + + +## Draws one shot. cam is a ShotCamera result ({"vp", "view", ...}); chunks from shot_chunks(). +func render_shot(cam: Dictionary, width: int, height: int, chunks: Array[Vector2i]) -> Image: + var offs := PackedFloat32Array() + for c in chunks: + offs.append(float(c.x * 16)) + offs.append(0.0) + offs.append(float(c.y * 16)) + offs.append(0.0) + var view: PackedFloat64Array = cam["view"] + # translucent order: back to front along the view direction (the negated view z row makes + # the tile sorter's ascending order end with the nearest quad) + var row2 := PackedFloat64Array([-view[2], -view[6], -view[10]]) + var g := gmesher.mesh(world, chunks, offs, row2, reg.water_tex, reg.lava_tex) + var order := _sort_translucent(g["trans"], chunks, row2) + var b_vf: RID = g["vf"] + var b_vi: RID = g["vi"] + var b_qc: RID = g["qchunk"] + var nquads: int = g["nquads"] + if nquads == 0: + b_vf = _storage(PackedByteArray()) + b_vi = _storage(PackedByteArray()) + b_qc = _storage(PackedByteArray()) + var vp_vk := ShotCamera.multiply(_VK, cam["vp"]) + var bytes := _draw_persp(width, height, b_vf, b_vi, b_qc, offs, order, nquads, vp_vk) + return Image.create_from_data(width, height, false, Image.FORMAT_RGBA8, bytes) + + +func _ensure_pipes() -> void: + if _pipe_p_opaque.is_valid(): + return + _pipe_p_opaque = _make_persp_pipeline(false) + _pipe_p_trans = _make_persp_pipeline(true) + + +func _make_persp_pipeline(trans: bool) -> RID: + var rs := RDPipelineRasterizationState.new() + rs.cull_mode = RenderingDevice.POLYGON_CULL_DISABLED # block models emit single-sided faces + var ms := RDPipelineMultisampleState.new() + var ds := RDPipelineDepthStencilState.new() + ds.enable_depth_test = true + ds.enable_depth_write = not trans + ds.depth_compare_operator = RenderingDevice.COMPARE_OP_GREATER + var cb := RDPipelineColorBlendState.new() + var att := RDPipelineColorBlendStateAttachment.new() + if trans: + att.enable_blend = true + att.src_color_blend_factor = RenderingDevice.BLEND_FACTOR_ONE + att.dst_color_blend_factor = RenderingDevice.BLEND_FACTOR_ONE_MINUS_SRC_ALPHA + att.color_blend_op = RenderingDevice.BLEND_OP_ADD + att.src_alpha_blend_factor = RenderingDevice.BLEND_FACTOR_ONE + att.dst_alpha_blend_factor = RenderingDevice.BLEND_FACTOR_ONE_MINUS_SRC_ALPHA + att.alpha_blend_op = RenderingDevice.BLEND_OP_ADD + cb.attachments = [att] + var sc := RDPipelineSpecializationConstant.new() + sc.constant_id = 0 + sc.value = trans + return rd.render_pipeline_create(_shader_p, _fb_format, RenderingDevice.INVALID_FORMAT_ID, RenderingDevice.RENDER_PRIMITIVE_TRIANGLES, rs, ms, ds, cb, 0, 0, [sc]) + + +## The perspective twin of _draw (same buffers, atlas, finish pass and readback). +func _draw_persp(w: int, h: int, b_vf: RID, b_vi: RID, b_qc: RID, offs: PackedFloat32Array, order: PackedInt32Array, nquads: int, vp_vk: PackedFloat64Array) -> PackedByteArray: + var fbd := _get_fb(w, h) + _ensure_pipes() + var u := PackedFloat32Array() + for i in 16: + u.append(float(vp_vk[i])) + u.append_array(PackedFloat32Array([float(w), float(h), 0.0, 0.0])) + var ui := PackedInt32Array([16, ATLAS_COLS, 0, 0]) + ui.append_array(_shadow) + var ubytes := u.to_byte_array() + ubytes.append_array(ui.to_byte_array()) + var ubuf := rd.uniform_buffer_create(ubytes.size(), ubytes) + var b_off := _storage(offs.to_byte_array()) + var b_order := _storage(order.to_byte_array()) + var uset := rd.uniform_set_create([ + _u(RenderingDevice.UNIFORM_TYPE_UNIFORM_BUFFER, 0, [ubuf]), + _u(RenderingDevice.UNIFORM_TYPE_SAMPLER_WITH_TEXTURE, 1, [_sampler, _atlas]), + _u(RenderingDevice.UNIFORM_TYPE_STORAGE_BUFFER, 2, [b_vf]), + _u(RenderingDevice.UNIFORM_TYPE_STORAGE_BUFFER, 3, [b_vi]), + _u(RenderingDevice.UNIFORM_TYPE_STORAGE_BUFFER, 4, [b_off]), + _u(RenderingDevice.UNIFORM_TYPE_STORAGE_BUFFER, 5, [b_order]), + _u(RenderingDevice.UNIFORM_TYPE_STORAGE_BUFFER, 6, [b_qc]), + ], _shader_p, 0) + var out_buf := rd.storage_buffer_create(w * h * 4) + var fin_set := rd.uniform_set_create([ + _u(RenderingDevice.UNIFORM_TYPE_SAMPLER_WITH_TEXTURE, 0, [_sampler, fbd["color"]]), + _u(RenderingDevice.UNIFORM_TYPE_STORAGE_BUFFER, 1, [out_buf]), + ], _finish_shader, 0) + var dl := rd.draw_list_begin(fbd["fb"], RenderingDevice.DRAW_CLEAR_COLOR_ALL | RenderingDevice.DRAW_CLEAR_DEPTH, PackedColorArray([background]), 0.0) + if nquads > 0: + rd.draw_list_bind_uniform_set(dl, uset, 0) + rd.draw_list_bind_render_pipeline(dl, _pipe_p_opaque) + rd.draw_list_draw(dl, false, 1, nquads * 6) + if order.size() > 0: + rd.draw_list_bind_render_pipeline(dl, _pipe_p_trans) + rd.draw_list_draw(dl, false, 1, order.size() * 6) + rd.draw_list_end() + var pc := PackedInt32Array([w, h, 0, 0]).to_byte_array() + var cl := rd.compute_list_begin() + rd.compute_list_bind_compute_pipeline(cl, _finish_pipe) + rd.compute_list_bind_uniform_set(cl, fin_set, 0) + rd.compute_list_set_push_constant(cl, pc, pc.size()) + rd.compute_list_dispatch(cl, ceili(w / 8.0), ceili(h / 8.0), 1) + rd.compute_list_end() + rd.submit() + rd.sync() + var bytes := rd.buffer_get_data(out_buf) + for r in [fin_set, uset, out_buf, b_order, b_off, b_qc, b_vi, b_vf, ubuf]: + rd.free_rid(r) + return bytes + diff --git a/scripts/render/shot_renderer.gd.uid b/scripts/render/shot_renderer.gd.uid new file mode 100644 index 0000000..903e3b0 --- /dev/null +++ b/scripts/render/shot_renderer.gd.uid @@ -0,0 +1 @@ +uid://bexul7r6rh2vc diff --git a/scripts/render/state_registry.gd b/scripts/render/state_registry.gd index 48c292f..9448cf1 100644 --- a/scripts/render/state_registry.gd +++ b/scripts/render/state_registry.gd @@ -37,6 +37,8 @@ static var _name_re := RegEx.create_from_string("^([a-z0-9_.-]+:)?[a-z0-9_/.-]+$ var data_dir := "" var tex_names := PackedStringArray() var tex_index := {} +## entity sheet name -> size in 16x16 tiles; sheets are cut into "entity/#," textures +var entity_sheets := {} ## per texture: 1 when every texel of the 16x16 sprite is fully opaque var tex_opaque := PackedByteArray() var tex_rgba := PackedByteArray() @@ -93,6 +95,12 @@ func load_dir(dir: String) -> bool: _defaults = JSON.parse_string(df.get_as_text()) else: push_warning("block_defaults.json missing; default block properties unavailable") + var ef := FileAccess.open(dir.path_join("entity_textures.json"), FileAccess.READ) + if ef != null: + var ej = JSON.parse_string(ef.get_as_text()) + if ej is Dictionary: + for k in ej: + entity_sheets[k] = Vector2i(int(ej[k][0]), int(ej[k][1])) water_tex = tex_id("block/water_still") lava_tex = tex_id("block/lava_still") _add_state("minecraft:air", true) @@ -277,7 +285,12 @@ func _build(full_name: String, props: Dictionary) -> int: for vr in _select_variants(def, props): var m = _resolve_model(vr["model"]) if m != null and not (m["elements"] as Array).is_empty(): - _bake(m, vr["x"], vr["y"], qpos, qmeta) + _bake(m, vr["x"], vr["y"], bool(vr.get("uvlock", false)), qpos, qmeta) + if qpos.is_empty(): + # no model geometry: the client draws this block from code (a block entity) + var et := _bake_entity(n, props, qpos, qmeta) + if et >= 0: + s_tint[sid] = TINT_FIXED | et var nq := qmeta.size() / 5 var all_opaque := true for q in nq: @@ -508,11 +521,38 @@ static func _dir_from_vec(v: Array) -> int: return SOUTH if v[2] >= 0.0 else NORTH -func _bake(model: Dictionary, rx: int, ry: int, qpos: PackedFloat32Array, qmeta: PackedInt32Array) -> void: +func _bake(model: Dictionary, rx: int, ry: int, uvlock: bool, qpos: PackedFloat32Array, qmeta: PackedInt32Array) -> void: var nx := ((rx / 90) % 4 + 4) % 4 var ny := ((ry / 90) % 4 + 4) % 4 var textures: Dictionary = model["textures"] for el in model["elements"]: + # uvlock pins the texture to the world: the face UVs come from the element's bounds + # after every rotation (the element's own and the blockstate's), not from the model + var lock_from := [] + var lock_to := [] + if uvlock: + var mn := [1e9, 1e9, 1e9] + var mx := [-1e9, -1e9, -1e9] + for cx in [el["from"][0], el["to"][0]]: + for cy in [el["from"][1], el["to"][1]]: + for cz in [el["from"][2], el["to"][2]]: + var cp := [cx, cy, cz] + var erot = el["rot"] + if erot != null: + cp = _rotate_point(cp, erot[0], erot[1], erot[2], erot[3]) + for _k in nx: + var cc := [_r(cp[0] - 8.0), _r(cp[1] - 8.0), _r(cp[2] - 8.0)] + var cr := _rot_x90(cc) + cp = [_r(cr[0] + 8.0), _r(cr[1] + 8.0), _r(cr[2] + 8.0)] + for _k in ny: + var cc2 := [_r(cp[0] - 8.0), _r(cp[1] - 8.0), _r(cp[2] - 8.0)] + var cr2 := _rot_y90(cc2) + cp = [_r(cr2[0] + 8.0), _r(cr2[1] + 8.0), _r(cr2[2] + 8.0)] + for k in 3: + mn[k] = minf(mn[k], cp[k]) + mx[k] = maxf(mx[k], cp[k]) + lock_from = mn + lock_to = mx for df in el["faces"]: var d: int = df[0] var face: Dictionary = df[1] @@ -561,6 +601,9 @@ func _bake(model: Dictionary, rx: int, ry: int, qpos: PackedFloat32Array, qmeta: _r(_r(e1[2] * e2[0]) - _r(e1[0] * e2[2])), _r(_r(e1[0] * e2[1]) - _r(e1[1] * e2[0]))] var normal := _dir_from_vec(nrm) + if uvlock: + var luv := _default_uv(normal, lock_from, lock_to) + uvs = [[luv[0], luv[1]], [luv[0], luv[3]], [luv[2], luv[3]], [luv[2], luv[1]]] for i in 4: qpos.append(verts[i][0] / 16.0) qpos.append(verts[i][1] / 16.0) @@ -686,3 +729,264 @@ func _select_variants(def: Dictionary, props: Dictionary) -> Array: if part["when"] == null or _cond_matches(part["when"], props): out.append(part["apply"]) return out + + +# --------------------------------------------------------------------------------------------- +# Block entities: blocks the client draws from code, not from a block model (chests, banners, +# skulls and heads, shulker boxes). Baked here from built-in box definitions that mirror the +# client's own entity models, textured from the client's entity sheets (build-data extracts +# them as 16x16 tiles named "entity/#,", with the sheet sizes in +# entity_textures.json). Boxes use the entity box-UV layout: for a box with texture offset +# (u, v) and size (dx, dy, dz), the faces take these regions of the sheet (sheet pixels, +# v downwards): +# up (u+dz, v, dx, dz) down (u+dz+dx, v, dx, dz) +# west (u, v+dz, dz, dy) north (u+dz, v+dz, dx, dy) +# east (u+dz+dx, v+dz, dz, dy) south (u+dz+dx+dz, v+dz, dx, dy) +# A face region is split at sheet tile borders so every emitted quad samples one 16x16 texture. +# Sign text and banner patterns live in block-entity data the region files do not carry in the +# block states, so banners are baked in their base colour and signs keep their block model. + +const DYE_COLORS := { + "white": 0xF9FFFE, "orange": 0xF9801D, "magenta": 0xC74EBD, "light_blue": 0x3AB3DA, + "yellow": 0xFED83D, "lime": 0x80C71F, "pink": 0xF38BAA, "gray": 0x474F52, + "light_gray": 0x9D9D97, "cyan": 0x169C9C, "purple": 0x8932B8, "blue": 0x3C44AA, + "brown": 0x835432, "green": 0x5E7C16, "red": 0xB02E26, "black": 0x1D1D21, +} + +## Blockstate y rotations for a model whose front faces +z (south). _rotate_point turns the +## other way than the blockstate rotation, so the angles are negated. +static func _facing_rots(facing: String) -> Array: + match facing: + "west": + return [["y", -90.0]] + "north": + return [["y", 180.0]] + "east": + return [["y", 90.0]] + return [] + + +## Bakes the block-entity model of block n into qpos/qmeta (nothing when n has none). +## Returns the fixed tint colour for states that carry one (banner cloth), else -1. +func _bake_entity(n: String, props: Dictionary, qpos: PackedFloat32Array, qmeta: PackedInt32Array) -> int: + var base := n.substr(6) if n.begins_with("waxed_") else n + match base: + "chest", "trapped_chest", "ender_chest", "copper_chest", "exposed_copper_chest", "weathered_copper_chest", "oxidized_copper_chest": + _bake_chest(base, props, qpos, qmeta) + return -1 + "shulker_box": + _bake_shulker("entity/shulker/shulker", props, qpos, qmeta) + return -1 + "skeleton_skull", "skeleton_wall_skull": + _bake_head("entity/skeleton/skeleton", props, base.ends_with("wall_skull"), false, qpos, qmeta) + return -1 + "wither_skeleton_skull", "wither_skeleton_wall_skull": + _bake_head("entity/skeleton/wither_skeleton", props, base.ends_with("wall_skull"), false, qpos, qmeta) + return -1 + "zombie_head", "zombie_wall_head": + _bake_head("entity/zombie/zombie", props, base.ends_with("wall_head"), false, qpos, qmeta) + return -1 + "creeper_head", "creeper_wall_head": + _bake_head("entity/creeper/creeper", props, base.ends_with("wall_head"), false, qpos, qmeta) + return -1 + "piglin_head", "piglin_wall_head": + _bake_head("entity/piglin/piglin", props, base.ends_with("wall_head"), false, qpos, qmeta) + return -1 + "dragon_head", "dragon_wall_head": + _bake_head("entity/enderdragon/dragon", props, base.ends_with("wall_head"), true, qpos, qmeta) + return -1 + "player_head", "player_wall_head": + # the owner profile is block-entity data; the shape is drawn with the default skin + _bake_head("entity/player/wide/steve", props, base.ends_with("wall_head"), false, qpos, qmeta) + return -1 + if base.ends_with("_shulker_box"): + var color := base.trim_suffix("_shulker_box") + _bake_shulker("entity/shulker/shulker_" + color, props, qpos, qmeta) + return -1 + if base.ends_with("_banner") or base.ends_with("_wall_banner"): + return _bake_banner(base, props, qpos, qmeta) + return -1 + + +func _bake_chest(n: String, props: Dictionary, qpos: PackedFloat32Array, qmeta: PackedInt32Array) -> void: + var kind := "normal" + match n: + "trapped_chest": + kind = "trapped" + "ender_chest": + kind = "ender" + "copper_chest": + kind = "copper" + "exposed_copper_chest": + kind = "copper_exposed" + "weathered_copper_chest": + kind = "copper_weathered" + "oxidized_copper_chest": + kind = "copper_oxidized" + var type: String = props.get("type", "single") + var sheet := "entity/chest/" + kind + if type == "left": + sheet += "_left" + elif type == "right": + sheet += "_right" + var rots := _facing_rots(props.get("facing", "south")) + # canonical: front towards +z (south); a double chest's left half has its partner at -x and + # its sheet leaves the seam (west) face blank, the right half mirrors that + var x0 := 1.0 + var x1 := 15.0 + if type == "left": + x0 = 0.0 + elif type == "right": + x1 = 16.0 + var w := x1 - x0 + _entity_box(qpos, qmeta, Vector3(x0, 0, 1), Vector3(x1, 10, 15), sheet, Vector2(0, 19), Vector3(w, 10, 14), 1.0, -1, rots) + _entity_box(qpos, qmeta, Vector3(x0, 9, 1), Vector3(x1, 14, 15), sheet, Vector2(0, 0), Vector3(w, 5, 14), 1.0, -1, rots) + if type != "right": + # the latch sits on the front, centred on the seam of a double chest + var lx := 7.0 + if type == "left": + lx = -1.0 + _entity_box(qpos, qmeta, Vector3(lx, 10, 15), Vector3(lx + 2, 14, 16), "entity/chest/" + kind, Vector2(0, 0), Vector3(2, 4, 1), 1.0, -1, rots) + + +func _bake_shulker(sheet: String, props: Dictionary, qpos: PackedFloat32Array, qmeta: PackedInt32Array) -> void: + var rots: Array = [] + match props.get("facing", "up"): + "down": + rots = [["x", 180.0]] + "north": + rots = [["x", -90.0]] + "south": + rots = [["x", 90.0]] + "west": + rots = [["z", 90.0]] + "east": + rots = [["z", -90.0]] + _entity_box(qpos, qmeta, Vector3(0, 0, 0), Vector3(16, 8, 16), sheet, Vector2(0, 28), Vector3(16, 8, 16), 1.0, -1, rots) + _entity_box(qpos, qmeta, Vector3(0, 4, 0), Vector3(16, 16, 16), sheet, Vector2(0, 0), Vector3(16, 12, 16), 1.0, -1, rots) + + +func _bake_head(sheet: String, props: Dictionary, wall: bool, dragon: bool, qpos: PackedFloat32Array, qmeta: PackedInt32Array) -> void: + if dragon: + if wall: + _entity_box(qpos, qmeta, Vector3(0, 4, 0), Vector3(16, 16, 8), sheet, Vector2(0, 0), Vector3(16, 16, 16), 4.0, -1, _facing_rots(props.get("facing", "south"))) + else: + _entity_box(qpos, qmeta, Vector3(0, 0, 0), Vector3(16, 16, 16), sheet, Vector2(0, 0), Vector3(16, 16, 16), 4.0, -1, [["y", -int(props.get("rotation", "0")) * 22.5]]) + return + if wall: + _entity_box(qpos, qmeta, Vector3(4, 4, 0), Vector3(12, 12, 8), sheet, Vector2(0, 0), Vector3(8, 8, 8), 1.0, -1, _facing_rots(props.get("facing", "south"))) + else: + _entity_box(qpos, qmeta, Vector3(4, 0, 4), Vector3(12, 8, 12), sheet, Vector2(0, 0), Vector3(8, 8, 8), 1.0, -1, [["y", -int(props.get("rotation", "0")) * 22.5]]) + + +func _bake_banner(n: String, props: Dictionary, qpos: PackedFloat32Array, qmeta: PackedInt32Array) -> int: + var wall := n.ends_with("_wall_banner") + var cname := n.trim_suffix("_wall_banner").trim_suffix("_banner") + var sheet := "entity/banner/banner_base" + # the client's banner model is built in units of 2/3 block pixels: pole 42, crossbar 20x2, + # cloth 20x40 hanging from the bar; the pole and bar keep the sheet's wood colours, the + # cloth takes the banner's dye colour as its tint + if wall: + var rots := _facing_rots(props.get("facing", "south")) + _entity_box(qpos, qmeta, Vector3(1.3333, 14.6667, 0), Vector3(14.6667, 16, 1.3333), sheet, Vector2(0, 42), Vector3(20, 2, 2), 1.0, -1, rots) + _entity_box(qpos, qmeta, Vector3(1.3333, -12, 0), Vector3(14.6667, 14.6667, 1.3333), sheet, Vector2(0, 0), Vector3(20, 40, 2), 1.0, 0, rots) + else: + var rot := int(props.get("rotation", "0")) + var rots: Array = [["y", -rot * 22.5]] if rot != 0 else [] + _entity_box(qpos, qmeta, Vector3(7.3333, 0, 7.3333), Vector3(8.6667, 28, 8.6667), sheet, Vector2(44, 0), Vector3(2, 42, 2), 1.0, -1, rots) + _entity_box(qpos, qmeta, Vector3(1.3333, 28, 7.3333), Vector3(14.6667, 29.3333, 8.6667), sheet, Vector2(0, 42), Vector3(20, 2, 2), 1.0, -1, rots) + _entity_box(qpos, qmeta, Vector3(1.3333, 1.3333, 7.3333), Vector3(14.6667, 28, 8.6667), sheet, Vector2(0, 0), Vector3(20, 40, 2), 1.0, 0, rots) + return DYE_COLORS.get(cname, 0xFFFFFF) + + +## One box of a block-entity model. from/to are the box corners in 16-space (they may leave the +## block: banner cloth hangs into the block below, a chest latch crosses into the partner half). +## uv_off/uv_size give the entity box-UV layout in sheet pixels; uv_scale multiplies them (the +## dragon's sheet is drawn at 4x). tint is the model tintindex written to every face. +## rots are [axis, degrees] rotations about the block centre, applied in order. +func _entity_box(qpos: PackedFloat32Array, qmeta: PackedInt32Array, from: Vector3, to: Vector3, sheet: String, uv_off: Vector2, uv_size: Vector3, uv_scale: float, tint: int, rots: Array) -> void: + if not entity_sheets.has(sheet): + return + var dx := uv_size.x + var dy := uv_size.y + var dz := uv_size.z + var u := uv_off.x + var v := uv_off.y + var regions := { + UP: [u + dz, v, dx, dz], + DOWN: [u + dz + dx, v, dx, dz], + WEST: [u, v + dz, dz, dy], + NORTH: [u + dz, v + dz, dx, dy], + EAST: [u + dz + dx, v + dz, dz, dy], + SOUTH: [u + dz + dx + dz, v + dz, dx, dy], + } + for d in regions: + var r: Array = regions[d] + _entity_face(qpos, qmeta, d, from, to, sheet, Rect2(r[0] * uv_scale, r[1] * uv_scale, r[2] * uv_scale, r[3] * uv_scale), tint, rots) + + +func _entity_face(qpos: PackedFloat32Array, qmeta: PackedInt32Array, d: int, from: Vector3, to: Vector3, sheet: String, region: Rect2, tint: int, rots: Array) -> void: + var verts := _face_verts(d, [from.x, from.y, from.z], [to.x, to.y, to.z]) + for i in 4: + var p: Array = verts[i] + for r in rots: + p = _rotate_point(p, r[0], float(r[1]), [8.0, 8.0, 8.0], false) + verts[i] = p + var tiles: Vector2i = entity_sheets[sheet] + var xs := _split_points(region.position.x, region.position.x + region.size.x) + var ys := _split_points(region.position.y, region.position.y + region.size.y) + for xi in xs.size() - 1: + for yi in ys.size() - 1: + var a0: float = xs[xi] + var a1: float = xs[xi + 1] + var b0: float = ys[yi] + var b1: float = ys[yi + 1] + var tx := int(a0) / 16 + var ty := int(b0) / 16 + if tx >= tiles.x or ty >= tiles.y or a1 <= a0 or b1 <= b0: + continue + var tid := tex_id("%s#%d,%d" % [sheet, tx, ty]) + var corners := [] + for c in [[a0, b0], [a0, b1], [a1, b1], [a1, b0]]: + var su: float = (c[0] - region.position.x) / region.size.x + var sv: float = (c[1] - region.position.y) / region.size.y + corners.append([_bilinear(verts, su, sv), [(c[0] - tx * 16) / 16.0, (c[1] - ty * 16) / 16.0]]) + _emit_entity_quad(qpos, qmeta, corners, tid, tint) + + +static func _split_points(a: float, b: float) -> Array: + var out := [a] + var t := (floori(a / 16.0) + 1) * 16.0 + while t < b: + out.append(t) + t += 16.0 + out.append(b) + return out + + +static func _bilinear(verts: Array, su: float, sv: float) -> Array: + var out := [0.0, 0.0, 0.0] + var ws := [(1.0 - su) * (1.0 - sv), (1.0 - su) * sv, su * sv, su * (1.0 - sv)] + for i in 4: + for k in 3: + out[k] += verts[i][k] * ws[i] + return out + + +## corners: [[position (16-space), [u, v] in 0..1 of one sheet tile] x 4], in _face_verts order +func _emit_entity_quad(qpos: PackedFloat32Array, qmeta: PackedInt32Array, corners: Array, tid: int, tint: int) -> void: + var e1 := [corners[1][0][0] - corners[0][0][0], corners[1][0][1] - corners[0][0][1], corners[1][0][2] - corners[0][0][2]] + var e2 := [corners[2][0][0] - corners[0][0][0], corners[2][0][1] - corners[0][0][1], corners[2][0][2] - corners[0][0][2]] + var nrm := [e1[1] * e2[2] - e1[2] * e2[1], e1[2] * e2[0] - e1[0] * e2[2], e1[0] * e2[1] - e1[1] * e2[0]] + for i in 4: + qpos.append(corners[i][0][0] / 16.0) + qpos.append(corners[i][0][1] / 16.0) + qpos.append(corners[i][0][2] / 16.0) + for i in 4: + qpos.append(corners[i][1][0]) + qpos.append(corners[i][1][1]) + qmeta.append(tid) + qmeta.append(tint) + qmeta.append(NO_DIR) + qmeta.append(_dir_from_vec(nrm)) + qmeta.append(1) diff --git a/shaders/raster_persp.glsl b/shaders/raster_persp.glsl new file mode 100644 index 0000000..8658c7d --- /dev/null +++ b/shaders/raster_persp.glsl @@ -0,0 +1,191 @@ +#[vertex] +#version 450 + +// Perspective raster of baked quads with Dynmap-style shading: the same vertex data, atlas and +// fragment shading as raster.glsl, but the vertices are world positions projected with a real +// view-projection matrix (passed already converted to Vulkan clip space: y flipped, depth +// reversed so the greater-depth-wins test of the tile path keeps working). + +layout(constant_id = 0) const bool TRANS = false; + +layout(set = 0, binding = 0, std140) uniform U { + vec4 vp[4]; + vec2 size; + float p0; + float p1; + uint scale; + uint atlas_cols; + uint p2; + uint p3; + uvec4 shadow[4]; +} u; + +layout(set = 0, binding = 2, std430) readonly buffer VF { float vf[]; }; +layout(set = 0, binding = 3, std430) readonly buffer VI { uint vi[]; }; +layout(set = 0, binding = 4, std430) readonly buffer Chunks { vec4 chunk_off[]; }; // xyz = world offset of a chunk +layout(set = 0, binding = 5, std430) readonly buffer Order { uint order[]; }; // sorted quad indices (translucent pass) +layout(set = 0, binding = 6, std430) readonly buffer QChunk { uint qchunk[]; }; // chunk (offset table index) of each quad + +layout(location = 0) out vec2 o_uv; +layout(location = 1) flat out uint o_tf; +layout(location = 2) flat out uint o_color; +layout(location = 3) flat out uint o_light; +layout(location = 4) out vec3 o_local; + +const uint CORNER[6] = uint[6](0u, 1u, 2u, 0u, 2u, 3u); + +void main() { + uint qi = uint(gl_VertexIndex) / 6u; + uint corner = CORNER[uint(gl_VertexIndex) % 6u]; + uint quad = TRANS ? order[qi] : qi; + uint v = quad * 4u + corner; + uint fo = v * 8u; + vec3 p = vec3(vf[fo], vf[fo + 1u], vf[fo + 2u]); + vec3 wp = p + chunk_off[qchunk[quad]].xyz; + gl_Position = u.vp[0] * wp.x + u.vp[1] * wp.y + u.vp[2] * wp.z + u.vp[3]; + o_uv = vec2(vf[fo + 3u], vf[fo + 4u]); + o_local = vec3(vf[fo + 5u], vf[fo + 6u], vf[fo + 7u]); + uint io = v * 3u; + o_tf = vi[io]; + o_color = vi[io + 1u]; + o_light = vi[io + 2u]; +} + +#[fragment] +#version 450 + +layout(constant_id = 0) const bool TRANS = false; + +layout(set = 0, binding = 0, std140) uniform U { + vec4 vp[4]; + vec2 size; + float p0; + float p1; + uint scale; + uint atlas_cols; + uint p2; + uint p3; + uvec4 shadow[4]; +} u; + +layout(set = 0, binding = 1) uniform sampler2D atlas; + +layout(location = 0) in vec2 i_uv; +layout(location = 1) flat in uint i_tf; +layout(location = 2) flat in uint i_color; +layout(location = 3) flat in uint i_light; +layout(location = 4) in vec3 i_local; + +layout(location = 0) out vec4 frag; + +uint shadow_at(uint i) { + return u.shadow[i / 4u][i % 4u]; +} + +uint cscale_for(uint light, uint cls, vec3 local) { + int s = int(u.scale); + int mid = s / 2; + ivec3 sub = clamp(ivec3(floor(local * float(s))), ivec3(0), ivec3(s - 1)); + int c1 = 0; + int c2 = 0; + if (cls == 1u) { + c1 = sub.y; + c2 = sub.z; + } else if (cls == 2u) { + c1 = sub.x; + c2 = sub.y; + } else { + c1 = sub.x; + c2 = sub.z; + } + int lv0 = int(light & 15u); + int lv1 = int((light >> 8u) & 15u); + if (c1 < mid) { + lv1 = int((light >> 4u) & 15u); + } + int lv2 = int((light >> 16u) & 15u); + if (c2 < mid) { + lv2 = int((light >> 12u) & 15u); + } + int w1 = abs(c1 - mid); + int w2 = abs(c2 - mid); + int weight = 0; + if (lv1 < lv0) { + weight = weight - w1; + } else if (lv1 > lv0) { + weight = weight + w1; + } + if (lv2 < lv0) { + weight = weight - w2; + } else if (lv2 > lv0) { + weight = weight + w2; + } + int base = int(shadow_at(uint(lv0))); + if (weight == 0) { + return uint(base); + } + if (weight < 0) { + int w = -weight; + if (lv0 > 0) { + return uint((base * (s - w) + int(shadow_at(uint(lv0 - 1))) * w) / s); + } + return uint(base); + } + if (lv0 < 15) { + return uint((base * (s - weight) + int(shadow_at(uint(lv0 + 1))) * weight) / s); + } + return uint(base); +} + +void main() { + uint tex = i_tf & 0xFFFFu; + uint cls = (i_tf >> 16u) & 7u; + uint yeven = (i_tf >> 19u) & 1u; + int s = int(u.scale); + int cx = int(tex % u.atlas_cols) * s; + int cy = int(tex / u.atlas_cols) * s; + int tx = clamp(int(floor(i_uv.x * float(s))), 0, s - 1); + int ty = clamp(int(floor(i_uv.y * float(s))), 0, s - 1); + vec4 t = texelFetch(atlas, ivec2(cx + tx, cy + ty), 0); + uvec3 rgb = uvec3(roundEven(t.rgb * 255.0)); + uvec3 tint = uvec3((i_color >> 16u) & 255u, (i_color >> 8u) & 255u, i_color & 255u); + rgb = rgb * tint / 255u; + uint m = 255u; + if (cls == 1u) { + m = 0x99u; + } else if (cls == 2u) { + m = 0xCDu; + } else if (cls == 3u) { + if (yeven == 1u) { + m = 0xF3u; + } + } else if (cls == 4u) { + m = 0x80u; + } + uint noshade = (i_tf >> 20u) & 1u; + if (noshade == 1u) { + m = 255u; + } + rgb = rgb * m / 255u; + uint cs = cscale_for(i_light, cls, i_local); + if (noshade == 1u) { + cs = shadow_at(i_light & 15u); + } + if (cs < 256u) { + rgb = (rgb * cs) / 256u; + } + uint a = uint(roundEven(t.a * 255.0)); + vec3 col = vec3(rgb) / 255.0; + if (!TRANS) { + if (a < 255u) { + discard; + } + frag = vec4(col, 1.0); + } else { + if (a == 0u || a == 255u) { + discard; + } + float af = float(a) / 255.0; + frag = vec4(col * af, af); + } +}