XSharp

Level editor implementation

The level editor provides a Windows editing host over the portable XSharp.LevelEditing API. The editor itself initializes no game or graphics device. The music picker opens audio output only on an explicit Preview request. F5 builds the current document and opens a separate muted LevelSandbox process.

Source projects and assets

XSharp.LevelEditing provides a UI-independent .NET API. A .xproject is a UTF-8 JSON document with format xsharp.level-project, version 1. It contains map dimensions, linear foreground/background tile layers, metadata/checkpoints, placed entities with stable GUIDs, their editable JSON properties and output connections, and four-edge terrain definitions. World tiles are 16x16 pixels; layer cells are row-major map IDs, with -1 meaning empty.

External asset references map runtime entry names to source file paths, relative to the project file. Palettes, indexed 8x8 tile graphics, 16x16 tile definitions, scripts and imported graphics snapshots live in separate editable files. The project does not embed them. Save As copies assets beside the new project; ordinary saves write changed asset files and then the source document.

ProjectStorage.Import opens an existing .xlevel without modifying it, extracts its resources into a dedicated asset directory, and flattens its map/block/scene hierarchy into editable layers. Native map IDs, palette banks, flips, collision definitions, scripts, checkpoints, selectors and graphics snapshots are retained. A layout currently uses one tilemap (matching all native imports); importing a mixed-tilemap layout reports that restriction explicitly.

ProjectCompiler rebuilds the block/scene/layout hierarchy, deduplicating blocks and scenes, preserving external resources, and writing a deterministic .xlevel. It validates with the production LevelPackage reader before atomically replacing the runtime output. Building never overwrites the source project or referenced assets. Authoring-only visibility/lock/opacity are editor presentation settings.

Editing commands

MapDocument provides pencil/line/rectangle/flood fill, bounded stamp copy/paste, four-edge terrain reflow, entity/property/output edits and JSON resource edits. Undo/redo tracks sparse changed cells per stroke, not copies of the entire map. History is capped at 200 edits and a cell-change budget, while allowing one large operation to remain undoable. The saved revision is tracked separately, including undoing back to the saved state and branching history after undo.

Terrain masks use north=1, east=2, south=4, west=8. Painting/erasing updates the edited cell and adjacent terrain cells in the same undoable stroke. All sixteen edge patterns can be assigned independently, following the edge-terrain workflow in Tiled.

Editor workflow

Build XSharpLevelEditor and XSharp.LevelSandbox, then open an .xproject through File > Open or pass its path on the editor command line. File > Import extracts an existing .xlevel to an editable source tree. File > New creates indexed art, solid ground, player spawn, a checkpoint and camera bounds as a playable starting point. Save and Save As write source documents; Build writes a separate runtime package without changing the source.

The canvas supports pencil, erase, line, rectangle, flood fill, four-edge terrain, tile selection/stamps and entity placement. Mouse wheel zooms around the pointer; middle drag/Alt+drag pans. Right-click picks a map tile. Select drags entities in eight-pixel steps (Ctrl for one-pixel movement), or selects a tile rectangle. Ctrl+C/X/V copy/cut/paste tiles; Ctrl+D duplicates an entity. Ctrl+Z/Y undo/redo. Layer controls provide visibility, lock and opacity; foreground/background dimensions remain independent.

The searchable catalog includes all currently exposed built-in package classes, attributed entities, enemy rosters and registered object/subtype placements from installed X1/X2/X3 content modules (173 public entries in the validated build). The previous generic entries and duplicate native aliases are consolidated under public classnames; the smoke explicitly checks every roster actor remains present. Enumeration constructs no actors. This is a catalog of implemented content, not a claim that missing game bosses have been implemented. Unreviewed generic enemy controllers remain idle.

Classnames are public authoring names such as trigger_teleport, enemy_scriver and vehicle_ride_armor, independent of CLR namespaces/types. Recognized native imports resolve to those named entries automatically. Hidden adapter definitions retain source IDs and unknown subtype bits; authors select intelligible Behavior properties such as facing, ceiling mounting or a movement route. Only confirmed masks are exposed. Building/reimporting retains public names, properties and opaque native flags. Older runtime adapters remain valid. See native keyvalue meanings and evidence.

Placed actors display the first declared idle frame, with their original pivot, alpha, orientation and appropriate composite parts. Direction changes repaint the sprite immediately and are undoable. Selection/hit testing follows the sprite bounds, and dragging previews the sprite at its new origin. The editor reads existing art/metadata without running gameplay precache or AI; logical entities, tile-based scenery and stubs without a sprite keep markers. The current smoke covers visible previews for 137 public classes, including native rosters, legacy enemies, Ride Armor, pickups and the boss door. Previewing is not gameplay or original-game frame-parity validation.

Select an entity on the map or the Placed entities tab. PropertyGrid edits are typed, undoable document changes. Unset engine defaults stay visibly unset; Reset removes the override. Outputs has editable output, target/name/GUID, input, parameter, delay and once columns. Input uses a target-aware, editable dropdown: choose a known input or type a custom name; it is preserved even if absent from the suggestion list. Output and target also offer autocomplete. The output table scrolls horizontally and the sidebar can be resized.

The tile-resource dialog edits 8x8 indexed pixels, palette colors/banks, four quadrants of 16x16 maps, mirror/flip/priority and collision bytes. Clone map and New tile extend the resources. Pixel/color edits update both previews immediately; Apply is one undoable edit and Cancel leaves source assets unchanged. Terrain patterns have a visual sixteen-row mask table, map previews and a Use selected tile button. Editing patterns updates already-painted terrain; undo restores imported map variations exactly.

PNG import creates separate palette/tileset/tilemap resources and retains the source PNG as an external asset. Dimensions must be divisible by sixteen. It supports fifteen opaque colors plus transparency per 8x8 tile, sixteen banks, and up to 1024 maps/unique indexed tiles. It reports incompatible art instead of silently quantizing it. Replacing a layer’s tileset clears that layer with undo support; the imported sheet is available as a paste stamp. Set collision in the resource dialog after importing visual art.

Level metadata/music and checkpoints/camera limits are edited visually in the Level settings tab and Properties panel. Lua source and raw asset source remain available in source dialogs. Add Lua script creates a separate referenced file and script-index entry; place logic_script to run it. The Assets tab edits JSON or Lua source and validates a candidate resource change before applying it.

Visual level settings

Level > Metadata / music / spawn and Checkpoints / camera bounds open the Level settings tree. Select Level metadata / music to edit the project name, game, stage, native-controller option, initial spawn/camera, resource selectors and music. Expand nested entries in Properties; game/boolean fields have typed choices, and coordinates/timing use numeric fields. Music file is relative to the host’s sound root and accepts WAV, FLAC or MP3. Set file first to configure music, then optional name/stopTime/loopTime. Use Reset on music to remove it. Choose music from the Level menu, the settings button, or the ellipsis on music.file to avoid typing a path. The picker enumerates available WAV/MP3/FLAC assets, with search, folder/category filters, manifest durations and loop markers. It lists each file once even when native IDs alias that file. Scanning/decoding run away from the UI thread; malformed manifests are reported without hiding the remaining assets. Preview uses the game’s decoder and PCM loop provider without a game/renderer instance. Volume attenuates this preview’s PCM only. Stop, selection changes, cancellation and closing the picker release output and decoded caches. Double-click previews; only Use selected applies the track. Switching tracks resets explicit timing to -1 so the engine consults the new asset’s manifest. Reselecting the current path preserves its configured times. Paths remain relative to the host’s sound root; the source assets stay external. The same picker is available on ambient_generic.file in the entity inspector, with All audio as its initial category for an unconfigured emitter. Selecting an entity asset never edits level music. An actual file change also assigns a matching unique cache name, removes any stale SoundName override, and resets stopTime/loopTime to manifest defaults in a single undo operation. Channel, startSilent, targetname and outputs are preserved. Selecting the current file does not reset configured timing. The unset runtime SoundName is not offered as a second path field; imported explicit overrides remain visible until replaced.

Writable string properties marked [AudioAsset] also receive the shared picker, including [Property] aliases and unset schema properties. This engine-side metadata has no Windows/UI dependency and does not load/precache sounds by itself. It identifies file paths explicitly rather than guessing from property names such as SoundName, which can represent an existing cache key. Imported extension fields are retained and shown as expandable properties; source hashes, format version and native checkpoint records are read-only.

Select a checkpoint to edit spawn, initial camera, camera bounds, optional background/forced-background coordinates, scroll, teleport collision delay and resource selectors. Add checkpoint and Duplicate append a consecutive ID. Remove checkpoint rejects a checkpoint still used by a trigger; removing an unreferenced checkpoint renumbers later checkpoint triggers in the same undo step. Script source may contain numeric checkpoint IDs and is not rewritten; review those references if deleting checkpoints in a scripted imported stage. Ctrl+D/Delete also duplicate/remove the selected checkpoint.

The selected checkpoint is overlaid on the map: green spawn cross, yellow initial 256x224 camera view, blue camera limits. Place spawn / Place camera set the selected checkpoint’s point by clicking. Center moves the view to its spawn. Fit limits frames the selected limits. Edit bounds / CameraBounds lets you drag eight white handles to resize, drag inside to move, or drag outside to draw replacement limits. Coordinates snap to eight pixels; hold Ctrl for one-pixel precision. A drag is a preview until release, commits one undo entry, and Esc or lost capture cancels it without changing persisted state.

Camera lock regions in the same tree are authored trigger_camera_lock entities. Add camera lock creates one; their limits use the same map tools and expandable Properties. + extension / - extension append/remove the last extension point; expand extensions to edit every coordinate. Violet markers show these points. The legacy boudingBox spelling and all existing extension points are preserved. Moving/resizing keeps entity position and the runtime bounds origin aligned.

Every settings edit is validated with the production package reader before entering history. Invalid values leave both the document and history unchanged. Settings commands are part of the UI-independent LevelSettingsEditor API.

Validation

XSharp.LevelEditing.Tests covers deterministic runtime builds and production preflight, external assets, import/atlas preservation, sparse undo/redo, terrain adjacency, fill/stamps, entity properties/outputs in source documents, Save As, source protection, invalid geometry and failed build preservation. These are headless data/authoring tests. Additional tests cover indexed art color/bank round trips, flips, invalid color counts, independently sized layers and terrain pattern changes with exact undo.

Run XSharpLevelEditor.exe –self-test for an STA integration smoke (report: %TEMP%/xsharp-editor-smoke.log). It exercises catalog placement, PropertyGrid and output-grid bindings, history, Save/Save As/reopen, production runtime preflight, resource-dialog construction and full-form painting. Desktop checks additionally verified pencil/undo, selection/property display, output rows, and pixel/map preview updates with cancellation. Native Snow Training runs 420 muted frames and asserts exactly one authored console message, timer self-disable and an empty pending queue. Full-stage completion is not claimed by those checks.

The validated extraction milestone adds ROMExporter --format runtime|editable|both, package-to-project conversion, project compilation and two shared-asset Chill Penguin examples. Native foreground and background dimensions are retained independently, UTF-8 BOM-prefixed assets remain editable, and camera trigger positions come from their bounds origin. Authored maps can disable automatic original-game stage controllers with nativeControllers: false; imported native stages retain the default behavior. The examples’ validation record compares geometry, checkpoints, all 92 entity descriptors and eleven resource entries, and records successful muted native startup/landing for both compiled projects. Full-stage completion and the new editor workflows are documented above.

Runtime entity properties and outputs

EntitySchema is shared by runtime loading and authoring. Concrete [Entity] classes can be loaded from level descriptors, with writable supported data properties and explicitly attributed inputs/outputs. Entity-valued properties accept target names or authored GUIDs; forward references are resolved after all roots exist. Runtime-only indices and lifetime flags cannot be configured.

EntityOutputSystem connects authored source GUIDs or target-name groups to declared inputs. Connections carry an output value or a configured parameter, delay in seconds, and an optional fire-once flag. Selectors include names, wildcards, authored GUIDs, !caller/!self, !activator and !player. Only declared inputs are callable. Common lifecycle outputs and Kill/Enable/Disable/ Toggle inputs are exposed. A 256-dispatch frame budget and 4096 pending-call limit diagnose cycles without freezing gameplay.

Save states retain queued calls, once flags, stable caller identity and pending property links. Generated handlers are transient and rebound after restoration; an entity reusing a removed caller’s slot cannot receive its delayed calls. The output footer is optional for old save states. Full-engine muted DX9 checks compared a 40-frame trace (frame, RNG, target state and pending count) after both save-state restoration and BK2 recording/playback.

Missing targets, outputs/inputs and bad arguments emit a single warning and isolate that connection without stopping other routes or repeating diagnostics. Isolation survives state/demo restoration; see fault isolation. Tile libraries and category files are described in tile definitions.

The broad core suite currently has 31 existing common-enemy fixture failures: the same failures reproduce with this milestone temporarily removed (2798 passed, 34 skipped at baseline; 2818 passed, 34 skipped with the twenty new entity-I/O tests). This milestone does not claim those unrelated actor fixtures are repaired.