feat: generate world-backed situations and commitments
This commit is contained in:
@@ -0,0 +1,117 @@
|
||||
class_name QuestJournalSystem
|
||||
extends RefCounted
|
||||
|
||||
var _entries_by_id: Dictionary = {}
|
||||
var _entry_id_by_situation: Dictionary = {}
|
||||
var _next_entry_id := 0
|
||||
|
||||
|
||||
func add_situation(
|
||||
situation: SituationStateRecord,
|
||||
definition: SituationDefinition,
|
||||
alternative_id: StringName,
|
||||
current_tick: int
|
||||
) -> QuestJournalEntryStateRecord:
|
||||
if (
|
||||
situation == null
|
||||
or definition == null
|
||||
or not situation.is_active()
|
||||
or situation.get_definition_id() != definition.situation_definition_id
|
||||
or definition.get_alternative(alternative_id) == null
|
||||
or current_tick < situation.get_created_tick()
|
||||
or _entry_id_by_situation.has(situation.get_situation_id())
|
||||
or not situation.select_alternative(alternative_id)
|
||||
):
|
||||
return null
|
||||
var entry := QuestJournalEntryStateRecord.create(
|
||||
_next_entry_id,
|
||||
situation.get_situation_id(),
|
||||
definition.situation_definition_id,
|
||||
current_tick,
|
||||
alternative_id
|
||||
)
|
||||
_entries_by_id[_next_entry_id] = entry
|
||||
_entry_id_by_situation[situation.get_situation_id()] = _next_entry_id
|
||||
_next_entry_id += 1
|
||||
return entry
|
||||
|
||||
|
||||
func synchronize(
|
||||
situation: SituationStateRecord, current_tick: int
|
||||
) -> QuestJournalEntryStateRecord:
|
||||
if situation == null:
|
||||
return null
|
||||
var entry := get_for_situation(situation.get_situation_id())
|
||||
if entry == null or not entry.is_active() or situation.is_active():
|
||||
return null
|
||||
var status := QuestJournalEntryStateRecord.STATUS_ARCHIVED
|
||||
if situation.get_status() == SituationStateRecord.STATUS_RESOLVED:
|
||||
status = QuestJournalEntryStateRecord.STATUS_COMPLETED
|
||||
elif situation.get_status() == SituationStateRecord.STATUS_EXPIRED:
|
||||
status = QuestJournalEntryStateRecord.STATUS_FAILED
|
||||
return entry if entry.close(status, current_tick) else null
|
||||
|
||||
|
||||
func derive_progress(
|
||||
entry: QuestJournalEntryStateRecord,
|
||||
situation_system: SituationSystem,
|
||||
world_events: WorldEventStore,
|
||||
state_facts: Dictionary
|
||||
) -> SituationProgressSnapshot:
|
||||
if entry == null or situation_system == null:
|
||||
return SituationProgressSnapshot.new()
|
||||
return situation_system.derive_progress(
|
||||
situation_system.get_by_id(entry.get_situation_id()),
|
||||
world_events,
|
||||
state_facts,
|
||||
entry.get_selected_alternative_id()
|
||||
)
|
||||
|
||||
|
||||
func restore(records: Array[QuestJournalEntryStateRecord], restored_next_id: int) -> bool:
|
||||
var by_id: Dictionary = {}
|
||||
var by_situation: Dictionary = {}
|
||||
var next_id := maxi(restored_next_id, 0)
|
||||
for record in records:
|
||||
if (
|
||||
record == null
|
||||
or by_id.has(record.get_entry_id())
|
||||
or by_situation.has(record.get_situation_id())
|
||||
):
|
||||
return false
|
||||
by_id[record.get_entry_id()] = record
|
||||
by_situation[record.get_situation_id()] = record.get_entry_id()
|
||||
next_id = maxi(next_id, record.get_entry_id() + 1)
|
||||
_entries_by_id = by_id
|
||||
_entry_id_by_situation = by_situation
|
||||
_next_entry_id = next_id
|
||||
return true
|
||||
|
||||
|
||||
func get_by_id(entry_id: int) -> QuestJournalEntryStateRecord:
|
||||
return _entries_by_id.get(entry_id) as QuestJournalEntryStateRecord
|
||||
|
||||
|
||||
func get_for_situation(situation_id: int) -> QuestJournalEntryStateRecord:
|
||||
if not _entry_id_by_situation.has(situation_id):
|
||||
return null
|
||||
return get_by_id(int(_entry_id_by_situation[situation_id]))
|
||||
|
||||
|
||||
func get_all_sorted() -> Array[QuestJournalEntryStateRecord]:
|
||||
var records: Array[QuestJournalEntryStateRecord] = []
|
||||
for record in _entries_by_id.values():
|
||||
records.append(record)
|
||||
records.sort_custom(
|
||||
func(first: QuestJournalEntryStateRecord, second: QuestJournalEntryStateRecord) -> bool:
|
||||
return first.get_entry_id() < second.get_entry_id()
|
||||
)
|
||||
return records
|
||||
|
||||
|
||||
func get_active_sorted() -> Array[QuestJournalEntryStateRecord]:
|
||||
var records: Array[QuestJournalEntryStateRecord] = []
|
||||
for record in get_all_sorted():
|
||||
if record.is_active():
|
||||
records.append(record)
|
||||
return records
|
||||
@@ -0,0 +1 @@
|
||||
uid://b2g8tagh2m8rj
|
||||
@@ -0,0 +1,40 @@
|
||||
class_name SituationAlternativeDefinition
|
||||
extends Resource
|
||||
|
||||
@export var alternative_id: StringName
|
||||
@export var display_name: String
|
||||
@export_multiline var description: String
|
||||
@export var resolution_predicate_ids: Array[StringName] = []
|
||||
@export var dialogue_topic_ids: Array[StringName] = []
|
||||
@export var commitment_terms: Dictionary = {}
|
||||
|
||||
|
||||
func validate() -> Array[String]:
|
||||
var errors: Array[String] = []
|
||||
if alternative_id.is_empty():
|
||||
errors.append("alternative_id is empty")
|
||||
if display_name.is_empty():
|
||||
errors.append("display_name is empty for alternative '%s'" % alternative_id)
|
||||
if resolution_predicate_ids.is_empty():
|
||||
errors.append("alternative '%s' has no resolution predicates" % alternative_id)
|
||||
for predicate_id in resolution_predicate_ids:
|
||||
if predicate_id.is_empty():
|
||||
errors.append("alternative '%s' has an empty resolution predicate ID" % alternative_id)
|
||||
for topic_id in dialogue_topic_ids:
|
||||
if topic_id.is_empty():
|
||||
errors.append("alternative '%s' has an empty dialogue topic ID" % alternative_id)
|
||||
for term_key in commitment_terms:
|
||||
if not term_key is String and not term_key is StringName:
|
||||
errors.append("alternative '%s' has a non-string commitment term key" % alternative_id)
|
||||
return errors
|
||||
|
||||
|
||||
func duplicate_alternative() -> SituationAlternativeDefinition:
|
||||
var copy := SituationAlternativeDefinition.new()
|
||||
copy.alternative_id = alternative_id
|
||||
copy.display_name = display_name
|
||||
copy.description = description
|
||||
copy.resolution_predicate_ids = resolution_predicate_ids.duplicate()
|
||||
copy.dialogue_topic_ids = dialogue_topic_ids.duplicate()
|
||||
copy.commitment_terms = commitment_terms.duplicate(true)
|
||||
return copy
|
||||
@@ -0,0 +1 @@
|
||||
uid://cp0yvfu4igrk3
|
||||
@@ -0,0 +1,158 @@
|
||||
class_name SituationDefinition
|
||||
extends Resource
|
||||
|
||||
@export var situation_definition_id: StringName
|
||||
@export var display_name: String
|
||||
@export_multiline var description: String
|
||||
@export_range(0, 100, 1) var severity := 1
|
||||
@export_range(-100, 100, 1) var priority := 0
|
||||
@export var trigger_predicates: Array[SituationPredicate] = []
|
||||
@export var resolution_predicates: Array[SituationPredicate] = []
|
||||
@export var expiry_predicate_ids: Array[StringName] = []
|
||||
@export var dedupe_key_fields: Array[StringName] = []
|
||||
@export_range(0, 1000000, 1) var expiry_ticks := 0
|
||||
@export_range(0, 1000000, 1) var cooldown_ticks := 0
|
||||
@export var dialogue_topic_ids: Array[StringName] = []
|
||||
@export var alternatives: Array[SituationAlternativeDefinition] = []
|
||||
|
||||
|
||||
func validate(
|
||||
supported_event_predicate_ids: Array[StringName] = [],
|
||||
supported_state_predicate_ids: Array[StringName] = [],
|
||||
supported_expiry_predicate_ids: Array[StringName] = []
|
||||
) -> Array[String]:
|
||||
var errors: Array[String] = []
|
||||
if situation_definition_id.is_empty():
|
||||
errors.append("situation_definition_id is empty")
|
||||
if display_name.is_empty():
|
||||
errors.append("display_name is empty for '%s'" % situation_definition_id)
|
||||
if trigger_predicates.is_empty():
|
||||
errors.append("'%s' has no trigger predicates" % situation_definition_id)
|
||||
if severity < 0 or severity > 100:
|
||||
errors.append("severity is outside 0..100 for '%s'" % situation_definition_id)
|
||||
if priority < -100 or priority > 100:
|
||||
errors.append("priority is outside -100..100 for '%s'" % situation_definition_id)
|
||||
if expiry_ticks < 0 or cooldown_ticks < 0:
|
||||
errors.append("expiry/cooldown ticks cannot be negative for '%s'" % situation_definition_id)
|
||||
_validate_predicates(
|
||||
trigger_predicates,
|
||||
"trigger",
|
||||
supported_event_predicate_ids,
|
||||
supported_state_predicate_ids,
|
||||
errors
|
||||
)
|
||||
_validate_predicates(
|
||||
resolution_predicates,
|
||||
"resolution",
|
||||
supported_event_predicate_ids,
|
||||
supported_state_predicate_ids,
|
||||
errors
|
||||
)
|
||||
for predicate_id in expiry_predicate_ids:
|
||||
if predicate_id.is_empty():
|
||||
errors.append("'%s' has an empty expiry predicate ID" % situation_definition_id)
|
||||
elif (
|
||||
not supported_expiry_predicate_ids.is_empty()
|
||||
and predicate_id not in supported_expiry_predicate_ids
|
||||
):
|
||||
errors.append(
|
||||
(
|
||||
"'%s' references unsupported expiry predicate '%s'"
|
||||
% [situation_definition_id, predicate_id]
|
||||
)
|
||||
)
|
||||
_validate_unique_names(dedupe_key_fields, "dedupe key", errors)
|
||||
_validate_unique_names(dialogue_topic_ids, "dialogue topic", errors)
|
||||
var alternatives_by_id: Dictionary = {}
|
||||
for alternative in alternatives:
|
||||
if alternative == null:
|
||||
errors.append("'%s' contains a null alternative" % situation_definition_id)
|
||||
continue
|
||||
for error in alternative.validate():
|
||||
errors.append("Alternative '%s': %s" % [alternative.alternative_id, error])
|
||||
if alternatives_by_id.has(alternative.alternative_id):
|
||||
errors.append(
|
||||
(
|
||||
"'%s' has duplicate alternative '%s'"
|
||||
% [situation_definition_id, alternative.alternative_id]
|
||||
)
|
||||
)
|
||||
alternatives_by_id[alternative.alternative_id] = true
|
||||
for predicate_id in alternative.resolution_predicate_ids:
|
||||
if not _has_predicate(predicate_id):
|
||||
errors.append(
|
||||
(
|
||||
"Alternative '%s' references unknown resolution predicate '%s'"
|
||||
% [alternative.alternative_id, predicate_id]
|
||||
)
|
||||
)
|
||||
return errors
|
||||
|
||||
|
||||
func get_predicate(predicate_id: StringName) -> SituationPredicate:
|
||||
for predicate in trigger_predicates:
|
||||
if predicate != null and predicate.predicate_id == predicate_id:
|
||||
return predicate
|
||||
for predicate in resolution_predicates:
|
||||
if predicate != null and predicate.predicate_id == predicate_id:
|
||||
return predicate
|
||||
return null
|
||||
|
||||
|
||||
func get_alternative(alternative_id: StringName) -> SituationAlternativeDefinition:
|
||||
for alternative in alternatives:
|
||||
if alternative != null and alternative.alternative_id == alternative_id:
|
||||
return alternative
|
||||
return null
|
||||
|
||||
|
||||
func _has_predicate(predicate_id: StringName) -> bool:
|
||||
return get_predicate(predicate_id) != null
|
||||
|
||||
|
||||
func _validate_predicates(
|
||||
predicates: Array[SituationPredicate],
|
||||
label: String,
|
||||
supported_event_ids: Array[StringName],
|
||||
supported_state_ids: Array[StringName],
|
||||
errors: Array[String]
|
||||
) -> void:
|
||||
var seen: Dictionary = {}
|
||||
for predicate in predicates:
|
||||
if predicate == null:
|
||||
errors.append("'%s' contains a null %s predicate" % [situation_definition_id, label])
|
||||
continue
|
||||
for error in predicate.validate():
|
||||
errors.append(
|
||||
"%s predicate '%s': %s" % [label.capitalize(), predicate.predicate_id, error]
|
||||
)
|
||||
if seen.has(predicate.predicate_id):
|
||||
errors.append(
|
||||
(
|
||||
"'%s' has duplicate %s predicate '%s'"
|
||||
% [situation_definition_id, label, predicate.predicate_id]
|
||||
)
|
||||
)
|
||||
seen[predicate.predicate_id] = true
|
||||
var supported_ids := (
|
||||
supported_event_ids
|
||||
if StringName(predicate.source) == SituationPredicate.SOURCE_EVENT
|
||||
else supported_state_ids
|
||||
)
|
||||
if not supported_ids.is_empty() and predicate.evaluator_id not in supported_ids:
|
||||
errors.append(
|
||||
(
|
||||
"'%s' references unsupported %s predicate '%s'"
|
||||
% [situation_definition_id, predicate.source, predicate.evaluator_id]
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
func _validate_unique_names(names: Array[StringName], label: String, errors: Array[String]) -> void:
|
||||
var seen: Dictionary = {}
|
||||
for name in names:
|
||||
if name.is_empty():
|
||||
errors.append("'%s' has an empty %s" % [situation_definition_id, label])
|
||||
elif seen.has(name):
|
||||
errors.append("'%s' has duplicate %s '%s'" % [situation_definition_id, label, name])
|
||||
seen[name] = true
|
||||
@@ -0,0 +1 @@
|
||||
uid://dbiw73jhv8yj8
|
||||
@@ -0,0 +1,18 @@
|
||||
class_name SituationEvaluationResult
|
||||
extends RefCounted
|
||||
|
||||
var definition_id: StringName
|
||||
var dedupe_key: String
|
||||
var matched := false
|
||||
var opened_situation_id := -1
|
||||
var reason_traces: Array[String] = []
|
||||
|
||||
|
||||
func _init(definition: StringName = &"", key: String = "", reasons: Array[String] = []) -> void:
|
||||
definition_id = definition
|
||||
dedupe_key = key
|
||||
reason_traces = reasons.duplicate()
|
||||
|
||||
|
||||
func add_reason(reason: String) -> void:
|
||||
reason_traces.append(reason)
|
||||
@@ -0,0 +1 @@
|
||||
uid://my8p2s1inc56
|
||||
@@ -0,0 +1,33 @@
|
||||
class_name SituationPredicate
|
||||
extends Resource
|
||||
|
||||
const SOURCE_EVENT := &"event"
|
||||
const SOURCE_STATE := &"state"
|
||||
|
||||
@export var predicate_id: StringName
|
||||
@export var evaluator_id: StringName
|
||||
@export_enum("event", "state") var source: String = String(SOURCE_EVENT)
|
||||
@export var parameters: Dictionary = {}
|
||||
|
||||
|
||||
func validate() -> Array[String]:
|
||||
var errors: Array[String] = []
|
||||
if predicate_id.is_empty():
|
||||
errors.append("predicate_id is empty")
|
||||
if evaluator_id.is_empty():
|
||||
errors.append("evaluator_id is empty for predicate '%s'" % predicate_id)
|
||||
if StringName(source) not in [SOURCE_EVENT, SOURCE_STATE]:
|
||||
errors.append("predicate '%s' has invalid source '%s'" % [predicate_id, source])
|
||||
for key in parameters:
|
||||
if not key is String and not key is StringName:
|
||||
errors.append("predicate '%s' has a non-string parameter key" % predicate_id)
|
||||
return errors
|
||||
|
||||
|
||||
func duplicate_predicate() -> SituationPredicate:
|
||||
var copy := SituationPredicate.new()
|
||||
copy.predicate_id = predicate_id
|
||||
copy.evaluator_id = evaluator_id
|
||||
copy.source = source
|
||||
copy.parameters = parameters.duplicate(true)
|
||||
return copy
|
||||
@@ -0,0 +1 @@
|
||||
uid://cfcfymyk6bqc0
|
||||
@@ -0,0 +1,16 @@
|
||||
class_name SituationProgressSnapshot
|
||||
extends RefCounted
|
||||
|
||||
var situation_id := -1
|
||||
var alternative_id: StringName
|
||||
var resolved := false
|
||||
var current_value := 0.0
|
||||
var target_value := 0.0
|
||||
var matched_event_id := -1
|
||||
var reason_traces: Array[String] = []
|
||||
|
||||
|
||||
func ratio() -> float:
|
||||
if target_value <= 0.0:
|
||||
return 1.0 if resolved else 0.0
|
||||
return clampf(current_value / target_value, 0.0, 1.0)
|
||||
@@ -0,0 +1 @@
|
||||
uid://is8x3qvgfplr
|
||||
@@ -0,0 +1,603 @@
|
||||
class_name SituationSystem
|
||||
extends RefCounted
|
||||
|
||||
const MAX_CONCURRENT_SITUATIONS := 3
|
||||
const DEFINITION_PANTRY_SHORTAGE := &"situation_pantry_shortage"
|
||||
const PREDICATE_EVENT_TYPE := &"event_type"
|
||||
const PREDICATE_EVENT_PAYLOAD_EQUALS := &"event_payload_equals"
|
||||
const PREDICATE_EVENT_PARTICIPANT_ID := &"event_participant_id"
|
||||
const PREDICATE_EVENT_PANTRY_SUPPLIED := &"event_pantry_supplied"
|
||||
const PREDICATE_STATE_NUMBER_LTE := &"state_number_lte"
|
||||
const PREDICATE_STATE_NUMBER_GTE := &"state_number_gte"
|
||||
const EXPIRY_STATE_NUMBER_GT := &"state_number_gt"
|
||||
const EXPIRY_AGE_REACHED := &"age_reached"
|
||||
const ALTERNATIVE_RESTOCK := &"restock_pantry"
|
||||
const ALTERNATIVE_ENDURE := &"endure_shortage"
|
||||
const DIALOGUE_TOPIC_PANTRY_SHORTAGE := &"topic_pantry_shortage"
|
||||
const CLOSE_RESOLVED := &"predicate_resolved"
|
||||
const CLOSE_EXPIRED := &"predicate_expired"
|
||||
const CLOSE_CAPACITY := &"capacity_superseded"
|
||||
const DEFAULT_WORLD_ID := &"jajce"
|
||||
|
||||
var _definitions_by_id: Dictionary = {}
|
||||
var _situations_by_id: Dictionary = {}
|
||||
var _next_situation_id := 0
|
||||
|
||||
|
||||
static func create_default() -> SituationSystem:
|
||||
var system := SituationSystem.new()
|
||||
var definitions: Array[SituationDefinition] = [create_pantry_shortage_definition()]
|
||||
system.configure(definitions)
|
||||
return system
|
||||
|
||||
|
||||
static func create_pantry_shortage_definition() -> SituationDefinition:
|
||||
var definition := SituationDefinition.new()
|
||||
definition.situation_definition_id = DEFINITION_PANTRY_SHORTAGE
|
||||
definition.display_name = "The Pantry Is Empty"
|
||||
definition.description = "The village pantry has run out of food."
|
||||
definition.severity = 70
|
||||
definition.priority = 80
|
||||
definition.trigger_predicates = [
|
||||
_event_predicate(
|
||||
&"pantry_withdrawal", PREDICATE_EVENT_TYPE, {"event_type": "storage_withdrawn"}
|
||||
),
|
||||
_event_predicate(
|
||||
&"withdrawal_from_pantry",
|
||||
PREDICATE_EVENT_PARTICIPANT_ID,
|
||||
{"role": "source", "entity_id": "village_pantry"}
|
||||
),
|
||||
_event_predicate(
|
||||
&"withdrawal_of_food",
|
||||
PREDICATE_EVENT_PAYLOAD_EQUALS,
|
||||
{"key": "item_id", "value": "food"}
|
||||
),
|
||||
_state_predicate(
|
||||
&"pantry_empty", PREDICATE_STATE_NUMBER_LTE, {"fact_key": "pantry.food", "value": 0.0}
|
||||
),
|
||||
]
|
||||
definition.resolution_predicates = [
|
||||
_event_predicate(
|
||||
&"pantry_restocked",
|
||||
PREDICATE_EVENT_PANTRY_SUPPLIED,
|
||||
{"target_id": "village_pantry", "item_id": "food", "amount": 1.0}
|
||||
)
|
||||
]
|
||||
definition.expiry_predicate_ids = [EXPIRY_AGE_REACHED]
|
||||
definition.dedupe_key_fields = [&"world_id", &"source_id"]
|
||||
definition.expiry_ticks = 200
|
||||
definition.cooldown_ticks = 50
|
||||
definition.dialogue_topic_ids = [DIALOGUE_TOPIC_PANTRY_SHORTAGE]
|
||||
var restock := SituationAlternativeDefinition.new()
|
||||
restock.alternative_id = ALTERNATIVE_RESTOCK
|
||||
restock.display_name = "Restock the pantry"
|
||||
restock.description = "Bring at least one food item to the village pantry."
|
||||
restock.resolution_predicate_ids = [&"pantry_restocked"]
|
||||
restock.dialogue_topic_ids = [DIALOGUE_TOPIC_PANTRY_SHORTAGE]
|
||||
restock.commitment_terms = {
|
||||
"action_id": "deposit_food",
|
||||
"target_id": "village_pantry",
|
||||
"item_id": "food",
|
||||
"amount": 1.0,
|
||||
}
|
||||
var endure := SituationAlternativeDefinition.new()
|
||||
endure.alternative_id = ALTERNATIVE_ENDURE
|
||||
endure.display_name = "Endure the shortage"
|
||||
endure.description = "Make no promise and let the immediate concern pass."
|
||||
endure.resolution_predicate_ids = [&"pantry_restocked"]
|
||||
endure.dialogue_topic_ids = [DIALOGUE_TOPIC_PANTRY_SHORTAGE]
|
||||
definition.alternatives = [restock, endure]
|
||||
return definition
|
||||
|
||||
|
||||
func configure(definitions: Array[SituationDefinition]) -> Array[String]:
|
||||
var errors: Array[String] = []
|
||||
var definitions_by_id: Dictionary = {}
|
||||
for definition in definitions:
|
||||
if definition == null:
|
||||
errors.append("Situation definitions contain null")
|
||||
continue
|
||||
for error in (
|
||||
definition
|
||||
. validate(
|
||||
[
|
||||
PREDICATE_EVENT_TYPE,
|
||||
PREDICATE_EVENT_PAYLOAD_EQUALS,
|
||||
PREDICATE_EVENT_PARTICIPANT_ID,
|
||||
PREDICATE_EVENT_PANTRY_SUPPLIED,
|
||||
],
|
||||
[PREDICATE_STATE_NUMBER_LTE, PREDICATE_STATE_NUMBER_GTE],
|
||||
[EXPIRY_STATE_NUMBER_GT, EXPIRY_AGE_REACHED]
|
||||
)
|
||||
):
|
||||
errors.append("Situation '%s': %s" % [definition.situation_definition_id, error])
|
||||
if definitions_by_id.has(definition.situation_definition_id):
|
||||
errors.append(
|
||||
"Duplicate situation definition '%s'" % definition.situation_definition_id
|
||||
)
|
||||
else:
|
||||
definitions_by_id[definition.situation_definition_id] = definition
|
||||
errors.sort()
|
||||
if not errors.is_empty():
|
||||
return errors
|
||||
_definitions_by_id = definitions_by_id
|
||||
return []
|
||||
|
||||
|
||||
func consider_event(
|
||||
event: WorldEventRecord, current_tick: int, state_facts: Dictionary
|
||||
) -> Array[SituationEvaluationResult]:
|
||||
var results: Array[SituationEvaluationResult] = []
|
||||
if event == null or current_tick < event.get_tick():
|
||||
return results
|
||||
for definition in _get_definitions_sorted():
|
||||
var context := _build_context(event, state_facts)
|
||||
var dedupe_key := _build_dedupe_key(definition, context)
|
||||
var result := SituationEvaluationResult.new(definition.situation_definition_id, dedupe_key)
|
||||
var trigger_matched := true
|
||||
for predicate in definition.trigger_predicates:
|
||||
var evaluation := _evaluate_predicate(predicate, event, state_facts)
|
||||
result.add_reason(evaluation["reason"])
|
||||
if not bool(evaluation["matched"]):
|
||||
trigger_matched = false
|
||||
result.matched = trigger_matched
|
||||
if trigger_matched:
|
||||
var blocked_reason := _opening_block_reason(definition, dedupe_key, current_tick)
|
||||
if blocked_reason.is_empty():
|
||||
var situation := SituationStateRecord.create(
|
||||
_next_situation_id,
|
||||
definition.situation_definition_id,
|
||||
dedupe_key,
|
||||
current_tick,
|
||||
event.get_event_id(),
|
||||
context
|
||||
)
|
||||
_situations_by_id[_next_situation_id] = situation
|
||||
result.opened_situation_id = _next_situation_id
|
||||
result.add_reason("opened situation %d" % _next_situation_id)
|
||||
_next_situation_id += 1
|
||||
else:
|
||||
result.add_reason(blocked_reason)
|
||||
results.append(result)
|
||||
return results
|
||||
|
||||
|
||||
func maintain(
|
||||
current_tick: int, world_events: WorldEventStore, state_facts: Dictionary
|
||||
) -> Array[SituationStateRecord]:
|
||||
var closed: Array[SituationStateRecord] = []
|
||||
for situation in get_active_sorted():
|
||||
var definition := get_definition(situation.get_definition_id())
|
||||
if definition == null:
|
||||
continue
|
||||
var resolution := derive_progress(situation, world_events, state_facts)
|
||||
if resolution.resolved:
|
||||
if situation.close(
|
||||
SituationStateRecord.STATUS_RESOLVED,
|
||||
current_tick,
|
||||
CLOSE_RESOLVED,
|
||||
resolution.matched_event_id
|
||||
):
|
||||
closed.append(situation)
|
||||
continue
|
||||
if _is_expired(situation, definition, current_tick, state_facts):
|
||||
if situation.close(SituationStateRecord.STATUS_EXPIRED, current_tick, CLOSE_EXPIRED):
|
||||
closed.append(situation)
|
||||
return closed
|
||||
|
||||
|
||||
func derive_progress(
|
||||
situation: SituationStateRecord,
|
||||
world_events: WorldEventStore,
|
||||
state_facts: Dictionary,
|
||||
alternative_id: StringName = &""
|
||||
) -> SituationProgressSnapshot:
|
||||
var snapshot := SituationProgressSnapshot.new()
|
||||
if situation == null:
|
||||
snapshot.reason_traces.append("situation is null")
|
||||
return snapshot
|
||||
snapshot.situation_id = situation.get_situation_id()
|
||||
var definition := get_definition(situation.get_definition_id())
|
||||
if definition == null:
|
||||
snapshot.reason_traces.append("definition is unavailable")
|
||||
return snapshot
|
||||
var selected_alternative := alternative_id
|
||||
if selected_alternative.is_empty():
|
||||
selected_alternative = situation.get_selected_alternative_id()
|
||||
snapshot.alternative_id = selected_alternative
|
||||
var predicate_ids: Array[StringName] = []
|
||||
if not selected_alternative.is_empty():
|
||||
var alternative := definition.get_alternative(selected_alternative)
|
||||
if alternative == null:
|
||||
snapshot.reason_traces.append("selected alternative is unavailable")
|
||||
return snapshot
|
||||
predicate_ids = alternative.resolution_predicate_ids
|
||||
else:
|
||||
for predicate in definition.resolution_predicates:
|
||||
predicate_ids.append(predicate.predicate_id)
|
||||
for predicate_id in predicate_ids:
|
||||
var predicate := definition.get_predicate(predicate_id)
|
||||
if predicate == null:
|
||||
snapshot.reason_traces.append("predicate '%s' is unavailable" % predicate_id)
|
||||
continue
|
||||
var evaluation := _evaluate_resolution_predicate(
|
||||
predicate, situation, world_events, state_facts
|
||||
)
|
||||
snapshot.reason_traces.append(evaluation["reason"])
|
||||
if bool(evaluation["matched"]):
|
||||
snapshot.resolved = true
|
||||
snapshot.current_value = float(evaluation.get("current_value", 1.0))
|
||||
snapshot.target_value = float(evaluation.get("target_value", 1.0))
|
||||
snapshot.matched_event_id = int(evaluation.get("event_id", -1))
|
||||
return snapshot
|
||||
snapshot.current_value = float(evaluation.get("current_value", snapshot.current_value))
|
||||
snapshot.target_value = float(evaluation.get("target_value", snapshot.target_value))
|
||||
return snapshot
|
||||
|
||||
|
||||
func import_opportunities(opportunities: Array[OpportunityStateRecord]) -> Array[String]:
|
||||
var errors: Array[String] = []
|
||||
for opportunity in opportunities:
|
||||
var mapped_definition_id := opportunity.get_opportunity_type()
|
||||
if opportunity.get_opportunity_type() == SimulationIds.OPPORTUNITY_RESTOCK_EMPTY_PANTRY:
|
||||
mapped_definition_id = DEFINITION_PANTRY_SHORTAGE
|
||||
if not _definitions_by_id.has(mapped_definition_id):
|
||||
errors.append(
|
||||
(
|
||||
"No situation definition maps opportunity type '%s'"
|
||||
% opportunity.get_opportunity_type()
|
||||
)
|
||||
)
|
||||
continue
|
||||
var situation := SituationStateRecord.from_opportunity(opportunity, mapped_definition_id)
|
||||
if situation == null:
|
||||
errors.append("Could not convert an opportunity")
|
||||
continue
|
||||
var situation_id := situation.get_situation_id()
|
||||
if _situations_by_id.has(situation_id):
|
||||
errors.append("Duplicate imported situation ID %d" % situation_id)
|
||||
continue
|
||||
_situations_by_id[situation_id] = situation
|
||||
_next_situation_id = maxi(_next_situation_id, situation_id + 1)
|
||||
return errors
|
||||
|
||||
|
||||
func restore(records: Array[SituationStateRecord], restored_next_id: int) -> bool:
|
||||
var by_id: Dictionary = {}
|
||||
var active_keys: Dictionary = {}
|
||||
var active_count := 0
|
||||
for record in records:
|
||||
if (
|
||||
record == null
|
||||
or by_id.has(record.get_situation_id())
|
||||
or not _definitions_by_id.has(record.get_definition_id())
|
||||
):
|
||||
return false
|
||||
if record.is_active():
|
||||
var active_key := "%s|%s" % [record.get_definition_id(), record.get_dedupe_key()]
|
||||
if active_keys.has(active_key):
|
||||
return false
|
||||
active_keys[active_key] = true
|
||||
active_count += 1
|
||||
if active_count > MAX_CONCURRENT_SITUATIONS:
|
||||
return false
|
||||
by_id[record.get_situation_id()] = record
|
||||
_situations_by_id = by_id
|
||||
_next_situation_id = maxi(restored_next_id, 0)
|
||||
for situation_id in by_id:
|
||||
_next_situation_id = maxi(_next_situation_id, int(situation_id) + 1)
|
||||
return true
|
||||
|
||||
|
||||
func get_definition(definition_id: StringName) -> SituationDefinition:
|
||||
return _definitions_by_id.get(definition_id) as SituationDefinition
|
||||
|
||||
|
||||
func get_by_id(situation_id: int) -> SituationStateRecord:
|
||||
return _situations_by_id.get(situation_id) as SituationStateRecord
|
||||
|
||||
|
||||
func get_all_sorted() -> Array[SituationStateRecord]:
|
||||
var situations: Array[SituationStateRecord] = []
|
||||
for situation in _situations_by_id.values():
|
||||
situations.append(situation)
|
||||
situations.sort_custom(_sort_situations)
|
||||
return situations
|
||||
|
||||
|
||||
func get_active_sorted() -> Array[SituationStateRecord]:
|
||||
var active: Array[SituationStateRecord] = []
|
||||
for situation in _situations_by_id.values():
|
||||
if situation.is_active():
|
||||
active.append(situation)
|
||||
active.sort_custom(_sort_situations)
|
||||
return active
|
||||
|
||||
|
||||
func _get_definitions_sorted() -> Array[SituationDefinition]:
|
||||
var definitions: Array[SituationDefinition] = []
|
||||
for definition in _definitions_by_id.values():
|
||||
definitions.append(definition)
|
||||
definitions.sort_custom(_sort_definitions)
|
||||
return definitions
|
||||
|
||||
|
||||
func _opening_block_reason(
|
||||
definition: SituationDefinition, dedupe_key: String, current_tick: int
|
||||
) -> String:
|
||||
for situation in get_all_sorted():
|
||||
if (
|
||||
situation.get_definition_id() != definition.situation_definition_id
|
||||
or situation.get_dedupe_key() != dedupe_key
|
||||
):
|
||||
continue
|
||||
if situation.is_active():
|
||||
return "dedupe blocked by active situation %d" % situation.get_situation_id()
|
||||
if current_tick - situation.get_closed_tick() < definition.cooldown_ticks:
|
||||
return (
|
||||
"cooldown active until tick %d"
|
||||
% (situation.get_closed_tick() + definition.cooldown_ticks)
|
||||
)
|
||||
if get_active_sorted().size() >= MAX_CONCURRENT_SITUATIONS:
|
||||
return "concurrency cap %d reached" % MAX_CONCURRENT_SITUATIONS
|
||||
return ""
|
||||
|
||||
|
||||
func _build_context(event: WorldEventRecord, state_facts: Dictionary) -> Dictionary:
|
||||
var context := {
|
||||
"world_id": String(DEFAULT_WORLD_ID),
|
||||
"event_id": event.get_event_id(),
|
||||
"event_type": String(event.get_event_type()),
|
||||
}
|
||||
if event.has_location() and not event.get_location().get_world_id().is_empty():
|
||||
context["world_id"] = String(event.get_location().get_world_id())
|
||||
var destination := event.get_participant(WorldEventRecord.ROLE_DESTINATION)
|
||||
var source := event.get_participant(WorldEventRecord.ROLE_SOURCE)
|
||||
var actor := event.get_participant(WorldEventRecord.ROLE_ACTOR)
|
||||
if actor != null:
|
||||
context["actor_id"] = String(actor.get_entity_id())
|
||||
context["actor_type"] = String(actor.get_entity_type())
|
||||
if state_facts.has("interested_npc_id"):
|
||||
context["interested_npc_id"] = str(state_facts["interested_npc_id"])
|
||||
elif actor != null and actor.get_entity_type() == WorldEventRecord.ENTITY_TYPE_NPC:
|
||||
context["interested_npc_id"] = String(actor.get_entity_id())
|
||||
if source != null:
|
||||
context["source_id"] = String(source.get_entity_id())
|
||||
if destination != null:
|
||||
context["destination_id"] = String(destination.get_entity_id())
|
||||
context["target_id"] = String(destination.get_entity_id())
|
||||
elif state_facts.has("target_id"):
|
||||
context["target_id"] = String(state_facts["target_id"])
|
||||
return context
|
||||
|
||||
|
||||
func _build_dedupe_key(definition: SituationDefinition, context: Dictionary) -> String:
|
||||
var parts: Array[String] = [String(definition.situation_definition_id)]
|
||||
for field in definition.dedupe_key_fields:
|
||||
parts.append("%s=%s" % [field, str(context.get(String(field), ""))])
|
||||
return "|".join(parts)
|
||||
|
||||
|
||||
func _evaluate_predicate(
|
||||
predicate: SituationPredicate, event: WorldEventRecord, state_facts: Dictionary
|
||||
) -> Dictionary:
|
||||
if StringName(predicate.source) == SituationPredicate.SOURCE_EVENT:
|
||||
return _evaluate_event_predicate(predicate, event)
|
||||
return _evaluate_state_predicate(predicate, state_facts)
|
||||
|
||||
|
||||
func _evaluate_event_predicate(
|
||||
predicate: SituationPredicate, event: WorldEventRecord
|
||||
) -> Dictionary:
|
||||
if predicate.evaluator_id == PREDICATE_EVENT_TYPE:
|
||||
var expected := StringName(predicate.parameters.get("event_type", ""))
|
||||
var matched := event.get_event_type() == expected
|
||||
return {
|
||||
"matched": matched,
|
||||
"reason":
|
||||
(
|
||||
"event type %s %s %s"
|
||||
% [event.get_event_type(), "matched" if matched else "did not match", expected]
|
||||
),
|
||||
"event_id": event.get_event_id(),
|
||||
}
|
||||
if predicate.evaluator_id == PREDICATE_EVENT_PAYLOAD_EQUALS:
|
||||
var key := String(predicate.parameters.get("key", ""))
|
||||
var expected: Variant = predicate.parameters.get("value")
|
||||
var actual: Variant = event.get_payload().get(key)
|
||||
var matched: bool = actual == expected
|
||||
return {
|
||||
"matched": matched,
|
||||
"reason":
|
||||
(
|
||||
"event payload %s=%s %s expected %s"
|
||||
% [key, actual, "matched" if matched else "did not match", expected]
|
||||
),
|
||||
"event_id": event.get_event_id(),
|
||||
}
|
||||
if predicate.evaluator_id == PREDICATE_EVENT_PARTICIPANT_ID:
|
||||
var role := StringName(predicate.parameters.get("role", ""))
|
||||
var expected := StringName(predicate.parameters.get("entity_id", ""))
|
||||
var participant := event.get_participant(role)
|
||||
var actual: StringName = participant.get_entity_id() if participant != null else &""
|
||||
var matched: bool = actual == expected
|
||||
return {
|
||||
"matched": matched,
|
||||
"reason":
|
||||
(
|
||||
"event participant %s=%s %s %s"
|
||||
% [role, actual, "matched" if matched else "did not match", expected]
|
||||
),
|
||||
"event_id": event.get_event_id(),
|
||||
}
|
||||
if predicate.evaluator_id == PREDICATE_EVENT_PANTRY_SUPPLIED:
|
||||
return _evaluate_pantry_supply_event(predicate, event)
|
||||
return {
|
||||
"matched": false,
|
||||
"reason": "unsupported event predicate '%s'" % predicate.evaluator_id,
|
||||
}
|
||||
|
||||
|
||||
func _evaluate_state_predicate(
|
||||
predicate: SituationPredicate, state_facts: Dictionary
|
||||
) -> Dictionary:
|
||||
var fact_key := String(predicate.parameters.get("fact_key", ""))
|
||||
if fact_key.is_empty() or not state_facts.has(fact_key):
|
||||
return {"matched": false, "reason": "state fact '%s' is unavailable" % fact_key}
|
||||
var actual := float(state_facts[fact_key])
|
||||
var expected := float(predicate.parameters.get("value", 0.0))
|
||||
var matched := false
|
||||
match predicate.evaluator_id:
|
||||
PREDICATE_STATE_NUMBER_LTE:
|
||||
matched = actual <= expected
|
||||
PREDICATE_STATE_NUMBER_GTE:
|
||||
matched = actual >= expected
|
||||
_:
|
||||
return {
|
||||
"matched": false,
|
||||
"reason": "unsupported state predicate '%s'" % predicate.evaluator_id
|
||||
}
|
||||
return {
|
||||
"matched": matched,
|
||||
"reason":
|
||||
(
|
||||
"state %s=%.2f %s %.2f"
|
||||
% [fact_key, actual, "matched" if matched else "did not match", expected]
|
||||
),
|
||||
"current_value": actual,
|
||||
"target_value": expected,
|
||||
}
|
||||
|
||||
|
||||
func _evaluate_resolution_predicate(
|
||||
predicate: SituationPredicate,
|
||||
situation: SituationStateRecord,
|
||||
world_events: WorldEventStore,
|
||||
state_facts: Dictionary
|
||||
) -> Dictionary:
|
||||
if StringName(predicate.source) == SituationPredicate.SOURCE_STATE:
|
||||
return _evaluate_state_predicate(predicate, state_facts)
|
||||
if world_events == null:
|
||||
return {"matched": false, "reason": "world event store is unavailable"}
|
||||
for event in world_events.get_between_ticks(situation.get_created_tick(), 2147483647):
|
||||
if event.get_event_id() <= situation.get_trigger_event_id():
|
||||
continue
|
||||
var evaluation := _evaluate_event_predicate(predicate, event)
|
||||
if bool(evaluation["matched"]):
|
||||
return evaluation
|
||||
return {"matched": false, "reason": "no later event matched '%s'" % predicate.predicate_id}
|
||||
|
||||
|
||||
func _evaluate_pantry_supply_event(
|
||||
predicate: SituationPredicate, event: WorldEventRecord
|
||||
) -> Dictionary:
|
||||
var expected_target := StringName(predicate.parameters.get("target_id", ""))
|
||||
var expected_item := StringName(predicate.parameters.get("item_id", ""))
|
||||
var expected_amount := float(predicate.parameters.get("amount", 0.0))
|
||||
var payload := event.get_payload()
|
||||
var destination := event.get_participant(WorldEventRecord.ROLE_DESTINATION)
|
||||
var source := event.get_participant(WorldEventRecord.ROLE_SOURCE)
|
||||
var actor := event.get_participant(WorldEventRecord.ROLE_ACTOR)
|
||||
var destination_id := destination.get_entity_id() if destination != null else &""
|
||||
var source_id := source.get_entity_id() if source != null else &""
|
||||
var actor_id := actor.get_entity_id() if actor != null else &""
|
||||
var event_type := event.get_event_type()
|
||||
var item_matches := StringName(payload.get("item_id", "")) == expected_item
|
||||
var amount := float(payload.get("amount", 0.0))
|
||||
var route_matches := false
|
||||
if event_type == &"storage_deposited":
|
||||
var expected_source := (
|
||||
&"player_inventory" if actor_id == &"-1" else StringName("npc_inventory_%s" % actor_id)
|
||||
)
|
||||
route_matches = not actor_id.is_empty() and source_id == expected_source
|
||||
elif event_type == &"resource_extracted":
|
||||
route_matches = actor_id == &"-1" and not source_id.is_empty()
|
||||
var matched := (
|
||||
destination_id == expected_target
|
||||
and item_matches
|
||||
and amount >= expected_amount
|
||||
and route_matches
|
||||
)
|
||||
return {
|
||||
"matched": matched,
|
||||
"reason":
|
||||
(
|
||||
"supply event %d %s target=%s item=%s amount=%.2f"
|
||||
% [
|
||||
event.get_event_id(),
|
||||
"matched" if matched else "did not match",
|
||||
destination_id,
|
||||
payload.get("item_id", ""),
|
||||
amount
|
||||
]
|
||||
),
|
||||
"event_id": event.get_event_id(),
|
||||
"current_value": amount if matched else 0.0,
|
||||
"target_value": expected_amount,
|
||||
}
|
||||
|
||||
|
||||
func _is_expired(
|
||||
situation: SituationStateRecord,
|
||||
definition: SituationDefinition,
|
||||
current_tick: int,
|
||||
state_facts: Dictionary
|
||||
) -> bool:
|
||||
for expiry_id in definition.expiry_predicate_ids:
|
||||
if expiry_id == EXPIRY_AGE_REACHED and definition.expiry_ticks > 0:
|
||||
if current_tick - situation.get_created_tick() >= definition.expiry_ticks:
|
||||
return true
|
||||
elif expiry_id == EXPIRY_STATE_NUMBER_GT:
|
||||
var fact_key := String(situation.get_context().get("expiry_fact_key", ""))
|
||||
var threshold := float(situation.get_context().get("expiry_value", 0.0))
|
||||
if state_facts.has(fact_key) and float(state_facts[fact_key]) > threshold:
|
||||
return true
|
||||
return false
|
||||
|
||||
|
||||
static func _event_predicate(
|
||||
label: StringName, predicate_id: StringName, parameters: Dictionary
|
||||
) -> SituationPredicate:
|
||||
var predicate := SituationPredicate.new()
|
||||
predicate.resource_name = String(label)
|
||||
predicate.predicate_id = label
|
||||
predicate.evaluator_id = predicate_id
|
||||
predicate.source = String(SituationPredicate.SOURCE_EVENT)
|
||||
predicate.parameters = parameters
|
||||
return predicate
|
||||
|
||||
|
||||
static func _state_predicate(
|
||||
label: StringName, predicate_id: StringName, parameters: Dictionary
|
||||
) -> SituationPredicate:
|
||||
var predicate := SituationPredicate.new()
|
||||
predicate.resource_name = String(label)
|
||||
predicate.predicate_id = label
|
||||
predicate.evaluator_id = predicate_id
|
||||
predicate.source = String(SituationPredicate.SOURCE_STATE)
|
||||
predicate.parameters = parameters
|
||||
return predicate
|
||||
|
||||
|
||||
static func _sort_definitions(first: SituationDefinition, second: SituationDefinition) -> bool:
|
||||
if first.priority != second.priority:
|
||||
return first.priority > second.priority
|
||||
if first.severity != second.severity:
|
||||
return first.severity > second.severity
|
||||
return String(first.situation_definition_id) < String(second.situation_definition_id)
|
||||
|
||||
|
||||
func _sort_situations(first: SituationStateRecord, second: SituationStateRecord) -> bool:
|
||||
var first_definition := get_definition(first.get_definition_id())
|
||||
var second_definition := get_definition(second.get_definition_id())
|
||||
var first_priority := first_definition.priority if first_definition != null else -101
|
||||
var second_priority := second_definition.priority if second_definition != null else -101
|
||||
if first_priority != second_priority:
|
||||
return first_priority > second_priority
|
||||
var first_severity := first_definition.severity if first_definition != null else -1
|
||||
var second_severity := second_definition.severity if second_definition != null else -1
|
||||
if first_severity != second_severity:
|
||||
return first_severity > second_severity
|
||||
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()
|
||||
@@ -0,0 +1 @@
|
||||
uid://d26pney80ye7h
|
||||
@@ -0,0 +1,189 @@
|
||||
class_name SocialCommitmentSystem
|
||||
extends RefCounted
|
||||
|
||||
const REASON_FACT_FULFILLED := &"world_fact_fulfilled"
|
||||
const REASON_DEADLINE_MISSED := &"deadline_missed"
|
||||
const REASON_SITUATION_EXPIRED := &"situation_expired"
|
||||
const REASON_SITUATION_SUPERSEDED := &"situation_superseded"
|
||||
|
||||
var _commitments_by_id: Dictionary = {}
|
||||
var _active_contract_keys: Dictionary = {}
|
||||
var _next_commitment_id := 0
|
||||
|
||||
|
||||
func create_for_alternative(
|
||||
situation: SituationStateRecord,
|
||||
definition: SituationDefinition,
|
||||
alternative_id: StringName,
|
||||
debtor: WorldEntityRef,
|
||||
creditor: WorldEntityRef,
|
||||
current_tick: int,
|
||||
deadline_tick: int = -1
|
||||
) -> CommitmentStateRecord:
|
||||
if (
|
||||
situation == null
|
||||
or definition == null
|
||||
or not situation.is_active()
|
||||
or situation.get_definition_id() != definition.situation_definition_id
|
||||
or current_tick < situation.get_created_tick()
|
||||
):
|
||||
return null
|
||||
var alternative := definition.get_alternative(alternative_id)
|
||||
if alternative == null or alternative.commitment_terms.is_empty():
|
||||
return null
|
||||
var contract_key := _contract_key(situation.get_situation_id(), debtor, creditor)
|
||||
if contract_key.is_empty() or _active_contract_keys.has(contract_key):
|
||||
return null
|
||||
if not situation.select_alternative(alternative_id):
|
||||
return null
|
||||
var commitment := CommitmentStateRecord.create(
|
||||
_next_commitment_id,
|
||||
situation.get_situation_id(),
|
||||
debtor,
|
||||
creditor,
|
||||
alternative.commitment_terms,
|
||||
current_tick,
|
||||
deadline_tick
|
||||
)
|
||||
if commitment == null:
|
||||
return null
|
||||
_commitments_by_id[_next_commitment_id] = commitment
|
||||
_active_contract_keys[contract_key] = _next_commitment_id
|
||||
_next_commitment_id += 1
|
||||
return commitment
|
||||
|
||||
|
||||
func maintain(
|
||||
current_tick: int,
|
||||
situation_system: SituationSystem,
|
||||
world_events: WorldEventStore,
|
||||
state_facts: Dictionary
|
||||
) -> Array[CommitmentStateRecord]:
|
||||
var closed: Array[CommitmentStateRecord] = []
|
||||
if situation_system == null:
|
||||
return closed
|
||||
for commitment in get_active_sorted():
|
||||
var situation := situation_system.get_by_id(commitment.get_situation_id())
|
||||
if situation == null:
|
||||
continue
|
||||
var progress := situation_system.derive_progress(
|
||||
situation, world_events, state_facts, situation.get_selected_alternative_id()
|
||||
)
|
||||
if progress.resolved:
|
||||
if _close(
|
||||
commitment,
|
||||
CommitmentStateRecord.STATUS_FULFILLED,
|
||||
current_tick,
|
||||
REASON_FACT_FULFILLED,
|
||||
progress.matched_event_id
|
||||
):
|
||||
closed.append(commitment)
|
||||
continue
|
||||
if situation.get_status() == SituationStateRecord.STATUS_SUPERSEDED:
|
||||
if _close(
|
||||
commitment,
|
||||
CommitmentStateRecord.STATUS_SUPERSEDED,
|
||||
current_tick,
|
||||
REASON_SITUATION_SUPERSEDED
|
||||
):
|
||||
closed.append(commitment)
|
||||
continue
|
||||
if situation.get_status() == SituationStateRecord.STATUS_EXPIRED:
|
||||
if _close(
|
||||
commitment,
|
||||
CommitmentStateRecord.STATUS_BROKEN,
|
||||
current_tick,
|
||||
REASON_SITUATION_EXPIRED
|
||||
):
|
||||
closed.append(commitment)
|
||||
continue
|
||||
var deadline := commitment.get_deadline_tick()
|
||||
if deadline >= 0 and current_tick > deadline:
|
||||
if _close(
|
||||
commitment,
|
||||
CommitmentStateRecord.STATUS_BROKEN,
|
||||
current_tick,
|
||||
REASON_DEADLINE_MISSED
|
||||
):
|
||||
closed.append(commitment)
|
||||
return closed
|
||||
|
||||
|
||||
func release(commitment_id: int, current_tick: int, reason: StringName) -> bool:
|
||||
var commitment := get_by_id(commitment_id)
|
||||
return _close(commitment, CommitmentStateRecord.STATUS_RELEASED, current_tick, reason)
|
||||
|
||||
|
||||
func supersede(commitment_id: int, current_tick: int, reason: StringName) -> bool:
|
||||
var commitment := get_by_id(commitment_id)
|
||||
return _close(commitment, CommitmentStateRecord.STATUS_SUPERSEDED, current_tick, reason)
|
||||
|
||||
|
||||
func restore(records: Array[CommitmentStateRecord], restored_next_id: int) -> bool:
|
||||
var by_id: Dictionary = {}
|
||||
var active_keys: Dictionary = {}
|
||||
var next_id := maxi(restored_next_id, 0)
|
||||
for record in records:
|
||||
if record == null or by_id.has(record.get_commitment_id()):
|
||||
return false
|
||||
if record.is_active():
|
||||
var key := _contract_key(
|
||||
record.get_situation_id(), record.get_debtor(), record.get_creditor()
|
||||
)
|
||||
if key.is_empty() or active_keys.has(key):
|
||||
return false
|
||||
active_keys[key] = record.get_commitment_id()
|
||||
by_id[record.get_commitment_id()] = record
|
||||
next_id = maxi(next_id, record.get_commitment_id() + 1)
|
||||
_commitments_by_id = by_id
|
||||
_active_contract_keys = active_keys
|
||||
_next_commitment_id = next_id
|
||||
return true
|
||||
|
||||
|
||||
func get_by_id(commitment_id: int) -> CommitmentStateRecord:
|
||||
return _commitments_by_id.get(commitment_id) as CommitmentStateRecord
|
||||
|
||||
|
||||
func get_all_sorted() -> Array[CommitmentStateRecord]:
|
||||
var records: Array[CommitmentStateRecord] = []
|
||||
for record in _commitments_by_id.values():
|
||||
records.append(record)
|
||||
records.sort_custom(
|
||||
func(first: CommitmentStateRecord, second: CommitmentStateRecord) -> bool:
|
||||
return first.get_commitment_id() < second.get_commitment_id()
|
||||
)
|
||||
return records
|
||||
|
||||
|
||||
func get_active_sorted() -> Array[CommitmentStateRecord]:
|
||||
var records: Array[CommitmentStateRecord] = []
|
||||
for record in get_all_sorted():
|
||||
if record.is_active():
|
||||
records.append(record)
|
||||
return records
|
||||
|
||||
|
||||
func _close(
|
||||
commitment: CommitmentStateRecord,
|
||||
status: StringName,
|
||||
current_tick: int,
|
||||
reason: StringName,
|
||||
cause_event_id: int = CommitmentStateRecord.NO_EVENT_ID
|
||||
) -> bool:
|
||||
if commitment == null or not commitment.close(status, current_tick, reason, cause_event_id):
|
||||
return false
|
||||
_active_contract_keys.erase(
|
||||
_contract_key(
|
||||
commitment.get_situation_id(), commitment.get_debtor(), commitment.get_creditor()
|
||||
)
|
||||
)
|
||||
return true
|
||||
|
||||
|
||||
static func _contract_key(
|
||||
situation_id: int, debtor: WorldEntityRef, creditor: WorldEntityRef
|
||||
) -> String:
|
||||
if situation_id < 0 or debtor == null or creditor == null:
|
||||
return ""
|
||||
return "%d|%s|%s" % [situation_id, debtor.index_key(), creditor.index_key()]
|
||||
@@ -0,0 +1 @@
|
||||
uid://hec6h85fctec
|
||||
Reference in New Issue
Block a user