test(M00): add checkpoint perceptual comparison #1

Merged
sindoring merged 2 commits from work/sindo-main-codex/m00-checkpoint-diff into master 2026-07-11 17:57:05 +03:00
9 changed files with 423 additions and 11 deletions
+4
View File
@@ -2,6 +2,10 @@
Воспроизводимый renderer baseline для текущей цели M00, regression manifest, метрики и правила сравнения описаны в [`docs/RENDER_BASELINE.md`](docs/RENDER_BASELINE.md). Baseline фиксирует текущее поведение и известные расхождения, но не заявляет parity с WoW 3.3.5a. Воспроизводимый renderer baseline для текущей цели M00, regression manifest, метрики и правила сравнения описаны в [`docs/RENDER_BASELINE.md`](docs/RENDER_BASELINE.md). Baseline фиксирует текущее поведение и известные расхождения, но не заявляет parity с WoW 3.3.5a.
Парные checkpoint PNG можно автоматически проверить через `src/tools/compare_render_checkpoints.gd`; reference-снимки оригинального клиента остаются вне Git, а автоматический tolerance не заменяет human fidelity approval.
Paired run 2026-07-11 подтвердил крупный coordinate/placement gap: некоторые server-derived camera positions оказываются под terrain или внутри WMO/rocks OpenWC. До исправления этого расхождения perceptual metrics измеряют также несовпадение композиции, а не только материалы и свет.
Цель renderer-работы в этом проекте: добиться ощущения производительности оригинального клиента WoW 3.3.5a в Godot, без видимых фризов при переходе ADT -> ADT и без постоянного отката видимых участков к низкому качеству. Цель renderer-работы в этом проекте: добиться ощущения производительности оригинального клиента WoW 3.3.5a в Godot, без видимых фризов при переходе ADT -> ADT и без постоянного отката видимых участков к низкому качеству.
Этот документ фиксирует текущее состояние рендера, сделанные оптимизации и практические правила дальнейшей работы. Этот документ фиксирует текущее состояние рендера, сделанные оптимизации и практические правила дальнейшей работы.
@@ -0,0 +1,78 @@
# M00-QAR-VISUAL-DIFF-001 — Renderer checkpoint visual diff
<!-- OPENWC_CLAIM:M00-QAR-VISUAL-DIFF-001:sindo-main-codex:2026-07-13 -->
## Ownership
- Target: M00
- Program: QAR
- Owner/Agent ID: sindo-main-codex
- Branch: `work/sindo-main-codex/m00-checkpoint-diff`
- Lease expires UTC: 2026-07-13
- Integrator: milestone integrator
## Outcome
Provide a deterministic, headless perceptual comparison for paired renderer checkpoint PNGs, with machine-readable results and synthetic regression coverage.
## Non-goals
- Supplying or committing original-client screenshots.
- Claiming visual parity or replacing human approval.
- Image registration, camera correction, or temporal animation matching.
## Paths
- Exclusive: `src/tools/compare_render_checkpoints.gd`
- Shared/hotspots: `src/tools/render_baseline_manifest.json`, `tools/run_render_baseline.ps1`, `docs/RENDER_BASELINE.md`, `docs/modules/world-renderer.md`, `RENDER.md`
- Generated/ignored: comparison reports, diff PNGs, original-client captures
## Contracts and data
- Public API/events: headless CLI arguments and JSON report documented in renderer baseline docs
- Schema/format version: comparison report schema 1; baseline manifest schema remains 1
- Migration/compatibility: additive manifest budget fields
- Consumers: developers and CI
## Dependencies
- Requires: Godot `Image` API and M00 checkpoint naming contract
- Blocks: automated portion of original-client paired comparison
- External state: approved build 12340 screenshots remain unavailable
## Verification
- Commands: headless self-test; manifest verification; documentation and coordination gates
- Fixtures: tool-generated identical and changed 2x2 PNGs
- Fidelity evidence: algorithm is deterministic; real-client evidence remains a manual/external input
- Performance budget: offline checkpoint operation, linear in pixel count
## Documentation deliverables
- Inline public API docs: CLI usage in script header
- Module specification: update renderer verification and source map
- Data-flow diagram: update baseline documentation
- Sequence/state/dependency diagrams: not stateful or asynchronous; not applicable
- Source map/status updates: renderer module and RENDER notes
## Simplicity and naming
- Important names introduced: `mean_perceptual_error`, `changed_pixel_ratio`
- Simplest considered solution: direct Godot Image iteration with no dependency
- Rejected complexity/abstractions: external image library, SSIM window pipeline, image registration
- Unavoidable complexity and justification: sRGB linearization avoids comparing encoded channel values directly
- Measured optimization evidence: not required for offline seven-checkpoint comparison
## Status
- State: ready
- Done: comparator, runner integration, manifest tolerance contract, synthetic regression, five local build 12340 references, three viewpoint calibrations, corrected visual capture and first paired report
- Next: integrator review; coordinate/placement gap should be resolved before tolerance calibration
- Blocked by: real paired screenshots only for final human fidelity approval
## Handoff
- Commit: branch HEAD
- Results: ten pairs compared with no missing candidates; mean error 0.0707..0.1746 and changed ratio 0.5504..0.8187; human review identified under-terrain/inside-geometry camera mismatches
- Remaining risks: coordinate/placement mismatch blocks meaningful tolerance calibration; synthetic animation, dusk and full human approval remain incomplete
- Documentation updated: `docs/RENDER_BASELINE.md`, `docs/modules/world-renderer.md`, `RENDER.md`
+47 -1
View File
@@ -24,6 +24,46 @@
- `<checkpoint>__cold_process.png` — первый визит в текущем процессе; - `<checkpoint>__cold_process.png` — первый визит в текущем процессе;
- `<checkpoint>__warm_revisit.png` — повторный визит в том же процессе после обхода контрольных точек. - `<checkpoint>__warm_revisit.png` — повторный визит в том же процессе после обхода контрольных точек.
## Парное визуальное сравнение
Одобренные снимки оригинального клиента хранятся вне Git. Если каталог с ними доступен локально, единый запуск может сразу сравнить PNG с одинаковыми именами:
```powershell
.\tools\run_render_baseline.ps1 `
-ReferenceCheckpointDirectory 'D:\private-fixtures\wow-3.3.5a-checkpoints'
```
Результат записывается в `user://render_baseline/visual_comparison.json`. Другой путь задаётся через `-VisualComparisonReport`. `-DryRun` несовместим с визуальным сравнением, потому что не создаёт PNG. Runner сохраняет обычный performance capture в нормативном `1280×900`, затем отдельно снимает visual candidates в `2560×1440`; разрешение можно переопределить через `-VisualComparisonWidth` и `-VisualComparisonHeight`, не меняя performance baseline.
Отдельный запуск сравнения:
```powershell
godot --headless --path . `
--script res://src/tools/compare_render_checkpoints.gd -- `
--reference 'D:\private-fixtures\wow-3.3.5a-checkpoints' `
--candidate "$env:APPDATA\Godot\app_userdata\OpenWC\render_baseline" `
--output user://render_baseline/visual_comparison.json
```
Reference-каталог принимает JPG/JPEG/PNG оригинального клиента с именем checkpoint, например `goldshire_dense_m2.jpg`. Диагностические кадры с префиксом `diagnostic_` игнорируются. Один reference автоматически сопоставляется с `<checkpoint>__cold_process.png` и `<checkpoint>__warm_revisit.png` OpenWC.
Сравнение переводит sRGB в linear color space, вычисляет взвешенную ошибку яркости/цвета для каждого пикселя, среднюю ошибку кадра и долю пикселей выше локального порога. Нормативные defaults находятся в `comparison_budgets` manifest: mean error `0.015`, changed-pixel ratio `0.01`, pixel error threshold `0.04`. Любое превышение, несовпадение размеров, отсутствие пары или пустой reference-каталог возвращает ненулевой exit code.
Автоматический pass не является доказательством parity: animation phase, weather, camera alignment и intentional gaps требуют human approval. Для проверки алгоритма без proprietary данных используется:
```powershell
godot --headless --path . --script res://src/tools/compare_render_checkpoints.gd -- --self-test
```
```mermaid
flowchart LR
R[Private approved reference PNGs] --> C[Checkpoint comparator]
N[New baseline PNGs] --> C
M[Manifest tolerance defaults] --> C
C --> J[JSON metrics and pass/fail]
J --> H[Human fidelity approval]
```
`cold_process` не означает очищенный Windows filesystem cache. Поле `cache_state` и полный inventory обязаны интерпретироваться вместе с результатом. Удаление или принудительная пересборка cache не входит в baseline-команду. Для отдельного запуска после контролируемой очистки безопасного локального cache следует передать осмысленную метку, например `-CacheState rebuilt-clean`; proprietary source assets команда не изменяет. `cold_process` не означает очищенный Windows filesystem cache. Поле `cache_state` и полный inventory обязаны интерпретироваться вместе с результатом. Удаление или принудительная пересборка cache не входит в baseline-команду. Для отдельного запуска после контролируемой очистки безопасного локального cache следует передать осмысленную метку, например `-CacheState rebuilt-clean`; proprietary source assets команда не изменяет.
## Контрольные точки и детерминизм ## Контрольные точки и детерминизм
@@ -38,7 +78,7 @@
- синтетический native-animation probe `GryphonRoost01.m2`; - синтетический native-animation probe `GryphonRoost01.m2`;
- тот же Elwynn overview в 19:00 для sky transition. - тот же Elwynn overview в 19:00 для sky transition.
Зафиксированы camera/target/player position, viewport, FOV, quality preset и время мира. Для temporal shader/animation кадров SHA-256 служит идентификатором артефакта, но не pass-критерием: будущая автоматическая визуальная проверка должна использовать perceptual diff и согласованный tolerance. Синтетический animation probe существует только внутри capture tool и не меняет runtime streaming scene. Зафиксированы camera/target/player position, viewport, FOV, quality preset и время мира. Для temporal shader/animation кадров SHA-256 служит идентификатором артефакта, но не самостоятельным pass-критерием: автоматическая визуальная проверка использует perceptual diff и согласованный tolerance. Синтетический animation probe существует только внутри capture tool и не меняет runtime streaming scene.
## Метрики и budget ## Метрики и budget
@@ -74,3 +114,9 @@ Baseline пока не имеет approved парных кадров ориги
- возможная смена D3D12 на Vulkan при ошибке descriptor heap — фактический backend всегда берётся из `report.json`. - возможная смена D3D12 на Vulkan при ошибке descriptor heap — фактический backend всегда берётся из `report.json`.
Парное сравнение с клиентом 3.3.5a должно использовать те же map position, local time и weather. Каждый gap регистрируется как terrain/material, placement, animation, lighting, liquid или culling; baseline сам по себе gap не закрывает. Парное сравнение с клиентом 3.3.5a должно использовать те же map position, local time и weather. Каждый gap регистрируется как terrain/material, placement, animation, lighting, liquid или culling; baseline сам по себе gap не закрывает.
Локальная сессия build 12340 от 2026-07-11 откалибровала три непригодные исходные позиции: dense-M2 camera была полностью закрыта кронами, large-WMO camera находилась у дымохода кузни, liquid camera попадала под terrain оригинального клиента. Manifest теперь содержит проверенные replacement camera positions. Пять approved локальных reference JPG хранятся вне Git; synthetic animated probe и dusk checkpoint всё ещё требуют отдельной процедуры.
Первый paired run после калибровки создал десять сравнений (пять reference × cold/warm), без missing pairs. Все пары ожидаемо превысили строгий tolerance: mean perceptual error `0.0707..0.1746`, changed-pixel ratio `0.5504..0.8187`. Human inspection показал, что это пока не чистая material/lighting ошибка: при тех же WoW-derived координатах OpenWC terrain-overview camera находится под terrain/placements, WMO camera — внутри таверны, liquid camera — внутри скал; ADT и dense-M2 композиции также существенно смещены. До исправления coordinate/placement mismatch эти значения являются gap evidence, а не основанием расширять tolerance.
Capture tool строит camera basis явно из target и world-up. Это исключает неоднозначный roll `look_at` при автоматической съёмке. `ViewportTexture.get_image()` сохраняется без дополнительного vertical flip для Godot 4.6.1.
+6 -3
View File
@@ -7,7 +7,7 @@
| Status | Partial | | Status | Partial |
| Target/work package | M00 active; декомпозиция M01–M03 | | Target/work package | M00 active; декомпозиция M01–M03 |
| Owners | Renderer workstream / milestone integrator | | Owners | Renderer workstream / milestone integrator |
| Last verified | `93bfe11` + M00 worktree baseline, 2026-07-10 | | Last verified | M00 visual-diff worktree, 2026-07-11 |
| Profiles/capabilities | `Performance`, `Balanced`, `High`, `Custom`; Blizzlike fidelity incomplete | | Profiles/capabilities | `Performance`, `Balanced`, `High`, `Custom`; Blizzlike fidelity incomplete |
## Purpose ## Purpose
@@ -192,9 +192,9 @@ Exact exported settings and cache versions remain documented in [`../../RENDER.m
## Verification ## Verification
- Unit/contract tests: material mapping, unique-ID dedupe, placement probes, baseline manifest. - Unit/contract tests: material mapping, unique-ID dedupe, placement probes, baseline manifest, synthetic perceptual checkpoint diff.
- Integration/E2E: Eastern Kingdoms/Kalimdor streaming scenes and seven cold/warm checkpoints. - Integration/E2E: Eastern Kingdoms/Kalimdor streaming scenes and seven cold/warm checkpoints.
- Fidelity evidence: current fixed-position captures exist; approved original-client paired screenshots are still missing. - Fidelity evidence: пять локальных build 12340 reference JPG откалибровали terrain/ADT/M2/WMO/liquid viewpoints; automated paired-image metrics exist, но synthetic animation/dusk и полный human approval ещё не закрыты.
- Performance budgets: M00 report records cold/warm p95 and max hitch; no final acceptance threshold yet. - Performance budgets: M00 report records cold/warm p95 and max hitch; no final acceptance threshold yet.
- Manual diagnostics: [`../RENDER_BASELINE.md`](../RENDER_BASELINE.md) and [`../../RENDER.md`](../../RENDER.md). - Manual diagnostics: [`../RENDER_BASELINE.md`](../RENDER_BASELINE.md) and [`../../RENDER.md`](../../RENDER.md).
@@ -222,6 +222,7 @@ Exact exported settings and cache versions remain documented in [`../../RENDER.m
- Monolithic streamer mixes planning, jobs, caches and presentation. - Monolithic streamer mixes planning, jobs, caches and presentation.
- Direct camera path remains until M01/M03. - Direct camera path remains until M01/M03.
- Original-client paired fidelity evidence incomplete. - Original-client paired fidelity evidence incomplete.
- Первый paired run выявил coordinate/placement mismatch: несколько совпадающих server-derived camera positions оказываются под terrain или внутри WMO/rocks OpenWC.
- D3D12 descriptor and shutdown RID/resource issues remain. - D3D12 descriptor and shutdown RID/resource issues remain.
- M2/WMO/material/particle/ribbon/portal parity incomplete. - M2/WMO/material/particle/ribbon/portal parity incomplete.
- Public API is mostly exported configuration rather than stable contracts. - Public API is mostly exported configuration rather than stable contracts.
@@ -239,6 +240,8 @@ Exact exported settings and cache versions remain documented in [`../../RENDER.m
| `src/native/src/*_loader.cpp` | Native binary parsing | | `src/native/src/*_loader.cpp` | Native binary parsing |
| `src/tools/build_*cache.gd`, `src/tools/bake_*cache.gd` | Offline cache generation | | `src/tools/build_*cache.gd`, `src/tools/bake_*cache.gd` | Offline cache generation |
| `tools/run_render_baseline.ps1` | Unified M00 baseline runner | | `tools/run_render_baseline.ps1` | Unified M00 baseline runner |
| `src/tools/compare_render_checkpoints.gd` | Offline JPG/PNG paired-image perceptual metrics and JSON pass/fail report |
| `src/tools/capture_render_checkpoints.gd` | Deterministic no-roll checkpoint camera, performance and visual capture |
## Related decisions and references ## Related decisions and references
+13 -3
View File
@@ -25,7 +25,9 @@ func _capture_async() -> void:
var headless := DisplayServer.get_name().to_lower() == "headless" var headless := DisplayServer.get_name().to_lower() == "headless"
var dry_run := args.has("--dry-run") or headless var dry_run := args.has("--dry-run") or headless
var viewport: Array = manifest.get("viewport", [1280, 900]) var viewport: Array = manifest.get("viewport", [1280, 900])
get_root().size = Vector2i(maxi(16, int(viewport[0])), maxi(16, int(viewport[1]))) var viewport_width := int(_arg(args, "--viewport-width", str(viewport[0])))
var viewport_height := int(_arg(args, "--viewport-height", str(viewport[1])))
get_root().size = Vector2i(maxi(16, viewport_width), maxi(16, viewport_height))
var abs_output_dir := ProjectSettings.globalize_path(output_dir) var abs_output_dir := ProjectSettings.globalize_path(output_dir)
DirAccess.make_dir_recursive_absolute(abs_output_dir) DirAccess.make_dir_recursive_absolute(abs_output_dir)
@@ -107,7 +109,7 @@ func _capture_async() -> void:
probe.scale = Vector3.ONE * float(checkpoint.get("probe_scale", 1.0)) probe.scale = Vector3.ONE * float(checkpoint.get("probe_scale", 1.0))
camera.global_position = _vector3(checkpoint.get("camera", [0.0, 0.0, 0.0])) camera.global_position = _vector3(checkpoint.get("camera", [0.0, 0.0, 0.0]))
camera.look_at(_vector3(checkpoint.get("target", [0.0, 0.0, 0.0])), Vector3.UP) _orient_camera_without_roll(camera, _vector3(checkpoint.get("target", [0.0, 0.0, 0.0])))
if player != null: if player != null:
player.global_position = _vector3(checkpoint.get("player", checkpoint.get("target", [0.0, 0.0, 0.0]))) player.global_position = _vector3(checkpoint.get("player", checkpoint.get("target", [0.0, 0.0, 0.0])))
_set_sky_time(world, float(checkpoint.get("time_hours", 13.0))) _set_sky_time(world, float(checkpoint.get("time_hours", 13.0)))
@@ -135,7 +137,6 @@ func _capture_async() -> void:
await RenderingServer.frame_post_draw await RenderingServer.frame_post_draw
var image := get_root().get_texture().get_image() var image := get_root().get_texture().get_image()
image.flip_y()
var file_name := "%s__%s.png" % [checkpoint_name, pass_name] var file_name := "%s__%s.png" % [checkpoint_name, pass_name]
var abs_path := abs_output_dir.path_join(file_name) var abs_path := abs_output_dir.path_join(file_name)
var err := image.save_png(abs_path) var err := image.save_png(abs_path)
@@ -196,6 +197,15 @@ func _measure_frames(seconds: float, world: Node) -> Dictionary:
} }
func _orient_camera_without_roll(camera: Camera3D, target_position: Vector3) -> void:
var forward := (target_position - camera.global_position).normalized()
var right := forward.cross(Vector3.UP).normalized()
if right.is_zero_approx():
right = Vector3.RIGHT
var corrected_up := right.cross(forward).normalized()
camera.global_basis = Basis(right, corrected_up, -forward)
func _result_record(checkpoint: Dictionary, pass_name: String, load_time_ms: float, metrics: Dictionary, sha256: String) -> Dictionary: func _result_record(checkpoint: Dictionary, pass_name: String, load_time_ms: float, metrics: Dictionary, sha256: String) -> Dictionary:
return { return {
"name": checkpoint.get("name", "checkpoint"), "name": checkpoint.get("name", "checkpoint"),
+229
View File
@@ -0,0 +1,229 @@
extends SceneTree
## Compares original-client JPG/PNG references with OpenWC checkpoint PNGs.
## Usage: godot --headless --path . --script res://src/tools/compare_render_checkpoints.gd --
## --reference <directory> --candidate <directory> [--output <report.json>]
## [--pixel-threshold 0.04] [--mean-threshold 0.015] [--changed-ratio-threshold 0.01]
## Use --self-test for a synthetic regression check that writes only under user://.
const REPORT_SCHEMA_VERSION := 1
const DEFAULT_PIXEL_THRESHOLD := 0.04
const DEFAULT_MEAN_THRESHOLD := 0.015
const DEFAULT_CHANGED_RATIO_THRESHOLD := 0.01
func _initialize() -> void:
var arguments := _parse_arguments(OS.get_cmdline_user_args())
if arguments.has("error"):
push_error("RENDER_CHECKPOINT_DIFF: %s" % arguments.error)
quit(2)
return
if arguments.get("self_test", false):
quit(_run_self_test())
return
var reference_directory := String(arguments.get("reference", ""))
var candidate_directory := String(arguments.get("candidate", ""))
if reference_directory.is_empty() or candidate_directory.is_empty():
push_error("RENDER_CHECKPOINT_DIFF: --reference and --candidate are required")
quit(2)
return
var report := _compare_directories(reference_directory, candidate_directory, arguments)
var output_path := String(arguments.get("output", ""))
if not output_path.is_empty() and not _write_report(output_path, report):
quit(2)
return
print("RENDER_CHECKPOINT_DIFF %s compared=%d failed=%d missing=%d" % [
"PASS" if report.passed else "FAIL",
report.compared_count,
report.failed_count,
report.missing_count,
])
quit(0 if report.passed else 1)
func _parse_arguments(raw_arguments: PackedStringArray) -> Dictionary:
var parsed := {
"pixel_threshold": DEFAULT_PIXEL_THRESHOLD,
"mean_threshold": DEFAULT_MEAN_THRESHOLD,
"changed_ratio_threshold": DEFAULT_CHANGED_RATIO_THRESHOLD,
}
var index := 0
while index < raw_arguments.size():
var argument := raw_arguments[index]
if argument == "--self-test":
parsed.self_test = true
index += 1
continue
if argument not in ["--reference", "--candidate", "--output", "--pixel-threshold", "--mean-threshold", "--changed-ratio-threshold"]:
return {"error": "unknown argument: %s" % argument}
if index + 1 >= raw_arguments.size():
return {"error": "missing value for %s" % argument}
var key := argument.trim_prefix("--").replace("-", "_")
var value := raw_arguments[index + 1]
if key.ends_with("threshold"):
if not value.is_valid_float():
return {"error": "%s requires a number" % argument}
parsed[key] = float(value)
else:
parsed[key] = value
index += 2
return parsed
func _compare_directories(reference_directory: String, candidate_directory: String, options: Dictionary) -> Dictionary:
reference_directory = ProjectSettings.globalize_path(reference_directory)
candidate_directory = ProjectSettings.globalize_path(candidate_directory)
var reference_files := _reference_image_file_names(reference_directory)
var results: Array[Dictionary] = []
var failed_count := 0
var missing_count := 0
for file_name in reference_files:
var reference_path := reference_directory.path_join(file_name)
var checkpoint_name := file_name.get_basename()
var candidate_file_names := _candidate_file_names(candidate_directory, checkpoint_name)
if candidate_file_names.is_empty():
results.append({"checkpoint": checkpoint_name, "reference": file_name, "status": "missing_candidate"})
missing_count += 1
continue
for candidate_file_name in candidate_file_names:
var candidate_path := candidate_directory.path_join(candidate_file_name)
var comparison := _compare_images(reference_path, candidate_path, options)
comparison.checkpoint = checkpoint_name
comparison.reference = file_name
comparison.candidate = candidate_file_name
results.append(comparison)
if comparison.status != "passed":
failed_count += 1
var no_reference_images := reference_files.is_empty()
return {
"schema_version": REPORT_SCHEMA_VERSION,
"passed": not no_reference_images and failed_count == 0 and missing_count == 0,
"reference_directory": reference_directory,
"candidate_directory": candidate_directory,
"pixel_threshold": options.pixel_threshold,
"mean_threshold": options.mean_threshold,
"changed_ratio_threshold": options.changed_ratio_threshold,
"compared_count": results.size() - missing_count,
"failed_count": failed_count,
"missing_count": missing_count,
"no_reference_images": no_reference_images,
"results": results,
}
func _compare_images(reference_path: String, candidate_path: String, options: Dictionary) -> Dictionary:
var reference_image := Image.load_from_file(reference_path)
var candidate_image := Image.load_from_file(candidate_path)
if reference_image == null or candidate_image == null or reference_image.is_empty() or candidate_image.is_empty():
return {"status": "load_error"}
if reference_image.get_size() != candidate_image.get_size():
return {
"status": "size_mismatch",
"reference_size": [reference_image.get_width(), reference_image.get_height()],
"candidate_size": [candidate_image.get_width(), candidate_image.get_height()],
}
var error_sum := 0.0
var changed_pixel_count := 0
var pixel_count := reference_image.get_width() * reference_image.get_height()
for y in reference_image.get_height():
for x in reference_image.get_width():
var perceptual_error := _perceptual_color_error(reference_image.get_pixel(x, y), candidate_image.get_pixel(x, y))
error_sum += perceptual_error
if perceptual_error > float(options.pixel_threshold):
changed_pixel_count += 1
var mean_perceptual_error := error_sum / float(pixel_count)
var changed_pixel_ratio := float(changed_pixel_count) / float(pixel_count)
var passed := mean_perceptual_error <= float(options.mean_threshold) and changed_pixel_ratio <= float(options.changed_ratio_threshold)
return {
"status": "passed" if passed else "threshold_exceeded",
"width": reference_image.get_width(),
"height": reference_image.get_height(),
"mean_perceptual_error": mean_perceptual_error,
"changed_pixel_ratio": changed_pixel_ratio,
}
func _perceptual_color_error(reference_color: Color, candidate_color: Color) -> float:
var reference_linear := reference_color.srgb_to_linear()
var candidate_linear := candidate_color.srgb_to_linear()
var red_delta := absf(reference_linear.r - candidate_linear.r)
var green_delta := absf(reference_linear.g - candidate_linear.g)
var blue_delta := absf(reference_linear.b - candidate_linear.b)
var alpha_delta := absf(reference_linear.a - candidate_linear.a)
return 0.2126 * red_delta + 0.7152 * green_delta + 0.0722 * blue_delta + 0.25 * alpha_delta
func _reference_image_file_names(directory_path: String) -> Array[String]:
var directory := DirAccess.open(directory_path)
if directory == null:
return []
var file_names: Array[String] = []
for file_name in directory.get_files():
var lower_name := file_name.to_lower()
if not lower_name.begins_with("diagnostic_") and (lower_name.ends_with(".png") or lower_name.ends_with(".jpg") or lower_name.ends_with(".jpeg")):
file_names.append(file_name)
file_names.sort()
return file_names
func _candidate_file_names(candidate_directory: String, checkpoint_name: String) -> Array[String]:
var candidates: Array[String] = []
for pass_name in ["cold_process", "warm_revisit"]:
var file_name := "%s__%s.png" % [checkpoint_name, pass_name]
if FileAccess.file_exists(candidate_directory.path_join(file_name)):
candidates.append(file_name)
if candidates.is_empty():
var exact_file_name := "%s.png" % checkpoint_name
if FileAccess.file_exists(candidate_directory.path_join(exact_file_name)):
candidates.append(exact_file_name)
return candidates
func _write_report(output_path: String, report: Dictionary) -> bool:
var absolute_path := ProjectSettings.globalize_path(output_path)
var error := DirAccess.make_dir_recursive_absolute(absolute_path.get_base_dir())
if error != OK:
push_error("RENDER_CHECKPOINT_DIFF: cannot create report directory: %s" % error_string(error))
return false
var report_file := FileAccess.open(absolute_path, FileAccess.WRITE)
if report_file == null:
push_error("RENDER_CHECKPOINT_DIFF: cannot write report: %s" % output_path)
return false
report_file.store_string(JSON.stringify(report, " "))
return true
func _run_self_test() -> int:
var root := "user://render_checkpoint_diff_self_test"
var reference_directory := root.path_join("reference")
var identical_directory := root.path_join("identical")
var changed_directory := root.path_join("changed")
for directory_path in [reference_directory, identical_directory, changed_directory]:
DirAccess.make_dir_recursive_absolute(ProjectSettings.globalize_path(directory_path))
var reference_image := Image.create(2, 2, false, Image.FORMAT_RGBA8)
reference_image.fill(Color(0.25, 0.5, 0.75, 1.0))
var changed_image := reference_image.duplicate()
changed_image.set_pixel(0, 0, Color.WHITE)
if reference_image.save_jpg(reference_directory.path_join("synthetic.jpg"), 1.0) != OK:
push_error("RENDER_CHECKPOINT_DIFF SELF_TEST: cannot save JPG reference")
return 1
for pass_name in ["cold_process", "warm_revisit"]:
if reference_image.save_png(identical_directory.path_join("synthetic__%s.png" % pass_name)) != OK:
return 1
if changed_image.save_png(changed_directory.path_join("synthetic__%s.png" % pass_name)) != OK:
return 1
var options := {
"pixel_threshold": DEFAULT_PIXEL_THRESHOLD,
"mean_threshold": DEFAULT_MEAN_THRESHOLD,
"changed_ratio_threshold": DEFAULT_CHANGED_RATIO_THRESHOLD,
}
var identical_report := _compare_directories(reference_directory, identical_directory, options)
var changed_report := _compare_directories(reference_directory, changed_directory, options)
if not identical_report.passed or changed_report.passed:
push_error("RENDER_CHECKPOINT_DIFF SELF_TEST: expected identical pass and changed failure")
return 1
print("RENDER_CHECKPOINT_DIFF SELF_TEST PASS")
return 0
+8 -4
View File
@@ -5,6 +5,7 @@
"map": "Azeroth", "map": "Azeroth",
"quality_preset": "High", "quality_preset": "High",
"viewport": [1280, 900], "viewport": [1280, 900],
"fidelity_comparison_viewport": [2560, 1440],
"camera_fov": 62.0, "camera_fov": 62.0,
"default_wait_seconds": 8.0, "default_wait_seconds": 8.0,
"default_measure_seconds": 3.0, "default_measure_seconds": 3.0,
@@ -14,7 +15,10 @@
"max_hitch_ms_max_regression_percent": 10.0, "max_hitch_ms_max_regression_percent": 10.0,
"load_time_ms_max_regression_percent": 10.0, "load_time_ms_max_regression_percent": 10.0,
"memory_bytes_max_regression_percent": 10.0, "memory_bytes_max_regression_percent": 10.0,
"visual_diff": "perceptual comparison required; exact PNG hashes are evidence, not an animated-scene pass criterion" "visual_mean_perceptual_error_max": 0.015,
"visual_changed_pixel_ratio_max": 0.01,
"visual_pixel_error_threshold": 0.04,
"visual_diff": "automated thresholds require human approval; exact PNG hashes are evidence, not an animated-scene pass criterion"
}, },
"required_coverage": [ "required_coverage": [
"terrain", "terrain",
@@ -54,7 +58,7 @@
{ {
"name": "goldshire_dense_m2", "name": "goldshire_dense_m2",
"coverage": ["dense_m2"], "coverage": ["dense_m2"],
"camera": [16835.0, 135.0, 26435.0], "camera": [16956.666, 150.0, 26466.666],
"target": [17015.0, 62.0, 26525.0], "target": [17015.0, 62.0, 26525.0],
"player": [17015.0, 58.0, 26525.0], "player": [17015.0, 58.0, 26525.0],
"time_hours": 13.0 "time_hours": 13.0
@@ -62,7 +66,7 @@
{ {
"name": "goldshire_inn_large_wmo", "name": "goldshire_inn_large_wmo",
"coverage": ["large_wmo"], "coverage": ["large_wmo"],
"camera": [16942.0, 82.0, 26503.0], "camera": [17013.666, 72.0, 26451.666],
"target": [17042.27, 66.0, 26530.91], "target": [17042.27, 66.0, 26530.91],
"player": [17042.27, 58.0, 26530.91], "player": [17042.27, 58.0, 26530.91],
"time_hours": 13.0 "time_hours": 13.0
@@ -70,7 +74,7 @@
{ {
"name": "elwynn_waterfall_liquid", "name": "elwynn_waterfall_liquid",
"coverage": ["liquid"], "coverage": ["liquid"],
"camera": [16445.0, 125.0, 26295.0], "camera": [16481.666, 190.0, 26366.666],
"target": [16518.84, 68.0, 26427.27], "target": [16518.84, 68.0, 26427.27],
"player": [16518.84, 55.0, 26427.27], "player": [16518.84, 55.0, 26427.27],
"time_hours": 13.0 "time_hours": 13.0
@@ -20,6 +20,8 @@ func _initialize() -> void:
_expect(int(manifest.get("schema_version", 0)) == 1, "manifest schema must be version 1", failures) _expect(int(manifest.get("schema_version", 0)) == 1, "manifest schema must be version 1", failures)
_expect(String(manifest.get("profile", "")) == "Blizzlike335", "manifest profile must be Blizzlike335", failures) _expect(String(manifest.get("profile", "")) == "Blizzlike335", "manifest profile must be Blizzlike335", failures)
_expect(ResourceLoader.exists(String(manifest.get("scene", ""))), "streaming scene must exist", failures) _expect(ResourceLoader.exists(String(manifest.get("scene", ""))), "streaming scene must exist", failures)
var fidelity_viewport: Array = manifest.get("fidelity_comparison_viewport", [])
_expect(fidelity_viewport.size() == 2 and int(fidelity_viewport[0]) > 0 and int(fidelity_viewport[1]) > 0, "fidelity comparison viewport must contain positive width and height", failures)
var covered := {} var covered := {}
var names := {} var names := {}
@@ -42,6 +44,11 @@ func _initialize() -> void:
var required := String(required_variant) var required := String(required_variant)
_expect(covered.has(required), "missing checkpoint coverage: %s" % required, failures) _expect(covered.has(required), "missing checkpoint coverage: %s" % required, failures)
var comparison_budgets: Dictionary = manifest.get("comparison_budgets", {})
for threshold_name in ["visual_mean_perceptual_error_max", "visual_changed_pixel_ratio_max", "visual_pixel_error_threshold"]:
var threshold := float(comparison_budgets.get(threshold_name, -1.0))
_expect(threshold >= 0.0 and threshold <= 1.0, "%s must be between 0 and 1" % threshold_name, failures)
var contract: Dictionary = manifest.get("cache_contract", {}) var contract: Dictionary = manifest.get("cache_contract", {})
var actual_versions := { var actual_versions := {
"baked_terrain": STREAMING_LOADER.REQUIRED_BAKED_TILE_FORMAT_VERSION, "baked_terrain": STREAMING_LOADER.REQUIRED_BAKED_TILE_FORMAT_VERSION,
+31
View File
@@ -5,6 +5,10 @@ param(
[string]$CacheState = "existing", [string]$CacheState = "existing",
[double]$WaitSeconds = 8.0, [double]$WaitSeconds = 8.0,
[double]$MeasureSeconds = 3.0, [double]$MeasureSeconds = 3.0,
[string]$ReferenceCheckpointDirectory,
[string]$VisualComparisonReport = "user://render_baseline/visual_comparison.json",
[int]$VisualComparisonWidth = 2560,
[int]$VisualComparisonHeight = 1440,
[switch]$DryRun [switch]$DryRun
) )
@@ -57,6 +61,33 @@ try {
$captureArgs = @("--headless") + $captureArgs + @("--dry-run") $captureArgs = @("--headless") + $captureArgs + @("--dry-run")
} }
Invoke-GodotStep "capture" $captureArgs Invoke-GodotStep "capture" $captureArgs
if ($ReferenceCheckpointDirectory) {
if ($DryRun) {
throw "Reference checkpoint comparison requires PNG capture; remove -DryRun"
}
$visualCandidateOutput = "$Output/visual_comparison_candidates"
$visualCaptureArgs = @(
"--path", ".",
"--script", "res://src/tools/capture_render_checkpoints.gd",
"--",
"--output", $visualCandidateOutput,
"--cache-state", $CacheState,
"--revision", $revision,
"--wait", $WaitSeconds.ToString([Globalization.CultureInfo]::InvariantCulture),
"--measure", $MeasureSeconds.ToString([Globalization.CultureInfo]::InvariantCulture),
"--viewport-width", $VisualComparisonWidth.ToString(),
"--viewport-height", $VisualComparisonHeight.ToString()
)
Invoke-GodotStep "visual-capture" $visualCaptureArgs
Invoke-GodotStep "visual-comparison" @(
"--headless", "--path", ".",
"--script", "res://src/tools/compare_render_checkpoints.gd",
"--",
"--reference", $ReferenceCheckpointDirectory,
"--candidate", $visualCandidateOutput,
"--output", $VisualComparisonReport
)
}
Write-Host "Renderer baseline completed. Report: $Output/report.json" Write-Host "Renderer baseline completed. Report: $Output/report.json"
} finally { } finally {
Pop-Location Pop-Location