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.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(editor): converge .tmj shape objects into Trigger Area entities
yhha3ef8cd9e14c
diff --git a/desktop/src/engine/ViewportController.ts b/desktop/src/engine/ViewportController.tsindex 9d5120f3f..20542b5f4 100644--- a/desktop/src/engine/ViewportController.ts+++ b/desktop/src/engine/ViewportController.ts@@ -3,7 +3,7 @@import {Camera, CameraView, EditorView, Light2D, Sprite, Transform, Canvas, BoxCollider, CircleCollider,CapsuleCollider, SegmentCollider, PolygonCollider, ChainCollider,- ParticleEmitter, OneWayPlatform,+ ParticleEmitter, OneWayPlatform, RigidBody,RevoluteJoint, DistanceJoint, PrismaticJoint, WeldJoint, WheelJoint, MotorJoint,UINode, UICameraInfo, screenToUiWorld, uiWorldToScreen, uiPickAllWorld, type UICameraData,Marker,@@ -656,7 +656,10 @@ export const ViewportController = {if (!world) return [];const out: EntityId[] = [];for (const e of world.getAllEntities()) {- if (world.has(e, Marker) && world.has(e, Transform)) out.push(e);+ // A pin is for POINT markers only — a Marker + Transform with no body of its own.+ // A Trigger Area also carries a Marker but has a RigidBody + sensor collider (shown+ // by the collider gizmo), so a pin on top of its outline would just be clutter.+ if (world.has(e, Marker) && world.has(e, Transform) && !world.has(e, RigidBody)) out.push(e);}return out;},diff --git a/desktop/src/main.tsx b/desktop/src/main.tsxindex 59c4e92a7..dce9cc56e 100644--- a/desktop/src/main.tsx+++ b/desktop/src/main.tsx@@ -150,10 +150,22 @@ if (new URLSearchParams(location.search).has('automation')) {/** All LIVE Marker entities (hand-placed model entities AND `.tmj`-derived RuntimeOnly* children), each with its `type` + whether it's a model entity (`src != null`) or a* derived projection (`src == null`) — verifies object-group → Marker convergence. */- liveMarkers: () => ViewportController.markerIds().map((rt) => {- const g = ViewportController.getMarkerGizmo(rt);- return { rt, type: g?.type ?? null, properties: g?.properties ?? {}, src: SceneModel.sourceFor(rt) ?? null };- }),+ liveMarkers: () => {+ const w = EngineHost.world;+ const md = getComponent('Marker');+ const rb = getComponent('RigidBody');+ if (!w || !md) return [];+ return w.getEntitiesWithComponents([md]).map((rt) => {+ const m = w.get(rt, md) as { type?: string; properties?: Record<string, string> };+ return {+ rt,+ type: typeof m?.type === 'string' ? m.type : null,+ properties: m?.properties ?? {},+ isTrigger: !!(rb && w.has(rt, rb)), // a Trigger Area carries a RigidBody + sensor collider+ src: SceneModel.sourceFor(rt) ?? null,+ };+ });+ },/** Probe a layer's resolved tile-collision overlay — the SAME pieces the viewport* draws + Play spawns. Returns null if nothing resolves; else piece counts by kind.* Verifies the collision-layer pipeline end-to-end (refs → palette model → outlines). */diff --git a/desktop/src/panels/Viewport.tsx b/desktop/src/panels/Viewport.tsxindex d9901979c..fdd0e81ac 100644--- a/desktop/src/panels/Viewport.tsx+++ b/desktop/src/panels/Viewport.tsx@@ -853,6 +853,13 @@ export function Viewport() {// so draw each as a gizmo (icon + authored view rect). The id set updates on// structural change; the rAF below positions them every frame.const structRev = useSyncExternalStore(SceneStore.subscribe, SceneStore.getStructureRevision);+ // Derived (RuntimeOnly) entities — the marker / trigger-area / sprite children a `.tmj`+ // source projects — never bump the model's structure/data revision (they're not in the+ // scene model). `worldRev` bumps whenever the live world's entity count changes (polled+ // in the rAF), so the per-entity gizmo id lists (markers, colliders) re-enumerate to pick+ // up or drop those derived entities as a source loads / tears down.+ const [worldRev, setWorldRev] = useState(0);+ const worldCountRef = useRef(-1);const camRefs = useRef(new Map<number, HTMLDivElement | null>());const camIds = useMemo(() => (engine.status === 'ready' ? ViewportController.cameraIds() : []),@@ -875,14 +882,14 @@ export function Viewport() {// set once the async source load + derive lands.const markerIds = useMemo(() => (engine.status === 'ready' ? ViewportController.markerIds() : []),- [structRev, dataRev, engine.status],+ [structRev, dataRev, worldRev, engine.status],);// Physics colliders aren't drawn by the renderer — outline each (box polygon /// circle) as a gizmo so you can see/tune collider shapes without entering Play.const colliderRefs = useRef(new Map<number, SVGSVGElement | null>());const colliderIds = useMemo(() => (engine.status === 'ready' && showColliders ? ViewportController.colliderIds() : []),- [structRev, engine.status, showColliders],+ [structRev, worldRev, engine.status, showColliders],);// Tile-collision overlay: the selected TilemapLayer's per-tile collision, drawn into// ONE SVG (not one per tile). Its world-space outlines are (re)built into a ref by the@@ -1045,6 +1052,14 @@ export function Viewport() {const showG = useEditorStore.getState().showGizmos;const toolMode = useEditorStore.getState().tool;+ // Poll the world's entity count so gizmos for RuntimeOnly derived entities (a `.tmj`+ // source's markers / trigger areas) appear once the async source load derives them —+ // those never bump the model revisions the id lists otherwise key on.+ if (ready) {+ const wc = EngineHost.world?.entityCount() ?? 0;+ if (wc !== worldCountRef.current) { worldCountRef.current = wc; setWorldRev((v) => v + 1); }+ }+// Keep the zoom % readout honest: derive it from the ACTUAL world→screen scale// (pixels per world unit ×100). Frame Selected, the minimap, and device presets// all change orthoSize without any wheel event, so a tracked counter drifts.diff --git a/examples/tilemap-demo/assets/maps/level.tmj b/examples/tilemap-demo/assets/maps/level.tmjindex 248020dc1..8f59ae333 100644--- a/examples/tilemap-demo/assets/maps/level.tmj+++ b/examples/tilemap-demo/assets/maps/level.tmj@@ -10,8 +10,8 @@"height": 18,"tilewidth": 18,"tileheight": 18,- "nextlayerid": 6,- "nextobjectid": 4,+ "nextlayerid": 7,+ "nextobjectid": 6,"tilesets": [{"firstgid": 1,@@ -2464,6 +2464,20 @@"visible":true,"x":0,"y":0+ },+ {+ "draworder":"topdown",+ "id":6,+ "name":"triggers",+ "objects":[+ {"id":4,"name":"door-a","type":"door","point":false,"x":200,"y":90,"width":36,"height":54,"rotation":0,"visible":true,"properties":[{"name":"target","type":"string","value":"level2"}]},+ {"id":5,"name":"heal-zone","type":"zone","ellipse":true,"x":330,"y":170,"width":72,"height":56,"rotation":0,"visible":true,"properties":[]}+ ],+ "opacity":1,+ "type":"objectgroup",+ "visible":true,+ "x":0,+ "y":0}]}\ No newline at end of filediff --git a/sdk/src/tilemap/index.ts b/sdk/src/tilemap/index.tsindex f0525d321..f081c4d25 100644--- a/sdk/src/tilemap/index.ts+++ b/sdk/src/tilemap/index.ts@@ -8,7 +8,7 @@ export {parseTmjJson, parseTmjWithExternals, loadTiledMap, loadTiledCollisionObjects,generateTileCollision, generateLayerCollision, generateChunkCollision,generateChunkPolygonCollision, generateChunkTileShapes, generateLayerTileShapes,- tiledObjectgroupShape, tiledCollisionMods, generateObjectCollision, isCollisionObjectGroup,+ tiledObjectgroupShape, tiledCollisionMods, generateObjectCollision, spawnObjectTriggerArea, isCollisionObjectGroup,polygonLocalVerts, tileColliderShape, oneWayNormalWorld, resolveRelativePath, packCollectionGrid,type TiledMapData, type TiledLayerData, type TiledTilesetData,type TiledCollectionTile, type CollectionGridTile,diff --git a/sdk/src/tilemap/tiledLoader.ts b/sdk/src/tilemap/tiledLoader.tsindex 58d64b3b0..decd66bfe 100644--- a/sdk/src/tilemap/tiledLoader.ts+++ b/sdk/src/tilemap/tiledLoader.ts@@ -4,7 +4,7 @@ import { TilemapAPI } from './tilemapAPI';import type { World } from '../world';import type { Entity } from '../types';import { TilemapLayer } from './components';-import { Transform } from '../component';+import { Transform, Marker, RuntimeOnly } from '../component';// Matches TilemapSystem::CHUNK_SIZE on the C++ side.const TILEMAP_CHUNK_SIZE = 16;@@ -771,6 +771,91 @@ export function generateObjectCollision(return entities;}+/** A Tiled object's custom properties as a plain string→string record (Marker.properties). */+function objectPropsRecord(obj: TiledObjectData): Record<string, string> {+ const props: Record<string, string> = {};+ for (const [k, v] of obj.properties) props[k] = String(v);+ return props;+}++/**+ * @brief Project ONE Tiled SHAPE object (rect / ellipse / polygon) into a real Trigger-Area+ * entity — the same shape a hand-authored Trigger Area preset builds: Transform ++ * Marker{type,properties} + static RigidBody + a SENSOR collider matching the shape.+ *+ * The converged target for imported object-group regions: instead of living only inside+ * `getTilemapSource().objectGroups`, a region becomes a parented, RuntimeOnly (re-derived,+ * never serialized) entity so it's `Query(Marker)`-able and shows the collider gizmo in the+ * editor — exactly like a hand-placed Trigger Area. LOCAL coords (the tilemap parent carries+ * the origin), mirroring the tile-object sprites; geometry is metres (÷ ppu) like+ * {@link generateObjectCollision}. Point / polyline / gid objects project elsewhere → null.+ */+export function spawnObjectTriggerArea(+ world: World,+ obj: TiledObjectData,+ parent: Entity,+ pixelsPerUnit: number,+): Entity | null {+ if (obj.shape !== 'rect' && obj.shape !== 'ellipse' && obj.shape !== 'polygon') return null;+ const rad = obj.rotation * DEG_TO_RAD;+ const cos = Math.cos(rad);+ const sin = Math.sin(rad);+ // Local shape centre (parent = tilemap origin) — generateObjectCollision's spawnAt with+ // origin 0; Tiled rotates clockwise about the object anchor (y-down), realized as -rot z.+ const spawnAt = (lx: number, ly: number): Entity => {+ const e = world.spawn(obj.name || `Trigger_${obj.id}`);+ const position = { x: obj.x + lx * cos - ly * sin, y: -(obj.y + lx * sin + ly * cos), z: 0 };+ if (rad !== 0) {+ const half = -rad * 0.5;+ world.insert(e, Transform, { position, rotation: { w: Math.cos(half), x: 0, y: 0, z: Math.sin(half) } });+ } else {+ world.insert(e, Transform, { position });+ }+ world.insert(e, Marker, { type: obj.type || '', properties: objectPropsRecord(obj) });+ world.insert(e, RigidBody, { bodyType: BodyType.Static });+ world.insert(e, RuntimeOnly, {});+ world.setParent(e, parent);+ return e;+ };+ if (obj.shape === 'rect') {+ const e = spawnAt(obj.width * 0.5, obj.height * 0.5);+ world.insert(e, BoxCollider, {+ halfExtents: { x: obj.width * 0.5 / pixelsPerUnit, y: obj.height * 0.5 / pixelsPerUnit },+ isSensor: true,+ });+ return e;+ }+ if (obj.shape === 'ellipse') {+ const e = spawnAt(obj.width * 0.5, obj.height * 0.5);+ world.insert(e, CircleCollider, { radius: (obj.width + obj.height) * 0.25 / pixelsPerUnit, isSensor: true });+ return e;+ }+ // polygon (needs ≥ 3 points = 6 flat coords)+ if (!obj.vertices || obj.vertices.length < 6) return null;+ const local: { x: number; y: number }[] = [];+ for (let i = 0; i < obj.vertices.length; i += 2) {+ local.push({ x: obj.vertices[i] / pixelsPerUnit, y: (0 - obj.vertices[i + 1]) / pixelsPerUnit });+ }+ if (local.length <= 8) {+ const e = spawnAt(0, 0);+ world.insert(e, PolygonCollider, { vertices: local, isSensor: true });+ return e;+ }+ // > 8 verts: Box2D's cap — a bounding-box sensor (predictably shaped, never truncated).+ let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;+ for (let i = 0; i < obj.vertices.length; i += 2) {+ const vx = obj.vertices[i], vy = obj.vertices[i + 1];+ if (vx < minX) minX = vx; if (vx > maxX) maxX = vx;+ if (vy < minY) minY = vy; if (vy > maxY) maxY = vy;+ }+ const e = spawnAt((minX + maxX) * 0.5, (minY + maxY) * 0.5);+ world.insert(e, BoxCollider, {+ halfExtents: { x: (maxX - minX) * 0.5 / pixelsPerUnit, y: (maxY - minY) * 0.5 / pixelsPerUnit },+ isSensor: true,+ });+ return e;+}+/*** @brief Spawn static colliders for EVERY object group of a parsed map (the code-driven* `loadTiledMap` path; the scene path filters by {@link isCollisionObjectGroup}).diff --git a/sdk/src/tilemap/tilemapPlugin.ts b/sdk/src/tilemap/tilemapPlugin.tsindex 1bddaaff0..922c732b7 100644--- a/sdk/src/tilemap/tilemapPlugin.ts+++ b/sdk/src/tilemap/tilemapPlugin.ts@@ -16,7 +16,7 @@ import { _bindTileCollisionLookup, type LayerCollisionTable } from './tileQuery'import type { ResolvedTileCollision } from './tilesetResolve';import {generateLayerCollision, generateLayerTileShapes, generateChunkCollision, generateChunkTileShapes,- generateObjectCollision, isCollisionObjectGroup, decodeTiledGid,+ generateObjectCollision, spawnObjectTriggerArea, isCollisionObjectGroup, decodeTiledGid,} from './tiledLoader';import { decodeTilemapChunks } from './chunkCodec';import { Assets } from '../asset/AssetPlugin';@@ -511,16 +511,18 @@ export class TilemapPlugin implements Plugin {// rotation-invariant). Pixel-verified against Tiled's rendering.for (const group of cached.objectGroups ?? []) {if (group.visible === false) continue;+ // A `collision` group's shapes are SOLID geometry (walls/floors) —+ // the play-mode collider path handles them; a non-collision group's+ // shapes are trigger REGIONS → Trigger-Area entities below.+ const isCollision = isCollisionObjectGroup(group);for (const obj of group.objects) {if (obj.visible === false) continue;- // Non-tile objects: a POINT converges to a real Marker entity- // (spawn point / waypoint), so imported and hand-authored- // markers share ONE `Query(Marker)` surface. World-only- // (re-derived from the .tmj each load, like the tile-object- // sprites), parented so its local position is the object's map- // offset (Tiled anchors the point at x,y, y-down; world Y up).- // Other shapes (rect/ellipse/polygon) stay collision-group- // colliders — not projected here.+ // Non-tile objects converge to real, parented, RuntimeOnly+ // entities (re-derived from the .tmj each load, like the+ // tile-object sprites), so imported and hand-authored objects+ // share ONE `Query(Marker)` surface: a POINT → a Marker (spawn+ // point / waypoint); a rect/ellipse/polygon in a non-collision+ // group → a Trigger Area (Marker + sensor collider, gizmo-visible).if (obj.gid === undefined) {if (obj.shape === 'point') {// Carry the Tiled object's custom properties (stringified) so@@ -533,6 +535,9 @@ export class TilemapPlugin implements Plugin {world.insert(markerChild, RuntimeOnly, {});world.setParent(markerChild, entity);children.push(markerChild);+ } else if (!isCollision) {+ const trigger = spawnObjectTriggerArea(world, obj, entity, pixelsPerUnit);+ if (trigger != null) children.push(trigger);}continue;}diff --git a/sdk/tests/tilemap.test.ts b/sdk/tests/tilemap.test.tsindex 316ada058..aec51d521 100644--- a/sdk/tests/tilemap.test.ts+++ b/sdk/tests/tilemap.test.ts@@ -15,7 +15,7 @@ import {} from '../src/tilemap/tilesetCache';import {loadTiledMap, parseTmjJson, parseTmjWithExternals, resolveRelativePath, loadTiledCollisionObjects,- generateLayerCollision, generateObjectCollision, isCollisionObjectGroup, decodeTiledGid,+ generateLayerCollision, generateObjectCollision, spawnObjectTriggerArea, isCollisionObjectGroup, decodeTiledGid,packCollectionGrid,type TiledObjectData, type TiledObjectGroupData,} from '../src/tilemap/tiledLoader';@@ -25,8 +25,8 @@ import type { TilesetAsset } from '../src/tilemap/tilesetAsset';import { mergeCollisionTiles } from '../src/tilemap/collisionMerge';import { TilemapAssetLoader } from '../src/asset/loaders/TilemapAssetLoader';import type { LoadContext } from '../src/asset/AssetLoader';-import { BodyType } from '../src/physics/PhysicsComponents';-import { clearUserComponents } from '../src/component';+import { BodyType, RigidBody, BoxCollider, CircleCollider, PolygonCollider } from '../src/physics/PhysicsComponents';+import { clearUserComponents, Transform, Marker } from '../src/component';import type { World } from '../src/world';import type { Entity } from '../src/types';@@ -1436,6 +1436,45 @@ describe('loadTiledMap — collision integration', () => {expect(entities).toHaveLength(1);});+ describe('spawnObjectTriggerArea (object → Trigger Area convergence)', () => {+ const obj = (over: Partial<Record<string, unknown>>) => ({+ id: 7, name: 'gate', type: 'door', visible: true, rotation: 0,+ x: 100, y: 50, width: 40, height: 20, vertices: null,+ properties: new Map([['event', 'open']]),+ ...over,+ }) as never;++ it('rect → parented Marker + static body + SENSOR box (metres), custom props carried', () => {+ const world = createMockWorld();+ const parent = world.spawn();+ const e = spawnObjectTriggerArea(world, obj({ shape: 'rect' }), parent, 100);+ expect(e).not.toBeNull();+ expect(world.get(e!, Marker)).toEqual({ type: 'door', properties: { event: 'open' } });+ expect(world.get(e!, RigidBody).bodyType).toBe(0); // Static+ const box = world.get(e!, BoxCollider);+ expect(box.isSensor).toBe(true);+ expect(box.halfExtents).toEqual({ x: 40 * 0.5 / 100, y: 20 * 0.5 / 100 });+ expect(world.get(e!, Transform).position).toEqual({ x: 120, y: -60, z: 0 }); // local centre, y-up+ expect(world.setParent).toHaveBeenCalledWith(e, parent);+ });++ it('ellipse → SENSOR circle on the mean semi-axis', () => {+ const world = createMockWorld();+ const e = spawnObjectTriggerArea(world, obj({ shape: 'ellipse', width: 80, height: 40 }), world.spawn(), 100);+ const c = world.get(e!, CircleCollider);+ expect(c.isSensor).toBe(true);+ expect(c.radius).toBeCloseTo((80 + 40) * 0.25 / 100);+ });++ it('polygon (≤8 pts) → SENSOR polygon; point/polyline → null (projected elsewhere)', () => {+ const world = createMockWorld();+ const poly = spawnObjectTriggerArea(world, obj({ shape: 'polygon', vertices: [0, 0, 30, 0, 30, 30] }), world.spawn(), 100);+ expect(world.get(poly!, PolygonCollider).isSensor).toBe(true);+ expect(spawnObjectTriggerArea(world, obj({ shape: 'point' }), world.spawn(), 100)).toBeNull();+ expect(spawnObjectTriggerArea(world, obj({ shape: 'polyline', vertices: [0, 0, 10, 10] }), world.spawn(), 100)).toBeNull();+ });+ });+it('should generate tile collision from collisionTileIds option', () => {const world = createMockWorld();const tiles = new Uint16Array([1, 1, 0, 0]);