# MSW Platform Rules — Core

Core rules that apply **across all map types** in the MSW engine. Without these, you'll keep falling into the trap of "the code is correct but nothing happens."

> **What you can only find in this file**: 8 core rules / File authority & `.directory` (§2) / `.mlua + .codeblock` pair (§3) / TileMapMode↔Body mapping + LEA-3004 (§4) / Coordinate system & visible screen range (§5) / SortingLayer & OrderInLayer (§6) / SpriteRUID rules (§7) / `SpawnByModelId` usage & initialization order (§8) / Dynamic entity classification (§8.5) / `MovementComponent` per-map-type InputSpeed conversion formula (§10) / ECS (§13) / ID generation (§14) / `.config` (§15) / CoreVersion (§16).
>
> **What is NOT in this file (split out)**:
> - **Per-map-type development guides** (Foothold patrol / RectTile 4-directional movement / SideView wall detection, etc.) → [`platform-maple.md`](platform-maple.md) / [`platform-rect.md`](platform-rect.md) / [`platform-sideview.md`](platform-sideview.md)
> - **Symptom→cause→fix dictionary** ("not moving" / "not visible" / `LEA-3004` / "floating in mid-air", etc. — 17 cases) → [`troubleshooting.md`](troubleshooting.md)
> - **Per-map-type checklists** → §8 of each `platform-{type}.md`

---

## 1. Rule Summary (Mandatory)

1. **TileMapMode ↔ Body mapping** mismatch causes entities not to move — **fails silently with no error** (§4).
2. User scripts only work as `.mlua` + `.codeblock` **pairs**. `.codeblock` is generated by Maker Refresh (§3).
3. If `SpriteRUID` is an empty string, the entity is **invisible on screen** (§7).
4. Passing a non-map entity as `parent` in `SpawnByModelId` causes a runtime error (§8).
5. Coordinates use **world units** (1 unit = 100 px). Pixel values are off by 100× (§5).
6. Maker only scans `RootDesk/`. User files placed in `Global/` are not recognized (§2).
7. **Do not modify** `.d.mlua` / `.codeblock`.
8. Hand-authored entry files take their `CoreVersion` from `Environment/config`; builder output needs no version handling (§16).

---

## 2. File-Level Authority

| File type | AI create | AI edit | Location | Notes |
|---|:---:|:---:|---|---|
| `.mlua` | **O** | **O** | `RootDesk/MyDesk/` | Script source — AI's primary work target |
| `.codeblock` | **X** | **X** | `RootDesk/MyDesk/` | Auto-generated by **Maker Refresh** after `.mlua` is written |
| `.model` | **O** | **O** | `RootDesk/MyDesk/` | Entity template. **Not recognized if placed in Global/** |
| `.directory` | **X** | **X** | `RootDesk/MyDesk/` | Auto-generated by **Maker Refresh** after creating actual folders |
| `.ui` | △ | △ (properties) | `ui/` | Complex hierarchy. Maker or dedicated tools recommended |
| `.map` | △ | △ (properties/entities) | `map/` | Complex hierarchy. Maker or dedicated tools recommended |
| `.config` | X | **O** (values only) | `Global/` | WorldConfig, SectorConfig (managed by Maker directly) |
| `.d.mlua` | **X** | **X** | `Environment/NativeScripts/` | Engine API definitions. **Do not modify** |
| `.collisiongroupset` | X | △ | `Global/` | Collision group matrix |

> **Global/ warning**: `Global/` is for engine default templates only. Since Maker's file scan only looks at `RootDesk/`, files created by AI in `Global/` **will not appear in the Maker editor**.

### `.directory` Refresh Rule

`.directory` is treated as a Refresh artifact, same as `.codeblock`.

- If a subdirectory (e.g., `Models/`) is needed, just create the actual folder.
- File operations proceed based on the actual folder path even if `.directory` doesn't exist yet.
- Missing `.directory` files are auto-generated when Maker Refresh runs.
- Only run Refresh when the folder needs to appear in Maker UI immediately. If no Refresh tool is available, just leave the folder.

---

## 3. File Pair Rules

All user scripts must exist as `.mlua` + `.codeblock` pairs.

| File | Role | Creation |
|---|---|---|
| `ScriptName.mlua` | Lua source code | **AI Agent writes directly** |
| `ScriptName.codeblock` | JSON metadata (type, inheritance, ID) | **Maker Refresh auto-generates** |

**Rules**:
- Creating only `.mlua` won't register it in MSW → **Maker Refresh required**
- Maker auto-generates `.codeblock` by analyzing the `script ... extends ...` declaration in `.mlua`
- Script location: `RootDesk/MyDesk/`
- After Maker Refresh, `.codeblock`'s `Id` / `Name` auto-align with the script name

### AI Workflow

```
1. AI writes .mlua (RootDesk/MyDesk/)
2. User runs Refresh in Maker
3. Maker auto-generates .codeblock
4. Script is recognized → executable
```

---

## 4. TileMapMode ↔ Body Mapping (Most Important)

**If the mapping is wrong, the entity won't move — silent failure with no error.**

| Value | TileMapMode | View | Body Component | Map Component | Gravity | Terrain | Movement axes | Collision system | Representative genres |
|:---:|---|---|---|---|:---:|---|---|---|---|
| `0` | `MapleTile` | Side-view (side-scrolling) | `RigidbodyComponent` | `TileMapComponent` + `FootholdComponent` | O (built-in) | Foothold (line segments) | Left/right + jump (Y = gravity) | Foothold collision | MapleStory-style platformer |
| `1` | `RectTile` | Top-down | `KinematicbodyComponent` | `RectTileMapComponent` | X | Square tile grid | Free 4-directional | Tile collision (Movable) | Top-down RPG, Bomberman |
| `2` | `SideViewRectTile` | Side-view (side-scrolling) | `SideviewbodyComponent` | `RectTileMapComponent` | O (built-in) | Square tile grid | Left/right + jump (Y = gravity) | Tile collision (Collision) | Side-view action, tile platformer |

> In `.map` files, this field is **serialized as a number** (e.g., `"TileMapMode": 0`). The `Value` column above is that mapping.

**Check protocol** (mandatory preflight for all map work):
1. Identify the target map file (e.g., `./map/{mapname}.map`).
2. Open the `.map` file and read `MapComponent.TileMapMode` as a **number**. Since 0 / 1 / 2 determines the entire physics/movement/collision/terrain stack, **no entity placement, model authoring, or script work may begin without knowing this value.**
3. Verify that Player.model / monster .model / all other dynamic entities have the correct Body per the table above.
4. If mismatched → Body component swap. **Cannot be fixed by modifying script code.**

### LEA-3004 MissingComponent — Runtime Signal of TileMapMode ↔ Body Mismatch

When an entity has logic requiring a Body (`MovementComponent`, `PlayerControllerComponent`, AI components, etc.) but the matching Body is missing, the engine logs exactly one of these three:

| TileMapMode | Required Body | Log when missing |
|---|---|---|
| `0` MapleTile | `RigidbodyComponent` | `[LEA-3004] MissingComponent : Entity is missing 'RigidbodyComponent'.` |
| `1` RectTile | `KinematicbodyComponent` | `[LEA-3004] MissingComponent : Entity is missing 'KinematicbodyComponent'.` |
| `2` SideViewRectTile | `SideviewbodyComponent` | `[LEA-3004] MissingComponent : Entity is missing 'SideviewbodyComponent'.` |

**Meaning**:
- Almost always a model that doesn't match the map's `TileMapMode` was placed, or a dynamic entity is missing a Body entirely.
- **Fix**: Add/swap the Body from the table above in the `.model` or the map entity's `@components` → `maker_refresh_workspace`. **Do not work around this by removing `MovementComponent`** — collision/events will break.
- **Prevention**: Following the Check protocol above prevents this error entirely. This is a silent-failure zone that syntax/API validation cannot catch, so if `LEA-3004` appears, re-verify the Body ↔ TileMapMode mapping before anything else.

### TileMapMode Switching Is Performed by the User in Maker

**MapleTile ↔ RectTile ↔ SideViewRectTile mode switching itself** is not done by AI editing `.map` files directly. Mode switching requires tile component swap, Foothold reconstruction, tile data conversion, etc. — internal Maker processing — so **the user must change it directly in the Maker editor**.

**Maker procedure (convey to user)**:

1. Open the **Hierarchy** panel in the Maker editor.
2. **Right-click the target map entity**.
3. Select the **"Switch ..." option** from the context menu (Switch TileMap (MapleTile) / Switch RectTileMap (RectTile) / Switch SideViewRectTileMap (SideViewRectTile)). Maker performs conversion, tile component swap, and terrain reset.
4. User saves → AI runs MCP **`maker_refresh_workspace`** → re-read `MapComponent.TileMapMode` to confirm the new value.

> What AI cannot do: Change `TileMapMode` value by directly editing `.map` JSON
> User action required: **Maker Hierarchy panel → right-click target map entity → select "Switch ..." menu**
> What AI can do: **Recommend** the right mode for the user's game — matrix is in [`msw-general` SKILL.md "Recommending the right mode"](../SKILL.md). After switching, fix Body component mismatches and adjust scripts.

### DefaultPlayer Body Component Structure

The DefaultPlayer model **includes all 3 Body components**.

```
DefaultPlayer
├── RigidbodyComponent      ← Active in MapleTile
├── KinematicbodyComponent  ← Active in RectTile
├── SideviewbodyComponent   ← Active in SideViewRectTile
├── MovementComponent       ← high-level wrapper (always active)
└── PlayerControllerComponent ← input handling (always active)
```

**The engine automatically activates the appropriate Body based on map type.** The rest are deactivated.

→ Custom monster/NPC models only need **the Body matching the map type**. No need to include all 3.

### Cautions When Switching Map Type

**A single map can only use one TileMapMode.**

When changing map type:
1. **All existing terrain is reset** (irreversible).
2. Body component swap required (Player.model + all monster/NPC models).
3. Movement/collision scripts must be overhauled.
4. Event handlers must be replaced (Foothold events ↔ RectTile events).

→ **Decide the map type early in the project and do not change it.**

---

## 5. Coordinate System and Screen

### Visible Screen Range

Camera is in 2D Orthographic mode. The following area is visible centered on the player:

| Platform | Width | Height | OrthographicSize | Example (camera at 0,0) |
|---|---|---|:---:|---|
| **PC** | **12.8** world units | **7.2** world units | 3.6 | X: ±6.4, Y: ±3.6 |
| **Mobile** | **9.6** world units | **5.4** world units | 2.7 | X: ±4.8, Y: ±2.7 |

- 1 world unit = **100 pixels** (PPU)
- Zoom range: **30% ~ 500%** (visible range changes with zoom)

> Use this range to determine whether an entity is on-screen or off-screen.

### World Coordinates

- Unit: **world unit** (1 unit = 100 px). Since the visible range is about ±6.4 units, coordinate values are typically **single or double digits**.
- Y axis: positive = up (standard game coordinate system).
- `TransformComponent.Position`: **local coordinates relative to parent** (`Vector3`, world units). Serialized/synced.
- `TransformComponent.WorldPosition`: **absolute coordinates** through the parent chain (`Vector3`, world units). Usually read-only — setting it internally converts to Position via the parent's inverse matrix.
- Root entities without a parent have `Position == WorldPosition`.
- Z value: affects render order (larger value = further back).
- Waypoints, spawn coordinates, movement targets — all Position-based values use world units. **Pixel values (hundreds range) are off by 100×.**

### UI Coordinates

- **Reference resolution**: 1920 x 1080 (Landscape) / 1080 x 1920 (Portrait)
- Origin: screen center `(0, 0)`
- Screen edges: X `±960`, Y `±540` (Landscape)
- `UITransformComponent.anchoredPosition`: coordinates relative to parent
- Scales based on 1920x1080 reference regardless of actual device resolution

### Cautions

- World coordinates and UI coordinates are **separate spaces** — no direct conversion.
- UI element `Position` is fixed at `(0, 0, 0)` — **use `anchoredPosition` for placement**.
- To place UI at screen edges, use anchor presets (safer than specifying ±960/±540 directly with `anchoredPosition`).

---

## 6. Map Layer Priority (Rendering Order)

Entity display order is determined by the following **3-level priority**:

```
Priority 1: SpriteRendererComponent's SortingLayer (map layer)
Priority 2: SpriteRendererComponent's OrderInLayer
Priority 3: TransformComponent's Position Z value
```

### Default OrderInLayer by Model Type

When a model is placed on a map, a default OrderInLayer is automatically assigned based on type:

| Model Type | Default OrderInLayer |
|---|:---:|
| Object | 0 |
| Tile | 1 |
| Monster, NPC, Platform, Ladder, Rope, Portal, Trap, Item | 2 |
| Other player avatars | 3 |
| My avatar | 4 |

> When OrderInLayer is the same, **smaller Z values are drawn in front**. If an entity is hidden behind another, check this 3-level priority in order.

---

## 7. SpriteRUID Is Mandatory

If `SpriteRendererComponent`'s `SpriteRUID` is an empty string (`""`), the entity is **invisible on screen**.

- The component name alone doesn't make it obvious that an RUID is required.
- All entities that should be visible (player, monster, object) need an RUID.
- Default sprite RUID: `1705e3c5b2c146ac9a699f96fb067408` (placeholder when nothing else is available)

**Setting RUID**:
```lua
-- Set at runtime
self.Entity.SpriteRendererComponent.SpriteRUID = "ruid-string-here"

-- In .model file (Values array)
{
  "Name": "SpriteRUID",
  "Value": "1705e3c5b2c146ac9a699f96fb067408"
}
```

**`animationclip` and `thumbnail://`**: `SpriteRUID` also accepts an `animationclip` RUID directly for looping animation playback. To display any resource (`animationclip` / `skeleton` / `avataritem`) as a **static thumbnail**, prepend `thumbnail://` — see `msw-sprite-ruid` skill.

```lua
-- Animation playback
self.Entity.SpriteRendererComponent.SpriteRUID = animationClipRuid

-- Static thumbnail of any resource type
self.Entity.SpriteRendererComponent.SpriteRUID = "thumbnail://" .. anyRuid
```

**Searching for RUID**: Query assets via `_ResourceService`. Only resources registered in the project can be used. (Or use the `msw-search` skill — more accurate.)

---

## 8. Entity Spawn Rules

### SpawnService Usage Rules

```lua
-- Correct usage (model ID is case-insensitive)
_SpawnService:SpawnByModelId("chasemonster", "entityName", spawnPosition, mapEntity)

-- Error (parent is nil)
_SpawnService:SpawnByModelId("chasemonster", "entityName", spawnPosition, nil)  -- runtime error!
```

**Rules**:
- First parameter `id` is the **model ID** — the string after `model://` in the `.model` file's EntryKey.
- Case-insensitive (`"ChaseMonster"`, `"chasemonster"` both OK).
- Returns nil if the model doesn't exist (silent failure) → **always nil-check the return value.**
- Pass a **map entity** as the `parent` parameter.
- Passing `nil` causes a runtime error.
- Get the map entity via `self.Entity.CurrentMap`.

### SpawnByModelId vs SpawnByEntity

| Method | Purpose | Notes |
|---|---|---|
| `SpawnByModelId(id, name, pos, parent)` | Create from `.model` | Model file required |
| `SpawnByEntity(entity, name, pos, parent)` | Clone existing entity | Source entity required |

### Spawn Initialization Order

Execution order guaranteed by the engine when creating an entity:

```
1. Empty entity created
2. Components from Components array instantiated
3. Properties links connected
4. Values array iterated → defaults applied by TargetType + Name matching
5. Synchronization (@Sync) registered
6. OnBeginPlay() callback invoked
```

**Implication**: At OnBeginPlay time, all components and default values are already in place.

---

## 8.5 Dynamic Entities and Body Components

**Dynamic entity** = an entity that moves or needs to collide with terrain at runtime.
Examples: Player, Monster, NPC, Pet/Follower, Projectile, Movable Trap, Pushable Object, Drop Item.

**Rule**: Every dynamic entity needs the Body component matching the map's `TileMapMode`:

| TileMapMode | Body component |
|---|---|
| `MapleTile` (0) | `RigidbodyComponent` |
| `RectTile` (1) | `KinematicbodyComponent` |
| `SideViewRectTile` (2) | `SideviewbodyComponent` |

Static decorations, trigger areas, and VFX-only entities do **not need** a Body.

> The 3 Body types are **not interchangeable** — their APIs, properties, events, and physics models all differ. Switching map modes requires not just component swaps but also rewriting movement/collision scripts (see §9.x of each `platform-{type}.md`).

---

## 9. Per-Map-Type Development Guides — moved

Per-map-type detailed guides (physics setup, foothold/tile collision, events, monster patrol patterns, special features) have been **split by map type**. Read only the file matching the `.map`'s `TileMapMode` you're working with.

| TileMapMode | File |
|---|---|
| `0` MapleTile | [`platform-maple.md`](platform-maple.md) — Foothold, `Gravity`, `WalkSpeed`, `PredictFootholdEnd`, `IsOnGround`, `DownJump`, FootholdEnter/LeaveEvent |
| `1` RectTile | [`platform-rect.md`](platform-rect.md) — `SpeedFactor`, free 4-directional movement, Tile Movable, RectTileEnter/LeaveEvent, dynamic tiles |
| `2` SideViewRectTile | [`platform-sideview.md`](platform-sideview.md) — `JumpSpeed`/`JumpDrag`, `EnableDownJump`, wall detection (`RectTileCollisionBeginEvent + Normal`), `GetUnderfootTile` |

Each file includes its own **map-type-specific troubleshooting + checklist** in §7 / §8.

---

## 10. MovementComponent — Common Wrapper

`MovementComponent` is a **high-level movement controller** usable with all 3 Body types.

```lua
-- MovementComponent (map-type agnostic)
local movement = self.Entity.MovementComponent
movement.InputSpeed = 3       -- movement speed
movement.JumpForce = 1.5      -- jump strength
movement:Jump()               -- execute jump
movement:DownJump()           -- down-jump
movement:MoveToDirection(Vector2(1, 0), delta)  -- directional movement
movement:Stop()               -- stop
```

**How InputSpeed converts to actual speed per map type** (engine-internal, `MovementComponentPartDefault`):

| TileMapMode | Actual speed | Notes |
|---|---|---|
| **MapleTile** | `InputSpeed` passed directly to Rigidbody | — |
| **RectTile** | `direction * InputSpeed / 1.2f` | 1.2 divisor for migration compatibility |
| **SideViewRectTile** | `direction.x * InputSpeed * 1.5f`, Y preserved | Correction similar to Rigidbody |

- `InputSpeed` default: `1.0` (`MovementComponent`'s `[MODProperty]`, `@Sync`)
- The same `InputSpeed = 3` feels different across map types.

### Interaction with PlayerControllerComponent

`PlayerControllerComponent` handles input → action mapping and internally uses `MovementComponent`.

- Default key mapping: arrows (movement), Alt/Space (jump), down+jump (down-jump).
- For custom movement: set `PlayerControllerComponent.Enable = false` then control the Body component directly.

> Per-map-type `MovementComponent` usage code examples are in each [`platform-{type}.md` §7](platform-maple.md).

---

## 11. Troubleshooting — moved

The symptom→cause→fix dictionary has been moved to [`troubleshooting.md`](troubleshooting.md). Open that file immediately for these cases:

- When `[LEA-3004]` appears in the log
- Silent-failure symptoms like "not moving" / "not visible" / "floating in mid-air" / "stuck in wall"
- Coordinates off by 100× / file not visible in Maker / no multiplayer sync

Map-type-specific troubleshooting (e.g., MapleTile foothold-end handling, SideView wall detection) is also in §7 of each `platform-{type}.md`.

---

## 12. Per-Map-Type Development Checklist — moved

Per-map-type checklists are inside each [`platform-maple.md` §8](platform-maple.md) / [`platform-rect.md` §8](platform-rect.md) / [`platform-sideview.md` §8](platform-sideview.md) as **common checks + map-type-specific checks**. Just read the file for the map type you're working on.

---

## 13. ECS Architecture Essentials

MSW uses Entity-Component-System architecture: Entity (ID + Component set), Component (attached to entity), Logic (global singleton), Service (engine system API).

> **Script type comparison (@Component vs @Logic), declaration syntax, access pattern code** — see `msw-scripting` §3.

---

## 14. ID Generation Rules

ID rules used by AI Agents when creating/editing files.

### EntryKey Patterns

| File type | EntryKey format | Example |
|---|---|---|
| `.model` | `model://{name_lowercase}` | `model://chasemonster` |
| `.map` | `map://{mapname_lowercase}` | `map://map01` |
| `.ui` | `ui://{root_entity_UUID}` | `ui://c1ee38e4-b61d-4299-a1dd-d7a9b11f55c5` |
| `.codeblock` | `codeblock://{scriptname_lowercase}` | `codeblock://monster` |
| `.config` | `config://{fixed_value}` | `config://world`, `config://sectors` |

### Entity ID

Entity IDs inside `.ui` / `.map` files are **UUID v4** (with hyphens).

```
Format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
Example: bdadf19a-cc27-4a45-99c6-7a439c858a1b
```

- Generate a new UUID each time AI adds an entity.
- `.ui` file's EntryKey must match the root entity's UUID.

### Model ID

- `.model`'s `ContentProto.Json.Name`: display name (e.g., `"ChaseMonster"`).
- EntryKey identifier: lowercase of the name (e.g., `model://chasemonster`).
- The value passed as the first parameter to `SpawnByModelId()`.

### Top-level Id / GameId

- All files' top-level `Id` / `GameId`: **always keep as empty string** `""`.
- System fills them at runtime — AI should not touch them.

### CollisionGroup ID

- System groups: `MOD@{name}` format (do not modify).
- Custom groups: 32-character hex (no hyphens), e.g., `a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6`.

---

## 15. .config File Structure

### Environment/config

```json
{
  "CoreVersion": "<Maker version>"
}
```

### WorldConfig.config

```json
{
  "CoreVersion": "<Maker version>",
  "LegacyAnimationSupport": false,
  "PlayerEntityAuthorityCheck": false,
  "ServiceAuthorityCheck": false,
  "RestrictedPlayerEntitySync": false,
  "SourceLanguage": "en",
  "UseExtendedScriptFormat": true,
  "UseLitDefaultMaterial": false
}
```

### SectorConfig.config

```json
{
  "Sectors": [
    {
      "id": "sector01",
      "name": "sector01",
      "maxUserNo": 16,
      "entries": ["map://map01"]
    }
  ]
}
```

- `entries`: `"map://mapname"` format.
- Register a new entry here when adding a map.

### CollisionGroupSet.collisiongroupset

Collision group matrix. Defines which groups collide with which. Edit the existing `Global/CollisionGroupSet.collisiongroupset` through `CollisionGroupSetBuilder`, not raw JSON.

- `Groups[]`: `{ Id, Name }`. Scripts use `CollisionGroups.Name`; `.model` `CollisionGroup` values store `Id`.
- `Matrix`: keys and values are group `Id`s. Use `setCollidable()` for symmetric pairs unless one-way collision is intentional.
- Keep built-ins (`Default`, `TriggerBox`, `HitBox`, `Interaction`, `Portal`, `Climbable`) intact unless the user explicitly asks for a project-level collision policy change.

---

## 16. CoreVersion

- `Environment/config` → `CoreVersion` is the version of the Maker that last opened the workspace. Maker writes it.
- A hand-authored entry file (`.material`, `.userdataset`, …) takes its `CoreVersion` from that value. Builder output needs no version handling.
