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
|
||||
@@ -0,0 +1,202 @@
|
||||
class_name CommitmentStateRecord
|
||||
extends RefCounted
|
||||
|
||||
const SCHEMA_VERSION := 1
|
||||
const NO_EVENT_ID := -1
|
||||
const STATUS_ACTIVE := &"active"
|
||||
const STATUS_FULFILLED := &"fulfilled"
|
||||
const STATUS_BROKEN := &"broken"
|
||||
const STATUS_RELEASED := &"released"
|
||||
const STATUS_SUPERSEDED := &"superseded"
|
||||
const VALID_STATUSES := [
|
||||
STATUS_ACTIVE, STATUS_FULFILLED, STATUS_BROKEN, STATUS_RELEASED, STATUS_SUPERSEDED
|
||||
]
|
||||
|
||||
var data: Dictionary
|
||||
|
||||
|
||||
func _init(record_data: Dictionary = {}) -> void:
|
||||
data = record_data.duplicate(true)
|
||||
|
||||
|
||||
static func create(
|
||||
commitment_id: int,
|
||||
situation_id: int,
|
||||
debtor: WorldEntityRef,
|
||||
creditor: WorldEntityRef,
|
||||
terms: Dictionary,
|
||||
created_tick: int,
|
||||
deadline_tick: int = -1
|
||||
) -> CommitmentStateRecord:
|
||||
if (
|
||||
debtor == null
|
||||
or creditor == null
|
||||
or not debtor.is_valid()
|
||||
or not creditor.is_valid()
|
||||
or debtor.equals(creditor)
|
||||
or commitment_id < 0
|
||||
or situation_id < 0
|
||||
or terms.is_empty()
|
||||
or created_tick < 0
|
||||
or (deadline_tick != -1 and deadline_tick < created_tick)
|
||||
):
|
||||
return null
|
||||
return (
|
||||
CommitmentStateRecord
|
||||
. new(
|
||||
{
|
||||
"schema_version": SCHEMA_VERSION,
|
||||
"commitment_id": commitment_id,
|
||||
"situation_id": situation_id,
|
||||
"debtor": debtor.to_dictionary(),
|
||||
"creditor": creditor.to_dictionary(),
|
||||
"terms": terms.duplicate(true),
|
||||
"status": String(STATUS_ACTIVE),
|
||||
"created_tick": created_tick,
|
||||
"deadline_tick": deadline_tick,
|
||||
"closed_tick": -1,
|
||||
"cause_event_id": NO_EVENT_ID,
|
||||
"close_reason": "",
|
||||
}
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
static func from_dictionary(record_data: Dictionary) -> CommitmentStateRecord:
|
||||
if int(record_data.get("schema_version", -1)) != SCHEMA_VERSION:
|
||||
return null
|
||||
if not (
|
||||
record_data
|
||||
. has_all(
|
||||
[
|
||||
"commitment_id",
|
||||
"situation_id",
|
||||
"debtor",
|
||||
"creditor",
|
||||
"terms",
|
||||
"status",
|
||||
"created_tick",
|
||||
"deadline_tick",
|
||||
"closed_tick",
|
||||
"cause_event_id",
|
||||
"close_reason",
|
||||
]
|
||||
)
|
||||
):
|
||||
return null
|
||||
if (
|
||||
not record_data["debtor"] is Dictionary
|
||||
or not record_data["creditor"] is Dictionary
|
||||
or not record_data["terms"] is Dictionary
|
||||
):
|
||||
return null
|
||||
var debtor := WorldEntityRef.from_dictionary(record_data["debtor"])
|
||||
var creditor := WorldEntityRef.from_dictionary(record_data["creditor"])
|
||||
var commitment_id := int(record_data["commitment_id"])
|
||||
var situation_id := int(record_data["situation_id"])
|
||||
var status := StringName(record_data["status"])
|
||||
var created_tick := int(record_data["created_tick"])
|
||||
var deadline_tick := int(record_data["deadline_tick"])
|
||||
var closed_tick := int(record_data["closed_tick"])
|
||||
var cause_event_id := int(record_data["cause_event_id"])
|
||||
var close_reason := StringName(record_data["close_reason"])
|
||||
if (
|
||||
debtor == null
|
||||
or creditor == null
|
||||
or debtor.equals(creditor)
|
||||
or commitment_id < 0
|
||||
or situation_id < 0
|
||||
or record_data["terms"].is_empty()
|
||||
or status not in VALID_STATUSES
|
||||
or created_tick < 0
|
||||
or (deadline_tick != -1 and deadline_tick < created_tick)
|
||||
or cause_event_id < NO_EVENT_ID
|
||||
):
|
||||
return null
|
||||
if status == STATUS_ACTIVE:
|
||||
if closed_tick != -1 or cause_event_id != NO_EVENT_ID or not close_reason.is_empty():
|
||||
return null
|
||||
elif closed_tick < created_tick or close_reason.is_empty():
|
||||
return null
|
||||
var record := create(
|
||||
commitment_id,
|
||||
situation_id,
|
||||
debtor,
|
||||
creditor,
|
||||
record_data["terms"],
|
||||
created_tick,
|
||||
deadline_tick
|
||||
)
|
||||
if status != STATUS_ACTIVE:
|
||||
record.close(status, closed_tick, close_reason, cause_event_id)
|
||||
return record
|
||||
|
||||
|
||||
func get_commitment_id() -> int:
|
||||
return int(data["commitment_id"])
|
||||
|
||||
|
||||
func get_situation_id() -> int:
|
||||
return int(data["situation_id"])
|
||||
|
||||
|
||||
func get_debtor() -> WorldEntityRef:
|
||||
return WorldEntityRef.from_dictionary(data["debtor"])
|
||||
|
||||
|
||||
func get_creditor() -> WorldEntityRef:
|
||||
return WorldEntityRef.from_dictionary(data["creditor"])
|
||||
|
||||
|
||||
func get_terms() -> Dictionary:
|
||||
return data["terms"].duplicate(true)
|
||||
|
||||
|
||||
func get_status() -> StringName:
|
||||
return StringName(data["status"])
|
||||
|
||||
|
||||
func get_created_tick() -> int:
|
||||
return int(data["created_tick"])
|
||||
|
||||
|
||||
func get_deadline_tick() -> int:
|
||||
return int(data["deadline_tick"])
|
||||
|
||||
|
||||
func get_closed_tick() -> int:
|
||||
return int(data["closed_tick"])
|
||||
|
||||
|
||||
func get_cause_event_id() -> int:
|
||||
return int(data["cause_event_id"])
|
||||
|
||||
|
||||
func get_close_reason() -> StringName:
|
||||
return StringName(data["close_reason"])
|
||||
|
||||
|
||||
func is_active() -> bool:
|
||||
return get_status() == STATUS_ACTIVE
|
||||
|
||||
|
||||
func close(
|
||||
status: StringName, closed_tick: int, reason: StringName, cause_event_id: int = NO_EVENT_ID
|
||||
) -> bool:
|
||||
if (
|
||||
not is_active()
|
||||
or status not in [STATUS_FULFILLED, STATUS_BROKEN, STATUS_RELEASED, STATUS_SUPERSEDED]
|
||||
or closed_tick < get_created_tick()
|
||||
or reason.is_empty()
|
||||
or cause_event_id < NO_EVENT_ID
|
||||
):
|
||||
return false
|
||||
data["status"] = String(status)
|
||||
data["closed_tick"] = closed_tick
|
||||
data["cause_event_id"] = cause_event_id
|
||||
data["close_reason"] = String(reason)
|
||||
return true
|
||||
|
||||
|
||||
func to_dictionary() -> Dictionary:
|
||||
return data.duplicate(true)
|
||||
@@ -0,0 +1 @@
|
||||
uid://fthjvjr6x2ia
|
||||
@@ -0,0 +1,174 @@
|
||||
class_name QuestJournalEntryStateRecord
|
||||
extends RefCounted
|
||||
|
||||
const SCHEMA_VERSION := 1
|
||||
const STATUS_ACTIVE := &"active"
|
||||
const STATUS_COMPLETED := &"completed"
|
||||
const STATUS_FAILED := &"failed"
|
||||
const STATUS_ARCHIVED := &"archived"
|
||||
const VALID_STATUSES := [STATUS_ACTIVE, STATUS_COMPLETED, STATUS_FAILED, STATUS_ARCHIVED]
|
||||
const TRACKING_AUTO := &"auto"
|
||||
const TRACKING_TRACKED := &"tracked"
|
||||
const TRACKING_UNTRACKED := &"untracked"
|
||||
const VALID_TRACKING_PREFERENCES := [TRACKING_AUTO, TRACKING_TRACKED, TRACKING_UNTRACKED]
|
||||
|
||||
var data: Dictionary
|
||||
|
||||
|
||||
func _init(record_data: Dictionary = {}) -> void:
|
||||
data = record_data.duplicate(true)
|
||||
|
||||
|
||||
static func create(
|
||||
entry_id: int,
|
||||
situation_id: int,
|
||||
definition_id: StringName,
|
||||
discovered_tick: int,
|
||||
selected_alternative_id: StringName = &"",
|
||||
tracking_preference: StringName = TRACKING_AUTO
|
||||
) -> QuestJournalEntryStateRecord:
|
||||
if (
|
||||
entry_id < 0
|
||||
or situation_id < 0
|
||||
or definition_id.is_empty()
|
||||
or discovered_tick < 0
|
||||
or tracking_preference not in VALID_TRACKING_PREFERENCES
|
||||
):
|
||||
return null
|
||||
return (
|
||||
QuestJournalEntryStateRecord
|
||||
. new(
|
||||
{
|
||||
"schema_version": SCHEMA_VERSION,
|
||||
"entry_id": entry_id,
|
||||
"situation_id": situation_id,
|
||||
"definition_id": String(definition_id),
|
||||
"status": String(STATUS_ACTIVE),
|
||||
"discovered_tick": discovered_tick,
|
||||
"selected_alternative_id": String(selected_alternative_id),
|
||||
"tracking_preference": String(tracking_preference),
|
||||
"closed_tick": -1,
|
||||
}
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
static func from_dictionary(record_data: Dictionary) -> QuestJournalEntryStateRecord:
|
||||
if int(record_data.get("schema_version", -1)) != SCHEMA_VERSION:
|
||||
return null
|
||||
if not (
|
||||
record_data
|
||||
. has_all(
|
||||
[
|
||||
"entry_id",
|
||||
"situation_id",
|
||||
"definition_id",
|
||||
"status",
|
||||
"discovered_tick",
|
||||
"selected_alternative_id",
|
||||
"tracking_preference",
|
||||
"closed_tick",
|
||||
]
|
||||
)
|
||||
):
|
||||
return null
|
||||
var entry_id := int(record_data["entry_id"])
|
||||
var situation_id := int(record_data["situation_id"])
|
||||
var definition_id := StringName(record_data["definition_id"])
|
||||
var status := StringName(record_data["status"])
|
||||
var discovered_tick := int(record_data["discovered_tick"])
|
||||
var selected_alternative_id := StringName(record_data["selected_alternative_id"])
|
||||
var tracking_preference := StringName(record_data["tracking_preference"])
|
||||
var closed_tick := int(record_data["closed_tick"])
|
||||
if (
|
||||
entry_id < 0
|
||||
or situation_id < 0
|
||||
or definition_id.is_empty()
|
||||
or status not in VALID_STATUSES
|
||||
or discovered_tick < 0
|
||||
or tracking_preference not in VALID_TRACKING_PREFERENCES
|
||||
):
|
||||
return null
|
||||
if (
|
||||
(status == STATUS_ACTIVE and closed_tick != -1)
|
||||
or (status != STATUS_ACTIVE and closed_tick < discovered_tick)
|
||||
):
|
||||
return null
|
||||
var record := create(
|
||||
entry_id,
|
||||
situation_id,
|
||||
definition_id,
|
||||
discovered_tick,
|
||||
selected_alternative_id,
|
||||
tracking_preference
|
||||
)
|
||||
if status != STATUS_ACTIVE:
|
||||
record.close(status, closed_tick)
|
||||
return record
|
||||
|
||||
|
||||
func get_entry_id() -> int:
|
||||
return int(data["entry_id"])
|
||||
|
||||
|
||||
func get_situation_id() -> int:
|
||||
return int(data["situation_id"])
|
||||
|
||||
|
||||
func get_definition_id() -> StringName:
|
||||
return StringName(data["definition_id"])
|
||||
|
||||
|
||||
func get_status() -> StringName:
|
||||
return StringName(data["status"])
|
||||
|
||||
|
||||
func get_discovered_tick() -> int:
|
||||
return int(data["discovered_tick"])
|
||||
|
||||
|
||||
func get_selected_alternative_id() -> StringName:
|
||||
return StringName(data["selected_alternative_id"])
|
||||
|
||||
|
||||
func get_tracking_preference() -> StringName:
|
||||
return StringName(data["tracking_preference"])
|
||||
|
||||
|
||||
func get_closed_tick() -> int:
|
||||
return int(data["closed_tick"])
|
||||
|
||||
|
||||
func is_active() -> bool:
|
||||
return get_status() == STATUS_ACTIVE
|
||||
|
||||
|
||||
func is_archived() -> bool:
|
||||
return get_status() == STATUS_ARCHIVED
|
||||
|
||||
|
||||
func set_tracking_preference(preference: StringName) -> bool:
|
||||
if preference not in VALID_TRACKING_PREFERENCES:
|
||||
return false
|
||||
data["tracking_preference"] = String(preference)
|
||||
return true
|
||||
|
||||
|
||||
func archive(closed_tick: int) -> bool:
|
||||
return close(STATUS_ARCHIVED, closed_tick)
|
||||
|
||||
|
||||
func close(status: StringName, closed_tick: int) -> bool:
|
||||
if (
|
||||
not is_active()
|
||||
or status not in [STATUS_COMPLETED, STATUS_FAILED, STATUS_ARCHIVED]
|
||||
or closed_tick < get_discovered_tick()
|
||||
):
|
||||
return false
|
||||
data["status"] = String(status)
|
||||
data["closed_tick"] = closed_tick
|
||||
return true
|
||||
|
||||
|
||||
func to_dictionary() -> Dictionary:
|
||||
return data.duplicate(true)
|
||||
@@ -0,0 +1 @@
|
||||
uid://c5i631jie8rtt
|
||||
@@ -0,0 +1,233 @@
|
||||
class_name SituationStateRecord
|
||||
extends RefCounted
|
||||
|
||||
const SCHEMA_VERSION := 1
|
||||
const NO_EVENT_ID := -1
|
||||
const STATUS_ACTIVE := &"active"
|
||||
const STATUS_RESOLVED := &"resolved"
|
||||
const STATUS_EXPIRED := &"expired"
|
||||
const STATUS_SUPERSEDED := &"superseded"
|
||||
const VALID_STATUSES := [STATUS_ACTIVE, STATUS_RESOLVED, STATUS_EXPIRED, STATUS_SUPERSEDED]
|
||||
|
||||
var data: Dictionary
|
||||
|
||||
|
||||
func _init(record_data: Dictionary = {}) -> void:
|
||||
data = record_data.duplicate(true)
|
||||
|
||||
|
||||
static func create(
|
||||
situation_id: int,
|
||||
definition_id: StringName,
|
||||
dedupe_key: String,
|
||||
created_tick: int,
|
||||
trigger_event_id: int = NO_EVENT_ID,
|
||||
context: Dictionary = {}
|
||||
) -> SituationStateRecord:
|
||||
if situation_id < 0 or definition_id.is_empty() or dedupe_key.is_empty() or created_tick < 0:
|
||||
return null
|
||||
if trigger_event_id < NO_EVENT_ID:
|
||||
return null
|
||||
return (
|
||||
SituationStateRecord
|
||||
. new(
|
||||
{
|
||||
"schema_version": SCHEMA_VERSION,
|
||||
"situation_id": situation_id,
|
||||
"definition_id": String(definition_id),
|
||||
"dedupe_key": dedupe_key,
|
||||
"status": String(STATUS_ACTIVE),
|
||||
"created_tick": created_tick,
|
||||
"trigger_event_id": trigger_event_id,
|
||||
"selected_alternative_id": "",
|
||||
"resolution_event_id": NO_EVENT_ID,
|
||||
"closed_tick": -1,
|
||||
"close_reason": "",
|
||||
"context": context.duplicate(true),
|
||||
}
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
static func from_dictionary(record_data: Dictionary) -> SituationStateRecord:
|
||||
if int(record_data.get("schema_version", -1)) != SCHEMA_VERSION:
|
||||
return null
|
||||
if not (
|
||||
record_data
|
||||
. has_all(
|
||||
[
|
||||
"situation_id",
|
||||
"definition_id",
|
||||
"dedupe_key",
|
||||
"status",
|
||||
"created_tick",
|
||||
"trigger_event_id",
|
||||
"selected_alternative_id",
|
||||
"resolution_event_id",
|
||||
"closed_tick",
|
||||
"close_reason",
|
||||
"context",
|
||||
]
|
||||
)
|
||||
):
|
||||
return null
|
||||
var situation_id := int(record_data["situation_id"])
|
||||
var definition_id := StringName(record_data["definition_id"])
|
||||
var dedupe_key := String(record_data["dedupe_key"])
|
||||
var status := StringName(record_data["status"])
|
||||
var created_tick := int(record_data["created_tick"])
|
||||
var trigger_event_id := int(record_data["trigger_event_id"])
|
||||
var selected_alternative_id := StringName(record_data["selected_alternative_id"])
|
||||
var resolution_event_id := int(record_data["resolution_event_id"])
|
||||
var closed_tick := int(record_data["closed_tick"])
|
||||
var close_reason := StringName(record_data["close_reason"])
|
||||
if (
|
||||
situation_id < 0
|
||||
or definition_id.is_empty()
|
||||
or dedupe_key.is_empty()
|
||||
or status not in VALID_STATUSES
|
||||
or created_tick < 0
|
||||
or trigger_event_id < NO_EVENT_ID
|
||||
or not record_data["context"] is Dictionary
|
||||
):
|
||||
return null
|
||||
if status == STATUS_ACTIVE:
|
||||
if resolution_event_id != NO_EVENT_ID or closed_tick != -1 or not close_reason.is_empty():
|
||||
return null
|
||||
else:
|
||||
if closed_tick < created_tick or close_reason.is_empty():
|
||||
return null
|
||||
if status != STATUS_RESOLVED and resolution_event_id != NO_EVENT_ID:
|
||||
return null
|
||||
var record := create(
|
||||
situation_id,
|
||||
definition_id,
|
||||
dedupe_key,
|
||||
created_tick,
|
||||
trigger_event_id,
|
||||
record_data["context"]
|
||||
)
|
||||
if not selected_alternative_id.is_empty():
|
||||
record.select_alternative(selected_alternative_id)
|
||||
if status != STATUS_ACTIVE:
|
||||
record.close(status, closed_tick, close_reason, resolution_event_id)
|
||||
return record
|
||||
|
||||
|
||||
static func from_opportunity(
|
||||
opportunity: OpportunityStateRecord, mapped_definition_id: StringName = &""
|
||||
) -> SituationStateRecord:
|
||||
if opportunity == null:
|
||||
return null
|
||||
var context := {
|
||||
"opportunity_id": opportunity.get_opportunity_id(),
|
||||
"interested_npc_id": opportunity.get_interested_npc_id(),
|
||||
"target_id": String(opportunity.get_target_id()),
|
||||
"resource_id": String(opportunity.get_resource_id()),
|
||||
"target_amount": opportunity.get_target_amount(),
|
||||
}
|
||||
var dedupe_key := "opportunity:%d" % opportunity.get_opportunity_id()
|
||||
var definition_id := mapped_definition_id
|
||||
if definition_id.is_empty():
|
||||
definition_id = opportunity.get_opportunity_type()
|
||||
var record := create(
|
||||
opportunity.get_opportunity_id(),
|
||||
definition_id,
|
||||
dedupe_key,
|
||||
opportunity.get_created_tick(),
|
||||
opportunity.get_trigger_event_id(),
|
||||
context
|
||||
)
|
||||
if opportunity.get_status() == OpportunityStateRecord.STATUS_RESOLVED:
|
||||
record.close(
|
||||
STATUS_RESOLVED,
|
||||
opportunity.get_closed_tick(),
|
||||
&"opportunity_resolved",
|
||||
opportunity.get_resolution_event_id()
|
||||
)
|
||||
elif opportunity.get_status() == OpportunityStateRecord.STATUS_INVALIDATED:
|
||||
record.close(
|
||||
STATUS_EXPIRED, opportunity.get_closed_tick(), opportunity.get_invalidation_reason()
|
||||
)
|
||||
return record
|
||||
|
||||
|
||||
func get_situation_id() -> int:
|
||||
return int(data["situation_id"])
|
||||
|
||||
|
||||
func get_definition_id() -> StringName:
|
||||
return StringName(data["definition_id"])
|
||||
|
||||
|
||||
func get_dedupe_key() -> String:
|
||||
return String(data["dedupe_key"])
|
||||
|
||||
|
||||
func get_status() -> StringName:
|
||||
return StringName(data["status"])
|
||||
|
||||
|
||||
func get_created_tick() -> int:
|
||||
return int(data["created_tick"])
|
||||
|
||||
|
||||
func get_trigger_event_id() -> int:
|
||||
return int(data["trigger_event_id"])
|
||||
|
||||
|
||||
func get_selected_alternative_id() -> StringName:
|
||||
return StringName(data["selected_alternative_id"])
|
||||
|
||||
|
||||
func get_resolution_event_id() -> int:
|
||||
return int(data["resolution_event_id"])
|
||||
|
||||
|
||||
func get_closed_tick() -> int:
|
||||
return int(data["closed_tick"])
|
||||
|
||||
|
||||
func get_close_reason() -> StringName:
|
||||
return StringName(data["close_reason"])
|
||||
|
||||
|
||||
func get_context() -> Dictionary:
|
||||
return data["context"].duplicate(true)
|
||||
|
||||
|
||||
func is_active() -> bool:
|
||||
return get_status() == STATUS_ACTIVE
|
||||
|
||||
|
||||
func select_alternative(alternative_id: StringName) -> bool:
|
||||
if not is_active() or alternative_id.is_empty():
|
||||
return false
|
||||
var selected := get_selected_alternative_id()
|
||||
if not selected.is_empty() and selected != alternative_id:
|
||||
return false
|
||||
data["selected_alternative_id"] = String(alternative_id)
|
||||
return true
|
||||
|
||||
|
||||
func close(
|
||||
status: StringName, closed_tick: int, reason: StringName, resolution_event_id: int = NO_EVENT_ID
|
||||
) -> bool:
|
||||
if (
|
||||
not is_active()
|
||||
or status not in [STATUS_RESOLVED, STATUS_EXPIRED, STATUS_SUPERSEDED]
|
||||
or closed_tick < get_created_tick()
|
||||
or reason.is_empty()
|
||||
):
|
||||
return false
|
||||
if status != STATUS_RESOLVED and resolution_event_id != NO_EVENT_ID:
|
||||
return false
|
||||
data["status"] = String(status)
|
||||
data["resolution_event_id"] = resolution_event_id
|
||||
data["closed_tick"] = closed_tick
|
||||
data["close_reason"] = String(reason)
|
||||
return true
|
||||
|
||||
|
||||
func to_dictionary() -> Dictionary:
|
||||
return data.duplicate(true)
|
||||
@@ -0,0 +1 @@
|
||||
uid://c3x0msm0gmlpk
|
||||
@@ -0,0 +1,298 @@
|
||||
extends GutTest
|
||||
|
||||
|
||||
func test_pantry_definition_exposes_typed_lifecycle_contract() -> void:
|
||||
var definition := SituationSystem.create_pantry_shortage_definition()
|
||||
var errors := (
|
||||
definition
|
||||
. validate(
|
||||
[
|
||||
SituationSystem.PREDICATE_EVENT_TYPE,
|
||||
SituationSystem.PREDICATE_EVENT_PAYLOAD_EQUALS,
|
||||
SituationSystem.PREDICATE_EVENT_PARTICIPANT_ID,
|
||||
SituationSystem.PREDICATE_EVENT_PANTRY_SUPPLIED,
|
||||
],
|
||||
[
|
||||
SituationSystem.PREDICATE_STATE_NUMBER_LTE,
|
||||
SituationSystem.PREDICATE_STATE_NUMBER_GTE,
|
||||
],
|
||||
[SituationSystem.EXPIRY_AGE_REACHED]
|
||||
)
|
||||
)
|
||||
|
||||
assert_true(errors.is_empty(), str(errors))
|
||||
assert_eq(definition.situation_definition_id, SituationSystem.DEFINITION_PANTRY_SHORTAGE)
|
||||
assert_eq(definition.dedupe_key_fields, [&"world_id", &"source_id"])
|
||||
assert_eq(definition.severity, 70)
|
||||
assert_eq(definition.priority, 80)
|
||||
assert_eq(definition.cooldown_ticks, 50)
|
||||
assert_eq(definition.expiry_ticks, 200)
|
||||
assert_eq(definition.dialogue_topic_ids, [SituationSystem.DIALOGUE_TOPIC_PANTRY_SHORTAGE])
|
||||
var alternative := definition.get_alternative(SituationSystem.ALTERNATIVE_RESTOCK)
|
||||
assert_not_null(alternative)
|
||||
assert_eq(alternative.commitment_terms["target_id"], "village_pantry")
|
||||
assert_eq(alternative.commitment_terms["amount"], 1.0)
|
||||
|
||||
|
||||
func test_generation_exposes_reasons_dedupes_and_enforces_cooldown() -> void:
|
||||
var system := SituationSystem.create_default()
|
||||
var event := _pantry_withdrawal(4, 10)
|
||||
var opened_results := system.consider_event(event, 10, _pantry_facts(0.0))
|
||||
|
||||
assert_eq(opened_results.size(), 1)
|
||||
assert_true(opened_results[0].matched)
|
||||
assert_eq(opened_results[0].opened_situation_id, 0)
|
||||
assert_eq(opened_results[0].reason_traces.size(), 5)
|
||||
assert_string_contains(opened_results[0].reason_traces[-1], "opened situation")
|
||||
var situation := system.get_by_id(0)
|
||||
assert_not_null(situation)
|
||||
assert_eq(situation.get_context()["source_id"], "village_pantry")
|
||||
assert_eq(situation.get_context()["actor_id"], "2")
|
||||
assert_eq(situation.get_context()["interested_npc_id"], "2")
|
||||
|
||||
var duplicate := system.consider_event(_pantry_withdrawal(5, 11), 11, _pantry_facts(0.0))[0]
|
||||
assert_true(duplicate.matched)
|
||||
assert_eq(duplicate.opened_situation_id, -1)
|
||||
assert_string_contains(duplicate.reason_traces[-1], "dedupe blocked")
|
||||
|
||||
var world_events := WorldEventStore.new()
|
||||
assert_true(world_events.append(_pantry_supply(8, 12)))
|
||||
var closed := system.maintain(12, world_events, _pantry_facts(1.0))
|
||||
assert_eq(closed, [situation])
|
||||
assert_eq(situation.get_status(), SituationStateRecord.STATUS_RESOLVED)
|
||||
assert_eq(situation.get_resolution_event_id(), 8)
|
||||
var cooldown := system.consider_event(_pantry_withdrawal(6, 20), 20, _pantry_facts(0.0))[0]
|
||||
assert_string_contains(cooldown.reason_traces[-1], "cooldown active until tick 62")
|
||||
var reopened := system.consider_event(_pantry_withdrawal(7, 62), 62, _pantry_facts(0.0))[0]
|
||||
assert_eq(reopened.opened_situation_id, 1)
|
||||
|
||||
|
||||
func test_generator_caps_at_three_and_orders_by_priority_then_severity() -> void:
|
||||
var definitions: Array[SituationDefinition] = [
|
||||
_definition(&"lowest", 10, 10),
|
||||
_definition(&"highest", 40, 10),
|
||||
_definition(&"middle_high", 30, 40),
|
||||
_definition(&"middle_low", 30, 20),
|
||||
]
|
||||
var system := SituationSystem.new()
|
||||
assert_true(system.configure(definitions).is_empty())
|
||||
var results := system.consider_event(_pantry_withdrawal(10, 5), 5, _pantry_facts(0.0))
|
||||
|
||||
assert_eq(results.size(), 4)
|
||||
assert_eq(
|
||||
results.map(func(result: SituationEvaluationResult) -> String: return result.definition_id),
|
||||
["highest", "middle_high", "middle_low", "lowest"]
|
||||
)
|
||||
assert_eq(system.get_active_sorted().size(), SituationSystem.MAX_CONCURRENT_SITUATIONS)
|
||||
assert_eq(
|
||||
_definition_ids(system.get_active_sorted()), [&"highest", &"middle_high", &"middle_low"]
|
||||
)
|
||||
assert_string_contains(results[-1].reason_traces[-1], "concurrency cap 3 reached")
|
||||
|
||||
|
||||
func test_nonmatching_events_trace_each_failed_fact_without_opening() -> void:
|
||||
var system := SituationSystem.create_default()
|
||||
var wrong_item := EconomicEventRecord.create(
|
||||
1, &"storage_withdrawn", 3, 2, &"village_woodpile", &"npc_inventory_2", &"wood", 1.0
|
||||
)
|
||||
var result := (
|
||||
system
|
||||
. consider_event(
|
||||
WorldEventRecord.from_economic_event(wrong_item, &"jajce"), 3, _pantry_facts(2.0)
|
||||
)[0]
|
||||
)
|
||||
|
||||
assert_false(result.matched)
|
||||
assert_eq(result.opened_situation_id, -1)
|
||||
assert_true(system.get_active_sorted().is_empty())
|
||||
assert_true(
|
||||
result.reason_traces.any(func(reason: String) -> bool: return "did not match" in reason)
|
||||
)
|
||||
|
||||
|
||||
func test_progress_and_journal_are_derived_from_world_facts() -> void:
|
||||
var situation_system := SituationSystem.create_default()
|
||||
situation_system.consider_event(_pantry_withdrawal(1, 10), 10, _pantry_facts(0.0))
|
||||
var situation := situation_system.get_by_id(0)
|
||||
var journal := QuestJournalSystem.new()
|
||||
var entry := journal.add_situation(
|
||||
situation,
|
||||
situation_system.get_definition(situation.get_definition_id()),
|
||||
SituationSystem.ALTERNATIVE_RESTOCK,
|
||||
10
|
||||
)
|
||||
var entry_before := entry.to_dictionary()
|
||||
|
||||
var empty_progress := journal.derive_progress(
|
||||
entry, situation_system, WorldEventStore.new(), _pantry_facts(0.0)
|
||||
)
|
||||
var partial_progress := journal.derive_progress(
|
||||
entry, situation_system, WorldEventStore.new(), _pantry_facts(0.5)
|
||||
)
|
||||
var supplied_events := WorldEventStore.new()
|
||||
assert_true(supplied_events.append(_pantry_supply(4, 12)))
|
||||
var complete_progress := journal.derive_progress(
|
||||
entry, situation_system, supplied_events, _pantry_facts(1.0)
|
||||
)
|
||||
|
||||
assert_false(empty_progress.resolved)
|
||||
assert_eq(empty_progress.ratio(), 0.0)
|
||||
assert_false(partial_progress.resolved)
|
||||
assert_eq(partial_progress.ratio(), 0.0)
|
||||
assert_true(complete_progress.resolved)
|
||||
assert_eq(complete_progress.ratio(), 1.0)
|
||||
assert_eq(complete_progress.matched_event_id, 4)
|
||||
assert_eq(entry.to_dictionary(), entry_before)
|
||||
assert_false(entry.to_dictionary().has("progress"))
|
||||
assert_eq(entry.get_discovered_tick(), 10)
|
||||
assert_eq(entry.get_tracking_preference(), QuestJournalEntryStateRecord.TRACKING_AUTO)
|
||||
assert_true(entry.set_tracking_preference(QuestJournalEntryStateRecord.TRACKING_TRACKED))
|
||||
assert_eq(journal.get_for_situation(0), entry)
|
||||
|
||||
situation_system.maintain(12, supplied_events, _pantry_facts(1.0))
|
||||
assert_eq(journal.synchronize(situation, 12), entry)
|
||||
assert_eq(entry.get_status(), QuestJournalEntryStateRecord.STATUS_COMPLETED)
|
||||
assert_eq(
|
||||
QuestJournalEntryStateRecord.from_dictionary(entry.to_dictionary()).to_dictionary(),
|
||||
entry.to_dictionary()
|
||||
)
|
||||
var archive_entry := QuestJournalEntryStateRecord.create(4, 9, &"archive_test", 10)
|
||||
assert_true(archive_entry.archive(11))
|
||||
assert_true(archive_entry.is_archived())
|
||||
|
||||
|
||||
func test_commitments_fulfill_break_release_and_supersede() -> void:
|
||||
var system := SituationSystem.create_default()
|
||||
system.consider_event(_pantry_withdrawal(1, 10), 10, _pantry_facts(0.0))
|
||||
var situation := system.get_by_id(0)
|
||||
var definition := system.get_definition(situation.get_definition_id())
|
||||
var debtor := WorldEntityRef.create(&"player", &"-1")
|
||||
var creditor := WorldEntityRef.create(&"npc", &"4")
|
||||
var commitments := SocialCommitmentSystem.new()
|
||||
var fulfilled := commitments.create_for_alternative(
|
||||
situation, definition, SituationSystem.ALTERNATIVE_RESTOCK, debtor, creditor, 10, 20
|
||||
)
|
||||
|
||||
assert_not_null(fulfilled)
|
||||
assert_eq(fulfilled.get_terms()["item_id"], "food")
|
||||
assert_null(
|
||||
commitments.create_for_alternative(
|
||||
situation, definition, SituationSystem.ALTERNATIVE_RESTOCK, debtor, creditor, 10
|
||||
)
|
||||
)
|
||||
var supplied_events := WorldEventStore.new()
|
||||
assert_true(supplied_events.append(_pantry_supply(9, 12)))
|
||||
assert_eq(commitments.maintain(12, system, supplied_events, _pantry_facts(1.0)), [fulfilled])
|
||||
assert_eq(fulfilled.get_status(), CommitmentStateRecord.STATUS_FULFILLED)
|
||||
assert_eq(fulfilled.get_cause_event_id(), 9)
|
||||
|
||||
var broken := CommitmentStateRecord.create(1, 2, debtor, creditor, {"amount": 1.0}, 10, 11)
|
||||
var released := CommitmentStateRecord.create(2, 3, debtor, creditor, {"amount": 1.0}, 10)
|
||||
var superseded := CommitmentStateRecord.create(3, 4, debtor, creditor, {"amount": 1.0}, 10)
|
||||
assert_true(broken.close(CommitmentStateRecord.STATUS_BROKEN, 12, &"deadline_missed"))
|
||||
assert_true(released.close(CommitmentStateRecord.STATUS_RELEASED, 12, &"mutual_release"))
|
||||
assert_true(superseded.close(CommitmentStateRecord.STATUS_SUPERSEDED, 12, &"new_promise"))
|
||||
assert_eq(broken.get_status(), CommitmentStateRecord.STATUS_BROKEN)
|
||||
assert_eq(released.get_status(), CommitmentStateRecord.STATUS_RELEASED)
|
||||
assert_eq(superseded.get_status(), CommitmentStateRecord.STATUS_SUPERSEDED)
|
||||
for record in [fulfilled, broken, released, superseded]:
|
||||
assert_eq(
|
||||
CommitmentStateRecord.from_dictionary(record.to_dictionary()).to_dictionary(),
|
||||
record.to_dictionary()
|
||||
)
|
||||
|
||||
|
||||
func test_opportunity_bridge_maps_pantry_identity_and_preserves_lifecycle() -> void:
|
||||
var opportunity := OpportunityStateRecord.create(8, 10, 4, 2)
|
||||
assert_true(opportunity.resolve(12, 14))
|
||||
var system := SituationSystem.create_default()
|
||||
|
||||
assert_true(system.import_opportunities([opportunity]).is_empty())
|
||||
var imported := system.get_by_id(8)
|
||||
assert_not_null(imported)
|
||||
assert_eq(imported.get_definition_id(), SituationSystem.DEFINITION_PANTRY_SHORTAGE)
|
||||
assert_eq(imported.get_status(), SituationStateRecord.STATUS_RESOLVED)
|
||||
assert_eq(imported.get_trigger_event_id(), 4)
|
||||
assert_eq(imported.get_resolution_event_id(), 12)
|
||||
assert_eq(imported.get_context()["interested_npc_id"], 2)
|
||||
assert_eq(
|
||||
SituationStateRecord.from_dictionary(imported.to_dictionary()).to_dictionary(),
|
||||
imported.to_dictionary()
|
||||
)
|
||||
|
||||
|
||||
func test_record_parsers_reject_impossible_lifecycle_state() -> void:
|
||||
var situation := SituationStateRecord.create(1, &"definition", "definition|world=jajce", 10)
|
||||
var invalid_situation := situation.to_dictionary()
|
||||
invalid_situation["status"] = String(SituationStateRecord.STATUS_RESOLVED)
|
||||
invalid_situation["closed_tick"] = 9
|
||||
invalid_situation["close_reason"] = "done"
|
||||
assert_null(SituationStateRecord.from_dictionary(invalid_situation))
|
||||
|
||||
var entry := QuestJournalEntryStateRecord.create(1, 1, &"definition", 10)
|
||||
var invalid_entry := entry.to_dictionary()
|
||||
invalid_entry["status"] = String(QuestJournalEntryStateRecord.STATUS_COMPLETED)
|
||||
assert_null(QuestJournalEntryStateRecord.from_dictionary(invalid_entry))
|
||||
|
||||
var entity := WorldEntityRef.create(&"npc", &"1")
|
||||
assert_null(CommitmentStateRecord.create(1, 1, entity, entity, {"amount": 1.0}, 10))
|
||||
var valid_commitment := CommitmentStateRecord.create(
|
||||
1, 1, entity, WorldEntityRef.create(&"npc", &"2"), {"amount": 1.0}, 10
|
||||
)
|
||||
var invalid_commitment := valid_commitment.to_dictionary()
|
||||
invalid_commitment["status"] = String(CommitmentStateRecord.STATUS_FULFILLED)
|
||||
invalid_commitment["close_reason"] = "done"
|
||||
assert_null(CommitmentStateRecord.from_dictionary(invalid_commitment))
|
||||
|
||||
|
||||
func _pantry_withdrawal(event_id: int, tick: int) -> WorldEventRecord:
|
||||
var economic := EconomicEventRecord.create(
|
||||
event_id,
|
||||
&"storage_withdrawn",
|
||||
tick,
|
||||
2,
|
||||
&"village_pantry",
|
||||
&"npc_inventory_2",
|
||||
&"food",
|
||||
1.0,
|
||||
Vector3(2.0, 0.0, 3.0)
|
||||
)
|
||||
return WorldEventRecord.from_economic_event(economic, &"jajce", &"village_pantry")
|
||||
|
||||
|
||||
func _pantry_facts(amount: float) -> Dictionary:
|
||||
return {
|
||||
"pantry.food": amount,
|
||||
"target_id": "village_pantry",
|
||||
}
|
||||
|
||||
|
||||
func _pantry_supply(event_id: int, tick: int) -> WorldEventRecord:
|
||||
var economic := EconomicEventRecord.create(
|
||||
event_id,
|
||||
&"storage_deposited",
|
||||
tick,
|
||||
3,
|
||||
&"npc_inventory_3",
|
||||
&"village_pantry",
|
||||
&"food",
|
||||
1.0,
|
||||
Vector3(2.0, 0.0, 3.0)
|
||||
)
|
||||
return WorldEventRecord.from_economic_event(economic, &"jajce", &"village_pantry")
|
||||
|
||||
|
||||
func _definition(definition_id: StringName, priority: int, severity: int) -> SituationDefinition:
|
||||
var definition := SituationSystem.create_pantry_shortage_definition()
|
||||
definition.situation_definition_id = definition_id
|
||||
definition.priority = priority
|
||||
definition.severity = severity
|
||||
definition.cooldown_ticks = 0
|
||||
return definition
|
||||
|
||||
|
||||
func _definition_ids(situations: Array[SituationStateRecord]) -> Array[StringName]:
|
||||
var result: Array[StringName] = []
|
||||
for situation in situations:
|
||||
result.append(situation.get_definition_id())
|
||||
return result
|
||||
@@ -0,0 +1 @@
|
||||
uid://md0rhy8ik5gi
|
||||
Reference in New Issue
Block a user