style: apply gdformat formatting across the entire project

Auto-format all GDScript files using gdformat from gdtoolkit.
This is a baseline formatting pass to ensure consistent style:

- Normalizes indentation and spacing
- Wraps long lines to 100 characters
- Removes trailing whitespace
- Standardizes blank lines between functions

68 files reformatted, 8 files left unchanged (3rd-party addon files
with parse errors excluded).
This commit is contained in:
2026-07-05 23:06:23 +02:00
parent 28a2e42c41
commit 4463e524aa
69 changed files with 2253 additions and 1647 deletions
+11 -11
View File
@@ -33,6 +33,7 @@ var last_task: StringName
var random_source: RandomNumberGenerator
var debug_logs := true
func _init(
_id: int,
_npc_name: String,
@@ -53,11 +54,10 @@ func _init(
hunger = random_source.randf_range(20.0, 80.0)
energy = random_source.randf_range(40.0, 100.0)
position = Vector3(
random_source.randf_range(-8.0, 8.0),
0.0,
random_source.randf_range(-8.0, 8.0)
random_source.randf_range(-8.0, 8.0), 0.0, random_source.randf_range(-8.0, 8.0)
)
func die_from_starvation() -> void:
is_dead = true
current_task = SimulationIds.ACTION_DEAD
@@ -69,35 +69,35 @@ func die_from_starvation() -> void:
if debug_logs:
print("[SimNPC] ", npc_name, " died from starvation.")
func get_inventory_amount(item_id: StringName) -> float:
return float(inventory.get(String(item_id), 0.0))
func add_inventory(item_id: StringName, amount: float) -> void:
inventory[String(item_id)] = get_inventory_amount(item_id) + maxf(amount, 0.0)
func remove_inventory(item_id: StringName, requested_amount: float) -> float:
var removed := minf(
maxf(requested_amount, 0.0),
get_inventory_amount(item_id)
)
var removed := minf(maxf(requested_amount, 0.0), get_inventory_amount(item_id))
inventory[String(item_id)] = get_inventory_amount(item_id) - removed
return removed
func set_task(action_id: StringName, duration: float = -1.0) -> void:
var definition := SimulationDefinitions.get_action(action_id)
if definition == null:
push_error("SimNPC: unknown action_id '%s'" % action_id)
return
current_task = action_id
task_duration = (
duration if duration >= 0.0 else definition.default_duration
)
task_duration = (duration if duration >= 0.0 else definition.default_duration)
task_progress = 0.0
task_complete = false
task_state = TASK_STATE_TRAVELING
has_travel_target = false
func start_working() -> void:
if task_state != TASK_STATE_TRAVELING:
return
+30 -25
View File
@@ -17,6 +17,7 @@ var wood_priority := 1.0
var safety_priority := 1.0
var knowledge_priority := 1.0
func update_modifiers() -> void:
food_modifier = 1.0
wood_modifier = 1.0
@@ -30,15 +31,15 @@ func update_modifiers() -> void:
safety_modifier = 2.0
if knowledge > 25:
knowledge_modifier = 0.75
debug_log("FoodMod=%s SafetyMod=%s KnowledgeMod=%s" %
[
food_modifier,
safety_modifier,
knowledge_modifier
]
debug_log(
(
"FoodMod=%s SafetyMod=%s KnowledgeMod=%s"
% [food_modifier, safety_modifier, knowledge_modifier]
)
)
func update_priorities() -> void:
food_priority = 1.0
wood_priority = 1.0
@@ -68,6 +69,7 @@ func update_priorities() -> void:
if debug_logs:
print(get_priority_summary())
func apply_resource_delta(resource_id: StringName, amount: float) -> void:
match resource_id:
&"food":
@@ -87,6 +89,7 @@ func apply_resource_delta(resource_id: StringName, amount: float) -> void:
update_modifiers()
update_priorities()
func apply_npc_task(npc: SimNPC) -> void:
if npc.is_dead:
return
@@ -123,27 +126,29 @@ func apply_npc_task(npc: SimNPC) -> void:
update_modifiers()
update_priorities()
func get_summary() -> String:
return "Village | food: %s | wood: %s | safety: %s | knowledge: %s | priorities F/W/S/K: %s/%s/%s/%s" % [
round(food),
round(wood),
round(safety),
round(knowledge),
food_priority,
wood_priority,
safety_priority,
knowledge_priority
]
func get_summary() -> String:
return (
"Village | food: %s | wood: %s | safety: %s | knowledge: %s | priorities F/W/S/K: %s/%s/%s/%s"
% [
round(food),
round(wood),
round(safety),
round(knowledge),
food_priority,
wood_priority,
safety_priority,
knowledge_priority
]
)
func get_priority_summary() -> String:
return "Priorities | food: %s | wood: %s | safety: %s | knowledge: %s" % [
food_priority,
wood_priority,
safety_priority,
knowledge_priority
]
return (
"Priorities | food: %s | wood: %s | safety: %s | knowledge: %s"
% [food_priority, wood_priority, safety_priority, knowledge_priority]
)
func debug_log(message: String) -> void:
if debug_logs:
+3
View File
@@ -5,9 +5,11 @@ var tick_interval: float
var accumulator := 0.0
var elapsed_ticks := 0
func _init(interval: float = 1.0) -> void:
tick_interval = maxf(interval, 0.0001)
func advance(delta: float) -> int:
accumulator += maxf(delta, 0.0)
var ticks_due := 0
@@ -17,6 +19,7 @@ func advance(delta: float) -> int:
ticks_due += 1
return ticks_due
func reset() -> void:
accumulator = 0.0
elapsed_ticks = 0
+161 -145
View File
@@ -1,10 +1,6 @@
extends Node
signal npc_task_changed(
npc: SimNPC,
old_task: StringName,
new_task: StringName
)
signal npc_task_changed(npc: SimNPC, old_task: StringName, new_task: StringName)
signal village_changed(village: SimVillage)
signal npc_died(npc: SimNPC)
signal npc_target_requested(npc: SimNPC)
@@ -32,9 +28,8 @@ var action_selector := ActionSelectionSystem.new()
var action_executor := ActionExecutionSystem.new()
var target_resolver := ActionTargetResolver.new()
var names := [
"Amina", "Tarik", "Jasmin"
]
var names := ["Amina", "Tarik", "Jasmin"]
func _ready() -> void:
add_to_group("simulation_manager")
@@ -53,20 +48,19 @@ func _ready() -> void:
call_deferred("register_loaded_resource_nodes")
if debug_logs:
print("--- Simulation started ---")
func _process(delta: float) -> void:
var ticks_due := clock.advance(delta)
for tick in ticks_due:
simulate_tick()
func generate_npcs() -> void:
var profession_ids := SimulationDefinitions.get_profession_ids()
for i in range(names.size()):
var npc_random := _create_random_source(i, 0)
var profession_index := npc_random.randi_range(
0,
profession_ids.size() - 1
)
var profession_index := npc_random.randi_range(0, profession_ids.size() - 1)
var npc := SimNPC.new(
i,
names[i],
@@ -80,21 +74,20 @@ func generate_npcs() -> void:
npcs.append(npc)
wander_random_sources[i] = _create_random_source(i, 1)
func _create_random_source(npc_id: int, stream_id: int) -> RandomNumberGenerator:
var source := RandomNumberGenerator.new()
source.seed = simulation_seed + (npc_id + 1) * 1000003 + stream_id * 7919
return source
func get_wander_offset(npc_id: int) -> Vector3:
var source: RandomNumberGenerator = wander_random_sources.get(npc_id)
if source == null:
source = _create_random_source(npc_id, 1)
wander_random_sources[npc_id] = source
return Vector3(
source.randf_range(-6.0, 6.0),
0.0,
source.randf_range(-6.0, 6.0)
)
return Vector3(source.randf_range(-6.0, 6.0), 0.0, source.randf_range(-6.0, 6.0))
func simulate_tick() -> void:
tick_count += 1
@@ -113,21 +106,12 @@ func simulate_tick() -> void:
action_executor.advance_npc(npc, village)
if (
not npc.is_dead
and old_state in [
SimNPC.TASK_STATE_IDLE,
SimNPC.TASK_STATE_COMPLETE
]
and npc.task_state in [
SimNPC.TASK_STATE_IDLE,
SimNPC.TASK_STATE_COMPLETE
]
and old_state in [SimNPC.TASK_STATE_IDLE, SimNPC.TASK_STATE_COMPLETE]
and npc.task_state in [SimNPC.TASK_STATE_IDLE, SimNPC.TASK_STATE_COMPLETE]
):
var selection := action_selector.select_action(npc, village)
if selection != null:
npc.set_task(
selection.action_id,
selection.duration_override
)
npc.set_task(selection.action_id, selection.duration_override)
if old_task != npc.current_task and old_target != &"":
release_npc_reservation(npc.id)
@@ -147,45 +131,36 @@ func simulate_tick() -> void:
if not was_complete and npc.task_complete and not npc.is_dead:
var completed_task := npc.current_task
var completed_definition := SimulationDefinitions.get_action(
completed_task
)
var completed_definition := SimulationDefinitions.get_action(completed_task)
if (
npc.target_id != &""
and completed_definition != null
and completed_definition.target_type == SimulationIds.TARGET_RESOURCE
):
var resource_state := get_resource_state(npc.target_id)
if (
resource_state != null
and resource_state.get_reserved_by() == npc.id
):
if resource_state != null and resource_state.get_reserved_by() == npc.id:
var extracted := resource_state.extract()
if extracted > 0:
if resource_state.get_resource_id() == SimulationIds.RESOURCE_FOOD:
npc.add_inventory(
SimulationIds.RESOURCE_FOOD,
extracted
)
npc.add_inventory(SimulationIds.RESOURCE_FOOD, extracted)
npc_inventory_changed.emit(
npc,
SimulationIds.RESOURCE_FOOD,
npc.get_inventory_amount(
SimulationIds.RESOURCE_FOOD
)
npc.get_inventory_amount(SimulationIds.RESOURCE_FOOD)
)
else:
village.apply_resource_delta(
resource_state.get_resource_id(),
extracted
resource_state.get_resource_id(), extracted
)
_record_economic_event(
SimulationIds.EVENT_RESOURCE_EXTRACTED,
npc.id,
resource_state.get_node_id(),
_npc_inventory_id(npc.id)
if resource_state.get_resource_id() == SimulationIds.RESOURCE_FOOD
else &"village",
(
_npc_inventory_id(npc.id)
if resource_state.get_resource_id() == SimulationIds.RESOURCE_FOOD
else &"village"
),
resource_state.get_resource_id(),
extracted
)
@@ -201,7 +176,13 @@ func simulate_tick() -> void:
resource_state.get_node_id()
)
elif debug_logs:
print("[SimulationManager] ", npc.npc_name, " could not complete ", completed_task, ": target reservation was invalid")
print(
"[SimulationManager] ",
npc.npc_name,
" could not complete ",
completed_task,
": target reservation was invalid"
)
release_npc_reservation(npc.id)
elif completed_task == SimulationIds.ACTION_DEPOSIT_FOOD:
deposit_npc_inventory(npc, SimulationIds.RESOURCE_FOOD)
@@ -209,13 +190,19 @@ func simulate_tick() -> void:
withdraw_to_npc(npc, SimulationIds.RESOURCE_FOOD, 1.0)
elif completed_task == SimulationIds.ACTION_EAT:
consume_npc_food(npc)
elif completed_task not in [
SimulationIds.ACTION_GATHER_FOOD,
SimulationIds.ACTION_GATHER_WOOD
]:
elif (
completed_task
not in [SimulationIds.ACTION_GATHER_FOOD, SimulationIds.ACTION_GATHER_WOOD]
):
village.apply_npc_task(npc)
elif debug_logs:
print("[SimulationManager] ", npc.npc_name, " could not complete ", completed_task, ": no resource target")
print(
"[SimulationManager] ",
npc.npc_name,
" could not complete ",
completed_task,
": no resource target"
)
village_was_changed = true
@@ -254,20 +241,29 @@ func simulate_tick() -> void:
)
if old_state != npc.task_state:
print("[SimulationManager] State changed: ", npc.npc_name, " ", old_state, " -> ", npc.task_state)
print(
"[SimulationManager] State changed: ",
npc.npc_name,
" ",
old_state,
" -> ",
npc.task_state
)
if village_was_changed:
village_changed.emit(village)
if debug_logs:
print(village.get_summary())
func set_npc_target_id(npc_id: int, target_id: StringName) -> void:
for npc in npcs:
if npc.id == npc_id:
npc.target_id = target_id
return
func release_npc_reservation(npc_id: int) -> void:
for npc in npcs:
if npc.id == npc_id:
@@ -278,6 +274,7 @@ func release_npc_reservation(npc_id: int) -> void:
npc.target_id = &""
return
func notify_npc_arrived(npc_id: int) -> void:
for npc in npcs:
if npc.id == npc_id:
@@ -285,9 +282,7 @@ func notify_npc_arrived(npc_id: int) -> void:
return
if npc.task_state == SimNPC.TASK_STATE_TRAVELING:
var definition := SimulationDefinitions.get_action(
npc.current_task
)
var definition := SimulationDefinitions.get_action(npc.current_task)
if (
npc.target_id != &""
and definition != null
@@ -300,7 +295,13 @@ func notify_npc_arrived(npc_id: int) -> void:
or resource_state.get_reserved_by() != npc.id
):
if debug_logs:
print("[SimulationManager] ", npc.npc_name, " arrived but target ", npc.target_id, " is unavailable, replanning")
print(
"[SimulationManager] ",
npc.npc_name,
" arrived but target ",
npc.target_id,
" is unavailable, replanning"
)
notify_npc_navigation_failed(npc.id)
return
@@ -308,9 +309,15 @@ func notify_npc_arrived(npc_id: int) -> void:
npc.start_working()
if debug_logs:
print("[SimulationManager] ", npc.npc_name, " arrived and started working on: ", npc.current_task)
print(
"[SimulationManager] ",
npc.npc_name,
" arrived and started working on: ",
npc.current_task
)
return
func notify_npc_navigation_failed(npc_id: int) -> void:
for npc in npcs:
if npc.id != npc_id:
@@ -326,12 +333,20 @@ func notify_npc_navigation_failed(npc_id: int) -> void:
npc_target_requested.emit(npc)
if debug_logs:
print("[SimulationManager] ", npc.npc_name, " could not navigate for ", failed_task, " and is trying a wander target")
print(
"[SimulationManager] ",
npc.npc_name,
" could not navigate for ",
failed_task,
" and is trying a wander target"
)
return
func notify_npc_target_unavailable(npc_id: int) -> void:
notify_npc_navigation_failed(npc_id)
func resolve_npc_target(npc_id: int, origin: Vector3) -> bool:
if active_world_adapter == null:
push_error("SimulationManager: active_world_adapter is missing")
@@ -341,12 +356,7 @@ func resolve_npc_target(npc_id: int, origin: Vector3) -> bool:
continue
if npc.is_dead or npc.task_state != SimNPC.TASK_STATE_TRAVELING:
return false
var result := target_resolver.resolve(
npc,
origin,
self,
active_world_adapter
)
var result := target_resolver.resolve(npc, origin, self, active_world_adapter)
if result.is_empty():
notify_npc_target_unavailable(npc.id)
return false
@@ -357,6 +367,7 @@ func resolve_npc_target(npc_id: int, origin: Vector3) -> bool:
return true
return false
func request_current_travel(npc_id: int) -> bool:
for npc in npcs:
if npc.id != npc_id:
@@ -370,6 +381,7 @@ func request_current_travel(npc_id: int) -> bool:
return true
return false
func synchronize_npc_position(npc_id: int, active_position: Vector3) -> bool:
for npc in npcs:
if npc.id == npc_id:
@@ -377,9 +389,11 @@ func synchronize_npc_position(npc_id: int, active_position: Vector3) -> bool:
return true
return false
func _npc_inventory_id(npc_id: int) -> StringName:
return StringName("npc_%d_inventory" % npc_id)
func _record_economic_event(
event_type: StringName,
actor_id: int,
@@ -391,35 +405,26 @@ func _record_economic_event(
if amount <= 0.0:
return
var event := EconomicEventRecord.create(
next_event_id,
event_type,
tick_count,
actor_id,
source_id,
destination_id,
item_id,
amount
next_event_id, event_type, tick_count, actor_id, source_id, destination_id, item_id, amount
)
next_event_id += 1
economic_events.append(event)
economic_event_recorded.emit(event)
func _initialize_storage() -> void:
if storage_states.has(SimulationIds.STORAGE_VILLAGE_PANTRY):
_sync_village_food()
return
storage_states[SimulationIds.STORAGE_VILLAGE_PANTRY] = (
StorageStateRecord.create(
SimulationIds.STORAGE_VILLAGE_PANTRY,
{String(SimulationIds.RESOURCE_FOOD): village.food}
)
)
storage_states[SimulationIds.STORAGE_VILLAGE_PANTRY] = (StorageStateRecord.create(
SimulationIds.STORAGE_VILLAGE_PANTRY, {String(SimulationIds.RESOURCE_FOOD): village.food}
))
_sync_village_food()
func get_pantry() -> StorageStateRecord:
return storage_states.get(
SimulationIds.STORAGE_VILLAGE_PANTRY
) as StorageStateRecord
return storage_states.get(SimulationIds.STORAGE_VILLAGE_PANTRY) as StorageStateRecord
func _sync_village_food() -> void:
var pantry := get_pantry()
@@ -428,6 +433,7 @@ func _sync_village_food() -> void:
village.update_modifiers()
village.update_priorities()
func deposit_npc_inventory(npc: SimNPC, item_id: StringName) -> float:
var available := npc.get_inventory_amount(item_id)
var deposited := get_pantry().deposit(item_id, available)
@@ -445,11 +451,8 @@ func deposit_npc_inventory(npc: SimNPC, item_id: StringName) -> float:
)
return deposited
func withdraw_to_npc(
npc: SimNPC,
item_id: StringName,
amount: float
) -> float:
func withdraw_to_npc(npc: SimNPC, item_id: StringName, amount: float) -> float:
var withdrawn := get_pantry().withdraw(item_id, amount)
npc.add_inventory(item_id, withdrawn)
_sync_village_food()
@@ -465,6 +468,7 @@ func withdraw_to_npc(
)
return withdrawn
func consume_npc_food(npc: SimNPC) -> bool:
if npc.remove_inventory(SimulationIds.RESOURCE_FOOD, 1.0) < 1.0:
npc.hunger = minf(npc.hunger + 5.0, 100.0)
@@ -474,9 +478,7 @@ func consume_npc_food(npc: SimNPC) -> bool:
npc.starvation_ticks = 0
npc.is_starving = npc.hunger >= 90.0
npc_inventory_changed.emit(
npc,
SimulationIds.RESOURCE_FOOD,
npc.get_inventory_amount(SimulationIds.RESOURCE_FOOD)
npc, SimulationIds.RESOURCE_FOOD, npc.get_inventory_amount(SimulationIds.RESOURCE_FOOD)
)
_record_economic_event(
SimulationIds.EVENT_ITEM_CONSUMED,
@@ -488,10 +490,12 @@ func consume_npc_food(npc: SimNPC) -> bool:
)
return true
func register_loaded_resource_nodes() -> void:
for node in ResourceNode.get_all():
register_resource_node(node)
func register_resource_node(node: ResourceNode) -> bool:
if node == null or node.node_id.is_empty():
return false
@@ -502,8 +506,10 @@ func register_resource_node(node: ResourceNode) -> bool:
or action_definition.resource_action_id != node.action_id
):
push_error(
"SimulationManager: ResourceNode '%s' has invalid action_id '%s'"
% [node.node_id, node.action_id]
(
"SimulationManager: ResourceNode '%s' has invalid action_id '%s'"
% [node.node_id, node.action_id]
)
)
return false
var resource_state := get_resource_state(node.node_id)
@@ -511,46 +517,40 @@ func register_resource_node(node: ResourceNode) -> bool:
resource_state = ResourceStateRecord.create_from_node(node)
resource_states[node.node_id] = resource_state
elif not resource_state.apply_definition(node):
push_error(
"SimulationManager: ResourceNode definition mismatch for '%s'"
% node.node_id
)
push_error("SimulationManager: ResourceNode definition mismatch for '%s'" % node.node_id)
return false
return node.bind_state(resource_state)
func get_resource_state(node_id: StringName) -> ResourceStateRecord:
return resource_states.get(node_id) as ResourceStateRecord
func reserve_resource(node_id: StringName, agent_id: int) -> bool:
var resource_state := get_resource_state(node_id)
return resource_state != null and resource_state.reserve(agent_id)
func release_resource(node_id: StringName, agent_id: int) -> void:
var resource_state := get_resource_state(node_id)
if resource_state != null:
resource_state.release(agent_id)
func find_resource_node_for_player(
from_position: Vector3,
max_distance: float
) -> ResourceNode:
func find_resource_node_for_player(from_position: Vector3, max_distance: float) -> ResourceNode:
var best: ResourceNode
var best_distance := max_distance * max_distance
for node in ResourceNode.get_all():
var resource_state := get_resource_state(node.node_id)
if (
resource_state == null
or not resource_state.can_player_use_resource()
):
if resource_state == null or not resource_state.can_player_use_resource():
continue
var distance := from_position.distance_squared_to(
node.interaction_point.global_position
)
var distance := from_position.distance_squared_to(node.interaction_point.global_position)
if distance <= best_distance:
best_distance = distance
best = node
return best
func harvest_resource_node(node: ResourceNode) -> float:
if node == null:
return 0.0
@@ -570,9 +570,11 @@ func harvest_resource_node(node: ResourceNode) -> float:
SimulationIds.EVENT_RESOURCE_EXTRACTED,
-1,
resource_state.get_node_id(),
SimulationIds.STORAGE_VILLAGE_PANTRY
if resource_state.get_resource_id() == SimulationIds.RESOURCE_FOOD
else &"village",
(
SimulationIds.STORAGE_VILLAGE_PANTRY
if resource_state.get_resource_id() == SimulationIds.RESOURCE_FOOD
else &"village"
),
resource_state.get_resource_id(),
extracted
)
@@ -590,11 +592,13 @@ func harvest_resource_node(node: ResourceNode) -> float:
return extracted
func eat_food(amount: float) -> void:
get_pantry().withdraw(SimulationIds.RESOURCE_FOOD, amount)
_sync_village_food()
village_changed.emit(village)
func add_food(amount: float) -> void:
if amount >= 0.0:
get_pantry().deposit(SimulationIds.RESOURCE_FOOD, amount)
@@ -603,18 +607,22 @@ func add_food(amount: float) -> void:
_sync_village_food()
village_changed.emit(village)
func add_wood(amount: float) -> void:
village.apply_resource_delta(&"wood", amount)
village_changed.emit(village)
func add_safety(amount: float) -> void:
village.apply_resource_delta(&"safety", amount)
village_changed.emit(village)
func add_knowledge(amount: float) -> void:
village.apply_resource_delta(&"knowledge", amount)
village_changed.emit(village)
func get_starving_count() -> int:
var count := 0
for npc in npcs:
@@ -622,37 +630,42 @@ func get_starving_count() -> int:
count += 1
return count
func get_state_snapshot() -> Dictionary:
var npc_snapshots: Array[Dictionary] = []
for npc in npcs:
npc_snapshots.append({
"id": npc.id,
"name": npc.npc_name,
"profession": npc.profession,
"hunger": npc.hunger,
"energy": npc.energy,
"strength": npc.strength,
"intelligence": npc.intelligence,
"task": npc.current_task,
"task_state": npc.task_state,
"task_duration": npc.task_duration,
"task_progress": npc.task_progress,
"target_id": String(npc.target_id),
"position": [npc.position.x, npc.position.y, npc.position.z],
"travel_target_position": [
npc.travel_target_position.x,
npc.travel_target_position.y,
npc.travel_target_position.z
],
"has_travel_target": npc.has_travel_target,
"starvation_ticks": npc.starvation_ticks,
"is_dead": npc.is_dead
})
npc_snapshots.append(
{
"id": npc.id,
"name": npc.npc_name,
"profession": npc.profession,
"hunger": npc.hunger,
"energy": npc.energy,
"strength": npc.strength,
"intelligence": npc.intelligence,
"task": npc.current_task,
"task_state": npc.task_state,
"task_duration": npc.task_duration,
"task_progress": npc.task_progress,
"target_id": String(npc.target_id),
"position": [npc.position.x, npc.position.y, npc.position.z],
"travel_target_position":
[
npc.travel_target_position.x,
npc.travel_target_position.y,
npc.travel_target_position.z
],
"has_travel_target": npc.has_travel_target,
"starvation_ticks": npc.starvation_ticks,
"is_dead": npc.is_dead
}
)
return {
"seed": simulation_seed,
"tick_count": tick_count,
"village": {
"village":
{
"food": village.food,
"wood": village.wood,
"safety": village.safety,
@@ -661,9 +674,11 @@ func get_state_snapshot() -> Dictionary:
"npcs": npc_snapshots
}
func get_state_checksum() -> String:
return create_state_record().to_json().sha256_text()
func create_state_record() -> SimulationStateRecord:
var record := SimulationStateRecord.new()
var wander_streams: Array[Dictionary] = []
@@ -671,11 +686,9 @@ func create_state_record() -> SimulationStateRecord:
sorted_npc_ids.sort()
for npc_id in sorted_npc_ids:
var source: RandomNumberGenerator = wander_random_sources[npc_id]
wander_streams.append({
"npc_id": int(npc_id),
"seed": str(source.seed),
"state": str(source.state)
})
wander_streams.append(
{"npc_id": int(npc_id), "seed": str(source.seed), "state": str(source.state)}
)
record.simulation = {
"seed": simulation_seed,
@@ -704,9 +717,11 @@ func create_state_record() -> SimulationStateRecord:
record.economic_events.append(event)
return record
func serialize_state() -> String:
return create_state_record().to_json()
func restore_state_from_json(json_text: String) -> bool:
var record := SimulationStateRecord.from_json(json_text)
if record == null:
@@ -714,6 +729,7 @@ func restore_state_from_json(json_text: String) -> bool:
return false
return restore_state(record)
func restore_state(record: SimulationStateRecord) -> bool:
if record == null:
return false
@@ -1,6 +1,7 @@
class_name ActionExecutionSystem
extends RefCounted
func advance_npc(npc: SimNPC, village: SimVillage) -> void:
if npc.is_dead:
return
@@ -12,6 +13,7 @@ func advance_npc(npc: SimNPC, village: SimVillage) -> void:
npc.task_complete = true
npc.task_state = SimNPC.TASK_STATE_COMPLETE
func _update_needs(npc: SimNPC, village: SimVillage) -> void:
npc.hunger += 3.0 * village.food_modifier
match npc.task_state:
+2 -4
View File
@@ -4,9 +4,7 @@ extends RefCounted
var action_id: StringName
var duration_override := -1.0
func _init(
selected_action_id: StringName,
selected_duration_override: float = -1.0
) -> void:
func _init(selected_action_id: StringName, selected_duration_override: float = -1.0) -> void:
action_id = selected_action_id
duration_override = selected_duration_override
+46 -23
View File
@@ -1,6 +1,7 @@
class_name ActionSelectionSystem
extends RefCounted
func select_action(npc: SimNPC, village: SimVillage) -> ActionSelectionResult:
if npc.is_dead:
return null
@@ -8,10 +9,7 @@ func select_action(npc: SimNPC, village: SimVillage) -> ActionSelectionResult:
if npc.get_inventory_amount(SimulationIds.RESOURCE_FOOD) >= 1.0:
return ActionSelectionResult.new(SimulationIds.ACTION_EAT, 1.0)
if village.food > 0:
return ActionSelectionResult.new(
SimulationIds.ACTION_WITHDRAW_FOOD,
1.0
)
return ActionSelectionResult.new(SimulationIds.ACTION_WITHDRAW_FOOD, 1.0)
return ActionSelectionResult.new(SimulationIds.ACTION_GATHER_FOOD, 4.0)
if npc.hunger > 75.0:
if npc.get_inventory_amount(SimulationIds.RESOURCE_FOOD) >= 1.0:
@@ -25,34 +23,58 @@ func select_action(npc: SimNPC, village: SimVillage) -> ActionSelectionResult:
return ActionSelectionResult.new(SimulationIds.ACTION_REST)
return ActionSelectionResult.new(_choose_best_work_action(npc, village))
func _choose_best_work_action(
npc: SimNPC,
village: SimVillage
) -> StringName:
func _choose_best_work_action(npc: SimNPC, village: SimVillage) -> StringName:
var scores := {
SimulationIds.ACTION_GATHER_FOOD: _calculate_score(
npc, SimulationIds.ACTION_GATHER_FOOD, village.food_priority,
village.food, 15.0, 30.0, 3.0, 1.5
SimulationIds.ACTION_GATHER_FOOD:
_calculate_score(
npc,
SimulationIds.ACTION_GATHER_FOOD,
village.food_priority,
village.food,
15.0,
30.0,
3.0,
1.5
),
SimulationIds.ACTION_GATHER_WOOD: _calculate_score(
npc, SimulationIds.ACTION_GATHER_WOOD, village.wood_priority,
village.wood, 10.0, 20.0, 2.5, 1.0
SimulationIds.ACTION_GATHER_WOOD:
_calculate_score(
npc,
SimulationIds.ACTION_GATHER_WOOD,
village.wood_priority,
village.wood,
10.0,
20.0,
2.5,
1.0
),
SimulationIds.ACTION_PATROL: _calculate_score(
npc, SimulationIds.ACTION_PATROL, village.safety_priority,
village.safety, 30.0, 50.0, 3.0, 1.5
SimulationIds.ACTION_PATROL:
_calculate_score(
npc,
SimulationIds.ACTION_PATROL,
village.safety_priority,
village.safety,
30.0,
50.0,
3.0,
1.5
),
SimulationIds.ACTION_STUDY: _calculate_score(
npc, SimulationIds.ACTION_STUDY, village.knowledge_priority,
village.knowledge, 10.0, 25.0, 1.5, 0.75
SimulationIds.ACTION_STUDY:
_calculate_score(
npc,
SimulationIds.ACTION_STUDY,
village.knowledge_priority,
village.knowledge,
10.0,
25.0,
1.5,
0.75
)
}
var best_action := SimulationIds.ACTION_GATHER_FOOD
var best_score: float = scores[best_action]
for action_id in [
SimulationIds.ACTION_GATHER_WOOD,
SimulationIds.ACTION_PATROL,
SimulationIds.ACTION_STUDY
SimulationIds.ACTION_GATHER_WOOD, SimulationIds.ACTION_PATROL, SimulationIds.ACTION_STUDY
]:
var score: float = scores[action_id]
if score > best_score:
@@ -60,6 +82,7 @@ func _choose_best_work_action(
best_score = score
return best_action
func _calculate_score(
npc: SimNPC,
action_id: StringName,
+8 -19
View File
@@ -1,11 +1,9 @@
class_name ActionTargetResolver
extends RefCounted
func resolve(
npc: SimNPC,
origin: Vector3,
simulation_manager: Node,
active_world_adapter: Node
npc: SimNPC, origin: Vector3, simulation_manager: Node, active_world_adapter: Node
) -> Dictionary:
var definition := SimulationDefinitions.get_action(npc.current_task)
if definition == null:
@@ -13,18 +11,17 @@ func resolve(
match definition.target_type:
SimulationIds.TARGET_RESOURCE:
return _resolve_resource(
npc, origin, definition, simulation_manager,
active_world_adapter
npc, origin, definition, simulation_manager, active_world_adapter
)
SimulationIds.TARGET_ACTIVITY:
return active_world_adapter.get_activity_target(npc.current_task)
SimulationIds.TARGET_FREE:
return {
"target_id": "",
"position": origin + simulation_manager.get_wander_offset(npc.id)
"target_id": "", "position": origin + simulation_manager.get_wander_offset(npc.id)
}
return {}
func _resolve_resource(
npc: SimNPC,
origin: Vector3,
@@ -34,18 +31,10 @@ func _resolve_resource(
) -> Dictionary:
var best: Dictionary = {}
var best_distance := INF
for candidate in active_world_adapter.get_resource_candidates(
definition.resource_action_id
):
for candidate in active_world_adapter.get_resource_candidates(definition.resource_action_id):
var node_id := StringName(candidate["target_id"])
var state: ResourceStateRecord = simulation_manager.get_resource_state(
node_id
)
if (
state == null
or not state.can_npc_use()
or not state.is_available_for(npc.id)
):
var state: ResourceStateRecord = simulation_manager.get_resource_state(node_id)
if state == null or not state.can_npc_use() or not state.is_available_for(npc.id):
continue
var position: Vector3 = candidate["position"]
var distance := origin.distance_squared_to(position)
+7 -8
View File
@@ -8,6 +8,7 @@ extends Resource
@export var target_type: StringName = SimulationIds.TARGET_ACTIVITY
@export var resource_action_id: StringName
func validate() -> Array[String]:
var errors: Array[String] = []
if action_id.is_empty():
@@ -16,15 +17,13 @@ func validate() -> Array[String]:
errors.append("display_name is empty for '%s'" % action_id)
if default_duration <= 0.0:
errors.append("default_duration must be positive for '%s'" % action_id)
if target_type not in [
SimulationIds.TARGET_RESOURCE,
SimulationIds.TARGET_ACTIVITY,
SimulationIds.TARGET_FREE
]:
errors.append("target_type '%s' is invalid for '%s'" % [target_type, action_id])
if (
target_type == SimulationIds.TARGET_RESOURCE
and resource_action_id.is_empty()
target_type
not in [
SimulationIds.TARGET_RESOURCE, SimulationIds.TARGET_ACTIVITY, SimulationIds.TARGET_FREE
]
):
errors.append("target_type '%s' is invalid for '%s'" % [target_type, action_id])
if target_type == SimulationIds.TARGET_RESOURCE and resource_action_id.is_empty():
errors.append("resource_action_id is required for '%s'" % action_id)
return errors
@@ -4,6 +4,7 @@ extends Resource
@export var profession_id: StringName
@export var display_name: String
func validate() -> Array[String]:
var errors: Array[String] = []
if profession_id.is_empty():
@@ -21,6 +21,7 @@ const PROFESSION_PATHS := [
"res://simulation/definitions/professions/wanderer.tres"
]
static func get_actions() -> Array[ActionDefinition]:
var definitions: Array[ActionDefinition] = []
for path in ACTION_PATHS:
@@ -29,6 +30,7 @@ static func get_actions() -> Array[ActionDefinition]:
definitions.append(definition)
return definitions
static func get_professions() -> Array[ProfessionDefinition]:
var definitions: Array[ProfessionDefinition] = []
for path in PROFESSION_PATHS:
@@ -37,26 +39,28 @@ static func get_professions() -> Array[ProfessionDefinition]:
definitions.append(definition)
return definitions
static func get_action(action_id: StringName) -> ActionDefinition:
for definition in get_actions():
if definition.action_id == action_id:
return definition
return null
static func get_profession(
profession_id: StringName
) -> ProfessionDefinition:
static func get_profession(profession_id: StringName) -> ProfessionDefinition:
for definition in get_professions():
if definition.profession_id == profession_id:
return definition
return null
static func get_profession_ids() -> Array[StringName]:
var ids: Array[StringName] = []
for definition in get_professions():
ids.append(definition.profession_id)
return ids
static func validate() -> Array[String]:
var errors: Array[String] = []
if get_actions().size() != ACTION_PATHS.size():
@@ -85,15 +89,19 @@ static func validate() -> Array[String]:
and not profession_ids.has(definition.preferred_profession_id)
):
errors.append(
"Action '%s' references unknown profession '%s'"
% [definition.action_id, definition.preferred_profession_id]
(
"Action '%s' references unknown profession '%s'"
% [definition.action_id, definition.preferred_profession_id]
)
)
if (
definition.target_type == SimulationIds.TARGET_RESOURCE
and not action_ids.has(definition.resource_action_id)
):
errors.append(
"Action '%s' references unknown resource action '%s'"
% [definition.action_id, definition.resource_action_id]
(
"Action '%s' references unknown resource action '%s'"
% [definition.action_id, definition.resource_action_id]
)
)
return errors
@@ -4,6 +4,7 @@ extends Node
var store := SaveSlotStore.new()
func _unhandled_key_input(event: InputEvent) -> void:
if not event.pressed or event.echo:
return
+12 -4
View File
@@ -8,9 +8,11 @@ const MAX_SAVE_BYTES := 16 * 1024 * 1024
var save_directory: String
var last_error := ""
func _init(directory: String = DEFAULT_DIRECTORY) -> void:
save_directory = directory
func save(manager: Node, slot_name: String = DEFAULT_SLOT) -> bool:
last_error = ""
if manager == null or not manager.has_method("serialize_state"):
@@ -55,6 +57,7 @@ func save(manager: Node, slot_name: String = DEFAULT_SLOT) -> bool:
_remove_if_present(backup_path)
return true
func load_into(manager: Node, slot_name: String = DEFAULT_SLOT) -> bool:
last_error = ""
if manager == null or not manager.has_method("restore_state"):
@@ -72,14 +75,13 @@ func load_into(manager: Node, slot_name: String = DEFAULT_SLOT) -> bool:
return _fail("Simulation refused the validated save record")
return true
func has_slot(slot_name: String = DEFAULT_SLOT) -> bool:
if not _is_valid_slot_name(slot_name):
return false
var final_path := get_slot_path(slot_name)
return (
_read_record(final_path) != null
or _read_record(final_path + ".bak") != null
)
return _read_record(final_path) != null or _read_record(final_path + ".bak") != null
func delete_slot(slot_name: String = DEFAULT_SLOT) -> bool:
if not _is_valid_slot_name(slot_name):
@@ -90,9 +92,11 @@ func delete_slot(slot_name: String = DEFAULT_SLOT) -> bool:
_remove_if_present(final_path + ".bak")
return true
func get_slot_path(slot_name: String = DEFAULT_SLOT) -> String:
return save_directory.path_join(slot_name + ".json")
func _read_record(path: String) -> SimulationStateRecord:
if not FileAccess.file_exists(path):
return null
@@ -106,6 +110,7 @@ func _read_record(path: String) -> SimulationStateRecord:
file.close()
return SimulationStateRecord.from_json(json_text)
func _ensure_directory() -> bool:
var absolute_directory := ProjectSettings.globalize_path(save_directory)
var error := DirAccess.make_dir_recursive_absolute(absolute_directory)
@@ -113,6 +118,7 @@ func _ensure_directory() -> bool:
return _fail("Could not create the save directory")
return true
func _is_valid_slot_name(slot_name: String) -> bool:
if slot_name.is_empty() or slot_name.length() > 32:
return false
@@ -122,10 +128,12 @@ func _is_valid_slot_name(slot_name: String) -> bool:
return false
return true
func _remove_if_present(path: String) -> void:
if FileAccess.file_exists(path):
DirAccess.remove_absolute(path)
func _fail(message: String) -> bool:
last_error = message
return false
+29 -15
View File
@@ -5,9 +5,11 @@ const SCHEMA_VERSION := 1
var data: Dictionary
func _init(record_data: Dictionary = {}) -> void:
data = record_data.duplicate(true)
static func create(
event_id: int,
event_type: StringName,
@@ -18,25 +20,36 @@ static func create(
item_id: StringName,
amount: float
) -> EconomicEventRecord:
return EconomicEventRecord.new({
"schema_version": SCHEMA_VERSION,
"event_id": event_id,
"event_type": String(event_type),
"tick": tick,
"actor_id": actor_id,
"source_id": String(source_id),
"destination_id": String(destination_id),
"item_id": String(item_id),
"amount": amount
})
return EconomicEventRecord.new(
{
"schema_version": SCHEMA_VERSION,
"event_id": event_id,
"event_type": String(event_type),
"tick": tick,
"actor_id": actor_id,
"source_id": String(source_id),
"destination_id": String(destination_id),
"item_id": String(item_id),
"amount": amount
}
)
static func from_dictionary(record_data: Dictionary) -> EconomicEventRecord:
if int(record_data.get("schema_version", -1)) != SCHEMA_VERSION:
return null
if not record_data.has_all([
"event_id", "event_type", "tick", "actor_id", "source_id",
"destination_id", "item_id", "amount"
]):
if not record_data.has_all(
[
"event_id",
"event_type",
"tick",
"actor_id",
"source_id",
"destination_id",
"item_id",
"amount"
]
):
return null
var normalized := record_data.duplicate(true)
normalized["schema_version"] = SCHEMA_VERSION
@@ -60,5 +73,6 @@ static func from_dictionary(record_data: Dictionary) -> EconomicEventRecord:
return null
return EconomicEventRecord.new(normalized)
func to_dictionary() -> Dictionary:
return data.duplicate(true)
+74 -62
View File
@@ -7,41 +7,47 @@ const PREVIOUS_SCHEMA_VERSION := 2
var data: Dictionary
func _init(record_data: Dictionary = {}) -> void:
data = record_data.duplicate(true)
static func capture(npc: SimNPC) -> NPCStateRecord:
return NPCStateRecord.new({
"schema_version": SCHEMA_VERSION,
"id": npc.id,
"name": npc.npc_name,
"profession": String(npc.profession),
"hunger": npc.hunger,
"energy": npc.energy,
"strength": npc.strength,
"intelligence": npc.intelligence,
"current_task": String(npc.current_task),
"task_state": String(npc.task_state),
"position": [npc.position.x, npc.position.y, npc.position.z],
"is_starving": npc.is_starving,
"starvation_ticks": npc.starvation_ticks,
"starvation_death_threshold": npc.starvation_death_threshold,
"is_dead": npc.is_dead,
"task_duration": npc.task_duration,
"task_progress": npc.task_progress,
"task_complete": npc.task_complete,
"target_id": String(npc.target_id),
"travel_target_position": [
npc.travel_target_position.x,
npc.travel_target_position.y,
npc.travel_target_position.z
],
"has_travel_target": npc.has_travel_target,
"inventory": npc.inventory.duplicate(true),
"last_task": String(npc.last_task),
"random_seed": str(npc.random_source.seed),
"random_state": str(npc.random_source.state)
})
return NPCStateRecord.new(
{
"schema_version": SCHEMA_VERSION,
"id": npc.id,
"name": npc.npc_name,
"profession": String(npc.profession),
"hunger": npc.hunger,
"energy": npc.energy,
"strength": npc.strength,
"intelligence": npc.intelligence,
"current_task": String(npc.current_task),
"task_state": String(npc.task_state),
"position": [npc.position.x, npc.position.y, npc.position.z],
"is_starving": npc.is_starving,
"starvation_ticks": npc.starvation_ticks,
"starvation_death_threshold": npc.starvation_death_threshold,
"is_dead": npc.is_dead,
"task_duration": npc.task_duration,
"task_progress": npc.task_progress,
"task_complete": npc.task_complete,
"target_id": String(npc.target_id),
"travel_target_position":
[
npc.travel_target_position.x,
npc.travel_target_position.y,
npc.travel_target_position.z
],
"has_travel_target": npc.has_travel_target,
"inventory": npc.inventory.duplicate(true),
"last_task": String(npc.last_task),
"random_seed": str(npc.random_source.seed),
"random_state": str(npc.random_source.state)
}
)
static func from_dictionary(record_data: Dictionary) -> NPCStateRecord:
var version := int(record_data.get("schema_version", -1))
@@ -49,23 +55,40 @@ static func from_dictionary(record_data: Dictionary) -> NPCStateRecord:
record_data = _migrate_legacy(record_data, version)
elif version != SCHEMA_VERSION:
return null
if not record_data.has_all([
"id", "name", "profession", "hunger", "energy", "strength",
"intelligence", "current_task", "task_state", "position",
"is_starving", "starvation_ticks", "starvation_death_threshold",
"is_dead", "task_duration", "task_progress", "task_complete",
"target_id", "travel_target_position", "has_travel_target", "inventory",
"last_task", "random_seed", "random_state"
]):
if not record_data.has_all(
[
"id",
"name",
"profession",
"hunger",
"energy",
"strength",
"intelligence",
"current_task",
"task_state",
"position",
"is_starving",
"starvation_ticks",
"starvation_death_threshold",
"is_dead",
"task_duration",
"task_progress",
"task_complete",
"target_id",
"travel_target_position",
"has_travel_target",
"inventory",
"last_task",
"random_seed",
"random_state"
]
):
return null
var saved_position = record_data["position"]
if not saved_position is Array or saved_position.size() != 3:
return null
var saved_target_position = record_data["travel_target_position"]
if (
not saved_target_position is Array
or saved_target_position.size() != 3
):
if not saved_target_position is Array or saved_target_position.size() != 3:
return null
if not record_data["inventory"] is Dictionary:
return null
@@ -74,36 +97,26 @@ static func from_dictionary(record_data: Dictionary) -> NPCStateRecord:
return null
var action_id := StringName(record_data["current_task"])
if (
action_id not in [
SimulationIds.ACTION_IDLE,
SimulationIds.ACTION_DEAD
]
action_id not in [SimulationIds.ACTION_IDLE, SimulationIds.ACTION_DEAD]
and SimulationDefinitions.get_action(action_id) == null
):
return null
var last_action_id := StringName(record_data["last_task"])
if (
not last_action_id.is_empty()
and SimulationDefinitions.get_action(last_action_id) == null
):
if not last_action_id.is_empty() and SimulationDefinitions.get_action(last_action_id) == null:
return null
return NPCStateRecord.new(record_data)
static func _migrate_legacy(
legacy_data: Dictionary,
version: int
) -> Dictionary:
static func _migrate_legacy(legacy_data: Dictionary, version: int) -> Dictionary:
var migrated := legacy_data.duplicate(true)
migrated["schema_version"] = SCHEMA_VERSION
if version == LEGACY_SCHEMA_VERSION:
migrated["travel_target_position"] = legacy_data.get(
"position",
[0.0, 0.0, 0.0]
)
migrated["travel_target_position"] = legacy_data.get("position", [0.0, 0.0, 0.0])
migrated["has_travel_target"] = false
migrated["inventory"] = {}
return migrated
func restore(debug_logs: bool) -> SimNPC:
var random_source := RandomNumberGenerator.new()
random_source.seed = String(data["random_seed"]).to_int()
@@ -122,9 +135,7 @@ func restore(debug_logs: bool) -> SimNPC:
npc.current_task = StringName(data["current_task"])
npc.task_state = StringName(data["task_state"])
npc.position = Vector3(
float(saved_position[0]),
float(saved_position[1]),
float(saved_position[2])
float(saved_position[0]), float(saved_position[1]), float(saved_position[2])
)
npc.is_starving = bool(data["is_starving"])
npc.starvation_ticks = int(data["starvation_ticks"])
@@ -146,5 +157,6 @@ func restore(debug_logs: bool) -> SimNPC:
npc.debug_logs = debug_logs
return npc
func to_dictionary() -> Dictionary:
return data.duplicate(true)
+53 -28
View File
@@ -9,22 +9,27 @@ const LEGACY_SCHEMA_VERSION := 1
var data: Dictionary
func _init(record_data: Dictionary = {}) -> void:
data = record_data.duplicate(true)
static func create_from_node(node: ResourceNode) -> ResourceStateRecord:
return ResourceStateRecord.new({
"schema_version": SCHEMA_VERSION,
"node_id": String(node.node_id),
"action_id": String(node.action_id),
"resource_id": String(node.resource_id),
"amount_remaining": node.initial_amount,
"yield_per_action": node.yield_per_action,
"reserved_by": -1,
"enabled": node.initial_enabled,
"can_npcs_use": node.can_npcs_use,
"can_player_use": node.can_player_use
})
return ResourceStateRecord.new(
{
"schema_version": SCHEMA_VERSION,
"node_id": String(node.node_id),
"action_id": String(node.action_id),
"resource_id": String(node.resource_id),
"amount_remaining": node.initial_amount,
"yield_per_action": node.yield_per_action,
"reserved_by": -1,
"enabled": node.initial_enabled,
"can_npcs_use": node.can_npcs_use,
"can_player_use": node.can_player_use
}
)
static func from_dictionary(record_data: Dictionary) -> ResourceStateRecord:
var version := int(record_data.get("schema_version", -1))
@@ -33,26 +38,30 @@ static func from_dictionary(record_data: Dictionary) -> ResourceStateRecord:
elif version != SCHEMA_VERSION:
return null
if not record_data.has_all([
"node_id", "action_id", "resource_id", "amount_remaining",
"yield_per_action", "reserved_by", "enabled", "can_npcs_use",
"can_player_use"
]):
if not record_data.has_all(
[
"node_id",
"action_id",
"resource_id",
"amount_remaining",
"yield_per_action",
"reserved_by",
"enabled",
"can_npcs_use",
"can_player_use"
]
):
return null
if String(record_data["node_id"]).is_empty():
return null
var action_id := StringName(record_data["action_id"])
if (
not action_id.is_empty()
and SimulationDefinitions.get_action(action_id) == null
):
if not action_id.is_empty() and SimulationDefinitions.get_action(action_id) == null:
return null
return ResourceStateRecord.new(record_data)
static func _migrate_v1(legacy_data: Dictionary) -> Dictionary:
if not legacy_data.has_all([
"node_id", "amount_remaining", "reserved_by", "enabled"
]):
if not legacy_data.has_all(["node_id", "amount_remaining", "reserved_by", "enabled"]):
return {}
var migrated := legacy_data.duplicate(true)
migrated["schema_version"] = SCHEMA_VERSION
@@ -63,6 +72,7 @@ static func _migrate_v1(legacy_data: Dictionary) -> Dictionary:
migrated["can_player_use"] = false
return migrated
func apply_definition(node: ResourceNode) -> bool:
if node == null or node.node_id != get_node_id():
return false
@@ -85,44 +95,54 @@ func apply_definition(node: ResourceNode) -> bool:
and can_player_use_resource() == node.can_player_use
)
func get_node_id() -> StringName:
return StringName(data["node_id"])
func get_action_id() -> StringName:
return StringName(data["action_id"])
func get_resource_id() -> StringName:
return StringName(data["resource_id"])
func get_amount_remaining() -> float:
return float(data["amount_remaining"])
func get_yield_per_action() -> float:
return float(data["yield_per_action"])
func get_reserved_by() -> int:
return int(data["reserved_by"])
func is_enabled() -> bool:
return bool(data["enabled"])
func can_npc_use() -> bool:
return bool(data["can_npcs_use"])
func can_player_use_resource() -> bool:
return bool(data["can_player_use"])
func is_depleted() -> bool:
return get_amount_remaining() <= 0.0
func can_extract() -> bool:
return is_enabled() and not is_depleted()
func is_available_for(agent_id: int) -> bool:
return (
can_extract()
and (get_reserved_by() == -1 or get_reserved_by() == agent_id)
)
return can_extract() and (get_reserved_by() == -1 or get_reserved_by() == agent_id)
func reserve(agent_id: int) -> bool:
if not is_available_for(agent_id):
@@ -131,12 +151,14 @@ func reserve(agent_id: int) -> bool:
changed.emit(self)
return true
func release(agent_id: int) -> void:
if get_reserved_by() != agent_id:
return
data["reserved_by"] = -1
changed.emit(self)
func extract(requested_amount: float = -1.0) -> float:
if not can_extract():
return 0.0
@@ -152,6 +174,7 @@ func extract(requested_amount: float = -1.0) -> float:
depleted.emit(self)
return extracted
func set_amount_remaining(amount: float) -> void:
var was_depleted := is_depleted()
data["amount_remaining"] = maxf(amount, 0.0)
@@ -161,9 +184,11 @@ func set_amount_remaining(amount: float) -> void:
if not was_depleted and is_depleted():
depleted.emit(self)
func set_enabled(value: bool) -> void:
data["enabled"] = value
changed.emit(self)
func to_dictionary() -> Dictionary:
return data.duplicate(true)
+28 -16
View File
@@ -13,6 +13,7 @@ var resources: Array[ResourceStateRecord] = []
var storages: Array[StorageStateRecord] = []
var economic_events: Array[EconomicEventRecord] = []
func to_dictionary() -> Dictionary:
var npc_data: Array[Dictionary] = []
for npc_record in npcs:
@@ -39,15 +40,18 @@ func to_dictionary() -> Dictionary:
"economic_events": event_data
}
func to_json() -> String:
return JSON.stringify(to_dictionary())
static func from_json(json_text: String) -> SimulationStateRecord:
var parsed = JSON.parse_string(json_text)
if not parsed is Dictionary:
return null
return from_dictionary(parsed)
static func from_dictionary(record_data: Dictionary) -> SimulationStateRecord:
if record_data.get("schema", "") != SCHEMA_NAME:
return null
@@ -56,19 +60,25 @@ static func from_dictionary(record_data: Dictionary) -> SimulationStateRecord:
record_data = _migrate_legacy(record_data, version)
elif version != SCHEMA_VERSION:
return null
if not record_data.has_all([
"simulation", "village", "npcs", "resources", "storages",
"economic_events"
]):
if not record_data.has_all(
["simulation", "village", "npcs", "resources", "storages", "economic_events"]
):
return null
var simulation_data = record_data["simulation"]
if not simulation_data is Dictionary:
return null
if not simulation_data.has_all([
"seed", "tick_interval", "tick_count", "clock_accumulator",
"clock_elapsed_ticks", "wander_random_streams", "next_event_id"
]):
if not simulation_data.has_all(
[
"seed",
"tick_interval",
"tick_count",
"clock_accumulator",
"clock_elapsed_ticks",
"wander_random_streams",
"next_event_id"
]
):
return null
var wander_streams = simulation_data["wander_random_streams"]
if not wander_streams is Array:
@@ -160,20 +170,22 @@ static func from_dictionary(record_data: Dictionary) -> SimulationStateRecord:
return record
static func _migrate_legacy(
legacy_data: Dictionary,
version: int
) -> Dictionary:
static func _migrate_legacy(legacy_data: Dictionary, version: int) -> Dictionary:
var migrated := legacy_data.duplicate(true)
migrated["schema_version"] = SCHEMA_VERSION
if version == LEGACY_SCHEMA_VERSION:
var village_data: Dictionary = legacy_data.get("village", {})
var initial_food := float(village_data.get("food", 0.0))
migrated["storages"] = [
StorageStateRecord.create(
SimulationIds.STORAGE_VILLAGE_PANTRY,
{String(SimulationIds.RESOURCE_FOOD): initial_food}
).to_dictionary()
(
StorageStateRecord
. create(
SimulationIds.STORAGE_VILLAGE_PANTRY,
{String(SimulationIds.RESOURCE_FOOD): initial_food}
)
. to_dictionary()
)
]
migrated["economic_events"] = []
var simulation_data: Dictionary = migrated.get("simulation", {})
+20 -14
View File
@@ -5,20 +5,23 @@ const SCHEMA_VERSION := 1
var data: Dictionary
func _init(record_data: Dictionary = {}) -> void:
data = record_data.duplicate(true)
static func create(
storage_id: StringName,
initial_amounts: Dictionary,
capacity: float = 100.0
storage_id: StringName, initial_amounts: Dictionary, capacity: float = 100.0
) -> StorageStateRecord:
return StorageStateRecord.new({
"schema_version": SCHEMA_VERSION,
"storage_id": String(storage_id),
"amounts": initial_amounts.duplicate(true),
"capacity": capacity
})
return StorageStateRecord.new(
{
"schema_version": SCHEMA_VERSION,
"storage_id": String(storage_id),
"amounts": initial_amounts.duplicate(true),
"capacity": capacity
}
)
static func from_dictionary(record_data: Dictionary) -> StorageStateRecord:
if int(record_data.get("schema_version", -1)) != SCHEMA_VERSION:
@@ -34,34 +37,36 @@ static func from_dictionary(record_data: Dictionary) -> StorageStateRecord:
normalized["capacity"] = float(record_data["capacity"])
var normalized_amounts := {}
for item_id in record_data["amounts"]:
normalized_amounts[String(item_id)] = float(
record_data["amounts"][item_id]
)
normalized_amounts[String(item_id)] = float(record_data["amounts"][item_id])
normalized["amounts"] = normalized_amounts
return StorageStateRecord.new(normalized)
func get_storage_id() -> StringName:
return StringName(data["storage_id"])
func get_amount(item_id: StringName) -> float:
return float(data["amounts"].get(String(item_id), 0.0))
func get_total_amount() -> float:
var total := 0.0
for amount in data["amounts"].values():
total += float(amount)
return total
func deposit(item_id: StringName, requested_amount: float) -> float:
var accepted := minf(
maxf(requested_amount, 0.0),
maxf(float(data["capacity"]) - get_total_amount(), 0.0)
maxf(requested_amount, 0.0), maxf(float(data["capacity"]) - get_total_amount(), 0.0)
)
if accepted <= 0.0:
return 0.0
data["amounts"][String(item_id)] = get_amount(item_id) + accepted
return accepted
func withdraw(item_id: StringName, requested_amount: float) -> float:
var removed := minf(maxf(requested_amount, 0.0), get_amount(item_id))
if removed <= 0.0:
@@ -69,5 +74,6 @@ func withdraw(item_id: StringName, requested_amount: float) -> float:
data["amounts"][String(item_id)] = get_amount(item_id) - removed
return removed
func to_dictionary() -> Dictionary:
return data.duplicate(true)
+14 -7
View File
@@ -5,17 +5,22 @@ const SCHEMA_VERSION := 1
var data: Dictionary
func _init(record_data: Dictionary = {}) -> void:
data = record_data.duplicate(true)
static func capture(village: SimVillage) -> VillageStateRecord:
return VillageStateRecord.new({
"schema_version": SCHEMA_VERSION,
"food": village.food,
"wood": village.wood,
"safety": village.safety,
"knowledge": village.knowledge
})
return VillageStateRecord.new(
{
"schema_version": SCHEMA_VERSION,
"food": village.food,
"wood": village.wood,
"safety": village.safety,
"knowledge": village.knowledge
}
)
static func from_dictionary(record_data: Dictionary) -> VillageStateRecord:
if int(record_data.get("schema_version", -1)) != SCHEMA_VERSION:
@@ -24,6 +29,7 @@ static func from_dictionary(record_data: Dictionary) -> VillageStateRecord:
return null
return VillageStateRecord.new(record_data)
func restore(debug_logs: bool) -> SimVillage:
var village := SimVillage.new()
village.debug_logs = debug_logs
@@ -35,5 +41,6 @@ func restore(debug_logs: bool) -> SimVillage:
village.update_priorities()
return village
func to_dictionary() -> Dictionary:
return data.duplicate(true)