XSharp

Engine scripting

LogicScript (logic_script) is a nonphysical simulation entity with a private script scope, explicit entity inputs, optional OnSpawn and Think functions, and delayed function calls scheduled in simulation frames. It does not depend on a renderer, an audio device, MegaEDX or a ROM. The default language is Lua 5.2 through MoonSharp 2.0.0.

Architecture and Source reference

This follows the explicit, language-independent binding layer and private scopes described by Valve’s ivscript.h, and the script-container role of CLogicScript. It is not a binary/API compatibility layer for Valve VScript. XSharp’s existing entity [Input] / [Output] infrastructure remains in use.

Authoring a level

Register source and all sound/entity dependencies inside LevelDefinition.OnLoaded, which runs in the normal level precache window:

public override void OnLoaded(BaseEngine engine)
{
    // The host reads an embedded resource or an authored file here, during loading.
    engine.PrecacheScript("stage/controller", """
        local count = 0
        function OnSpawn()
            engine.call("schedule", "AfterOneSecond", 60)
        end
        function Think()
            count = count + 1
        end
        function AfterOneSecond()
            if engine.call("entity_exists", "gate") then
                engine.call("set_enabled", "gate", false)
            end
        end
        """);
    engine.AddLogicScript("stage/controller", "stage_logic");
}

Source is syntax-checked without executing it during precache. A new entity initializes its scope and calls OnSpawn at its first enabled controller update, after ordinary entity spawning. A trusted host can also call a function before that update; this initializes the scope once. Its ThinkFunction defaults to Think; an empty name disables automatic think calls. StartEnabled controls the initial enabled state. Disable/enable preserves the VM and delayed queue. Overdue calls run on the first enabled update, in due-frame / insertion order. A zero-frame delay runs no earlier than the next simulation frame.

Entity inputs:

Input Meaning
CallScriptFunction(name) Call a function without arguments in this scope
RunScriptFile(id) Execute another precached asset ID, in the same scope and language
RunScriptCode(source) Execute a chunk in this scope, with the same sandbox and limits

Trusted C# can use CallFunction(name, params ScriptValue[]) for typed arguments and a scalar result, and Schedule(name, frames) for delayed calls. Existing enable/disable controls apply. Script errors set LastError, disable the entity, and emit OnScriptError; a faulted scope is not resumed with partially executed instructions. A fresh spawn starts a fresh scope.

The Penguin level package contains scripts/Penguin.lua, its manifest alias and an opted-in logic_script entity. The engine forwards door events directly to that scope; there is no Penguin-specific C# level class or separate Lua resource. Its music remains declared in level.json. Both the demo’s embedded package and the LevelSandbox’s X1/08 package carry this behavior.

Imported level packages

An .xlevel can contain scripts without a compiled level subclass. Add scripts/scripts.json:

[
  { "id": "stage/controller", "language": "lua", "file": "scripts/controller.lua" }
]

Add an entity in entities/entities.json:

{
  "ClassName": "logic_script",
  "Properties": {
    "script": "stage/controller",
    "targetname": "stage_logic",
    "thinkfunction": "Think",
    "enabled": true,
    "levelEvents": true
  }
}

Put the UTF-8 source itself at scripts/controller.lua inside the ZIP. Lua files are automatically available by archive path, so "script": "scripts/controller.lua" works without a script manifest. A manifest can assign a friendly ID or declare a different adapter language; explicit file languages are preserved for path aliases too. The older inline source field remains supported, but a definition must specify exactly one of source or file. Archive source paths stay inside scripts/, and reads reject duplicate entries, invalid source encoding and oversized source before execution.

An entity with "levelEvents": true receives optional OnReady(), OnPlayerSpawned(), OnBossDoorOpening(secondDoor) and OnBossDoorClosed(secondDoor) functions directly from the engine. Missing functions are ignored. Disabled/unsubscribed scopes do not receive them; the subscription is serialized with the entity. Other hosts can explicitly dispatch their own events through DispatchLevelScriptEvent(name, arguments).

Trusted C# hosts can load a separate authored file during level precache with engine.PrecacheScriptFile("stage/controller", "Assets/Scripts/controller.lua"). The loaded contents enter the same immutable scope library and save payload as packaged files. RunScriptFile still resolves a precached ID/path; it does not perform filesystem reads during gameplay. This keeps file loading out of the sandbox’s exposed API.

IDs must be unique and every entity reference must resolve during package preflight. Script assets are registered before those entities are created; compilation is part of loading. Resource/palette transitions do not re-run script initialization. Unknown language adapters fail loading explicitly.

Explicit engine API

Registered API functions are available directly in Lua, for example engine.set_foreground_map(x, y, map) or engine.SetForegroundMap(x, y, map). Snake-case names match the registry; PascalCase aliases are provided when they do not conflict with an explicitly registered function. Both forms use the same argument validation and deterministic API journal as engine.call(name, ...), which remains supported by existing scripts and demo/save-state transcripts. Only the frozen registered API is exposed; this does not bind arbitrary CLR methods or the BaseEngine object. Other language adapters can opt into the registered-name overload without changing their existing Create implementation.

Lua calls registered methods on the engine table, or engine.call(name, ...). No engine instance, entity, Type, CLR delegate or arbitrary .NET object is exposed. Only nil, finite numbers, strings and booleans cross this boundary. Tables/closures can be used freely inside Lua, including cyclic/aliased tables; they cannot be passed as CLR objects.

Capability Arguments Result
frame none Current simulation frame
random_int positive exclusive maximum Integer from the engine RNG; advances its actual seed
entity_exists target name Boolean
entity_x, entity_y target name Coordinate
set_position target name, x, y nil
set_enabled target name, boolean nil; target must implement IEnableDisable
kill target name nil
schedule function name, frame delay nil; current scope only
scene_columns none Foreground scene column count
set_foreground_map world x, world y, source map ID nil; local cell edit inside the level
play_sound channel (0..3), precached sound name nil
play_music precached name, stop seconds, loop seconds nil; -1 selects no explicit stop/loop
sound_input emitter target name, PlaySound / StopSound / ToggleSound nil; only AmbientGeneric targets

Entity lookup uses the first live entity with the specified target name. !self and !player select the script entity and current player. A missing required target, unsupported operation or invalid argument faults the caller. Audio calls use the existing precached audio registry and never open asset paths.

Hosts may deliberately add capabilities with engine.Scripts.RegisterApi(name, (scope, arguments) => result). The registry is copied when a scope initializes. These are trusted C# callbacks: do not expose reflection, filesystem paths, process/network access, arbitrary method names or unrestricted object creation. Reentrant calls into a running script are rejected.

Lua enables basic scalar operations, table iteration, math and bit32. It does not load CLR integration, io, os, debug, package, loaders, external modules, coroutines, collection control, string/table callback libraries or implicit random/time sources. Use frame scheduling and the engine RNG instead. There is no automatic userdata registration. This follows MoonSharp’s sandbox guidance. The abandoned DX9-only NLua/LoadCLRPackage integration and its package dependency have been removed.

The in-process VM restricts capabilities; it is not a separate OS process with an independent memory limit. Scripts still consume managed memory. Keep plugins trusted and bound capabilities small when accepting third-party map content.

Save states and demos

ScriptExecutionState implements the engine’s ISerializable; entity save serialization writes a versioned session checkpoint instead of traversing VM objects/delegates. The existing engine snapshot embedded in XSharp BK2 demos therefore contains scripts, closures, globals, scheduler state and source. No changes to the BK2 input format are needed. Input-only BizHawk movies still require an explicitly aligned starting engine state, as before.

The checkpoint records executed chunks and callback invocations, their scalar arguments/results, and every engine API response/error. Restore recreates the VM and replays this history against the recorded responses. The real API is never called during reconstruction: RNG is not advanced again, audio is not replayed, map edits are not repeated, and delayed calls are not scheduled twice. This also restores internal Lua state which a single exported state table would miss: captured locals, aliases, cyclic tables, function replacement and closures.

The source library visible when a scope first initializes is also checkpointed. RunScriptFile therefore continues using those original source contents after restore, even if the current level asset or file has changed. It performs no filesystem access. Language ID, adapter compatibility ID, limits and the trace are validated. Engine demos retain their existing same-build compatibility gate.

Callbacks are atomic save boundaries: the engine saves between callbacks, never halfway through a Lua instruction. Delayed work belongs to the serializable entity scheduler. Over-budget callbacks terminate and fault their scope rather than leaving an uncheckpointable suspended coroutine. Other language adapters must be deterministic for the same code and ordered API responses, use no ambient randomness/clocks/I/O, enforce their execution budget, and change their compatibility ID when execution semantics or sandbox policy change.

Replay checkpoints deliberately trade restore time/storage for full internal state coverage: both grow with execution history. They are not constant-size heap snapshots. Defaults are 100,000 VM instructions per invocation, 262,144 source/string characters, 1,024 API calls per invocation and 1,000,000 journal events per scope. Configure engine.Scripts.Limits before scope initialization for the game’s workload; existing checkpoints retain their recorded limits. The delayed queue is capped at 1,024 calls and one day of 60 Hz delay. Frame scheduling is simulation-based and remains paused with the entity controllers.

Validation

dotnet test XSharp.Scripting.Tests --verbosity quiet
dotnet test XSharp.Tests --filter "FullyQualifiedName~LogicScript|FullyQualifiedName~ScriptLevelPackage|FullyQualifiedName~DemoControllerTests|FullyQualifiedName~DemoMovieTests|FullyQualifiedName~LevelReaderTests" --verbosity quiet
dotnet build tests/XSharp.LevelSmoke --verbosity quiet
dotnet tests/XSharp.LevelSmoke/bin/Debug/net9.0-windows7.0/XSharp.LevelSmoke.dll --penguin 0 --content-root=XSharp --scripting
python tools/Create-ScriptingSmokeLevel.py XSharpDemo/Assets/Levels/Penguin.xlevel "$env:TEMP/xsharp-scripting-smoke.xlevel"
dotnet tests/XSharp.LevelSmoke/bin/Debug/net9.0-windows7.0/XSharp.LevelSmoke.dll "$env:TEMP/xsharp-scripting-smoke.xlevel" 0 --content-root=XSharp --scripting

The scripting tests cover forbidden host facilities, explicit capabilities, portable values, instruction limits, fault persistence, private scopes, two registered languages, trace/version mismatch, additional chunks, captured locals, table cycles/aliasing and exactly-once host effects. Engine tests cover entity inputs, nonphysical behavior, enable/disable, ordered delays, precache-only source loading, pinned dependencies and package validation. The real DX9 level smoke round-trips a full engine save and records/replays an XSharp BK2, comparing script state, pose, pending calls and RNG on every observed frame. These checks establish engine integration; they do not certify every possible third-party adapter.

The level smoke host creates output-muted NAudio channels before loading starts. Muting is independent of logical channel volume, so stage transitions, music changes, gain changes and save-state volume restoration cannot make tests audible. Decoding, playback/cursor advancement and audio serialization still execute.

The packaged-level validation record also covers the wrapper-free Penguin package, raw source files, manifest file aliases, direct engine door events and the Sandbox copy with its original resource snapshots preserved.

The developer console can select a LogicScript scope, run code or precached script files, call functions and send declared entity inputs. Scripts share engine globals through convar_get / convar_set in the explicit capability API; readonly and cheat flags still apply, and scripts cannot enable sv_cheats themselves.