Refactor save manager validation and update state structure
- Updated the save manager to enforce a new format version (2) and improved validation checks for the save data structure. - Enhanced the `validate_data` function to ensure all required fields are present and valid. - Adjusted the handling of legacy saves and introduced new checks for various state fields. - Improved number formatting in the global script for better readability of large numbers. - Updated tests to reflect changes in the save manager and validation logic, ensuring compatibility with the new state structure. - Added new tests for group indexing and production transactions to ensure correctness of entity management and resource production.
This commit is contained in:
+4
-4
@@ -8,14 +8,14 @@ godot --headless --path Owniverse.GI --script res://tests/test_time.gd
|
||||
|
||||
Команда выполняется из общей папки проектов. Тесты используют искусственные состояния; сохранение игрока не читается и не перезаписывается.
|
||||
|
||||
Проверяются границы десятых долей года, производство ресурсов на этих границах, накопление дробного остатка, скорости 1–10 000 лет/сек, продолжение после загрузки, недопустимые интервалы и миграция сохранений.
|
||||
Проверяются границы десятых долей года, производство ресурсов на этих границах, накопление дробного остатка, скорости 1–10 000 лет/сек, продолжение после загрузки и недопустимые интервалы.
|
||||
|
||||
Схема состояния `0.1.1` хранит:
|
||||
|
||||
- `time.datetime` — накопленный возраст, включая необработанную дробную часть;
|
||||
- `time.year` — последний рассчитанный возраст с точностью до десятой доли года.
|
||||
|
||||
Сохранения `0.1.0` проходят старую проверку целого года. При загрузке стадией игры оставшийся промежуток до последней десятой рассчитывается ровно один раз, после чего применяется версия `0.1.1`. Оставшаяся часть меньше 0,1 года сохраняется.
|
||||
Сохранения используют только актуальную структуру состояния и не поддерживают прежние форматы.
|
||||
|
||||
## Согласованные правила эволюции
|
||||
|
||||
@@ -55,7 +55,7 @@ godot --headless --path Owniverse.GI --script res://tests/test_life.gd
|
||||
|
||||
Проверяются абиогенез, деградация, повторные попытки без создания дополнительных планет, появление C0.0 на прежней звезде, остатки вероятностей, сохранение/продолжение, однократная инициализация старых планет и отсутствие воскрешения после бластов.
|
||||
|
||||
Проверка загрузки этических правил, миграции распределений и отделения космических цивилизаций:
|
||||
Проверка загрузки этических правил, распределений и отделения космических цивилизаций:
|
||||
|
||||
```sh
|
||||
godot --headless --path Owniverse.GI --script res://tests/test_civilization_state.gd
|
||||
@@ -70,4 +70,4 @@ godot --headless --path Owniverse.GI --script res://tests/test_civilization_stat
|
||||
godot --headless --path Owniverse.GI --script res://tests/test_civilization_evolution.gd
|
||||
```
|
||||
|
||||
Проверяются реальные коэффициенты C0.2, войны и побочный ущерб C2.0, замена планет колониями с сохранением хозяина, дипломатическое влияние, бонус периода от структур и деградация при их отсутствии. Ускоренная модель проходит все стадии C0.2 → C4.4 → Ct. Проверки контролируют сохранение населения, целочисленность этик, валидацию сохранения и детерминированное продолжение после сериализации. Миграция часов цивилизаций использует `life_version = 3`.
|
||||
Проверяются реальные коэффициенты C0.2, войны и побочный ущерб C2.0, замена планет колониями с сохранением хозяина, дипломатическое влияние, бонус периода от структур и деградация при их отсутствии. Ускоренная модель проходит все стадии C0.2 → C4.4 → Ct. Проверки контролируют сохранение населения, целочисленность этик, валидацию сохранения и детерминированное продолжение после сериализации.
|
||||
|
||||
@@ -52,7 +52,7 @@ func invariants(world) -> void:
|
||||
check(sum_ethics(world, id) == physical.get(id, 0.0), "Ethics equal physical population for " + id)
|
||||
for n in world.state.ethics[id].values():
|
||||
if n < 0.0 or n != floorf(n): check(false, "Invalid ethic amount")
|
||||
check(root.get_node("SaveManager").validate_data({"state": world.state}) == "", "Civilization state validates")
|
||||
check(root.get_node("SaveManager").validate_data({"format_version": 2, "app_version": "", "ui": {"current_page": 0}, "state": world.state}) == "", "Civilization state validates")
|
||||
|
||||
func run() -> void:
|
||||
var global: Node = root.get_node("Global")
|
||||
|
||||
@@ -58,7 +58,7 @@ func run() -> void:
|
||||
world.state.amount["C0.2"] = 3.0
|
||||
world.initialize_life_batches()
|
||||
check(world.state.ethics["C0.2"].m == 3.0, "Losses reduce ethics without inventing population")
|
||||
check(root.get_node("SaveManager").validate_data({"state": world.state}) == "", "Ethics state validates")
|
||||
check(root.get_node("SaveManager").validate_data({"format_version": 2, "app_version": "", "ui": {"current_page": 0}, "state": world.state}) == "", "Ethics state validates")
|
||||
var restored = fixture()
|
||||
restored.state = bytes_to_var(var_to_bytes(world.state))
|
||||
restored.initialize_life_batches()
|
||||
@@ -116,7 +116,7 @@ func run() -> void:
|
||||
world.initialize_life_batches()
|
||||
check(world.state.amount["C4.2"] == 2.0, "SMBH capacity uses stellar mass equivalent")
|
||||
check(world._physical_amounts(world.state)["C1.9"] == 1.0, "Unsupported civilization degrades through missing habitat families")
|
||||
check(root.get_node("SaveManager").validate_data({"state": world.state}) == "", "Capacity-limited state validates")
|
||||
check(root.get_node("SaveManager").validate_data({"format_version": 2, "app_version": "", "ui": {"current_page": 0}, "state": world.state}) == "", "Capacity-limited state validates")
|
||||
dispose(world)
|
||||
|
||||
world = fixture()
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
extends SceneTree
|
||||
const Clock = preload("res://world/owniverse/simulation_time.gd")
|
||||
var checks: int = 0
|
||||
var failures: int = 0
|
||||
|
||||
func _initialize() -> void:
|
||||
call_deferred("run")
|
||||
|
||||
func check(condition: bool, message: String) -> void:
|
||||
checks += 1
|
||||
if not condition:
|
||||
failures += 1
|
||||
push_error(message)
|
||||
|
||||
func fixture():
|
||||
var world = load("res://world/owniverse/owniverse.gd").new()
|
||||
var global: Node = root.get_node("Global")
|
||||
for id in global.OwniverseEntities:
|
||||
var entity = load("res://world/owniverse/owniverse_entity.gd").new(global.OwniverseEntities[id])
|
||||
world.entities[id] = entity
|
||||
world.state.amount[id] = 0.0
|
||||
world.state.stats.total_amount[id] = 0.0
|
||||
if entity.group_as != "":
|
||||
world.state.amount[entity.group_as] = 0.0
|
||||
world.state.stats.total_amount[entity.group_as] = 0.0
|
||||
world.entities["N"].life_product = {}
|
||||
world.entities["N"].product_per_year_type = "H"
|
||||
world.entities["N"].product_per_year_amount = 10.0
|
||||
world.entities["N"].auto = 0.0
|
||||
world.state.amount.N = 1.0
|
||||
return world
|
||||
|
||||
func dispose(world) -> void:
|
||||
for entity in world.entities.values():
|
||||
entity.free()
|
||||
world.free()
|
||||
|
||||
func run() -> void:
|
||||
var world = fixture()
|
||||
for id in world.entities:
|
||||
var expected: Array = []
|
||||
for key in world.entities:
|
||||
if world.entities[key].group_as == id:
|
||||
expected.append(key)
|
||||
check(world._is_group(id) == (not expected.is_empty()), "Group classification: " + id)
|
||||
check(world._members(id) == (expected if not expected.is_empty() else [id]), "Group members: " + id)
|
||||
var members: Array = world._members("Star")
|
||||
members.clear()
|
||||
check(not world._members("Star").is_empty(), "Returned members are independent")
|
||||
world.entities.N.group_as = "TestGroup"
|
||||
world.rebuild_group_index()
|
||||
check(world._members("TestGroup") == ["N"], "Explicit definition reload")
|
||||
world.entities.N.free()
|
||||
world.entities.erase("N")
|
||||
check(not world._is_group("TestGroup"), "Removed definition invalidates index")
|
||||
print("Group index: %d checks, %d failures" % [checks, failures])
|
||||
dispose(world)
|
||||
quit(1 if failures else 0)
|
||||
@@ -0,0 +1 @@
|
||||
uid://bykrkembtacbw
|
||||
+4
-5
@@ -53,7 +53,7 @@ func run() -> void:
|
||||
check(world.state.batches.HP.size() > 0, "Survivors get next attempt")
|
||||
var physical: Dictionary = world._physical_amounts(world.state)
|
||||
check(physical.HP + physical.EON1 + physical.RP == 40000.0, "Life conserves planets")
|
||||
check(root.get_node("SaveManager").validate_data({"state": world.state}) == "", "Life save validates")
|
||||
check(root.get_node("SaveManager").validate_data({"format_version": 2, "app_version": "", "ui": {"current_page": 0}, "state": world.state}) == "", "Life save validates")
|
||||
var restored = fixture()
|
||||
restored.state = bytes_to_var(var_to_bytes(world.state))
|
||||
world._evolve_batches(world.state, 11e6)
|
||||
@@ -100,13 +100,12 @@ func run() -> void:
|
||||
dispose(world)
|
||||
world = fixture()
|
||||
world.state.time = {"datetime": 123.4, "year": 123.4}
|
||||
world.state.life_version = 1
|
||||
world.state.amount["C0.0"] = 40000.0
|
||||
world.initialize_life_batches()
|
||||
check(world.state.life_version == 3 and world.state.batches["C0.0"][0].created_from == 123.4, "Previous life saves receive missing civilization cohorts")
|
||||
check(world.state.batches["C0.0"][0].created_from == 123.4, "Civilization cohorts begin at the current time")
|
||||
before = world.state.duplicate(true)
|
||||
world.initialize_life_batches()
|
||||
check(world.state == before, "Second life migration is idempotent")
|
||||
check(world.state == before, "Life batch initialization is idempotent")
|
||||
world._evolve_batches(world.state, 2173.4)
|
||||
check(world.state.amount["C0.1"] == 700.0 and world.state.amount.EON5 == 1000.0, "C0.0 progresses and degrades by Unity rates")
|
||||
check(world.state.amount["C0.0"] == 38300.0, "C0.0 remainder stays alive")
|
||||
@@ -118,7 +117,7 @@ func run() -> void:
|
||||
world._evolve_batches(world.state, 2050.0)
|
||||
check(world.state.binds.RD["C0.2"] == 700.0, "C0.1 reaches ethical civilization without losing host")
|
||||
check(world.state.binds.RD["C0.0"] == 1000.0, "C0.1 degradation follows Unity")
|
||||
check(root.get_node("SaveManager").validate_data({"state": world.state}) == "", "Extended life save validates")
|
||||
check(root.get_node("SaveManager").validate_data({"format_version": 2, "app_version": "", "ui": {"current_page": 0}, "state": world.state}) == "", "Extended life save validates")
|
||||
dispose(world)
|
||||
print("Life: %d checks, %d failures" % [checks, failures])
|
||||
quit(0 if failures == 0 else 1)
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
extends SceneTree
|
||||
const Clock = preload("res://world/owniverse/simulation_time.gd")
|
||||
var checks: int = 0
|
||||
var failures: int = 0
|
||||
|
||||
func _initialize() -> void:
|
||||
call_deferred("run")
|
||||
|
||||
func check(condition: bool, message: String) -> void:
|
||||
checks += 1
|
||||
if not condition:
|
||||
failures += 1
|
||||
push_error(message)
|
||||
|
||||
func fixture():
|
||||
var world = load("res://world/owniverse/owniverse.gd").new()
|
||||
var global: Node = root.get_node("Global")
|
||||
for id in global.OwniverseEntities:
|
||||
var entity = load("res://world/owniverse/owniverse_entity.gd").new(global.OwniverseEntities[id])
|
||||
world.entities[id] = entity
|
||||
world.state.amount[id] = 0.0
|
||||
world.state.stats.total_amount[id] = 0.0
|
||||
if entity.group_as != "":
|
||||
world.state.amount[entity.group_as] = 0.0
|
||||
world.state.stats.total_amount[entity.group_as] = 0.0
|
||||
world.entities["N"].life_product = {}
|
||||
world.entities["N"].product_per_year_type = "H"
|
||||
world.entities["N"].product_per_year_amount = 10.0
|
||||
world.entities["N"].auto = 0.0
|
||||
world.state.amount.N = 1.0
|
||||
return world
|
||||
|
||||
func dispose(world) -> void:
|
||||
for entity in world.entities.values():
|
||||
entity.free()
|
||||
world.free()
|
||||
|
||||
func run() -> void:
|
||||
var world = fixture()
|
||||
world.initialize_life_batches()
|
||||
world.entities.N.cost = {"H": 2.0}
|
||||
world.entities.N.bind = {"S": 3.0}
|
||||
world.state.amount.H = 10.0
|
||||
world.state.amount.S = 0.0
|
||||
world.state.auto_resources = {"H": 10.0}
|
||||
world.state.batches.H = [{"amount": 10.0, "start_year": 1.0, "end_year": 2.0}]
|
||||
var before: Dictionary = world.state.duplicate(true)
|
||||
check(not world._try_production(world.state, world.entities.N, 1.0, true), "Binding failure rejects production")
|
||||
check(world.state == before, "Failure preserves costs, batches and budget")
|
||||
world.state.amount.S = 10.0
|
||||
var old_batches: Array = world.state.batches.H
|
||||
check(world._try_production(world.state, world.entities.N, 2.0, true), "Funded production succeeds")
|
||||
check(world.state.amount.H == 6.0 and world.state.amount.S == 4.0, "Exact cost and binding")
|
||||
check(world.state.auto_resources.H == 6.0, "Exact automatic budget")
|
||||
check(old_batches[0].amount == 10.0 and world.state.batches.H[0].amount == 6.0, "Consumed batches isolated")
|
||||
print("Transaction: %d checks, %d failures" % [checks, failures])
|
||||
dispose(world)
|
||||
quit(1 if failures else 0)
|
||||
@@ -0,0 +1 @@
|
||||
uid://byjixspismsnh
|
||||
@@ -84,7 +84,7 @@ func run() -> void:
|
||||
check(world.state.binds.RD.GG == 16.0 and world.state.binds.RD.AB == 120.0, "Planet multiplicity applied")
|
||||
check(world.state.amount.HP == 0.0 and world.state.stats.total_amount.HP == 1.0, "Created planets are bound, counted once")
|
||||
var saves: Node = root.get_node("SaveManager")
|
||||
check(saves.validate_data({"state": world.state}) == "", "Planet carry save validates")
|
||||
check(saves.validate_data({"format_version": 2, "app_version": "", "ui": {"current_page": 0}, "state": world.state}) == "", "Planet carry save validates")
|
||||
restored = fixture()
|
||||
restored.state = bytes_to_var(var_to_bytes(world.state))
|
||||
world._create_planets(world.state, "RD", 37.0, 0.0, 0.0, 0.7)
|
||||
@@ -106,7 +106,7 @@ func run() -> void:
|
||||
check(world.state.amount.RP == 0.0 and world.state.amount["C1.3"] == 0.0, "Inherited planets never become free")
|
||||
world._evolve_batches(world.state, lifespan + width)
|
||||
check(world.state.binds.RD["C1.3"] == 0.0 and world.state.binds.TWD["C1.3"] == 4.0, "No planets left at extinct parent type")
|
||||
check(saves.validate_data({"state": world.state}) == "", "Inherited state validates")
|
||||
check(saves.validate_data({"format_version": 2, "app_version": "", "ui": {"current_page": 0}, "state": world.state}) == "", "Inherited state validates")
|
||||
dispose(world)
|
||||
|
||||
world = fixture()
|
||||
@@ -146,7 +146,7 @@ func run() -> void:
|
||||
check(world.state.amount.SN == 0.0 and world.state.amount.LNS == 1.0, "Supernova produces a remnant")
|
||||
check(world.state.amount.H == 8.0 and world.state.amount.He == 50.0 and world.state.amount.Met == 11.0, "Supernova returns table resources")
|
||||
check(not world.state.amount.has("blast"), "Supernova dispatches blast output")
|
||||
check(saves.validate_data({"state": world.state}) == "", "Blast state validates")
|
||||
check(saves.validate_data({"format_version": 2, "app_version": "", "ui": {"current_page": 0}, "state": world.state}) == "", "Blast state validates")
|
||||
dispose(world)
|
||||
|
||||
world = fixture()
|
||||
|
||||
+3
-22
@@ -50,10 +50,10 @@ func run() -> void:
|
||||
for invalid in [0.0, -1.0, NAN, INF, 1e308]:
|
||||
world.evolute(invalid)
|
||||
check(world.state == before, "Invalid/overflow interval rejected")
|
||||
check(saves.validate_data({"state": world.state}) == "", "Fractional save is valid")
|
||||
check(saves.validate_data({"format_version": 2, "app_version": "", "ui": {"current_page": 0}, "state": world.state}) == "", "Fractional save is valid")
|
||||
var invalid_save: Dictionary = world.state.duplicate(true)
|
||||
invalid_save.time.year = 0.25
|
||||
check(saves.validate_data({"state": invalid_save}) != "", "Reject inconsistent fractional clock")
|
||||
check(saves.validate_data({"format_version": 2, "app_version": "", "ui": {"current_page": 0}, "state": invalid_save}) != "", "Reject inconsistent fractional clock")
|
||||
dispose(world)
|
||||
|
||||
for fps in [30, 60, 144]:
|
||||
@@ -76,26 +76,7 @@ func run() -> void:
|
||||
dispose(world)
|
||||
|
||||
world = fixture()
|
||||
world.state.version = "0.1.0"
|
||||
world.state.time = {"datetime": 0.45, "year": 0.0}
|
||||
check(saves.validate_data({"state": world.state}) == "", "Accept legacy integer-year save")
|
||||
world.migrate_time_precision()
|
||||
check(world.state.version == "0.1.1", "Migrate schema version")
|
||||
check(world.state.time.year == 0.4 and world.state.time.datetime == 0.45, "Keep unprocessed sub-tenth remainder")
|
||||
check(world.state.amount.H == 4.0, "Migration processes pending legacy time")
|
||||
check(saves.validate_data({"state": world.state}) == "", "Migrated state validates")
|
||||
before = world.state.duplicate(true)
|
||||
world.migrate_time_precision()
|
||||
check(world.state == before, "Migration is idempotent")
|
||||
# Verify in-memory save roundtrip without touching the player's save.
|
||||
var restored = fixture()
|
||||
restored.state = bytes_to_var(var_to_bytes(world.state))
|
||||
world.evolute(0.05)
|
||||
restored.evolute(0.05)
|
||||
check(world.state == restored.state, "Save continuation preserves time and production")
|
||||
check(world.state.time.year == 0.5 and world.state.amount.H == 5.0, "No double-counted migration time")
|
||||
dispose(world)
|
||||
dispose(restored)
|
||||
|
||||
world = fixture()
|
||||
world.entities.N.output_and = {"He": 1.0}
|
||||
@@ -106,5 +87,5 @@ func run() -> void:
|
||||
dispose(world)
|
||||
check(Clock.processed_year(0.099) == 0.0, "Do not round a genuine incomplete tenth forward")
|
||||
check(Clock.processed_year(1e9 + 0.45) == 1e9 + 0.4, "Large ages preserve fractional precision")
|
||||
print("Time migration: %d checks, %d failures" % [checks, failures])
|
||||
print("Time state: %d checks, %d failures" % [checks, failures])
|
||||
quit(0 if failures == 0 else 1)
|
||||
|
||||
Reference in New Issue
Block a user