extends Node # gdlint: disable=max-file-lines # The manager is the deliberate scene-tree facade for the simulation slice and # intentionally keeps its orchestration readable in one authoritative file. const SimulationEventLogScript := preload("res://simulation/events/SimulationEventLog.gd") const VillageEconomyScript := preload("res://simulation/economy/VillageEconomy.gd") const AnimalCareSystemScript := preload("res://simulation/animals/animal_care_system.gd") const NpcTickDebugLog := preload("res://simulation/debug/npc_tick_debug_log.gd") const RelationshipSystemScript := preload("res://simulation/relationships/RelationshipSystem.gd") const EventKnowledgeSystemScript := preload("res://simulation/knowledge/EventKnowledgeSystem.gd") const ConflictSystemScript := preload("res://simulation/conflict/ConflictSystem.gd") 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) signal npc_travel_requested(npc: SimNPC, target_position: Vector3) signal npc_inventory_changed(npc: SimNPC, item_id: StringName, amount: float) signal economic_event_recorded(event: EconomicEventRecord) signal state_restored signal npc_decision_recorded(npc: SimNPC, decision: ActionSelectionResult) signal relationship_changed(relationship: RelationshipStateRecord, cause_event: EconomicEventRecord) signal event_knowledge_changed(knower_id: int, event: EconomicEventRecord) signal event_knowledge_transferred(speaker_id: int, listener_id: int, event: EconomicEventRecord) signal event_knowledge_forgotten(knower_id: int, event: EconomicEventRecord) signal opportunity_opened(opportunity: OpportunityStateRecord) signal opportunity_resolved(opportunity: OpportunityStateRecord, cause_event: EconomicEventRecord) signal opportunity_invalidated(opportunity: OpportunityStateRecord) signal situation_opened(situation: SituationStateRecord) signal situation_closed(situation: SituationStateRecord) signal quest_journal_changed(entry: QuestJournalEntryStateRecord) signal commitment_changed(commitment: CommitmentStateRecord) signal conversation_started(conversation_id: StringName, turn: ConversationTurn) signal conversation_turn_changed(conversation_id: StringName, turn: ConversationTurn) signal conversation_ended(conversation_id: StringName) signal combatant_spawned(combatant_id: StringName) signal combatant_died(combatant_id: StringName) signal raid_started(raider_ids: Array[StringName]) signal war_resolved(outcome: StringName) signal war_aborted signal player_downed var village := SimVillage.new() var player_system := PlayerCitizenSystem.new() var npcs: Array[SimNPC] = [] @export var tick_interval := 1.2 @export_range(1, 16, 1) var max_ticks_per_frame := 4 @export var simulation_seed: int = 1337 @export var cycle_duration_seconds := 240.0 @export var debug_logs := false @export var active_world_adapter: Node @export var home_positions: Array[Vector3] = [] var clock: SimulationClock var tick_count := 0 var wander_random_sources := {} var resource_states: Dictionary = {} var event_log := SimulationEventLogScript.new() var economy := VillageEconomyScript.new() var animal_care := AnimalCareSystemScript.new() var relationship_system := RelationshipSystemScript.new() var event_knowledge_system := EventKnowledgeSystemScript.new() var opportunity_system := VillageOpportunitySystem.new() var situation_system := SituationSystem.create_default() var quest_journal_system := QuestJournalSystem.new() var commitment_system := SocialCommitmentSystem.new() var commitment_lifecycle := CommitmentLifecycleService.new() var conversation_service := ConversationService.new() var conversation_history: Array[ConversationActStateRecord] = [] var conflict_system := ConflictSystemScript.new() var storage_states: Dictionary: get: return economy.storage_states var economic_events: Array[EconomicEventRecord]: get: return event_log.events var next_event_id: int: get: return event_log.next_event_id set(value): event_log.next_event_id = value var latest_decisions: Dictionary = {} var action_selector := ActionSelectionSystem.new() var action_executor := ActionExecutionSystem.new() var target_resolver := ActionTargetResolver.new() var activity_command_service: ActivityActionCommandService var interaction_service: CatalogInteractionService var _abstract_activity_registry: WorldTargetRegistry var _abstract_activity_command_service: ActivityActionCommandService var _active_activity_registry_instance_id := 0 var last_player_resource_query_stats: Dictionary = {} var _population_view := SimulationPopulationView.new() var speed_index := 2 var _dialogue_speed_index := -1 var _active_player_conversation: StringName var _conversation_context_by_id: Dictionary = {} var _next_conversation_act_id := 0 const SPEED_LEVELS := [0.25, 0.5, 1.0, 2.0, 4.0, 10.0] const KNOWLEDGE_COMMUNICATION_RADIUS := 2.5 const MAX_CONVERSATION_ACTS_PER_PAIR := 8 const MAX_CONVERSATION_HISTORY := 1024 const SEASON_DAYS := 4 const COLD_DAYS := 3 const SEASON_COLD := &"cold" const SEASON_WARM := &"warm" signal speed_changed(multiplier: float) const NPC_NAMES := ["Amina", "Tarik", "Jasmin", "Elma", "Mirza", "Lejla"] func _ready() -> void: add_to_group("simulation_manager") event_log.event_recorded.connect(_on_economic_event_recorded) economy.inventory_changed.connect(_on_economy_inventory_changed) economy.economic_event_requested.connect(_record_economic_event) economy.narrative_event_requested.connect(record_narrative_event) animal_care.economic_event_requested.connect(_record_economic_event_at) animal_care.narrative_event_requested.connect(record_narrative_event) conflict_system.narrative_event_requested.connect(record_narrative_event) conflict_system.combatant_spawned.connect(_on_conflict_combatant_spawned) conflict_system.combatant_died.connect(_on_conflict_combatant_died) conflict_system.raid_started.connect(func(raider_ids): raid_started.emit(raider_ids)) conflict_system.war_resolved.connect(func(outcome): war_resolved.emit(outcome)) conflict_system.war_aborted.connect(func(): war_aborted.emit()) conflict_system.player_damaged.connect(_on_player_damaged) conflict_system.player_downed.connect(func(): player_downed.emit()) action_selector.relationship_system = relationship_system var definition_errors := SimulationDefinitions.validate() if not definition_errors.is_empty(): for error in definition_errors: push_error("SimulationManager: " + error) set_process(false) return _configure_interaction_services() clock = SimulationClock.new(tick_interval) clock.cycle_duration_seconds = cycle_duration_seconds clock.elapsed_ticks = int(0.25 * cycle_duration_seconds / tick_interval) village.debug_logs = debug_logs economy.configure(village, debug_logs) animal_care.configure(economy, active_world_adapter) player_system.configure(economy, _record_player_event_at) conflict_system.configure(economy, tick_interval) economy.initialize_storage() village.update_modifiers() village.update_priorities() generate_npcs() relationship_system.initialize_households(npcs) conflict_system.initialize_factions() conflict_system.register_npc_combatants(npcs) call_deferred("register_loaded_resource_nodes") animal_care.call_deferred("register_loaded_nodes") call_deferred("register_loaded_storage_nodes") if debug_logs: print("--- Simulation started ---") func _process(delta: float) -> void: advance_player_combat_time(delta) var ticks_due := clock.advance(delta * SPEED_LEVELS[speed_index], max_ticks_per_frame) for tick in ticks_due: simulate_tick() func _input(event: InputEvent) -> void: if not event is InputEventKey or not event.pressed or event.echo: return if event.keycode == KEY_BRACKETLEFT: speed_index = maxi(speed_index - 1, 0) speed_changed.emit(SPEED_LEVELS[speed_index]) if debug_logs: print("[SimulationManager] Speed: %.2fx" % SPEED_LEVELS[speed_index]) elif event.keycode == KEY_BRACKETRIGHT: speed_index = mini(speed_index + 1, SPEED_LEVELS.size() - 1) speed_changed.emit(SPEED_LEVELS[speed_index]) if debug_logs: print("[SimulationManager] Speed: %.2fx" % SPEED_LEVELS[speed_index]) func generate_npcs() -> void: var profession_ids := SimulationDefinitions.get_profession_ids() for i in range(NPC_NAMES.size()): var npc_random := _create_random_source(i, 0) var profession_index := npc_random.randi_range(0, profession_ids.size() - 1) var npc := SimNPC.new( i, NPC_NAMES[i], profession_ids[profession_index], npc_random.randf_range(1.0, 10.0), npc_random.randf_range(1.0, 10.0), npc_random ) npc.debug_logs = debug_logs npcs.append(npc) wander_random_sources[i] = _create_random_source(i, 1) var home_count := home_positions.size() if home_count > 0: for i in range(npcs.size()): npcs[i].home_position = home_positions[i % home_count] refresh_population_index() func refresh_population_index() -> void: _population_view.rebuild(npcs) 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)) func simulate_tick() -> void: tick_count += 1 if debug_logs: print("--- Tick ", tick_count, " ---") animal_care.advance(tick_count) advance_player_needs() _advance_resource_regrowth() var village_was_changed := false refresh_population_index() for npc in npcs: village_was_changed = _simulate_npc_tick(npc) or village_was_changed if village_was_changed: village_changed.emit(village) conflict_system.advance(tick_count) var invalidated: OpportunityStateRecord = opportunity_system.maintain_open_opportunity( tick_count, get_knowledge_review_interval(), npcs, get_pantry(), get_woodpile() ) if invalidated != null: opportunity_invalidated.emit(invalidated) _maintain_emergent_world() if tick_count % get_knowledge_review_interval() == 0: _maintain_event_knowledge(true) if debug_logs: print(village.get_summary()) func _simulate_npc_tick(npc: SimNPC) -> bool: var previous_task := npc.current_task var previous_target := npc.target_id var previous_state := npc.task_state var was_complete := npc.task_complete var was_dead := npc.is_dead if animal_care.requires_working_feed_recovery(npc): npc.task_state = SimNPC.TASK_STATE_TRAVELING npc.task_complete = false if not _continue_animal_feed_delivery(npc): _redirect_npc_to_wander(npc) return false action_executor.advance_npc(npc, village) _population_view.refresh_npc(npc) _select_action_if_idle(npc, previous_state) if previous_task != npc.current_task and not previous_target.is_empty(): release_npc_reservation(npc.id) if not was_dead and npc.is_dead: _handle_npc_death(npc, previous_task, previous_target) elif previous_task != npc.current_task: npc_task_changed.emit(npc, previous_task, npc.current_task) npc_target_requested.emit(npc) var completed := not was_complete and npc.task_complete and not npc.is_dead if completed: _complete_current_action(npc) _population_view.refresh_npc(npc) if debug_logs: NpcTickDebugLog.print_tick(npc, previous_state) return completed func _select_action_if_idle(npc: SimNPC, previous_state: StringName) -> void: if npc.is_dead: return if previous_state not in [SimNPC.TASK_STATE_IDLE, SimNPC.TASK_STATE_COMPLETE]: return if npc.task_state not in [SimNPC.TASK_STATE_IDLE, SimNPC.TASK_STATE_COMPLETE]: return if _is_weak_villager_state(npc): record_narrative_event(SimulationIds.EVENT_VILLAGER_WEAK, npc.id) var helper := get_active_opportunity_helper() var animal_feed_available := animal_care.has_available_feed_target(npc.id) var war_raid_active := conflict_system.is_raiding() var selection := action_selector.select_action( npc, village, clock.time_of_day(), npcs, helper, _population_view, animal_feed_available, war_raid_active ) if selection == null: return latest_decisions[npc.id] = selection npc_decision_recorded.emit(npc, selection) npc.set_task(selection.action_id, selection.duration_override) var definition := SimulationDefinitions.get_action(selection.action_id) var display_name := ( definition.display_name if definition != null else String(selection.action_id) ) record_narrative_event(SimulationIds.EVENT_TASK_STARTED, npc.id, &"", display_name) func _is_weak_villager_state(npc: SimNPC) -> bool: return ( npc.is_starving and npc.energy < 25.0 and village.food <= 0.0 and npc.get_inventory_amount(SimulationIds.RESOURCE_FOOD) < 1.0 and opportunity_system.get_open_opportunity() == null ) func _on_conflict_combatant_spawned(combatant_id: StringName) -> void: combatant_spawned.emit(combatant_id) func _on_conflict_combatant_died(combatant_id: StringName) -> void: var combatant := conflict_system.get_combatant(combatant_id) var npc: SimNPC if combatant != null and combatant.get_npc_id() >= 0: npc = _find_npc_by_id(combatant.get_npc_id()) if npc != null: _population_view.refresh_npc(npc) combatant_died.emit(combatant_id) if npc == null or not npc.is_dead: return var previous_task := npc.last_task if npc.last_task != &"" else SimulationIds.ACTION_IDLE _handle_npc_death(npc, previous_task, npc.target_id) func player_attack(combatant_id: StringName) -> float: return conflict_system.player_attack(combatant_id) func player_attack_ready() -> bool: return conflict_system.is_player_attack_ready() func advance_player_combat_time(delta: float) -> void: conflict_system.advance_realtime(delta) func spawn_wolf(position: Vector3) -> StringName: return conflict_system.spawn_wolf(position) func get_combatant(combatant_id: StringName) -> CombatantStateRecord: return conflict_system.get_combatant(combatant_id) func get_faction(faction_id: StringName) -> FactionStateRecord: return conflict_system.get_faction(faction_id) func get_living_hostile_combatants() -> Array[CombatantStateRecord]: return conflict_system.get_living_hostiles() func get_village_defense() -> float: return conflict_system.village_defense() func get_village_defender_count() -> int: return conflict_system.village_defender_count() func get_tribe_war_plan() -> StringName: var tribe := conflict_system.get_faction(SimulationIds.FACTION_TRIBE) return tribe.get_war_plan() if tribe != null else SimulationIds.WAR_PLAN_NONE func _handle_npc_death(npc: SimNPC, previous_task: StringName, previous_target: StringName) -> void: if not previous_target.is_empty(): release_npc_reservation(npc.id) npc_died.emit(npc) npc_task_changed.emit(npc, previous_task, npc.current_task) record_narrative_event(SimulationIds.EVENT_NPC_DIED, npc.id) _notify_mourning(npc) if debug_logs: print("[SimulationManager] NPC died: ", npc.npc_name) func _complete_current_action(npc: SimNPC) -> void: var completed_task := npc.current_task var definition := SimulationDefinitions.get_action(completed_task) var completion_succeeded := false var completion_already_applied := false if _uses_activity_command_handler(definition): var activity_result := execute_activity_action( WorldEntityRef.create(SimulationIds.ENTITY_PERSON, StringName(str(npc.id))), completed_task, npc.target_id, get_action_state_revision() ) completion_succeeded = activity_result != null and activity_result.did_succeed() completion_already_applied = completion_succeeded elif completed_task == SimulationIds.ACTION_FEED_ANIMAL: completion_succeeded = feed_animal(npc.target_id, npc.id) else: completion_succeeded = economy.consume_completion_cost(npc, definition) if completion_succeeded and not completion_already_applied: _apply_action_completion(npc, completed_task, definition) elif not npc.target_id.is_empty(): release_npc_reservation(npc.id) npc.task_complete = true npc.task_state = SimNPC.TASK_STATE_IDLE npc.last_task = completed_task npc.current_task = SimulationIds.ACTION_IDLE npc.has_travel_target = false npc.target_id = &"" npc_task_changed.emit(npc, completed_task, npc.current_task) func _apply_action_completion( npc: SimNPC, completed_task: StringName, definition: ActionDefinition ) -> void: if definition != null and definition.target_type == SimulationIds.TARGET_RESOURCE: _complete_resource_gather(npc, completed_task) return match completed_task: SimulationIds.ACTION_DEPOSIT_FOOD: economy.deposit_inventory(npc, SimulationIds.RESOURCE_FOOD) SimulationIds.ACTION_DEPOSIT_WOOD: economy.deposit_inventory(npc, SimulationIds.RESOURCE_WOOD) SimulationIds.ACTION_WITHDRAW_FOOD: economy.withdraw_to_inventory(npc, SimulationIds.RESOURCE_FOOD, 1.0) SimulationIds.ACTION_EAT: economy.consume_npc_food(npc) SimulationIds.ACTION_SLEEP: npc.energy = minf(npc.energy + 40.0, 100.0) npc.position = npc.home_position record_narrative_event(SimulationIds.EVENT_NPC_SLEPT, npc.id) if village.safety < 25.0 and opportunity_system.get_open_opportunity() == null: record_narrative_event(SimulationIds.EVENT_HOME_DAMAGED, npc.id) SimulationIds.ACTION_FEED_ANIMAL: pass SimulationIds.ACTION_REST, SimulationIds.ACTION_WANDER: village.apply_npc_task(npc) SimulationIds.ACTION_DEFEND: village.apply_metric_delta(&"safety", 0.5) if debug_logs and completed_task == SimulationIds.ACTION_SLEEP: print("[SimulationManager] ", npc.npc_name, " completed sleep at home") func _complete_resource_gather(npc: SimNPC, completed_task: StringName) -> void: var resource_state := get_resource_state(npc.target_id) if resource_state == null or resource_state.get_reserved_by() != npc.id: if debug_logs: print( ( "[SimulationManager] %s could not complete %s: invalid reservation" % [npc.npc_name, completed_task] ) ) release_npc_reservation(npc.id) return var extracted := resource_state.extract( resource_state.get_yield_per_action() * _gather_yield_multiplier() ) if extracted > 0.0: var resource_id := resource_state.get_resource_id() npc.add_inventory(resource_id, extracted) npc_inventory_changed.emit(npc, resource_id, npc.get_inventory_amount(resource_id)) _record_economic_event( SimulationIds.EVENT_RESOURCE_EXTRACTED, npc.id, resource_state.get_node_id(), SimulationIds.npc_inventory_id(npc.id), resource_id, extracted ) if resource_state.get_amount_remaining() <= 0.0: record_narrative_event( SimulationIds.EVENT_RESOURCE_DEPLETED, npc.id, resource_state.get_node_id() ) if debug_logs: print( ( "[SimulationManager] %s extracted %.1f %s from %s" % [npc.npc_name, extracted, resource_id, resource_state.get_node_id()] ) ) release_npc_reservation(npc.id) func release_npc_reservation(npc_id: int) -> void: var npc := _find_npc_by_id(npc_id) if npc == null: return if npc.target_id != &"": var resource_state := get_resource_state(npc.target_id) if resource_state != null: resource_state.release(npc.id) var animal_state := animal_care.get_state(npc.target_id) if animal_state != null: animal_state.release(npc.id) npc.target_id = &"" func notify_npc_arrived(npc_id: int) -> void: var npc := _find_npc_by_id(npc_id) if npc == null or npc.is_dead: return if npc.task_state == SimNPC.TASK_STATE_TRAVELING: var definition := SimulationDefinitions.get_action(npc.current_task) if ( npc.target_id != &"" and definition != null and definition.target_type == SimulationIds.TARGET_RESOURCE ): var resource_state := get_resource_state(npc.target_id) if ( resource_state == null or not resource_state.can_extract() or resource_state.get_reserved_by() != npc.id ): if debug_logs: NpcTickDebugLog.print_unavailable_resource(npc) notify_npc_navigation_failed(npc.id) return if ( npc.target_id != &"" and definition != null and definition.target_type == SimulationIds.TARGET_ANIMAL ): if not animal_care.can_complete_feed(npc.target_id, npc.id): if debug_logs: NpcTickDebugLog.print_unavailable_animal(npc) notify_npc_navigation_failed(npc.id) return if animal_care.requires_feed_pickup(npc): if _continue_animal_feed_delivery(npc): return _redirect_npc_to_wander(npc) return npc.has_travel_target = false npc.start_working( npc.current_task == SimulationIds.ACTION_FEED_ANIMAL and npc.task_progress > 0.0 ) var working_speakers: Array[SimNPC] = [] if npc.target_id != &"": for other in npcs: if other.id == npc.id or other.is_dead: continue if other.target_id != npc.target_id: continue if other.task_state in [SimNPC.TASK_STATE_TRAVELING, SimNPC.TASK_STATE_WORKING]: relationship_system.increase_shared_work_familiarity(npc.id, other.id) if other.task_state == SimNPC.TASK_STATE_WORKING: working_speakers.append(other) working_speakers.sort_custom(_sort_npcs_by_id) for speaker in working_speakers: if try_communicate_at_shared_activity(speaker.id, npc.id): break if debug_logs: NpcTickDebugLog.print_started_work(npc) func _continue_animal_feed_delivery(npc: SimNPC) -> bool: var animal_target := target_resolver.resolve_claimed_animal(npc, self, active_world_adapter) var pantry_target := target_resolver.resolve_storage_target( SimulationIds.STORAGE_VILLAGE_PANTRY, active_world_adapter ) if animal_target.is_empty() or pantry_target.is_empty(): return false if not npc.travel_target_position.is_equal_approx(pantry_target["position"]): npc.travel_target_position = pantry_target["position"] npc.has_travel_target = true npc_travel_requested.emit(npc, npc.travel_target_position) return true var pickup_target := npc.travel_target_position npc.travel_target_position = animal_target["position"] npc.has_travel_target = true if not animal_care.collect_feed_supply(npc): npc.travel_target_position = pickup_target return false village_changed.emit(village) npc_travel_requested.emit(npc, npc.travel_target_position) return true func _redirect_npc_to_wander(npc: SimNPC) -> void: var failed_task := npc.current_task release_npc_reservation(npc.id) npc.last_task = failed_task npc.set_task(SimulationIds.ACTION_WANDER, 2.0) npc_task_changed.emit(npc, failed_task, npc.current_task) npc_target_requested.emit(npc) func notify_npc_navigation_failed(npc_id: int) -> void: var npc := _find_npc_by_id(npc_id) if npc == null or npc.is_dead or npc.task_state != SimNPC.TASK_STATE_TRAVELING: return var failed_task := npc.current_task _redirect_npc_to_wander(npc) if debug_logs: NpcTickDebugLog.print_navigation_failure(npc, failed_task) func resolve_npc_target(npc_id: int, origin: Vector3) -> bool: var npc := _find_npc_by_id(npc_id) if npc == null or npc.is_dead or npc.task_state != SimNPC.TASK_STATE_TRAVELING: return false if npc.current_task == SimulationIds.ACTION_SLEEP: npc.travel_target_position = npc.home_position npc.has_travel_target = true npc_travel_requested.emit(npc, npc.travel_target_position) return true if active_world_adapter == null: push_error("SimulationManager: active_world_adapter is missing") return false var definition := SimulationDefinitions.get_action(npc.current_task) if _uses_activity_command_handler(definition) and not _ensure_interaction_services_current(): return false var result := target_resolver.resolve(npc, origin, self, active_world_adapter) if result.is_empty(): notify_npc_navigation_failed(npc.id) return false npc.target_id = StringName(result.get("target_id", "")) npc.travel_target_position = result["position"] if ( definition != null and _uses_activity_command_handler(definition) and not _bind_abstract_activity_target( npc.target_id, npc.current_task, npc.travel_target_position ) ): notify_npc_navigation_failed(npc.id) return false npc.has_travel_target = true npc_travel_requested.emit(npc, npc.travel_target_position) return true func request_current_travel(npc_id: int) -> bool: var npc := _find_npc_by_id(npc_id) if npc == null or npc.task_state != SimNPC.TASK_STATE_TRAVELING: return false if npc.has_travel_target: npc_travel_requested.emit(npc, npc.travel_target_position) else: npc_target_requested.emit(npc) return true func synchronize_npc_position(npc_id: int, active_position: Vector3) -> bool: var npc := _find_npc_by_id(npc_id) if npc == null: return false npc.position = active_position return true func get_activity_target_claim_count(target_id: StringName, except_npc_id: int = -1) -> int: var count := 0 for npc in npcs: if npc.id == except_npc_id or npc.is_dead: continue if npc.target_id != target_id: continue if npc.task_state in [SimNPC.TASK_STATE_TRAVELING, SimNPC.TASK_STATE_WORKING]: count += 1 return count func get_action_state_revision() -> int: return event_log.next_event_id func get_player_activity_offer(from_position: Vector3, max_distance: float) -> Dictionary: if not _ensure_interaction_services_current(): return {} if ( interaction_service == null or active_world_adapter == null or not from_position.is_finite() or not is_finite(max_distance) or max_distance <= 0.0 or not active_world_adapter.has_method("get_target_registry") ): return {} var registry := active_world_adapter.call("get_target_registry") as WorldTargetRegistry if registry == null: return {} var actor := WorldEntityRef.create( SimulationIds.ENTITY_PLAYER, StringName(str(SimulationIds.PLAYER_ACTOR_ID)) ) var candidates: Array[Dictionary] = [] for descriptor in registry.get_descriptors(ActiveWorldAdapter.TARGET_KIND_ACTIVITY): var distance := from_position.distance_to(descriptor.get_local_position()) if distance > max_distance: continue var handle := registry.get_handle(descriptor.get_target_id()) for offer in interaction_service.get_offers(actor, handle): var definition := SimulationDefinitions.get_action(offer.get_action_id()) if not _uses_activity_command_handler(definition): continue var capability := descriptor.get_capability(offer.get_action_id()) var raw_range: Variant = capability.get_attribute(&"interaction_range", 0.0) if raw_range is not int and raw_range is not float: continue var capability_range := float(raw_range) if ( not is_finite(capability_range) or capability_range <= 0.0 or distance > capability_range ): continue ( candidates . append( { "action_id": String(offer.get_action_id()), "target_id": String(descriptor.get_target_id()), "display_name": descriptor.get_display_name(), "action_name": offer.get_display_name(), "distance": distance, "priority": offer.get_priority(), "state_revision": get_action_state_revision(), "target_generation": handle.get_generation(), "target_context_id": String(handle.get_context_id()), "target_registry_instance_id": registry.get_instance_id(), "target_kind": String(handle.get_target_kind()), "effect": _player_activity_effect_summary(definition), "enabled": offer.is_enabled(), "blocked_reason": offer.get_rejection_reason(), "offer_parameters": offer.get_parameters(), } ) ) if candidates.is_empty(): return {} candidates.sort_custom(_activity_offer_precedes) return candidates[0].duplicate(true) func execute_activity_action( actor: WorldEntityRef, action_id: StringName, target_id: StringName, expected_state_revision: int = -1 ) -> ActionResult: if ( actor == null or not actor.is_valid() or actor.get_entity_type() != SimulationIds.ENTITY_PERSON or expected_state_revision < 0 ): return ActionResult.rejected(&"activity_invalid_actor", &"invalid_actor") return _execute_authorized_activity_action(actor, action_id, target_id, expected_state_revision) func _execute_authorized_activity_action( actor: WorldEntityRef, action_id: StringName, target_id: StringName, expected_state_revision: int ) -> ActionResult: if not _ensure_interaction_services_current(): return ActionResult.rejected(&"activity_scope_mismatch", &"service_unavailable") var selected_service := activity_command_service var handle: WorldTargetHandle if actor.get_entity_type() == SimulationIds.ENTITY_PERSON: var npc_id_text := String(actor.get_entity_id()) var npc := _find_npc_by_id(npc_id_text.to_int()) if npc_id_text.is_valid_int() else null if ( npc == null or npc.is_dead or npc.task_state != SimNPC.TASK_STATE_COMPLETE or not npc.task_complete or npc.current_task != action_id or npc.target_id.is_empty() or npc.target_id != target_id ): return ActionResult.rejected( &"activity_assignment_mismatch", ActivityActionCommandService.REASON_UNSUPPORTED_ACTOR ) selected_service = _abstract_activity_command_service handle = _ensure_abstract_activity_handle(action_id, target_id) elif active_world_adapter != null and active_world_adapter.has_method("get_target_registry"): var registry := active_world_adapter.call("get_target_registry") as WorldTargetRegistry handle = registry.get_handle(target_id) if registry != null else null if selected_service == null or handle == null: return ActionResult.rejected(&"activity_unavailable", &"service_unavailable") var actor_key := actor.index_key() if actor != null else "invalid" var command_revision := get_action_state_revision() var command_id := StringName( ( "activity_%s_%s_%s_%d_%d" % [ actor_key.sha256_text().substr(0, 8), action_id, target_id, tick_count, command_revision, ] ) ) return selected_service.submit_command( ActionCommand.new(command_id, actor, action_id, handle, {}, expected_state_revision) ) func execute_player_activity_action( action_id: StringName, target_id: StringName, expected_state_revision: int = -1, expected_target_generation: int = -1, expected_context_id: StringName = &"", expected_registry_instance_id: int = 0 ) -> ActionResult: if not _ensure_interaction_services_current(): return ActionResult.rejected(&"player_activity_stale", &"service_unavailable") if ( expected_state_revision < 0 or expected_target_generation < 1 or expected_context_id.is_empty() or expected_registry_instance_id == 0 or active_world_adapter == null or not active_world_adapter.has_method("get_target_registry") ): return ActionResult.rejected( &"player_activity_stale", ActivityActionCommandService.REASON_STALE_TARGET, "The activity offer is incomplete; refresh it" ) var registry := active_world_adapter.call("get_target_registry") as WorldTargetRegistry var current_handle := registry.get_handle(target_id) if registry != null else null if ( current_handle == null or registry.get_instance_id() != expected_registry_instance_id or current_handle.get_generation() != expected_target_generation or current_handle.get_context_id() != expected_context_id or current_handle.get_target_kind() != SimulationIds.TARGET_ACTIVITY ): return ActionResult.rejected( &"player_activity_stale", ActivityActionCommandService.REASON_STALE_TARGET, "The activity changed; refresh the interaction offer" ) return _execute_authorized_activity_action( WorldEntityRef.create( SimulationIds.ENTITY_PLAYER, StringName(str(SimulationIds.PLAYER_ACTOR_ID)) ), action_id, target_id, expected_state_revision ) func _configure_interaction_services() -> bool: activity_command_service = null interaction_service = null _active_activity_registry_instance_id = 0 var current_scope := event_log.get_scope() var scope_world_id := StringName( current_scope.get("world_id", SimulationIds.REGIONAL_WORLD_BOSNIA) ) var scope_location_id := StringName( current_scope.get("location_id", SimulationIds.REGIONAL_LOCATION_JAJCE) ) if active_world_adapter != null and active_world_adapter.has_method("get_context_identity"): var identity: Dictionary = active_world_adapter.call("get_context_identity") scope_world_id = StringName(identity.get("world_id", scope_world_id)) scope_location_id = StringName(identity.get("location_id", scope_location_id)) if not event_log.configure_scope(scope_world_id, scope_location_id): return false _abstract_activity_registry = WorldTargetRegistry.new( &"simulation_jajce", scope_world_id, scope_location_id ) _abstract_activity_command_service = ActivityActionCommandService.new( _abstract_activity_registry, SimulationDefinitions.get_action, _get_activity_actor_position, get_action_state_revision, _complete_activity_command, false, false ) register_abstract_activity_target( SimulationIds.ACTIVITY_GUARD_POST, SimulationIds.ACTION_PATROL, Vector3.ZERO ) register_abstract_activity_target( SimulationIds.ACTIVITY_STUDY_DESK, SimulationIds.ACTION_STUDY, Vector3.ZERO ) _rebuild_abstract_activity_targets_from_npcs() var catalog := ContentCatalog.create_core() if not catalog.is_valid(): return false if active_world_adapter == null or not active_world_adapter.has_method("get_target_registry"): return true var registry := active_world_adapter.call("get_target_registry") as WorldTargetRegistry if registry == null: return false activity_command_service = ActivityActionCommandService.new( registry, SimulationDefinitions.get_action, _get_activity_actor_position, get_action_state_revision, _complete_activity_command, true ) interaction_service = CatalogInteractionService.new( registry, catalog, _evaluate_activity_availability, true ) _active_activity_registry_instance_id = registry.get_instance_id() return true func register_abstract_activity_target( target_id: StringName, action_id: StringName, position: Vector3, interaction_range: float = 0.5 ) -> bool: if ( _abstract_activity_registry == null or target_id.is_empty() or not position.is_finite() or not is_finite(interaction_range) or interaction_range <= 0.0 or _abstract_activity_registry.has_target(target_id) ): return false var definition := SimulationDefinitions.get_action(action_id) if not _uses_activity_command_handler(definition): return false var scope := _abstract_activity_registry.get_identity() var handle := ( _abstract_activity_registry . register_target( ( WorldTargetDescriptor . new( target_id, ActiveWorldAdapter.TARGET_KIND_ACTIVITY, [ WorldTargetCapability.new( action_id, {"interaction_range": interaction_range} ) ], position, definition.display_name, { "authority": "simulation", "world_id": String(scope["world_id"]), "location_id": String(scope["location_id"]), } ) ) ) ) return handle != null func _bind_abstract_activity_target( target_id: StringName, action_id: StringName, position: Vector3 ) -> bool: if _abstract_activity_registry == null or target_id.is_empty() or not position.is_finite(): return false var existing := _abstract_activity_registry.get_handle(target_id) if existing == null: return register_abstract_activity_target(target_id, action_id, position) var descriptor := _abstract_activity_registry.resolve_handle(existing) if ( descriptor == null or descriptor.get_target_kind() != SimulationIds.TARGET_ACTIVITY or not descriptor.has_capability(action_id) ): return false return _abstract_activity_registry.update_target_position(existing, position) func _rebuild_abstract_activity_targets_from_npcs() -> void: for npc in npcs: if npc.is_dead or npc.target_id.is_empty(): continue var definition := SimulationDefinitions.get_action(npc.current_task) if not _uses_activity_command_handler(definition): continue _bind_abstract_activity_target(npc.target_id, npc.current_task, npc.travel_target_position) func _ensure_interaction_services_current() -> bool: if active_world_adapter == null or not active_world_adapter.has_method("get_target_registry"): return _abstract_activity_command_service != null var registry := active_world_adapter.call("get_target_registry") as WorldTargetRegistry if registry == null: return false var identity := registry.get_identity() var event_scope := event_log.get_scope() if ( StringName(identity["world_id"]) != StringName(event_scope["world_id"]) or StringName(identity["location_id"]) != StringName(event_scope["location_id"]) ): if not economic_events.is_empty(): activity_command_service = null interaction_service = null return false if registry.get_instance_id() == _active_activity_registry_instance_id: return activity_command_service != null and _abstract_activity_command_service != null return _configure_interaction_services() func _ensure_abstract_activity_handle( action_id: StringName, requested_target_id: StringName ) -> WorldTargetHandle: if _abstract_activity_registry == null: return null var target_id := requested_target_id if target_id.is_empty(): var candidates := _abstract_activity_registry.get_target_ids( ActiveWorldAdapter.TARGET_KIND_ACTIVITY, action_id ) if candidates.size() != 1: return null target_id = candidates[0] var existing := _abstract_activity_registry.get_handle(target_id) if existing == null: return null var descriptor := _abstract_activity_registry.resolve_handle(existing) if descriptor == null or not descriptor.has_capability(action_id): return null return _abstract_activity_registry.get_handle(target_id) func _evaluate_activity_availability( actor: WorldEntityRef, _descriptor: WorldTargetDescriptor, definition: ActionDefinition, _capability: WorldTargetCapability ) -> InteractionAvailabilityDecision: if not _uses_activity_command_handler(definition): return InteractionAvailabilityDecision.denied( &"unsupported_handler", "This activity has no supported completion handler", [&"handler_missing"] ) var effect := ActivityActionCommandService._metric_effect(definition) var actor_id := _activity_actor_id(actor) if effect == null or actor_id < SimulationIds.PLAYER_ACTOR_ID: return InteractionAvailabilityDecision.denied( &"invalid_effect", "This activity has no valid effect", [&"effect_rejected"] ) var requested_amount := _activity_effect_amount(actor_id, effect.value, effect.parameters) if _bounded_activity_effect_amount(effect.subject_key, requested_amount) <= 0.0: return InteractionAvailabilityDecision.denied( &"no_effect", "This activity cannot improve the village further", [&"effect_capped"] ) if definition.has_completion_cost(): var storage := economy.get_storage_for_resource(definition.completion_cost_resource_id) var available := ( storage.get_amount(definition.completion_cost_resource_id) if storage != null else 0.0 ) if available < definition.completion_cost_amount: return InteractionAvailabilityDecision.denied( &"insufficient_cost", ( "Needs %.0f %s" % [definition.completion_cost_amount, definition.completion_cost_resource_id] ), [&"cost_rejected"], {"available": available, "required": definition.completion_cost_amount} ) return InteractionAvailabilityDecision.allowed([&"cost_allowed"]) func _get_activity_actor_position(actor: WorldEntityRef) -> Variant: var actor_id := _activity_actor_id(actor) if actor_id == SimulationIds.PLAYER_ACTOR_ID: var combatant := conflict_system.get_combatant(ConflictSystemScript.PLAYER_COMBATANT_ID) return combatant.get_position() if combatant != null else null var npc := _find_npc_by_id(actor_id) return npc.position if npc != null and not npc.is_dead else null func _complete_activity_command( actor: WorldEntityRef, action_id: StringName, target_id: StringName, metric_id: StringName, base_amount: float, effect_parameters: Dictionary, world_position: Vector3 ) -> Dictionary: var actor_id := _activity_actor_id(actor) var definition := SimulationDefinitions.get_action(action_id) if actor_id < SimulationIds.PLAYER_ACTOR_ID or not _uses_activity_command_handler(definition): return {"succeeded": false, "event_id": -1, "state_revision": get_action_state_revision()} var requested_amount := _activity_effect_amount(actor_id, base_amount, effect_parameters) var applied_amount := _bounded_activity_effect_amount(metric_id, requested_amount) if not is_finite(applied_amount) or applied_amount <= 0.0: return { "succeeded": false, "reason_code": "no_effect", "message": "This activity cannot improve the village further", "event_id": -1, "state_revision": get_action_state_revision(), } var cost_storage: StorageStateRecord var cost_item_id: StringName var cost_amount := 0.0 if definition.has_completion_cost(): cost_item_id = definition.completion_cost_resource_id cost_amount = definition.completion_cost_amount cost_storage = economy.get_storage_for_resource(cost_item_id) var available := cost_storage.get_amount(cost_item_id) if cost_storage != null else 0.0 if available < cost_amount: var blocked := event_log.record_activity_blocked( tick_count, actor_id, target_id, action_id, ( "%s: needs %.0f %s" % [definition.display_name, cost_amount, String(cost_item_id).capitalize()] ), world_position, cost_storage.get_storage_id() if cost_storage != null else &"", cost_item_id, cost_amount ) return { "succeeded": false, "reason_code": "insufficient_cost", "message": "Needs %.0f %s" % [cost_amount, cost_item_id], "event_id": int(blocked.data["event_id"]) if blocked != null else -1, "state_revision": get_action_state_revision(), } var previous_metric := village.safety if metric_id == &"safety" else village.knowledge if cost_storage != null and cost_storage.withdraw(cost_item_id, cost_amount) < cost_amount: return {"succeeded": false, "event_id": -1, "state_revision": get_action_state_revision()} if cost_storage != null: economy.sync_resource(cost_item_id) village.apply_metric_delta(metric_id, applied_amount) var actual_amount := ( village.safety - previous_metric if metric_id == &"safety" else village.knowledge - previous_metric ) if not is_finite(actual_amount) or actual_amount <= 0.0: if cost_storage != null: cost_storage.deposit(cost_item_id, cost_amount) economy.sync_resource(cost_item_id) _restore_village_metric(metric_id, previous_metric) return { "succeeded": false, "reason_code": "no_effect", "message": "This activity cannot improve the village further", "event_id": -1, "state_revision": get_action_state_revision(), } var event := event_log.record_activity_completed( tick_count, actor_id, target_id, action_id, definition.event_type_id, metric_id, actual_amount, world_position, cost_item_id, cost_amount ) if event == null: if cost_storage != null: cost_storage.deposit(cost_item_id, cost_amount) economy.sync_resource(cost_item_id) _restore_village_metric(metric_id, previous_metric) return {"succeeded": false, "event_id": -1, "state_revision": get_action_state_revision()} village_changed.emit(village) return { "succeeded": true, "event_id": int(event.data["event_id"]), "state_revision": get_action_state_revision(), "applied_amount": actual_amount, } func _activity_actor_id(actor: WorldEntityRef) -> int: if actor == null or not actor.is_valid(): return SimulationIds.PLAYER_ACTOR_ID - 1 var id_text := String(actor.get_entity_id()) if not id_text.is_valid_int(): return SimulationIds.PLAYER_ACTOR_ID - 1 var actor_id := id_text.to_int() if actor.get_entity_type() == SimulationIds.ENTITY_PLAYER: return ( actor_id if ( actor_id == SimulationIds.PLAYER_ACTOR_ID and player_system.player_state != null and not player_system.player_state.is_downed() ) else -2 ) if actor.get_entity_type() != SimulationIds.ENTITY_PERSON or actor_id < 0: return -2 var npc := _find_npc_by_id(actor_id) return actor_id if npc != null and not npc.is_dead else -2 func _activity_effect_amount(actor_id: int, base_amount: float, parameters: Dictionary) -> float: var result := base_amount if actor_id == SimulationIds.PLAYER_ACTOR_ID: var raw_multiplier: Variant = parameters.get("player_multiplier", 1.0) if raw_multiplier is int or raw_multiplier is float: result *= float(raw_multiplier) return result if bool(parameters.get("npc_productivity", false)): var npc := _find_npc_by_id(actor_id) if npc == null: return 0.0 if npc.is_starving: result *= 0.35 elif npc.energy < 20.0: result *= 0.25 elif npc.energy < 40.0: result *= 0.5 return result func _player_activity_effect_summary(definition: ActionDefinition) -> Dictionary: if definition == null: return {} var effect := ActivityActionCommandService._metric_effect(definition) if effect == null: return {} var requested_amount := _activity_effect_amount( SimulationIds.PLAYER_ACTOR_ID, effect.value, effect.parameters ) return { "metric_id": String(effect.subject_key), "amount": _bounded_activity_effect_amount(effect.subject_key, requested_amount), } func _bounded_activity_effect_amount(metric_id: StringName, requested_amount: float) -> float: if not is_finite(requested_amount) or requested_amount <= 0.0: return 0.0 if metric_id == &"safety": return minf(requested_amount, maxf(100.0 - village.safety, 0.0)) if metric_id == &"knowledge": return requested_amount return 0.0 func _restore_village_metric(metric_id: StringName, value: float) -> void: if metric_id == &"safety": village.safety = value elif metric_id == &"knowledge": village.knowledge = value village.update_modifiers() village.update_priorities() static func _uses_activity_command_handler(definition: ActionDefinition) -> bool: return ( definition != null and definition.completion_handler_id == ActivityActionCommandService.HANDLER_METRIC_DELTA ) static func _activity_offer_precedes(first: Dictionary, second: Dictionary) -> bool: if not is_equal_approx(float(first["distance"]), float(second["distance"])): return float(first["distance"]) < float(second["distance"]) if float(first["priority"]) != float(second["priority"]): return float(first["priority"]) > float(second["priority"]) if String(first["target_id"]) != String(second["target_id"]): return String(first["target_id"]) < String(second["target_id"]) return String(first["action_id"]) < String(second["action_id"]) func _notify_mourning(dead_npc: SimNPC) -> void: var mourner := relationship_system.get_most_familiar_living(dead_npc.id, npcs, _population_view) if mourner == null: return mourner.mourning_ticks = 100 if debug_logs: print("[SimulationManager] ", mourner.npc_name, " is mourning ", dead_npc.npc_name) func _record_economic_event( event_type: StringName, actor_id: int, source_id: StringName, destination_id: StringName, item_id: StringName, amount: float ) -> void: _record_economic_event_at( event_type, actor_id, source_id, destination_id, item_id, amount, _get_event_world_position(actor_id, source_id, destination_id) ) func _record_economic_event_at( event_type: StringName, actor_id: int, source_id: StringName, destination_id: StringName, item_id: StringName, amount: float, world_position: Vector3 ) -> void: event_log.record_economic( tick_count, event_type, actor_id, source_id, destination_id, item_id, amount, world_position ) func record_narrative_event( event_type: StringName, actor_id: int, source_id: StringName = &"", action_display: String = "", action_id: StringName = &"", item_id: StringName = &"", required_amount: float = 0.0 ) -> void: _record_narrative_event_at( event_type, actor_id, source_id, action_display, _get_event_world_position(actor_id, source_id, &""), action_id, item_id, required_amount ) func _record_narrative_event_at( event_type: StringName, actor_id: int, source_id: StringName, action_display: String, world_position: Vector3, action_id: StringName = &"", item_id: StringName = &"", required_amount: float = 0.0 ) -> void: event_log.record_narrative( tick_count, event_type, actor_id, source_id, action_display, world_position, action_id, item_id, required_amount ) func _get_event_world_position( actor_id: int, source_id: StringName, destination_id: StringName ) -> Vector3: for npc in npcs: if npc.id != actor_id: continue if not npc.target_id.is_empty() and npc.target_id in [source_id, destination_id]: return npc.travel_target_position return npc.position return Vector3.ZERO func get_npc_events(npc_id: int, max_count: int = 8) -> Array[EconomicEventRecord]: return event_log.get_for_actor(npc_id, max_count) func get_recent_events(max_count: int = 5) -> Array[EconomicEventRecord]: return event_log.get_recent(max_count) func _on_economic_event_recorded(event: EconomicEventRecord) -> void: var learned_records: Array[KnownEventStateRecord] = event_knowledge_system.observe_event( event, npcs ) for learned_record in learned_records: _apply_new_event_knowledge(learned_record, event) _update_opportunity_from_event(event) _update_situations_from_event(event) economic_event_recorded.emit(event) func try_communicate_at_shared_activity(speaker_id: int, listener_id: int) -> bool: var speaker := _find_npc_by_id(speaker_id) var listener := _find_npc_by_id(listener_id) if not _can_communicate_at_shared_activity(speaker, listener): return false var known_event_ids := event_knowledge_system.get_communicable_event_ids( speaker.id, _get_lasting_event_ids(speaker.id), opportunity_system.get_open_trigger_event_id() ) for event_id in known_event_ids: var event := event_log.get_by_id(event_id) if event == null: continue var learned_record := event_knowledge_system.communicate_event( event, speaker.id, listener.id, tick_count ) if learned_record == null: continue _apply_new_event_knowledge(learned_record, event) event_knowledge_transferred.emit(speaker.id, listener.id, event) _update_opportunity_from_event(event) return true return false func _can_communicate_at_shared_activity(speaker: SimNPC, listener: SimNPC) -> bool: if speaker == null or listener == null or speaker.id == listener.id: return false if speaker.is_dead or listener.is_dead: return false if ( speaker.task_state != SimNPC.TASK_STATE_WORKING or listener.task_state != SimNPC.TASK_STATE_WORKING ): return false if speaker.target_id.is_empty() or speaker.target_id != listener.target_id: return false if storage_states.has(speaker.target_id): return false var speaker_action := SimulationDefinitions.get_action(speaker.current_task) var listener_action := SimulationDefinitions.get_action(listener.current_task) if ( speaker_action == null or listener_action == null or speaker_action.target_type != SimulationIds.TARGET_ACTIVITY or listener_action.target_type != SimulationIds.TARGET_ACTIVITY ): return false return ( speaker.position.distance_squared_to(listener.position) <= KNOWLEDGE_COMMUNICATION_RADIUS * KNOWLEDGE_COMMUNICATION_RADIUS ) func _apply_new_event_knowledge( known_event: KnownEventStateRecord, event: EconomicEventRecord ) -> void: var newly_informed_ids: Array[int] = [known_event.get_knower_id()] var changed_relationships: Array[RelationshipStateRecord] = relationship_system.apply_event( event, npcs, newly_informed_ids ) event_knowledge_changed.emit(known_event.get_knower_id(), event) for relationship in changed_relationships: relationship_changed.emit(relationship, event) _maintain_event_knowledge(false) func _update_opportunity_from_event(event: EconomicEventRecord) -> void: var changed: OpportunityStateRecord = opportunity_system.consider_event( event, tick_count, get_pantry(), npcs, event_knowledge_system, resource_states, get_woodpile() ) if changed == null: return if changed.get_status() == OpportunityStateRecord.STATUS_OPEN: opportunity_opened.emit(changed) return opportunity_resolved.emit(changed, event) _maintain_event_knowledge(false) func _update_situations_from_event(event: EconomicEventRecord) -> void: var world_event := event_log.get_world_event(int(event.data["event_id"])) if world_event == null: return var interested_npc_id := int(event.data["actor_id"]) if interested_npc_id < 0 or _find_npc_by_id(interested_npc_id) == null: _maintain_emergent_world() return var facts := _get_situation_facts(interested_npc_id) for evaluation in situation_system.consider_event(world_event, tick_count, facts): if evaluation.opened_situation_id < 0: continue var opened := situation_system.get_by_id(evaluation.opened_situation_id) if opened != null: situation_opened.emit(opened) _maintain_emergent_world() func _maintain_emergent_world() -> void: var facts := _get_situation_facts() var closed := situation_system.maintain(tick_count, event_log.world_events, facts) var changed_commitments := commitment_lifecycle.maintain_and_record( tick_count, commitment_system, situation_system, event_log, facts, relationship_system ) for situation in closed: situation_closed.emit(situation) var journal_entry := quest_journal_system.synchronize(situation, tick_count) if journal_entry != null: quest_journal_changed.emit(journal_entry) for commitment in changed_commitments: var outcome_fact := commitment_lifecycle.record_outcome( commitment, event_log, relationship_system ) _share_commitment_fact_with_creditor(commitment, outcome_fact) commitment_changed.emit(commitment) func _get_situation_facts(interested_npc_id: int = -1) -> Dictionary: var facts := { "pantry.food": get_pantry().get_amount(SimulationIds.RESOURCE_FOOD), "target_id": String(SimulationIds.STORAGE_VILLAGE_PANTRY), } if interested_npc_id >= 0: facts["interested_npc_id"] = interested_npc_id return facts func _maintain_event_knowledge(expire_by_age: bool) -> void: var forgotten := event_knowledge_system.maintain_retention( tick_count, get_knowledge_review_interval(), _get_lasting_knowledge_records(), expire_by_age ) for known_event in forgotten: var event := event_log.get_by_id(known_event.get_event_id()) if event != null: event_knowledge_forgotten.emit(known_event.get_knower_id(), event) func _get_lasting_knowledge_records() -> Array[KnownEventStateRecord]: var lasting: Array[KnownEventStateRecord] = [] var seen := {} for relationship in relationship_system.get_all_sorted(): for dimension in RelationshipStateRecord.DIMENSIONS: var event_id := relationship.get_last_cause_event_id(dimension) _append_lasting_knowledge(lasting, seen, relationship.get_observer_id(), event_id) var open_opportunity: OpportunityStateRecord = opportunity_system.get_open_opportunity() if open_opportunity != null: var opportunity_record := event_knowledge_system.get_record( open_opportunity.get_interested_npc_id(), open_opportunity.get_trigger_event_id() ) if opportunity_record != null: var opportunity_key := ( "%d:%d" % [opportunity_record.get_knower_id(), opportunity_record.get_event_id()] ) if not seen.has(opportunity_key): seen[opportunity_key] = true lasting.append(opportunity_record) for situation in situation_system.get_all_sorted(): var context := situation.get_context() var interested_text := String(context.get("interested_npc_id", "")) if interested_text.is_valid_int(): _append_lasting_knowledge( lasting, seen, interested_text.to_int(), situation.get_trigger_event_id() ) if quest_journal_system.get_for_situation(situation.get_situation_id()) != null: _append_lasting_knowledge( lasting, seen, SimulationIds.PLAYER_ACTOR_ID, situation.get_trigger_event_id() ) return lasting func _append_lasting_knowledge( lasting: Array[KnownEventStateRecord], seen: Dictionary, knower_id: int, event_id: int ) -> void: if event_id < 0: return var record := event_knowledge_system.get_record(knower_id, event_id) if record == null: return var key := "%d:%d" % [record.get_knower_id(), record.get_event_id()] if seen.has(key): return seen[key] = true lasting.append(record) func _get_lasting_event_ids(npc_id: int) -> Array[int]: var event_ids: Array[int] = [] for record in _get_lasting_knowledge_records(): if record.get_knower_id() == npc_id: event_ids.append(record.get_event_id()) event_ids.sort() return event_ids func _find_npc_by_id(npc_id: int) -> SimNPC: var npc := _population_view.get_any(npc_id) if npc != null: return npc # Population growth can introduce an ID between scheduled rebuild points. # Rebuild once on a miss while keeping ordinary runtime callbacks O(1). refresh_population_index() return _population_view.get_any(npc_id) static func _sort_npcs_by_id(first: SimNPC, second: SimNPC) -> bool: return first.id < second.id func get_primary_relationship(npc_id: int) -> RelationshipStateRecord: return relationship_system.get_primary_relationship(npc_id) func get_relationship_cause(relationship: RelationshipStateRecord) -> EconomicEventRecord: if relationship == null: return null return event_log.get_by_id(relationship.get_last_trust_cause_event_id()) func get_known_events(npc_id: int, max_count: int = 3) -> Array[EconomicEventRecord]: return event_log.get_by_ids(event_knowledge_system.get_known_event_ids(npc_id, max_count)) func get_retained_memory_events(npc_id: int, max_count: int = 4) -> Array[EconomicEventRecord]: var event_ids := event_knowledge_system.get_retained_event_ids( npc_id, _get_lasting_event_ids(npc_id), max_count ) return event_log.get_by_ids(event_ids) func get_active_opportunity() -> OpportunityStateRecord: return opportunity_system.get_open_opportunity() func get_active_opportunity_helper() -> OpportunityHelperResult: var active := get_active_opportunity() if active == null: return null return opportunity_system.find_capable_helper( active, economy.get_storage(active.get_target_id()), npcs, event_knowledge_system, relationship_system, resource_states ) func get_active_opportunity_player_response() -> OpportunityPlayerResponseResult: var active := get_active_opportunity() if active == null: return null var helper := get_active_opportunity_helper() return opportunity_system.find_player_response( active, economy.get_storage(active.get_target_id()), resource_states, helper != null ) func get_latest_opportunity_for_npc(npc_id: int) -> OpportunityStateRecord: return opportunity_system.get_latest_for_npc(npc_id) func get_active_situations() -> Array[SituationStateRecord]: return situation_system.get_active_sorted() func get_quest_journal_entries() -> Array[QuestJournalEntryStateRecord]: return quest_journal_system.get_all_sorted() func get_active_commitments() -> Array[CommitmentStateRecord]: return commitment_system.get_active_sorted() func begin_player_conversation(npc_id: int) -> StringName: if not _active_player_conversation.is_empty(): return &"" var npc := _find_npc_by_id(npc_id) if npc == null or npc.is_dead: return &"" var situation := _get_known_situation_for_npc(npc_id) if situation != null: _discover_situation_from_speaker(situation, npc_id) var npc_ref := WorldEntityRef.create(WorldEventRecord.ENTITY_TYPE_NPC, StringName(str(npc_id))) var player_ref := WorldEntityRef.create( WorldEventRecord.ENTITY_TYPE_PLAYER, StringName(str(SimulationIds.PLAYER_ACTOR_ID)) ) var context := _build_conversation_context(npc, situation) var conversation_id := conversation_service.begin(npc_ref, player_ref, context) if conversation_id.is_empty(): return &"" _active_player_conversation = conversation_id _conversation_context_by_id[conversation_id] = { "npc_id": npc_id, "situation_id": situation.get_situation_id() if situation != null else -1, } _dialogue_speed_index = speed_index speed_index = SPEED_LEVELS.find(1.0) speed_changed.emit(SPEED_LEVELS[speed_index]) var turn := conversation_service.get_turn(conversation_id) _record_conversation_act(turn) conversation_started.emit(conversation_id, turn) return conversation_id func select_player_conversation_option( conversation_id: StringName, option_id: StringName, expected_revision: int ) -> ConversationSelectionResult: if conversation_id != _active_player_conversation: return ConversationSelectionResult.new() var current_turn := conversation_service.get_turn(conversation_id) var selected_option := current_turn.get_option(option_id) if current_turn != null else null var result := conversation_service.select_option(conversation_id, option_id, expected_revision) if not result.was_accepted(): return result if selected_option != null: _apply_conversation_intent(conversation_id, selected_option.get_intent_id()) var turn := result.get_turn() _record_conversation_act(turn) conversation_turn_changed.emit(conversation_id, turn) if turn != null and turn.is_terminal(): end_player_conversation(conversation_id, turn.get_revision()) return result func end_player_conversation(conversation_id: StringName, expected_revision: int = -1) -> bool: if conversation_id != _active_player_conversation: return false if not conversation_service.end(conversation_id, expected_revision): return false _active_player_conversation = &"" _conversation_context_by_id.erase(conversation_id) if _dialogue_speed_index >= 0: speed_index = clampi(_dialogue_speed_index, 0, SPEED_LEVELS.size() - 1) _dialogue_speed_index = -1 speed_changed.emit(SPEED_LEVELS[speed_index]) conversation_ended.emit(conversation_id) return true func is_dialogue_active() -> bool: return not _active_player_conversation.is_empty() func _get_known_situation_for_npc(npc_id: int) -> SituationStateRecord: var known: Array[SituationStateRecord] = [] for situation in situation_system.get_all_sorted(): var context := situation.get_context() if String(context.get("interested_npc_id", "")) != str(npc_id): continue if event_knowledge_system.knows_event(npc_id, situation.get_trigger_event_id()): known.append(situation) if known.is_empty(): return null known.sort_custom( func(first: SituationStateRecord, second: SituationStateRecord) -> bool: if first.get_created_tick() != second.get_created_tick(): return first.get_created_tick() > second.get_created_tick() return first.get_situation_id() > second.get_situation_id() ) return known[0] func _discover_situation_from_speaker(situation: SituationStateRecord, npc_id: int) -> void: var event := event_log.get_by_id(situation.get_trigger_event_id()) if event == null: return if not event_knowledge_system.knows_event( SimulationIds.PLAYER_ACTOR_ID, event.data["event_id"] ): var learned := event_knowledge_system.communicate_event_to_player(event, npc_id, tick_count) if learned != null: _apply_new_event_knowledge(learned, event) event_knowledge_transferred.emit(npc_id, SimulationIds.PLAYER_ACTOR_ID, event) event_knowledge_system.pin_event(SimulationIds.PLAYER_ACTOR_ID, int(event.data["event_id"])) var existing := quest_journal_system.get_for_situation(situation.get_situation_id()) if existing == null and situation.is_active(): var definition := situation_system.get_definition(situation.get_definition_id()) var entry := quest_journal_system.add_situation(situation, definition, &"", tick_count) if entry != null: quest_journal_changed.emit(entry) func _build_conversation_context(npc: SimNPC, situation: SituationStateRecord) -> Dictionary: var topics: Array[StringName] = [] var trace: Array[StringName] = [&"speaker_available"] var options: Dictionary = {} var initial_intent := ConversationIntentIds.GREET if situation != null: var definition := situation_system.get_definition(situation.get_definition_id()) topics = definition.dialogue_topic_ids.duplicate() trace.append(&"speaker_knows_trigger_fact") trace.append(&"listener_learned_trigger_fact") trace.append(StringName("evidence_event_%d" % situation.get_trigger_event_id())) if npc.hunger >= 60.0: trace.append(&"speaker_hungry") var relationship := relationship_system.get_relationship( npc.id, SimulationIds.PLAYER_ACTOR_ID ) if relationship == null: trace.append(&"relationship_unfamiliar") elif relationship.get_familiarity() >= 0.5: trace.append(&"relationship_familiar") else: trace.append(&"relationship_known") var outcome := _get_latest_commitment_for_npc(npc.id, situation.get_situation_id()) if outcome != null and not outcome.is_active(): trace.append(StringName("commitment_%s" % outcome.get_status())) if outcome.get_cause_event_id() >= 0: trace.append(StringName("outcome_event_%d" % outcome.get_cause_event_id())) match outcome.get_status(): CommitmentStateRecord.STATUS_FULFILLED: initial_intent = ConversationIntentIds.THANK CommitmentStateRecord.STATUS_BROKEN: initial_intent = ConversationIntentIds.REPROACH CommitmentStateRecord.STATUS_SUPERSEDED: initial_intent = ConversationIntentIds.ACKNOWLEDGE_SUPERSESSION options[ConversationIntentIds.GREET] = [ ConversationIntentIds.ASK_WELLBEING, ConversationIntentIds.ASK_WHAT_HAPPENED, ConversationIntentIds.OFFER_HELP, ConversationIntentIds.DECLINE, ConversationIntentIds.ASK_WHO_ELSE, ConversationIntentIds.GOODBYE, ] return { "conversation_key": &"jajce_npc_%d" % npc.id, "initial_intent_id": initial_intent, "topic_ids": topics, "option_intent_ids": options, "reason_trace": trace, } func _get_latest_commitment_for_npc(npc_id: int, situation_id: int = -1) -> CommitmentStateRecord: var latest: CommitmentStateRecord for commitment in commitment_system.get_all_sorted(): var creditor := commitment.get_creditor() if ( creditor.get_entity_type() != WorldEventRecord.ENTITY_TYPE_NPC or String(creditor.get_entity_id()) != str(npc_id) or (situation_id >= 0 and commitment.get_situation_id() != situation_id) ): continue if latest == null or commitment.get_commitment_id() > latest.get_commitment_id(): latest = commitment return latest func _apply_conversation_intent(conversation_id: StringName, intent_id: StringName) -> void: if intent_id not in [ConversationIntentIds.OFFER_HELP, ConversationIntentIds.ACCEPT]: return var context: Dictionary = _conversation_context_by_id.get(conversation_id, {}) var situation := situation_system.get_by_id(int(context.get("situation_id", -1))) var npc_id := int(context.get("npc_id", -1)) if situation == null or npc_id < 0: return var definition := situation_system.get_definition(situation.get_definition_id()) var alternative_id := SituationSystem.ALTERNATIVE_RESTOCK var entry := quest_journal_system.get_for_situation(situation.get_situation_id()) if entry != null and entry.get_selected_alternative_id().is_empty(): quest_journal_system.select_alternative(situation, definition, alternative_id) quest_journal_changed.emit(entry) var player_ref := WorldEntityRef.create( WorldEventRecord.ENTITY_TYPE_PLAYER, StringName(str(SimulationIds.PLAYER_ACTOR_ID)) ) var npc_ref := WorldEntityRef.create(WorldEventRecord.ENTITY_TYPE_NPC, StringName(str(npc_id))) var commitment := commitment_system.create_for_alternative( situation, definition, alternative_id, player_ref, npc_ref, tick_count, tick_count + 20 ) if commitment != null: var acceptance_fact := commitment_lifecycle.record_acceptance( commitment, event_log, relationship_system ) _share_commitment_fact_with_creditor(commitment, acceptance_fact) commitment_changed.emit(commitment) func _share_commitment_fact_with_creditor( commitment: CommitmentStateRecord, fact: EconomicEventRecord ) -> void: if commitment == null or fact == null: return var creditor := commitment.get_creditor() if ( creditor.get_entity_type() not in [WorldEventRecord.ENTITY_TYPE_NPC, WorldEventRecord.ENTITY_TYPE_PLAYER] ): return var creditor_text := String(creditor.get_entity_id()) if not creditor_text.is_valid_int(): return var debtor := commitment.get_debtor() var debtor_text := String(debtor.get_entity_id()) if not debtor_text.is_valid_int(): return var shared := event_knowledge_system.communicate_event( fact, debtor_text.to_int(), creditor_text.to_int(), tick_count ) if shared != null: _apply_new_event_knowledge(shared, fact) func _record_conversation_act(turn: ConversationTurn) -> void: if turn == null or turn.get_act() == null: return var act := turn.get_act() var record := ConversationActStateRecord.create( _next_conversation_act_id, tick_count, act.get_speaker(), act.get_listener(), act.get_intent_id(), act.get_causal_topic_ids() ) if record == null: return conversation_history.append(record) _next_conversation_act_id += 1 _prune_conversation_history(record) func _prune_conversation_history(latest: ConversationActStateRecord) -> void: var latest_pair := _conversation_pair_key(latest) var pair_count := 0 for index in range(conversation_history.size() - 1, -1, -1): if _conversation_pair_key(conversation_history[index]) != latest_pair: continue pair_count += 1 if pair_count > MAX_CONVERSATION_ACTS_PER_PAIR: conversation_history.remove_at(index) while conversation_history.size() > MAX_CONVERSATION_HISTORY: conversation_history.pop_front() func _conversation_pair_key(act: ConversationActStateRecord) -> String: var keys := [act.get_speaker().index_key(), act.get_listener().index_key()] keys.sort() return "%s|%s" % keys func get_opportunity_trigger_event(opportunity: OpportunityStateRecord) -> EconomicEventRecord: return event_log.get_by_id(opportunity.get_trigger_event_id() if opportunity != null else -1) func get_opportunity_resolution_event(opportunity: OpportunityStateRecord) -> EconomicEventRecord: return event_log.get_by_id(opportunity.get_resolution_event_id() if opportunity != null else -1) func npc_knows_event(npc_id: int, event_id: int) -> bool: return event_knowledge_system.knows_event(npc_id, event_id) func get_known_event_record(npc_id: int, event_id: int) -> KnownEventStateRecord: return event_knowledge_system.get_record(npc_id, event_id) func is_known_event_lasting(npc_id: int, event_id: int) -> bool: return event_id in _get_lasting_event_ids(npc_id) func get_memory_summary(npc_id: int) -> Dictionary: var total := event_knowledge_system.get_known_event_ids(npc_id, 0).size() var lasting := _get_lasting_event_ids(npc_id).size() return {"lasting": lasting, "recent": maxi(total - lasting, 0)} func get_knowledge_review_interval() -> int: var active_cycle_duration := ( clock.cycle_duration_seconds if clock != null else cycle_duration_seconds ) var active_tick_interval := clock.tick_interval if clock != null else tick_interval return maxi(roundi(active_cycle_duration / maxf(active_tick_interval, 0.0001)), 1) func get_current_speed() -> String: return "%.2fx" % SPEED_LEVELS[speed_index] func get_resource_rates() -> Dictionary: return event_log.get_consumption_rates(tick_count) func get_pantry() -> StorageStateRecord: return economy.get_pantry() func get_woodpile() -> StorageStateRecord: return economy.get_woodpile() func register_loaded_storage_nodes() -> void: for candidate in StorageNode.get_all(): var node := candidate as StorageNode register_storage_node(node) func register_storage_node(node: StorageNode) -> bool: if node == null or node.storage_id.is_empty(): return false var storage_state := storage_states.get(node.storage_id) as StorageStateRecord if storage_state == null: push_error( ( "SimulationManager: StorageNode '%s' has no authoritative StorageStateRecord" % node.storage_id ) ) return false return node.bind_state(storage_state) func _on_economy_inventory_changed(npc: SimNPC, item_id: StringName, amount: float) -> void: npc_inventory_changed.emit(npc, item_id, amount) func feed_animal(animal_id: StringName, actor_id: int = -1) -> bool: var succeeded := animal_care.feed(animal_id, actor_id, npcs, tick_count) if succeeded: village_changed.emit(village) return succeeded 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 var action_definition := SimulationDefinitions.get_action(node.action_id) if ( action_definition == null or action_definition.target_type != SimulationIds.TARGET_RESOURCE or action_definition.resource_action_id != node.action_id or node.resource_id not in [SimulationIds.RESOURCE_FOOD, SimulationIds.RESOURCE_WOOD] ): push_error( ( "SimulationManager: ResourceNode '%s' has invalid action/resource IDs '%s'/'%s'" % [node.node_id, node.action_id, node.resource_id] ) ) return false var resource_state := get_resource_state(node.node_id) if resource_state == null: 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) 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: var best: ResourceNode var best_distance := max_distance * max_distance var candidates: Array[ResourceNode] var query_mode := &"registry" if ( active_world_adapter != null and active_world_adapter.has_method("get_resource_nodes_in_radius") ): candidates = active_world_adapter.get_resource_nodes_in_radius(from_position, max_distance) query_mode = &"spatial" else: candidates = ResourceNode.get_all() last_player_resource_query_stats = { "mode": query_mode, "candidate_count": candidates.size(), } for node in candidates: var resource_state := get_resource_state(node.node_id) if ( resource_state == null or not resource_state.can_player_use_resource() or not resource_state.can_extract() ): continue 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 var resource_state := get_resource_state(node.node_id) if resource_state == null or not resource_state.can_player_use_resource(): return 0.0 var extracted := resource_state.extract( resource_state.get_yield_per_action() * _gather_yield_multiplier() ) if extracted <= 0.0: return 0.0 var resource_id := resource_state.get_resource_id() player_system.add_carried(resource_id, extracted) var event_position := ( node.interaction_point.global_position if node.interaction_point != null else node.global_position ) _record_economic_event_at( SimulationIds.EVENT_RESOURCE_EXTRACTED, SimulationIds.PLAYER_ACTOR_ID, resource_state.get_node_id(), SimulationIds.PLAYER_INVENTORY_ID, resource_id, extracted, event_position ) if resource_state.get_amount_remaining() <= 0.0: _record_narrative_event_at( SimulationIds.EVENT_RESOURCE_DEPLETED, SimulationIds.PLAYER_ACTOR_ID, resource_state.get_node_id(), "", event_position ) village_changed.emit(village) if debug_logs: print( "[SimulationManager] Player carried ", extracted, " ", resource_id, " from ", resource_state.get_node_id() ) return extracted func advance_player_needs() -> void: player_system.advance_needs(village.food_modifier) player_system.player_state.advance_health() _sync_player_combatant() func _sync_player_combatant() -> void: conflict_system.set_player_health( player_system.player_state.get_health(), player_system.player_state.is_downed() ) func _on_player_damaged(amount: float) -> void: player_system.player_state.take_damage(amount) _sync_player_combatant() func update_player_combatant(position: Vector3) -> void: conflict_system.set_player_combatant_position(position) func player_is_downed() -> bool: return player_system.player_state.is_downed() func get_player_health() -> float: return player_system.player_state.get_health() func get_season() -> StringName: var ticks_per_day := maxi(get_knowledge_review_interval(), 1) var season_day := int(clock.elapsed_ticks / ticks_per_day) return SEASON_COLD if season_day % SEASON_DAYS >= COLD_DAYS else SEASON_WARM func is_cold_season() -> bool: return get_season() == SEASON_COLD func _gather_yield_multiplier() -> float: return 0.5 if is_cold_season() else 1.0 func _advance_resource_regrowth() -> void: if is_cold_season(): return for resource_id in resource_states: var resource_state := resource_states[resource_id] as ResourceStateRecord resource_state.regrow() func get_player_state() -> PlayerStateRecord: return player_system.player_state func deposit_player_inventory(item_id: StringName) -> float: var storage := economy.get_storage_for_resource(item_id) var storage_node := ( StorageNode.get_by_id(storage.get_storage_id()) as StorageNode if storage != null else null ) var deposited := player_system.deposit( item_id, storage_node.get_interaction_position() if storage_node != null else Vector3.ZERO ) village_changed.emit(village) return deposited func eat_player_food() -> bool: var succeeded := player_system.eat(Vector3.ZERO) village_changed.emit(village) return succeeded func _record_player_event_at( event_type: StringName, source_id: StringName, destination_id: StringName, item_id: StringName, amount: float, world_position: Vector3 ) -> void: _record_economic_event_at( event_type, SimulationIds.PLAYER_ACTOR_ID, source_id, destination_id, item_id, amount, world_position ) func add_safety(amount: float) -> void: village.apply_metric_delta(&"safety", amount) village_changed.emit(village) func add_knowledge(amount: float) -> void: village.apply_metric_delta(&"knowledge", amount) village_changed.emit(village) func get_starving_count() -> int: return _population_view.starving_count() func get_state_checksum() -> String: return create_state_record().to_json().sha256_text() func get_latest_decision(npc_id: int) -> ActionSelectionResult: return latest_decisions.get(npc_id) func create_state_record() -> SimulationStateRecord: var record := SimulationStateRecord.new() var event_scope := event_log.get_scope() var wander_streams: Array[Dictionary] = [] var sorted_npc_ids: Array = wander_random_sources.keys() 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)} ) record.simulation = { "seed": simulation_seed, "tick_interval": tick_interval, "tick_count": tick_count, "clock_accumulator": clock.accumulator, "clock_elapsed_ticks": clock.elapsed_ticks, "wander_random_streams": wander_streams, "next_event_id": next_event_id, "next_opportunity_id": opportunity_system.next_opportunity_id, "next_situation_id": situation_system.get_next_situation_id(), "next_journal_entry_id": quest_journal_system.get_next_entry_id(), "next_commitment_id": commitment_system.get_next_commitment_id(), "next_conversation_act_id": _next_conversation_act_id, "world_id": String(event_scope["world_id"]), "location_id": String(event_scope["location_id"]), "cycle_duration_seconds": clock.cycle_duration_seconds } record.village = VillageStateRecord.capture(village) for npc in npcs: record.npcs.append(NPCStateRecord.capture(npc)) animal_care.append_state_records(record) var sorted_resource_ids: Array = resource_states.keys() sorted_resource_ids.sort() for resource_id in sorted_resource_ids: var resource_state: ResourceStateRecord = resource_states[resource_id] record.resources.append(resource_state) var sorted_storage_ids: Array = storage_states.keys() sorted_storage_ids.sort() for storage_id in sorted_storage_ids: var storage_state: StorageStateRecord = storage_states[storage_id] record.storages.append(storage_state) for event in economic_events: record.economic_events.append(event) for relationship in relationship_system.get_all_sorted(): record.relationships.append(relationship) for known_event in event_knowledge_system.get_all_sorted(): record.event_knowledge.append(known_event) for opportunity in opportunity_system.get_all_sorted(): record.opportunities.append(opportunity) for situation in situation_system.get_all_sorted(): record.situations.append(situation) for journal_entry in quest_journal_system.get_all_sorted(): record.quest_journal.append(journal_entry) for commitment in commitment_system.get_all_sorted(): record.commitments.append(commitment) for conversation_act in conversation_history: record.conversation_history.append(conversation_act) record.player = player_system.player_state conflict_system.append_state_records(record) 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: push_error("SimulationManager: refused invalid or unsupported simulation state") return false return restore_state(record) func restore_state(record: SimulationStateRecord) -> bool: if record == null or not _saved_scope_matches_active_adapter(record): return false simulation_seed = int(record.simulation["seed"]) tick_interval = float(record.simulation["tick_interval"]) tick_count = int(record.simulation["tick_count"]) clock = SimulationClock.new(tick_interval) clock.accumulator = float(record.simulation["clock_accumulator"]) clock.elapsed_ticks = int(record.simulation["clock_elapsed_ticks"]) clock.cycle_duration_seconds = float(record.simulation.get("cycle_duration_seconds", 240.0)) village = record.village.restore(debug_logs) economy.configure(village, debug_logs) economy.restore_storage(record.storages) # Priorities and modifiers are deterministic derived state, not save payload. # Rebuild them before the next decision so save/load cannot change outcomes. village.update_modifiers() village.update_priorities() if not event_log.restore( record.economic_events, int(record.simulation["next_event_id"]), StringName(record.simulation["world_id"]), StringName(record.simulation["location_id"]) ): return false latest_decisions.clear() npcs.clear() for npc_record in record.npcs: npcs.append(npc_record.restore(debug_logs)) refresh_population_index() if not _configure_interaction_services(): return false relationship_system.restore(record.relationships) event_knowledge_system.restore(record.event_knowledge) opportunity_system.restore(record.opportunities, int(record.simulation["next_opportunity_id"])) situation_system = SituationSystem.create_default() if not situation_system.restore(record.situations, int(record.simulation["next_situation_id"])): return false if record.situations.is_empty(): var migratable_opportunities: Array[OpportunityStateRecord] = [] for opportunity in record.opportunities: if opportunity.get_opportunity_type() == SimulationIds.OPPORTUNITY_RESTOCK_EMPTY_PANTRY: migratable_opportunities.append(opportunity) if not situation_system.import_opportunities(migratable_opportunities).is_empty(): return false quest_journal_system = QuestJournalSystem.new() if not quest_journal_system.restore( record.quest_journal, int(record.simulation["next_journal_entry_id"]) ): return false commitment_system = SocialCommitmentSystem.new() if not commitment_system.restore( record.commitments, int(record.simulation["next_commitment_id"]) ): return false commitment_lifecycle = CommitmentLifecycleService.new() conversation_service = ConversationService.new() conversation_history.assign(record.conversation_history) _next_conversation_act_id = int(record.simulation["next_conversation_act_id"]) _active_player_conversation = &"" _conversation_context_by_id.clear() _dialogue_speed_index = -1 _maintain_event_knowledge(tick_count % get_knowledge_review_interval() == 0) wander_random_sources.clear() var wander_streams: Array = record.simulation["wander_random_streams"] for stream_data in wander_streams: var source := RandomNumberGenerator.new() source.seed = String(stream_data["seed"]).to_int() source.state = String(stream_data["state"]).to_int() wander_random_sources[int(stream_data["npc_id"])] = source resource_states.clear() for resource_record in record.resources: resource_states[resource_record.get_node_id()] = resource_record register_loaded_resource_nodes() animal_care.restore_state_records(record.animals, tick_count) if record.player != null: player_system.player_state = record.player conflict_system.restore_state_records(record.combatants, record.factions, tick_count) conflict_system.register_npc_combatants(npcs) conflict_system.configure(economy, tick_interval) _sync_player_combatant() village_changed.emit(village) state_restored.emit() return true func _saved_scope_matches_active_adapter(record: SimulationStateRecord) -> bool: if active_world_adapter == null or not active_world_adapter.has_method("get_context_identity"): return true var identity: Dictionary = active_world_adapter.call("get_context_identity") return ( ( StringName(identity.get("world_id", &"")) == StringName(record.simulation.get("world_id", &"")) ) and ( StringName(identity.get("location_id", &"")) == StringName(record.simulation.get("location_id", &"")) ) )