Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

docs: add tilemap guide, physics debug draw, and plugin lifecycle docs

esenginee7e3477e3a3f
diff --git a/docs/astro/astro.config.mjs b/docs/astro/astro.config.mjs
index 858038194..c23deadfb 100644
--- a/docs/astro/astro.config.mjs
+++ b/docs/astro/astro.config.mjs
@@ -100,6 +100,7 @@ export default defineConfig({
{ label: 'Audio', translations: { 'zh-CN': '音频' }, slug: 'guides/audio' },
{ label: 'Particles', translations: { 'zh-CN': '粒子系统' }, slug: 'guides/particles' },
{ label: 'Physics', translations: { 'zh-CN': '物理' }, slug: 'guides/physics' },
+ { label: 'Tilemap', translations: { 'zh-CN': '瓦片地图' }, slug: 'guides/tilemap' },
],
},
{
diff --git a/docs/astro/src/content/docs/changelog-v081.mdx b/docs/astro/src/content/docs/changelog-v081.mdx
index 083d06381..b2b19fbf2 100644
--- a/docs/astro/src/content/docs/changelog-v081.mdx
+++ b/docs/astro/src/content/docs/changelog-v081.mdx
@@ -75,17 +75,22 @@ The PostProcessVolume inspector now exposes all volume fields:
## Tilemap System
-New Tiled map loader and tilemap rendering pipeline with full editor integration.
+New Tiled map loader and tilemap rendering pipeline with full editor integration. See the [Tilemap guide](/microes/guides/tilemap/) for details.
-- **Tiled JSON loader** — load `.tmj` / `.json` Tiled maps with automatic tileset texture resolution
+- **Tiled JSON loader** — load `.tmj` / `.json` Tiled maps with automatic tileset texture resolution, supports external tilesets
- **Tilemap components** — `Tilemap` and `TilemapLayer` components for ECS integration
- **Collision merge** — automatic rectangular collision region merging for physics optimization
+- **Per-layer properties** — opacity, tint color, parallax scrolling factor
- **Editor support** — Tilemap component inspector with asset picker
## Physics Debug Draw
-- **`PhysicsDebugDraw`** — visual overlay for physics colliders, joints, and contacts in the editor and at runtime
-- Renders wireframe outlines for box, circle, and capsule colliders
+See the [Physics guide — Debug Draw](/microes/guides/physics/#debug-draw) section for usage.
+
+- **`PhysicsDebugDraw`** — visual overlay for physics colliders and contacts in the editor and at runtime
+- Renders wireframe outlines for box, circle, and capsule colliders with color coding by body type
+- Velocity arrows on dynamic bodies and contact point markers
+- Toggle via `Physics.setDebugDraw(app, true)` or configure with `Physics.setDebugDrawConfig()`
## Bug Fixes
diff --git a/docs/astro/src/content/docs/guides/physics.mdx b/docs/astro/src/content/docs/guides/physics.mdx
index 302743f82..fd804c91b 100644
--- a/docs/astro/src/content/docs/guides/physics.mdx
+++ b/docs/astro/src/content/docs/guides/physics.mdx
@@ -168,8 +168,74 @@ addSystem(defineSystem(
| `setGravity(gravity)` | Change world gravity at runtime |
| `getGravity()` | Get current world gravity (Vec2) |
+## Debug Draw
+
+The physics debug draw overlay renders wireframe outlines for all colliders, velocity arrows, and contact points. It uses the engine's `Draw` API and works in both the editor and at runtime.
+
+### Enabling Debug Draw
+
+```typescript
+import { Physics } from 'esengine/physics';
+
+// Toggle debug draw on/off
+Physics.setDebugDraw(app, true);
+```
+
+### Configuration
+
+Control which elements are visualized:
+
+```typescript
+import { Physics } from 'esengine/physics';
+
+Physics.setDebugDrawConfig(app, {
+ enabled: true,
+ showColliders: true, // wireframe collider outlines
+ showVelocity: true, // velocity arrows on dynamic bodies
+ showContacts: false, // contact point markers
+});
+```
+
+| Property | Type | Default | Description |
+|----------|------|---------|-------------|
+| `enabled` | boolean | `false` | Master toggle for debug drawing |
+| `showColliders` | boolean | `true` | Draw collider wireframes |
+| `showVelocity` | boolean | `false` | Draw velocity arrows on dynamic bodies |
+| `showContacts` | boolean | `false` | Draw contact points on collision enter |
+
+### Color Coding
+
+Collider outlines are color-coded by body type:
+
+| Body Type | Color |
+|-----------|-------|
+| Static | Blue |
+| Dynamic | Green |
+| Kinematic | Cyan |
+| Sensor | Yellow (semi-transparent) |
+
+Velocity arrows are drawn in red. Contact points are shown as red dots.
+
+<Aside type="tip">
+ Debug draw is registered as a custom draw callback named `'physics-debug-draw'`. It is automatically set up when the physics plugin initializes — you only need to enable it.
+</Aside>
+
+### PhysicsDebugDraw Resource
+
+For advanced control, access the `PhysicsDebugDraw` resource directly:
+
+```typescript
+import { PhysicsDebugDraw } from 'esengine/physics';
+
+const config = app.getResource(PhysicsDebugDraw);
+config.enabled = true;
+config.showVelocity = true;
+app.insertResource(PhysicsDebugDraw, config);
+```
+
## Next Steps
- [Components](/microes/core-concepts/components/#physics) — full physics component property tables
- [Systems](/microes/core-concepts/systems/) — creating systems to handle physics logic
- [Custom Draw](/microes/guides/custom-draw/) — debug visualization of colliders
+- [Tilemap](/microes/guides/tilemap/) — tile-based collision generation
diff --git a/docs/astro/src/content/docs/guides/plugins.mdx b/docs/astro/src/content/docs/guides/plugins.mdx
index c8f1d4528..f99df1f36 100644
--- a/docs/astro/src/content/docs/guides/plugins.mdx
+++ b/docs/astro/src/content/docs/guides/plugins.mdx
@@ -181,9 +181,23 @@ const myPlugin: Plugin = {
// game logic
}));
},
+ finish(app: App) {
+ // Called after all plugins have been built — safe to read resources from other plugins
+ },
+ cleanup(app?: App) {
+ // Called when the app shuts down — release resources, remove listeners, etc.
+ },
};
```
+### Plugin Lifecycle
+
+| Method | When | Purpose |
+|--------|------|---------|
+| `build(app)` | Plugin is added | Register resources, systems, and components |
+| `finish?(app)` | After all plugins are built | Cross-plugin initialization that depends on other plugins being ready |
+| `cleanup?(app)` | App shutdown | Release resources, clean up listeners and state |
+
Plugins can declare resource dependencies:
```typescript
diff --git a/docs/astro/src/content/docs/guides/scenes.mdx b/docs/astro/src/content/docs/guides/scenes.mdx
index ce6ac9414..29523123b 100644
--- a/docs/astro/src/content/docs/guides/scenes.mdx
+++ b/docs/astro/src/content/docs/guides/scenes.mdx
@@ -343,8 +343,10 @@ app.registerScene({
// Register draw callbacks scoped to this scene
ctx.registerDrawCallback('game-debug', drawDebug);
- // Add post-process effects scoped to this scene
- ctx.addPostProcessPass('bloom', bloomShader);
+ // Bind post-process effects scoped to this scene
+ const fx = PostProcess.createStack();
+ fx.addPass('bloom', PostProcess.createBloom());
+ ctx.bindPostProcess(cameraEntity, fx);
// Mark entity as persistent (survives scene unload)
ctx.setPersistent(e, true);
diff --git a/docs/astro/src/content/docs/guides/tilemap.mdx b/docs/astro/src/content/docs/guides/tilemap.mdx
new file mode 100644
index 000000000..1023215a7
--- /dev/null
+++ b/docs/astro/src/content/docs/guides/tilemap.mdx
@@ -0,0 +1,200 @@
+---
+title: Tilemap
+description: Tiled map loading and tilemap rendering in ESEngine
+---
+
+import { Aside } from '@astrojs/starlight/components';
+
+The tilemap system loads [Tiled](https://www.mapeditor.org/) maps (`.tmj` / `.json`) and renders tile layers with automatic camera culling, per-layer tint/opacity, parallax scrolling, and collision generation.
+
+## Quick Start
+
+The simplest way to use tilemaps is through the editor:
+
+1. Export your map from Tiled as JSON (`.tmj`)
+2. Place the `.tmj` file and tileset images in your project assets folder
+3. Add a **Tilemap** component to an entity and set the **Source** to your `.tmj` file
+
+The scene loader automatically parses the map, loads tileset textures via the `AssetServer`, and registers everything for rendering.
+
+<Aside type="tip">
+ The `TilemapPlugin` is automatically included in `createWebApp()`. No manual plugin setup is needed.
+</Aside>
+
+## Components
+
+### Tilemap
+
+A marker component that references a Tiled map source file. The scene loader reads this field to preload map data and tileset textures before the scene is instantiated.
+
+| Property | Type | Default | Description |
+|----------|------|---------|-------------|
+| `source` | string | `''` | Path to the `.tmj` / `.json` map file |
+
+### TilemapLayer
+
+Describes a single tile layer for rendering. Each visible layer in a Tiled map creates one entity with this component.
+
+| Property | Type | Default | Description |
+|----------|------|---------|-------------|
+| `width` | number | `10` | Layer width in tiles |
+| `height` | number | `10` | Layer height in tiles |
+| `tileWidth` | number | `32` | Tile width in pixels |
+| `tileHeight` | number | `32` | Tile height in pixels |
+| `texture` | number | `0` | Tileset texture handle |
+| `tilesetColumns` | number | `1` | Number of columns in the tileset image |
+| `layer` | number | `0` | Sort layer index |
+| `tiles` | number[] | `[]` | Flat array of tile IDs (row-major) |
+| `tint` | Color | `{r:1,g:1,b:1,a:1}` | Per-layer tint color |
+| `opacity` | number | `1` | Layer opacity (0–1) |
+| `visible` | boolean | `true` | Whether the layer is rendered |
+| `parallaxFactor` | Vec2 | `{x:1,y:1}` | Parallax scroll factor |
+
+<Aside type="tip">
+ Tile IDs use local indices (1-based, 0 = empty). Flip flags for horizontal, vertical, and diagonal flips are encoded in the upper bits.
+</Aside>
+
+## How It Works
+
+### Scene Loading Pipeline
+
+When a scene contains an entity with a `Tilemap` component, the scene loader:
+
+1. Reads the `source` field (e.g., `maps/level1.tmj`)
+2. Loads the JSON via the `AssetServer` and parses it with `parseTmjJson`
+3. Resolves tileset image paths relative to the `.tmj` file
+4. Loads tileset textures via `AssetServer.loadTexture()` and registers their dimensions
+5. Caches the parsed map data with `registerTilemapSource()`
+
+At runtime, the `TilemapPlugin` reads the cache and submits visible layers for rendering each frame.
+
+### Build Targets
+
+The tilemap asset pipeline works across all build targets:
+
+- **Editor preview**: Loads via `AssetServer` over the preview HTTP server
+- **WeChat MiniGame / Playable Ads**: Loads via `RuntimeAssetProvider` using the bundled assets
+- **Web build**: Same as editor preview, assets served from the build output
+
+<Aside type="note">
+ `.tmj` files are registered as a known asset type with `wechatPackInclude: true`, so they are automatically included in WeChat and playable ad builds.
+</Aside>
+
+## Programmatic Loading
+
+For cases where you need to load a tilemap from code (outside the scene loader), use the lower-level APIs:
+
+```typescript
+import { parseTmjJson, loadTiledMap, registerTextureDimensions } from 'esengine';
+
+// Parse Tiled JSON data
+const mapData = parseTmjJson(jsonObject);
+
+// Load tileset textures through the AssetServer
+const textureHandles = new Map<string, number>();
+for (const tileset of mapData.tilesets) {
+ const info = await assetServer.loadTexture(tileset.image);
+ textureHandles.set(tileset.image, info.handle);
+ registerTextureDimensions(info.handle, info.width, info.height);
+}
+
+// Spawn tilemap layer entities into the world
+const entities = loadTiledMap(world, mapData, textureHandles);
+```
+
+### C++ Parser (WASM)
+
+For maps with external tilesets (`.tsj` files), use `parseTiledMap` which delegates to the C++ parser:
+
+```typescript
+import { parseTiledMap } from 'esengine';
+
+const mapData = await parseTiledMap(jsonString, async (source) => {
+ // Resolve external tileset files
+ return await assetServer.loadText(source);
+});
+```
+
+### loadTiledMap Options
+
+| Option | Type | Default | Description |
+|--------|------|---------|-------------|
+| `generateObjectCollision` | boolean | `true` | Create colliders from Tiled object layers |
+| `collisionTileIds` | number[] | auto-detected | Tile IDs that should generate collision bodies |
+
+## Collision Generation
+
+### Object Layer Collision
+
+Tiled object layers are automatically converted to physics bodies. Supported shapes:
+
+- **Rectangle** → `BoxCollider` with matching half-extents
+- **Ellipse** → `CircleCollider` with the larger axis as radius
+- **Polygon / Polyline** → `BoxCollider` fitted to the bounding box
+- **Point** → skipped
+
+Each collision object creates a static `RigidBody` entity with the appropriate collider.
+
+### Tile Collision
+
+Mark tiles as collidable in Tiled by adding a custom property `collision = true` to the tile in the tileset. The loader reads these IDs and generates merged collision rectangles:
+
+```typescript
+const entities = loadTiledMap(world, mapData, textureHandles, {
+ collisionTileIds: [1, 2, 3],
+});
+```
+
+### Collision Merging
+
+Adjacent collision tiles are automatically merged into larger rectangles to reduce physics body count. The algorithm scans row by row, expanding each rectangle rightward and downward as far as possible:
+
+```
+Before merge: [1][1][1] After merge: [ 1 ]
+ [1][1][1] [ 1 ]
+```
+
+This produces fewer, larger `BoxCollider` bodies for better physics performance.
+
+## TilemapAPI
+
+Low-level API for runtime tile manipulation:
+
+| Method | Description |
+|--------|-------------|
+| `TilemapAPI.initLayer(entity, w, h, tw, th)` | Initialize a tile layer for an entity |
+| `TilemapAPI.destroyLayer(entity)` | Destroy a tile layer |
+| `TilemapAPI.setTile(entity, x, y, tileId)` | Set a single tile |
+| `TilemapAPI.getTile(entity, x, y)` | Get a tile ID |
+| `TilemapAPI.fillRect(entity, x, y, w, h, tileId)` | Fill a rectangle with a tile |
+| `TilemapAPI.setTiles(entity, tiles)` | Set all tiles from a `Uint16Array` |
+| `TilemapAPI.hasLayer(entity)` | Check if an entity has an initialized layer |
+
+## Editor Workflow
+
+1. Add a **Tilemap** component to an entity in the Hierarchy
+2. Set the **Source** field to a `.tmj` or `.json` Tiled map file using the asset picker
+3. The editor automatically loads the map, resolves tileset textures, and renders the layers
+4. Collision objects are visualized as gizmo overlays
+
+<Aside type="tip">
+ Design your maps in the [Tiled Map Editor](https://www.mapeditor.org/), export as JSON (`.tmj`), and place the file alongside your tileset images in the project assets folder.
+</Aside>
+
+## Layer Properties
+
+Tiled layer properties map directly to `TilemapLayer` fields:
+
+| Tiled Property | TilemapLayer Field | Description |
+|----------------|-------------------|-------------|
+| `opacity` | `opacity` | Layer transparency |
+| `tintcolor` | `tint` | Hex color string (`#AARRGGBB` or `#RRGGBB`) |
+| `parallaxx` | `parallaxFactor.x` | Horizontal parallax factor |
+| `parallaxy` | `parallaxFactor.y` | Vertical parallax factor |
+| `visible` | `visible` | Layer visibility |
+
+## Next Steps
+
+- [Physics](/microes/guides/physics/) — collision components and events
+- [Sprite](/microes/guides/sprite/) — sprite rendering alongside tilemaps
+- [Rendering Overview](/microes/guides/rendering/) — camera, transform, render order
diff --git a/docs/astro/src/content/docs/zh/changelog-v081.mdx b/docs/astro/src/content/docs/zh/changelog-v081.mdx
index 5267849d5..cab87d3e4 100644
--- a/docs/astro/src/content/docs/zh/changelog-v081.mdx
+++ b/docs/astro/src/content/docs/zh/changelog-v081.mdx
@@ -75,17 +75,22 @@ PostProcessVolume 检查器新增所有 Volume 属性编辑:
## Tilemap 系统
-新增 Tiled 地图加载器和瓦片地图渲染管线,完整编辑器集成。
+新增 Tiled 地图加载器和瓦片地图渲染管线,完整编辑器集成。详见[瓦片地图指南](/microes/zh/guides/tilemap/)。
-- **Tiled JSON 加载器** — 加载 `.tmj` / `.json` 格式的 Tiled 地图,自动解析 tileset 纹理
+- **Tiled JSON 加载器** — 加载 `.tmj` / `.json` 格式的 Tiled 地图,自动解析 tileset 纹理,支持外部 tileset
- **Tilemap 组件** — `Tilemap` 和 `TilemapLayer` 组件用于 ECS 集成
- **碰撞合并** — 自动矩形碰撞区域合并,优化物理性能
+- **逐图层属性** — 透明度、着色、视差滚动因子
- **编辑器支持** — Tilemap 组件检查器,带资源选择器
## 物理调试绘制
-- **`PhysicsDebugDraw`** — 物理碰撞体、关节和接触点的可视化叠加层,编辑器和运行时均可使用
-- 渲染 Box、Circle 和 Capsule 碰撞体的线框轮廓
+详见[物理指南 — 调试绘制](/microes/zh/guides/physics/#调试绘制)章节。
+
+- **`PhysicsDebugDraw`** — 物理碰撞体和接触点的可视化叠加层,编辑器和运行时均可使用
+- 渲染 Box、Circle 和 Capsule 碰撞体的线框轮廓,按刚体类型着色
+- 动态刚体的速度箭头和碰撞接触点标记
+- 通过 `Physics.setDebugDraw(app, true)` 开关,或使用 `Physics.setDebugDrawConfig()` 配置
## Bug 修复
diff --git a/docs/astro/src/content/docs/zh/guides/physics.mdx b/docs/astro/src/content/docs/zh/guides/physics.mdx
index 6d1f7554d..1a336d110 100644
--- a/docs/astro/src/content/docs/zh/guides/physics.mdx
+++ b/docs/astro/src/content/docs/zh/guides/physics.mdx
@@ -168,8 +168,74 @@ addSystem(defineSystem(
| `setGravity(gravity)` | 运行时修改世界重力 |
| `getGravity()` | 获取当前世界重力(Vec2) |
+## 调试绘制
+
+物理调试绘制叠加层渲染所有碰撞体的线框轮廓、速度箭头和接触点。使用引擎的 `Draw` API,在编辑器和运行时均可使用。
+
+### 启用调试绘制
+
+```typescript
+import { Physics } from 'esengine/physics';
+
+// 开启/关闭调试绘制
+Physics.setDebugDraw(app, true);
+```
+
+### 配置
+
+控制显示哪些元素:
+
+```typescript
+import { Physics } from 'esengine/physics';
+
+Physics.setDebugDrawConfig(app, {
+ enabled: true,
+ showColliders: true, // 碰撞体线框轮廓
+ showVelocity: true, // 动态刚体的速度箭头
+ showContacts: false, // 接触点标记
+});
+```
+
+| 属性 | 类型 | 默认值 | 说明 |
+|------|------|--------|------|
+| `enabled` | boolean | `false` | 调试绘制主开关 |
+| `showColliders` | boolean | `true` | 绘制碰撞体线框 |
+| `showVelocity` | boolean | `false` | 绘制动态刚体的速度箭头 |
+| `showContacts` | boolean | `false` | 绘制碰撞进入时的接触点 |
+
+### 颜色编码
+
+碰撞体轮廓按刚体类型着色:
+
+| 刚体类型 | 颜色 |
+|----------|------|
+| Static | 蓝色 |
+| Dynamic | 绿色 |
+| Kinematic | 青色 |
+| Sensor | 黄色(半透明) |
+
+速度箭头为红色。接触点显示为红色圆点。
+
+<Aside type="tip">
+ 调试绘制注册为名为 `'physics-debug-draw'` 的自定义绘制回调。物理插件初始化时自动设置——你只需启用它。
+</Aside>
+
+### PhysicsDebugDraw 资源
+
+如需高级控制,可直接访问 `PhysicsDebugDraw` 资源:
+
+```typescript
+import { PhysicsDebugDraw } from 'esengine/physics';
+
+const config = app.getResource(PhysicsDebugDraw);
+config.enabled = true;
+config.showVelocity = true;
+app.insertResource(PhysicsDebugDraw, config);
+```
+
## 下一步
- [组件](/microes/zh/core-concepts/components/#物理) — 完整物理组件属性表
- [系统](/microes/zh/core-concepts/systems/) — 创建系统处理物理逻辑
- [自定义绘制](/microes/zh/guides/custom-draw/) — 碰撞体调试可视化
+- [瓦片地图](/microes/zh/guides/tilemap/) — 基于瓦片的碰撞生成
diff --git a/docs/astro/src/content/docs/zh/guides/plugins.mdx b/docs/astro/src/content/docs/zh/guides/plugins.mdx
index 72e70e8bd..c4ed51c22 100644
--- a/docs/astro/src/content/docs/zh/guides/plugins.mdx
+++ b/docs/astro/src/content/docs/zh/guides/plugins.mdx
@@ -181,9 +181,23 @@ const myPlugin: Plugin = {
// 游戏逻辑
}));
},
+ finish(app: App) {
+ // 所有插件 build 完成后调用 — 可安全读取其他插件注册的资源
+ },
+ cleanup(app?: App) {
+ // 应用关闭时调用 — 释放资源、移除监听器等
+ },
};
```
+### 插件生命周期
+
+| 方法 | 调用时机 | 用途 |
+|------|---------|------|
+| `build(app)` | 插件被添加时 | 注册资源、系统和组件 |
+| `finish?(app)` | 所有插件 build 完成后 | 依赖其他插件就绪的跨插件初始化 |
+| `cleanup?(app)` | 应用关闭时 | 释放资源、清理监听器和状态 |
+
插件可以声明资源依赖:
```typescript
diff --git a/docs/astro/src/content/docs/zh/guides/scenes.mdx b/docs/astro/src/content/docs/zh/guides/scenes.mdx
index ad0f16435..8a5ac1775 100644
--- a/docs/astro/src/content/docs/zh/guides/scenes.mdx
+++ b/docs/astro/src/content/docs/zh/guides/scenes.mdx
@@ -337,8 +337,10 @@ app.registerScene({
// 注册作用域为此场景的绘制回调
ctx.registerDrawCallback('game-debug', drawDebug);
- // 添加作用域为此场景的后处理效果
- ctx.addPostProcessPass('bloom', bloomShader);
+ // 绑定作用域为此场景的后处理效果
+ const fx = PostProcess.createStack();
+ fx.addPass('bloom', PostProcess.createBloom());
+ ctx.bindPostProcess(cameraEntity, fx);
// 标记实体为持久(场景卸载时不销毁)
ctx.setPersistent(e, true);
diff --git a/docs/astro/src/content/docs/zh/guides/tilemap.mdx b/docs/astro/src/content/docs/zh/guides/tilemap.mdx
new file mode 100644
index 000000000..40cdeb773
--- /dev/null
+++ b/docs/astro/src/content/docs/zh/guides/tilemap.mdx
@@ -0,0 +1,200 @@
+---
+title: 瓦片地图
+description: ESEngine 中的 Tiled 地图加载与瓦片地图渲染
+---
+
+import { Aside } from '@astrojs/starlight/components';
+
+瓦片地图系统加载 [Tiled](https://www.mapeditor.org/) 地图(`.tmj` / `.json`),渲染瓦片图层,支持自动相机裁剪、逐图层着色/透明度、视差滚动和碰撞生成。
+
+## 快速开始
+
+最简单的使用方式是通过编辑器:
+
+1. 从 Tiled 导出地图为 JSON(`.tmj`)
+2. 将 `.tmj` 文件和 tileset 图片放在项目资源文件夹中
+3. 为实体添加 **Tilemap** 组件,将 **Source** 设置为 `.tmj` 文件
+
+场景加载器会自动解析地图、通过 `AssetServer` 加载 tileset 纹理,并注册到渲染管线。
+
+<Aside type="tip">
+ `TilemapPlugin` 已自动包含在 `createWebApp()` 中,无需手动设置插件。
+</Aside>
+
+## 组件
+
+### Tilemap
+
+标记组件,引用 Tiled 地图源文件。场景加载器读取此字段,在场景实例化前预加载地图数据和 tileset 纹理。
+
+| 属性 | 类型 | 默认值 | 说明 |
+|------|------|--------|------|
+| `source` | string | `''` | `.tmj` / `.json` 地图文件路径 |
+
+### TilemapLayer
+
+描述单个瓦片图层的渲染数据。Tiled 地图中每个可见图层会创建一个带有此组件的实体。
+
+| 属性 | 类型 | 默认值 | 说明 |
+|------|------|--------|------|
+| `width` | number | `10` | 图层宽度(瓦片数) |
+| `height` | number | `10` | 图层高度(瓦片数) |
+| `tileWidth` | number | `32` | 瓦片宽度(像素) |
+| `tileHeight` | number | `32` | 瓦片高度(像素) |
+| `texture` | number | `0` | Tileset 纹理句柄 |
+| `tilesetColumns` | number | `1` | Tileset 图片中的列数 |
+| `layer` | number | `0` | 排序图层索引 |
+| `tiles` | number[] | `[]` | 瓦片 ID 平铺数组(行优先) |
+| `tint` | Color | `{r:1,g:1,b:1,a:1}` | 逐图层着色 |
+| `opacity` | number | `1` | 图层透明度(0–1) |
+| `visible` | boolean | `true` | 是否渲染该图层 |
+| `parallaxFactor` | Vec2 | `{x:1,y:1}` | 视差滚动因子 |
+
+<Aside type="tip">
+ 瓦片 ID 使用局部索引(1-based,0 = 空白)。水平、垂直和对角线翻转标志编码在高位。
+</Aside>
+
+## 工作原理
+
+### 场景加载管线
+
+当场景包含带有 `Tilemap` 组件的实体时,场景加载器会:
+
+1. 读取 `source` 字段(如 `maps/level1.tmj`)
+2. 通过 `AssetServer` 加载 JSON 并使用 `parseTmjJson` 解析
+3. 解析 tileset 图片的相对路径
+4. 通过 `AssetServer.loadTexture()` 加载 tileset 纹理并注册其尺寸
+5. 使用 `registerTilemapSource()` 缓存解析后的地图数据
+
+运行时,`TilemapPlugin` 读取缓存,每帧提交可见图层进行渲染。
+
+### 构建目标
+
+瓦片地图资源管线适用于所有构建目标:
+
+- **编辑器预览**:通过预览 HTTP 服务器的 `AssetServer` 加载
+- **微信小游戏 / 可玩广告**:通过 `RuntimeAssetProvider` 使用打包资源加载
+- **Web 构建**:与编辑器预览相同,资源从构建输出提供
+
+<Aside type="note">
+ `.tmj` 文件注册为已知资源类型,`wechatPackInclude: true`,因此会自动包含在微信和可玩广告构建中。
+</Aside>
+
+## 代码加载
+
+在场景加载器之外需要从代码加载瓦片地图时,使用底层 API:
+
+```typescript
+import { parseTmjJson, loadTiledMap, registerTextureDimensions } from 'esengine';
+
+// 解析 Tiled JSON 数据
+const mapData = parseTmjJson(jsonObject);
+
+// 通过 AssetServer 加载 tileset 纹理
+const textureHandles = new Map<string, number>();
+for (const tileset of mapData.tilesets) {
+ const info = await assetServer.loadTexture(tileset.image);
+ textureHandles.set(tileset.image, info.handle);
+ registerTextureDimensions(info.handle, info.width, info.height);
+}
+
+// 将瓦片地图图层实体生成到世界中
+const entities = loadTiledMap(world, mapData, textureHandles);
+```
+
+### C++ 解析器(WASM)
+
+对于包含外部 tileset(`.tsj` 文件)的地图,使用 `parseTiledMap`,它委托给 C++ 解析器:
+
+```typescript
+import { parseTiledMap } from 'esengine';
+
+const mapData = await parseTiledMap(jsonString, async (source) => {
+ // 解析外部 tileset 文件
+ return await assetServer.loadText(source);
+});
+```
+
+### loadTiledMap 选项
+
+| 选项 | 类型 | 默认值 | 说明 |
+|------|------|--------|------|
+| `generateObjectCollision` | boolean | `true` | 从 Tiled 对象图层创建碰撞体 |
+| `collisionTileIds` | number[] | 自动检测 | 应生成碰撞体的瓦片 ID |
+
+## 碰撞生成
+
+### 对象图层碰撞
+
+Tiled 对象图层自动转换为物理刚体。支持的形状:
+
+- **矩形** → `BoxCollider`,半尺寸与原始尺寸匹配
+- **椭圆** → `CircleCollider`,以较大轴为半径
+- **多边形 / 折线** → `BoxCollider`,拟合包围盒
+- **点** → 跳过
+
+每个碰撞对象创建一个静态 `RigidBody` 实体和相应的碰撞体。
+
+### 瓦片碰撞
+
+在 Tiled 中为 tileset 中的瓦片添加自定义属性 `collision = true` 来标记可碰撞瓦片。加载器读取这些 ID 并生成合并后的碰撞矩形:
+
+```typescript
+const entities = loadTiledMap(world, mapData, textureHandles, {
+ collisionTileIds: [1, 2, 3],
+});
+```
+
+### 碰撞合并
+
+相邻的碰撞瓦片自动合并为更大的矩形,减少物理刚体数量。算法逐行扫描,尽可能向右和向下扩展每个矩形:
+
+```
+合并前: [1][1][1] 合并后: [ 1 ]
+ [1][1][1] [ 1 ]
+```
+
+这产生更少、更大的 `BoxCollider` 刚体,提升物理性能。
+
+## TilemapAPI
+
+底层运行时瓦片操作 API:
+
+| 方法 | 说明 |
+|------|------|
+| `TilemapAPI.initLayer(entity, w, h, tw, th)` | 为实体初始化瓦片图层 |
+| `TilemapAPI.destroyLayer(entity)` | 销毁瓦片图层 |
+| `TilemapAPI.setTile(entity, x, y, tileId)` | 设置单个瓦片 |
+| `TilemapAPI.getTile(entity, x, y)` | 获取瓦片 ID |
+| `TilemapAPI.fillRect(entity, x, y, w, h, tileId)` | 用指定瓦片填充矩形区域 |
+| `TilemapAPI.setTiles(entity, tiles)` | 从 `Uint16Array` 设置所有瓦片 |
+| `TilemapAPI.hasLayer(entity)` | 检查实体是否有已初始化的图层 |
+
+## 编辑器工作流
+
+1. 在 Hierarchy 中为实体添加 **Tilemap** 组件
+2. 使用资源选择器将 **Source** 字段设置为 `.tmj` 或 `.json` Tiled 地图文件
+3. 编辑器自动加载地图、解析 tileset 纹理并渲染图层
+4. 碰撞对象显示为 Gizmo 叠加层
+
+<Aside type="tip">
+ 在 [Tiled Map Editor](https://www.mapeditor.org/) 中设计地图,导出为 JSON(`.tmj`),将文件和 tileset 图片放在项目资源文件夹中。
+</Aside>
+
+## 图层属性
+
+Tiled 图层属性直接映射到 `TilemapLayer` 字段:
+
+| Tiled 属性 | TilemapLayer 字段 | 说明 |
+|------------|-------------------|------|
+| `opacity` | `opacity` | 图层透明度 |
+| `tintcolor` | `tint` | 十六进制颜色字符串(`#AARRGGBB` 或 `#RRGGBB`) |
+| `parallaxx` | `parallaxFactor.x` | 水平视差因子 |
+| `parallaxy` | `parallaxFactor.y` | 垂直视差因子 |
+| `visible` | `visible` | 图层可见性 |
+
+## 下一步
+
+- [物理](/microes/zh/guides/physics/) — 碰撞组件和事件
+- [精灵](/microes/zh/guides/sprite/) — 与瓦片地图一起使用精灵渲染
+- [渲染概览](/microes/zh/guides/rendering/) — 相机、变换、渲染顺序