Files

543 lines
19 KiB
GDScript

class_name ScriptInterpreterNode
extends Node3D
## Trusted interpreter for a [ScriptBehavior] attached to a world object.
##
## This is the **only** code that ever executes a ScriptBehavior's rules.
## The rule data (ScriptBehavior / ScriptRule) is plain JSON-shaped
## Dictionaries -- it is never handed to `eval`, never passed through
## [Expression], and never used to call a method by a name that came from
## the data. Every verb is dispatched through an explicit `match` in
## [method _execute_action], and every argument reaches the engine only
## after [ScriptBehavior] has validated it's a plain scalar / 3-vector and
## this class has resolved it through a fixed, code-defined path (a
## Dictionary lookup on a whitelisted catalog, a child node named
## "Inventory", etc). There is no reachable path from rule data to
## OS/FileAccess/networking/ClassDB/Callable. See
## docs/architecture/scripting_sandbox.md §3.1 for the design rationale.
##
## ## Usage
##
## Attach this script directly to the Node3D that represents the object in
## the scene (see the "ScriptedChest" node in scenes/worlds/test_level.tscn
## for a worked example). Either set [member behavior_path] (loaded on
## [method _ready]) or call [method set_behavior] directly with an
## already-parsed [ScriptBehavior] (e.g. from tests).
##
## Triggers:
## - `on_interact`: player presses the "interact" action while within
## [member interact_radius] of this node.
## - `on_enter`: fires once, edge-triggered, when a player's body starts
## overlapping this node's trigger volume.
## - `on_touch`: fires every physics frame while a player's body is
## overlapping this node's trigger volume (continuous contact).
## - `on_timer`: fires on a repeating interval regardless of any player,
## via a dedicated [Timer] child per on_timer rule.
# Sibling scripting scripts are referenced via preload rather than by their
# global class_name so this module parses correctly from a bare/cold
# compile -- see the note in script_behavior.gd.
const ScriptBehaviorClass := preload("res://scripts/scripting/script_behavior.gd")
const SpawnCatalogClass := preload("res://scripts/scripting/spawn_catalog.gd")
const PlayerInventoryClass := preload("res://scripts/scripting/player_inventory.gd")
## Emitted every time a verb actually executes, for observability/tests.
## `args` is the normalized action Dictionary that was executed.
signal verb_executed(verb: String, args: Dictionary)
## Emitted for every rule ScriptBehavior rejected at parse time (so callers
## can surface this in an editor / moderation tool).
signal rule_rejected(reason: String)
## JSON file to load the behavior from, if [member behavior] isn't set
## directly before this node enters the tree.
@export var behavior_path: String = ""
## How close (metres) a player must be for `on_interact` and to count as
## "in range" for the interact input check.
@export var interact_radius: float = 2.5
## Collision layer bit the player's body is on (see scenes/player.tscn --
## Player.collision_layer = 2). Used as this node's trigger Area3D's
## collision_mask so it only ever notices players, nothing else.
@export var player_collision_mask: int = 2
## The parsed behavior this node interprets. Set directly (tests) or leave
## null and set [member behavior_path] to load one on [method _ready].
var behavior: ScriptBehaviorClass = null
var _area: Area3D = null
var _players_in_range: Array[Node] = []
var _entered_once: Dictionary = {} # body instance id (int) -> true
# Local, per-object whitelisted state store (see docs/architecture/
# scripting_sandbox.md §4 open question re: static analysis of "what a
# script can possibly do" -- flags/timers are always plain scalars here).
var _flags: Dictionary = {} # name (String) -> scalar
var _timers: Dictionary = {} # name (String) -> {"remaining": float, "active": bool}
var _timer_nodes: Array[Timer] = []
var _spawn_catalog: SpawnCatalogClass = null
var _interact_prompt: Label3D = null
# ---------------------------------------------------------------------------
# Lifecycle
# ---------------------------------------------------------------------------
func _ready() -> void:
if behavior == null and not behavior_path.is_empty():
behavior = ScriptBehaviorClass.load_from_file(behavior_path)
_apply_loaded_behavior()
## Assign an already-parsed behavior (e.g. from a test, or built inline
## rather than loaded from a file). Safe to call before or after this node
## enters the tree.
func set_behavior(new_behavior: ScriptBehaviorClass) -> void:
behavior = new_behavior
if is_inside_tree():
_apply_loaded_behavior()
func _apply_loaded_behavior() -> void:
if behavior == null:
return
for msg in behavior.rejected_rules:
push_warning("ScriptInterpreterNode(%s): rejected rule -- %s" % [name, msg])
rule_rejected.emit(msg)
_setup_area()
_setup_timers()
_setup_prompt()
func _setup_area() -> void:
if _area != null:
_area.queue_free()
_area = null
_area = Area3D.new()
_area.name = "_ScriptTriggerArea"
_area.collision_layer = 0
_area.collision_mask = player_collision_mask
_area.monitoring = true
_area.monitorable = false
var shape := CollisionShape3D.new()
var sphere := SphereShape3D.new()
sphere.radius = interact_radius
shape.shape = sphere
_area.add_child(shape)
add_child(_area)
_area.body_entered.connect(_on_body_entered)
_area.body_exited.connect(_on_body_exited)
func _setup_timers() -> void:
for t in _timer_nodes:
if is_instance_valid(t):
t.queue_free()
_timer_nodes.clear()
if behavior == null:
return
for rule in behavior.rules:
if rule.trigger_type != "on_timer":
continue
var timer := Timer.new()
timer.wait_time = rule.trigger_interval
timer.autostart = true
timer.one_shot = false
# Tied to the fixed physics step (not idle/process delta) so
# on_timer fires deterministically off the simulation clock,
# matching physics_ticks_per_second (see project.godot §physics)
# rather than however fast the host happens to be rendering.
timer.process_callback = Timer.TIMER_PROCESS_PHYSICS
add_child(timer)
timer.timeout.connect(_on_rule_timer_timeout.bind(rule))
_timer_nodes.append(timer)
func _setup_prompt() -> void:
if _interact_prompt != null and is_instance_valid(_interact_prompt):
_interact_prompt.queue_free()
_interact_prompt = null
if behavior == null:
return
var has_interact_rule := false
for rule in behavior.rules:
if rule.trigger_type == "on_interact":
has_interact_rule = true
break
if has_interact_rule and DisplayServer.get_name() != "headless":
_interact_prompt = Label3D.new()
_interact_prompt.name = "InteractPrompt"
_interact_prompt.text = "[E] Interact"
_interact_prompt.billboard = BaseMaterial3D.BILLBOARD_ENABLED
_interact_prompt.font_size = 32
_interact_prompt.outline_size = 8
_interact_prompt.modulate = Color(1.0, 0.88, 0.2)
_interact_prompt.outline_modulate = Color(0.0, 0.0, 0.0, 0.9)
_interact_prompt.no_depth_test = true
_interact_prompt.position = Vector3(0, 1.2, 0)
_interact_prompt.visible = false
add_child(_interact_prompt)
# ---------------------------------------------------------------------------
# Trigger sources
# ---------------------------------------------------------------------------
func _is_player_body(body: Node) -> bool:
# Player carries a global class_name (scripts/player.gd); this stays a
# plain `is` check against a known engine/script type, never a
# data-driven dispatch.
return body is CharacterBody3D and body.has_node("Inventory")
func _on_body_entered(body: Node) -> void:
if not _is_player_body(body):
return
if not _players_in_range.has(body):
_players_in_range.append(body)
if _interact_prompt != null and is_instance_valid(_interact_prompt):
_interact_prompt.visible = true
var id := body.get_instance_id()
if not _entered_once.has(id):
_entered_once[id] = true
fire("on_enter", body)
func _on_body_exited(body: Node) -> void:
_players_in_range.erase(body)
_entered_once.erase(body.get_instance_id())
if _interact_prompt != null and is_instance_valid(_interact_prompt) and _players_in_range.is_empty():
_interact_prompt.visible = false
func _unhandled_input(event: InputEvent) -> void:
if _players_in_range.is_empty():
return
if event.is_action_pressed("interact") and not event.is_echo():
fire("on_interact", _players_in_range[0])
func _on_rule_timer_timeout(rule) -> void:
_fire_rule(rule, null)
func _physics_process(delta: float) -> void:
# Continuous on_touch contact -- checked every physics frame while
# overlapping, unlike the edge-triggered on_enter above.
if behavior != null and _area != null:
for body in _area.get_overlapping_bodies():
if _is_player_body(body):
fire("on_touch", body)
# Tick down local timers set via the set_timer verb.
for t_name in _timers.keys():
var t: Dictionary = _timers[t_name]
if t.get("active", false):
t["remaining"] = maxf(0.0, float(t.get("remaining", 0.0)) - delta)
if t["remaining"] <= 0.0:
t["active"] = false
_timers[t_name] = t
# ---------------------------------------------------------------------------
# Public firing API -- this is what every trigger source above calls, and
# what a test can call directly to exercise a rule deterministically.
# ---------------------------------------------------------------------------
## Fire every rule of the given trigger type whose conditions currently
## hold, in order. `player` is the entity that caused the trigger (may be
## null for `on_timer`, which has no player context).
func fire(trigger_type: String, player: Node) -> void:
if behavior == null:
return
for rule in behavior.rules:
if rule.trigger_type == trigger_type:
_fire_rule(rule, player)
func _fire_rule(rule, player: Node) -> void:
if not _conditions_met(rule.conditions, player):
return
for action in rule.actions:
_execute_action(action, player)
# ---------------------------------------------------------------------------
# Condition evaluation -- reads only the small whitelisted state store
# (item counts via a player's Inventory, local flags, local timer state).
# No expression evaluation, no arbitrary field access.
# ---------------------------------------------------------------------------
func _conditions_met(conditions: Array[Dictionary], player: Node) -> bool:
for cond in conditions:
if not _eval_condition(cond, player):
return false
return true
func _eval_condition(cond: Dictionary, player: Node) -> bool:
var op: String = cond.get("op", "")
var expected: Variant = cond.get("value")
var actual: Variant = null
match cond.get("type", ""):
"item_count":
var inv := _get_inventory(player)
if inv == null:
return false
actual = inv.get_count(cond.get("item_id", ""))
"flag":
actual = _flags.get(cond.get("name", ""), false)
"timer_active":
var t: Dictionary = _timers.get(cond.get("name", ""), {})
actual = t.get("active", false)
"timer_remaining":
var tr: Dictionary = _timers.get(cond.get("name", ""), {})
actual = tr.get("remaining", 0.0)
_:
return false
return _compare(actual, op, expected)
func _compare(actual: Variant, op: String, expected: Variant) -> bool:
match op:
"==":
return actual == expected
"!=":
return actual != expected
"<", "<=", ">", ">=":
if not ((actual is int or actual is float) and (expected is int or expected is float)):
return false
var a: float = float(actual)
var b: float = float(expected)
match op:
"<":
return a < b
"<=":
return a <= b
">":
return a > b
">=":
return a >= b
return false
## Set a local flag on this object's whitelisted state store. Not driven by
## any ScriptBehavior verb yet (the verb list in the task spec has no
## setter) -- exposed for forward compatibility / tests exercising `flag`
## conditions without needing a real gameplay event to set one.
func set_flag(flag_name: String, value: Variant) -> void:
if not (value is String or value is int or value is float or value is bool):
return
_flags[flag_name] = value
# ---------------------------------------------------------------------------
# Verb dispatch -- the entire attack surface this system deliberately does
# NOT have. Every branch is a fixed, hand-written function; nothing here is
# ever `call()`-ed by a name that came from data.
# ---------------------------------------------------------------------------
func _execute_action(action: Dictionary, player: Node) -> void:
match action.get("verb", ""):
"give_item":
_act_give_item(action, player)
"play_sound":
_act_play_sound(action, player)
"move":
_act_move(action, player)
"rotate":
_act_rotate(action, player)
"spawn_from_catalog":
_act_spawn_from_catalog(action, player)
"set_timer":
_act_set_timer(action, player)
_:
# Unreachable in practice -- ScriptBehavior rejects unknown
# verbs at parse time, so this branch should never see a rule
# at all. Fail safe (do nothing) if it somehow does.
push_warning("ScriptInterpreterNode(%s): refused to run unknown verb '%s'" % [name, str(action.get("verb"))])
func _resolve_target(target: String, player: Node) -> Node3D:
match target:
"self":
return self
"player":
return player if player is Node3D else null
return null
func _get_inventory(player: Node) -> PlayerInventoryClass:
if player == null:
return null
var inv: Node = player.get_node_or_null("Inventory")
if inv is PlayerInventoryClass:
return inv as PlayerInventoryClass
return null
func _act_give_item(action: Dictionary, player: Node) -> void:
var inv := _get_inventory(player)
if inv == null:
push_warning("ScriptInterpreterNode(%s): give_item has no player Inventory to target" % name)
return
var item_id: String = str(action.get("item_id", ""))
var count: int = int(action.get("count", 0))
inv.give_item(item_id, count)
verb_executed.emit("give_item", action)
_show_give_feedback(item_id, count)
if item_id.to_lower() in ["buffalo_chips", "chips", "credits"]:
_deposit_to_wallet(count)
_act_play_sound({"sound_id": "coin"}, player)
func _show_give_feedback(item_id: String, count: int) -> void:
if DisplayServer.get_name() == "headless":
return
var text := ""
if item_id.to_lower() in ["buffalo_chips", "chips", "credits"]:
text = "+%d Buffalo Chips!" % count
else:
text = "+%d %s" % [count, item_id]
var toast := Label3D.new()
toast.text = text
toast.billboard = BaseMaterial3D.BILLBOARD_ENABLED
toast.font_size = 40
toast.outline_size = 10
toast.modulate = Color(1.0, 0.9, 0.2)
toast.outline_modulate = Color(0.1, 0.05, 0.0, 1.0)
toast.no_depth_test = true
toast.position = Vector3(0, 1.5, 0)
add_child(toast)
var tween := create_tween()
if tween != null:
tween.tween_property(toast, "position:y", toast.position.y + 1.2, 1.4)
tween.parallel().tween_property(toast, "modulate:a", 0.0, 1.4)
tween.tween_callback(toast.queue_free)
func _deposit_to_wallet(count: int) -> void:
if count <= 0:
return
if has_node("/root/ApiClient"):
var api = get_node("/root/ApiClient")
if api != null and api.has_token():
api.request(
HTTPClient.METHOD_POST,
"/api/wallet/reward",
JSON.stringify({"amount": count, "reason": "in_game_reward"}),
"application/json",
true
)
## Trusted, code-defined mapping from sound_id -> resource path. Rule data
## supplies only the key; this table (not the data) decides what actually
## plays.
const _TRUSTED_SOUND_TABLE: Dictionary = {
"bell": "res://assets/audio/bell.wav",
"coin": "res://assets/audio/coin.wav",
"click": "res://assets/audio/click.wav",
"chime": "res://assets/audio/chime.wav",
"fanfare": "res://assets/audio/fanfare.wav",
"door_open": "res://assets/audio/door_open.wav",
}
func _act_play_sound(action: Dictionary, _player: Node) -> void:
var sound_id: String = str(action.get("sound_id", "")).to_lower().strip_edges().trim_suffix(".wav")
var stream_path: String = _TRUSTED_SOUND_TABLE.get(sound_id, "")
if not stream_path.is_empty() and ResourceLoader.exists(stream_path):
var stream: Resource = load(stream_path)
if stream is AudioStream:
var player_node := AudioStreamPlayer.new()
player_node.stream = stream
add_child(player_node)
player_node.finished.connect(player_node.queue_free)
player_node.play()
verb_executed.emit("play_sound", action)
func _act_move(action: Dictionary, player: Node) -> void:
var target_node := _resolve_target(action.get("target", "self"), player)
if target_node == null:
push_warning("ScriptInterpreterNode(%s): move has no valid target" % name)
return
var offset: Vector3 = action.get("offset", Vector3.ZERO)
var duration: float = float(action.get("duration", ScriptBehaviorClass.DEFAULT_MOVE_DURATION))
var dest: Vector3 = target_node.global_position + offset
var tween := target_node.create_tween()
tween.tween_property(target_node, "global_position", dest, duration)
verb_executed.emit("move", action)
func _act_rotate(action: Dictionary, player: Node) -> void:
var target_node := _resolve_target(action.get("target", "self"), player)
if target_node == null:
push_warning("ScriptInterpreterNode(%s): rotate has no valid target" % name)
return
var degrees: float = float(action.get("degrees", 0.0))
var axis: String = action.get("axis", "y")
var duration: float = float(action.get("duration", ScriptBehaviorClass.DEFAULT_MOVE_DURATION))
var delta_rot := Vector3.ZERO
match axis:
"x":
delta_rot.x = degrees
"y":
delta_rot.y = degrees
"z":
delta_rot.z = degrees
var dest: Vector3 = target_node.rotation_degrees + delta_rot
var tween := target_node.create_tween()
tween.tween_property(target_node, "rotation_degrees", dest, duration)
verb_executed.emit("rotate", action)
func _act_spawn_from_catalog(action: Dictionary, _player: Node) -> void:
if _spawn_catalog == null:
_spawn_catalog = SpawnCatalogClass.new()
_spawn_catalog.load_catalog()
var catalog_id: String = action.get("catalog_id", "")
var entry: Dictionary = _spawn_catalog.resolve(catalog_id)
if entry.is_empty():
push_warning("ScriptInterpreterNode(%s): spawn_from_catalog unknown catalog_id '%s'" % [name, catalog_id])
return
var asset_id: String = entry.get("asset_id", "")
var position: Vector3 = action.get("position", Vector3.ZERO)
# Both WorldObject and DynamicObjectNode carry a global class_name and
# are already relied on elsewhere in the project (scripts/chunk_scene.gd)
# without preloading -- consistent with that existing convention.
var obj := WorldObject.new(
"spawned_%d" % Time.get_ticks_usec(), "prop", asset_id,
position, Vector4(0, 0, 0, 1), Vector3.ONE, {}, true
)
var node := DynamicObjectNode.new()
node.world_object = obj
node.position = position
node.name = "spawned_%s" % obj.id
var host := get_parent() if get_parent() != null else get_tree().current_scene
if host != null:
host.add_child(node)
verb_executed.emit("spawn_from_catalog", action)
func _act_set_timer(action: Dictionary, _player: Node) -> void:
var timer_name: String = action.get("name", "")
var seconds: float = float(action.get("seconds", 0.0))
_timers[timer_name] = {"remaining": seconds, "active": true}
verb_executed.emit("set_timer", action)