extends Node const SimulationEventLogScript := preload("res://simulation/events/SimulationEventLog.gd") const SimulationEventRecorderScript := preload("res://simulation/events/SimulationEventRecorder.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") 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 player_quest_opened(quest: PlayerQuestRecord) signal player_quest_completed(quest: PlayerQuestRecord) signal player_quest_expired(quest: PlayerQuestRecord) signal player_standing_changed(standing: PlayerStandingRecord) signal player_tier_advanced(tier: int, tier_name: String) signal player_needs_changed(state: PlayerStateRecord) signal player_inventory_changed(state: PlayerStateRecord) signal player_died(state: PlayerStateRecord) var village := SimVillage.new() var npcs: Array[SimNPC] = [] @export var tick_interval := 1.2 @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 event_recorder := SimulationEventRecorderScript.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 player_quest_system := PlayerQuestSystem.new() var player_needs := PlayerNeedsSystem.new() var _last_player_tier := PlayerStandingRecord.TIER_STRANGER 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 _population_view := SimulationPopulationView.new() var speed_index := 2 const SPEED_LEVELS := [0.25, 0.5, 1.0, 2.0, 4.0, 10.0] const KNOWLEDGE_COMMUNICATION_RADIUS := 2.5 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) event_recorder.configure(event_log, Callable(self, "get_tick_count_for_recording")) event_recorder.set_npcs(npcs) player_needs.configure(economy, event_recorder) player_needs.set_resource_states(resource_states) economy.inventory_changed.connect(_on_economy_inventory_changed) economy.economic_event_requested.connect(event_recorder.record_economic) economy.narrative_event_requested.connect(event_recorder.record_narrative) animal_care.economic_event_requested.connect(event_recorder.record_economic_at) animal_care.narrative_event_requested.connect(event_recorder.record_narrative) 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 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) economy.initialize_storage() village.update_modifiers() village.update_priorities() generate_npcs() relationship_system.initialize_households(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: var ticks_due := clock.advance(delta * SPEED_LEVELS[speed_index]) 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] _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) _consider_animal_care_quests() _advance_player_needs() var village_was_changed := false _population_view.rebuild(npcs) for npc in npcs: village_was_changed = _simulate_npc_tick(npc) or village_was_changed if village_was_changed: village_changed.emit(village) 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) var expired_quest := player_quest_system.on_opportunity_invalidated(invalidated, tick_count) if expired_quest != null: player_quest_expired.emit(expired_quest) 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 var helper := get_active_opportunity_helper() var animal_feed_available := animal_care.has_available_feed_target(npc.id) var selection := action_selector.select_action( npc, village, clock.time_of_day(), npcs, helper, _population_view, animal_feed_available ) 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) ) event_recorder.record_narrative(SimulationIds.EVENT_TASK_STARTED, npc.id, &"", display_name) 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) event_recorder.record_narrative(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 if 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: _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 event_recorder.record_narrative(SimulationIds.EVENT_NPC_SLEPT, npc.id) SimulationIds.ACTION_FEED_ANIMAL: pass SimulationIds.ACTION_PATROL, SimulationIds.ACTION_STUDY, SimulationIds.ACTION_REST, SimulationIds.ACTION_WANDER: village.apply_npc_task(npc) 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() 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)) event_recorder.record_economic( 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: event_recorder.record_narrative( 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: for npc in npcs: if npc.id == npc_id: 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 = &"" return func notify_npc_arrived(npc_id: int) -> void: for npc in npcs: if npc.id == npc_id: if 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) return 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: for npc in npcs: if npc.id != npc_id: continue if 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) return func resolve_npc_target(npc_id: int, origin: Vector3) -> bool: for npc in npcs: if npc.id != npc_id: continue if 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 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"] npc.has_travel_target = true npc_travel_requested.emit(npc, npc.travel_target_position) return true return false func request_current_travel(npc_id: int) -> bool: for npc in npcs: if npc.id != npc_id: continue if 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 return false func synchronize_npc_position(npc_id: int, active_position: Vector3) -> bool: for npc in npcs: if npc.id == npc_id: npc.position = active_position return true return false 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 _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 get_tick_count_for_recording() -> int: return tick_count 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) if StringName(event.data["event_type"]) == SimulationIds.EVENT_ANIMAL_FED: _finish_quest_resolution( player_quest_system.on_animal_fed( animal_care.get_state(StringName(event.data["destination_id"])), event, tick_count ) ) _update_opportunity_from_event(event) economic_event_recorded.emit(event) func _finish_quest_resolution(resolution: Dictionary) -> void: if not resolution.has("quest"): return var quest: PlayerQuestRecord = resolution["quest"] if not resolution["completed"]: player_quest_expired.emit(quest) return player_quest_completed.emit(quest) var standing := player_quest_system.standing player_standing_changed.emit(standing) if standing.get_tier() > _last_player_tier: _last_player_tier = standing.get_tier() player_tier_advanced.emit(standing.get_tier(), standing.get_tier_name()) 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 for event_id in event_knowledge_system.get_communicable_event_ids( speaker.id, _get_lasting_event_ids(speaker.id), opportunity_system.get_open_trigger_event_id() ): 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: return EventKnowledgeSystem.can_communicate_at_shared_activity( speaker, listener, storage_states, 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) var quest := player_quest_system.consider_opportunity_opened( changed, get_active_opportunity_player_response(), tick_count, player_quest_system.can_request_personally(changed) ) if quest != null: player_quest_opened.emit(quest) return opportunity_resolved.emit(changed, event) _finish_quest_resolution( player_quest_system.on_opportunity_resolved(changed, event, tick_count) ) _maintain_event_knowledge(false) 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]: return event_knowledge_system.collect_lasting_records( relationship_system.get_all_sorted(), opportunity_system.get_open_opportunity() ) 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: 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_player_quest() -> PlayerQuestRecord: return player_quest_system.get_active_quest() func _advance_player_needs() -> void: if player_needs.advance(village): player_died.emit(player_needs.state) player_needs.apply_death_consequence(player_quest_system.standing) _last_player_tier = player_quest_system.standing.get_tier() player_standing_changed.emit(player_quest_system.standing) return player_needs_changed.emit(player_needs.state) func respawn_player() -> bool: if not player_needs.state.is_dead(): return false player_needs.respawn() player_needs_changed.emit(player_needs.state) return true func get_player_state() -> PlayerStateRecord: return player_needs.state func player_eat(amount: float) -> float: var eaten := player_needs.eat(amount) if eaten > 0.0: player_needs_changed.emit(player_needs.state) return eaten func player_gather(node: ResourceNode) -> float: var gathered := player_needs.gather_node(node) if gathered > 0.0: player_inventory_changed.emit(player_needs.state) return gathered func player_deposit(resource_id: StringName) -> float: var deposited := player_needs.deposit_resource(resource_id) if deposited > 0.0: village_changed.emit(village) player_inventory_changed.emit(player_needs.state) return deposited func _consider_animal_care_quests() -> void: var pantry: StorageStateRecord = get_pantry() for animal_state in animal_care.get_all_states(): var quest := player_quest_system.consider_animal_care( animal_state, _nearest_npc_id(animal_state.get_position()), tick_count, pantry ) if quest != null: player_quest_opened.emit(quest) func _nearest_npc_id(from_position: Vector3) -> int: var nearest_id := -1 var nearest_distance := INF for npc in npcs: if npc.is_dead: continue var distance := npc.position.distance_squared_to(from_position) if distance < nearest_distance: nearest_distance = distance nearest_id = npc.id return nearest_id func get_player_quests() -> Array[PlayerQuestRecord]: return player_quest_system.get_all_sorted() func get_latest_player_quest_for_requester(requester_npc_id: int) -> PlayerQuestRecord: return player_quest_system.get_latest_for_requester(requester_npc_id) func get_player_standing() -> PlayerStandingRecord: return player_quest_system.standing 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_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_animal_display_name(animal_id: StringName) -> String: var animal_state := animal_care.get_state(animal_id) return animal_state.get_display_name() if animal_state != null else "" 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 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() or not resource_state.can_extract() ): continue var storage := economy.get_storage_for_resource(resource_state.get_resource_id()) if storage == null or storage.get_available_capacity() <= 0.0: 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 storage := economy.get_storage_for_resource(resource_state.get_resource_id()) if storage == null: return 0.0 var extracted := resource_state.extract( minf(resource_state.get_yield_per_action(), storage.get_available_capacity()) ) if extracted <= 0.0: return 0.0 var deposited := economy.deposit_resource(resource_state.get_resource_id(), extracted) var event_position := ( node.interaction_point.global_position if node.interaction_point != null else node.global_position ) event_recorder.record_economic_at( SimulationIds.EVENT_RESOURCE_EXTRACTED, -1, resource_state.get_node_id(), ( SimulationIds.STORAGE_VILLAGE_PANTRY if resource_state.get_resource_id() == SimulationIds.RESOURCE_FOOD else ( SimulationIds.STORAGE_VILLAGE_WOODPILE if resource_state.get_resource_id() == SimulationIds.RESOURCE_WOOD else &"village" ) ), resource_state.get_resource_id(), deposited, event_position ) if resource_state.get_amount_remaining() <= 0.0: event_recorder.record_narrative_at( SimulationIds.EVENT_RESOURCE_DEPLETED, -1, resource_state.get_node_id(), "", event_position ) village_changed.emit(village) if debug_logs: print( "[SimulationManager] Player extracted ", extracted, " ", resource_state.get_resource_id(), " from ", resource_state.get_node_id() ) return deposited func eat_food(amount: float) -> void: economy.withdraw_resource(SimulationIds.RESOURCE_FOOD, amount) village_changed.emit(village) 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 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_quest_id": player_quest_system.next_quest_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) record.player_standing = player_quest_system.standing for quest in player_quest_system.get_all_sorted(): record.player_quests.append(quest) record.player_state = player_needs.state 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: 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) event_log.restore(record.economic_events, int(record.simulation["next_event_id"])) latest_decisions.clear() npcs.clear() for npc_record in record.npcs: npcs.append(npc_record.restore(debug_logs)) _population_view.rebuild(npcs) relationship_system.restore(record.relationships) event_knowledge_system.restore(record.event_knowledge) opportunity_system.restore(record.opportunities, int(record.simulation["next_opportunity_id"])) player_quest_system.restore( record.player_quests, int(record.simulation.get("next_quest_id", 0)), record.player_standing ) _last_player_tier = player_quest_system.standing.get_tier() player_needs.restore(record.player_state) _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) village_changed.emit(village) state_restored.emit() return true