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(examples): add a chat demo — ListView log + TextInput composer
yhhafcdbf16ba6d
diff --git a/examples/chat/.gitignore b/examples/chat/.gitignorenew file mode 100644index 000000000..359472ac2--- /dev/null+++ b/examples/chat/.gitignore@@ -0,0 +1,7 @@+node_modules/+dist/+.vscode/+.idea/+.DS_Store+Thumbs.db+.esengine/cache/diff --git a/examples/chat/README.md b/examples/chat/README.mdnew file mode 100644index 000000000..e9fdf72f8--- /dev/null+++ b/examples/chat/README.md@@ -0,0 +1,30 @@+# Chat++The clearest showcase for two UI widgets working together:++- **`createListView`** — the message log. A virtualized list that recycles ~10+ entities for the entire history, so it stays cheap no matter how long the+ conversation grows. New messages auto-scroll into view via `scrollToIndex`.+- **`createTextInput`** — the composer field at the bottom, paired with a Send+ button. Pressing **Enter** or clicking **Send** appends your message and a+ canned bot reply.++## How it works++The scene (`assets/scenes/main.esscene`) lays out a `Panel` with three named+slots — `Title`, `MessagesSlot`, and `ComposerRow`. The startup `BuildSystem`+(`src/systems/build.ts`) finds those slots and mounts the widgets into them:++- Each list row pools a **left** (them) and a **right** (you) bubble, pinned at+ create time. `bind()` only enables the sender's side and fills its label —+ never touches layout — so recycling a row is a couple of component writes.+- The composer's `onSubmit` and the button's `onClick` share one `send()`:+ append your line, clear the field, then append the bot's answer.++The bot (`src/config.ts`) is deterministic — no randomness — so reloads read+identically.++## Run++Open the folder in the Estella editor and press **Play**, or build and run it+like the other examples.diff --git a/examples/chat/assets/scenes/main.esscene b/examples/chat/assets/scenes/main.esscenenew file mode 100644index 000000000..07abd022c--- /dev/null+++ b/examples/chat/assets/scenes/main.esscene@@ -0,0 +1,132 @@+{+ "version": "1.0",+ "name": "Main",+ "entities": [+ {+ "id": 0,+ "name": "Camera",+ "parent": null,+ "children": [],+ "components": [+ { "type": "Transform", "data": { "position": { "x": 0, "y": 0, "z": 10 } } },+ {+ "type": "Camera",+ "data": { "projectionType": 1, "orthoSize": 300, "isActive": true, "priority": 0 }+ }+ ],+ "visible": true+ },+ {+ "id": 1,+ "name": "Canvas",+ "parent": null,+ "children": [2],+ "components": [+ { "type": "Transform", "data": {} },+ {+ "type": "Canvas",+ "data": { "designResolution": { "x": 800, "y": 600 }, "scaleMode": 2 }+ },+ { "type": "UINode", "data": {} }+ ],+ "visible": true+ },+ {+ "id": 2,+ "name": "Panel",+ "parent": 1,+ "children": [3, 4, 5],+ "components": [+ { "type": "Transform", "data": {} },+ {+ "type": "UINode",+ "data": {+ "position": 1,+ "insetLeft": { "value": 20, "unit": 0 },+ "insetTop": { "value": 20, "unit": 0 },+ "insetRight": { "value": 20, "unit": 0 },+ "insetBottom": { "value": 20, "unit": 0 }+ }+ },+ {+ "type": "FlexContainer",+ "data": {+ "direction": 1,+ "justifyContent": 0,+ "alignItems": 3,+ "gap": { "x": 0, "y": 10 },+ "padding": { "left": 20, "top": 20, "right": 20, "bottom": 20 }+ }+ },+ {+ "type": "UIVisual",+ "data": {+ "visualType": 1,+ "color": { "r": 0.16, "g": 0.16, "b": 0.18, "a": 1 },+ "enabled": true+ }+ }+ ],+ "visible": true+ },+ {+ "id": 3,+ "name": "Title",+ "parent": 2,+ "children": [],+ "components": [+ { "type": "Transform", "data": {} },+ { "type": "UINode", "data": { "height": { "value": 28, "unit": 0 } } },+ {+ "type": "Text",+ "data": {+ "content": "Chat — ListView log + TextInput composer",+ "fontSize": 20,+ "bold": true,+ "color": { "r": 1, "g": 1, "b": 1, "a": 1 },+ "align": 0,+ "verticalAlign": 1+ }+ }+ ],+ "visible": true+ },+ {+ "id": 4,+ "name": "MessagesSlot",+ "parent": 2,+ "children": [],+ "components": [+ { "type": "Transform", "data": {} },+ {+ "type": "UINode",+ "data": {+ "width": { "value": 720, "unit": 0 },+ "height": { "value": 424, "unit": 0 }+ }+ }+ ],+ "visible": true+ },+ {+ "id": 5,+ "name": "ComposerRow",+ "parent": 2,+ "children": [],+ "components": [+ { "type": "Transform", "data": {} },+ { "type": "UINode", "data": { "height": { "value": 40, "unit": 0 } } },+ {+ "type": "FlexContainer",+ "data": {+ "direction": 0,+ "justifyContent": 0,+ "alignItems": 1,+ "gap": { "x": 10, "y": 0 }+ }+ }+ ],+ "visible": true+ }+ ]+}diff --git a/examples/chat/assets/scenes/main.esscene.meta b/examples/chat/assets/scenes/main.esscene.metanew file mode 100644index 000000000..5dd415833--- /dev/null+++ b/examples/chat/assets/scenes/main.esscene.meta@@ -0,0 +1,8 @@+{+ "uuid": "e2c1a7d4-9b63-4f05-a8e1-3c7f0b52d6a9",+ "version": "2.0",+ "type": "scene",+ "importer": {+ "autoMigrate": true+ }+}diff --git a/examples/chat/project.esproject b/examples/chat/project.esprojectnew file mode 100644index 000000000..318a32a5f--- /dev/null+++ b/examples/chat/project.esproject@@ -0,0 +1,13 @@+{+ "formatVersion": "1",+ "name": "Chat",+ "description": "A chat UI — a virtualized ListView log with a TextInput composer.",+ "tag": "UI",+ "version": "0.1.0",+ "defaultScene": "assets/scenes/main.esscene",+ "designResolution": {+ "width": 800,+ "height": 600+ },+ "spineVersion": "none"+}diff --git a/examples/chat/src/config.ts b/examples/chat/src/config.tsnew file mode 100644index 000000000..f07e78bc2--- /dev/null+++ b/examples/chat/src/config.ts@@ -0,0 +1,52 @@+import type { Color } from 'esengine';++// The message log is a virtualized createListView; its viewport size must be+// known up front (scroll math), and the MessagesSlot box in the scene matches.+export const CHAT_W = 720;+export const CHAT_H = 424;++// Fixed-height rows (the list recycles a handful of entities): a bubble plus an+// 8px gap. Bubbles are pinned left (them) or right (you) at a fixed max width.+export const ROW_H = 60;+export const ROW_SPACING = 8;+export const BUBBLE_W = 460;+// Right-side bubbles leave a gutter so they clear the scroll edge.+export const RIGHT_GUTTER = 24;++export const COMPOSER_H = 40;+export const SEND_W = 84;+export const INPUT_W = CHAT_W - SEND_W - 10; // + the row's 10px gap = CHAT_W++export type Sender = 'me' | 'bot';+export interface Message {+ id: number;+ from: Sender;+ text: string;+}++export const ME_BUBBLE: Color = { r: 0.20, g: 0.45, b: 0.85, a: 1 };+export const BOT_BUBBLE: Color = { r: 0.24, g: 0.24, b: 0.28, a: 1 };+export const BUBBLE_TEXT: Color = { r: 0.96, g: 0.96, b: 0.98, a: 1 };++// A canned, deterministic bot so reloads read identically (no randomness).+const REPLIES = [+ 'createListView recycles ~10 entities for the whole log — scroll to see.',+ 'Each bubble is one pooled row, re-bound as it enters the viewport.',+ 'The box below is a TextInput widget; Enter or Send appends a message.',+ 'New messages jump the list to the bottom via scrollToIndex.',+ 'Type a few more — the list virtualizes as many as you like.',+];++export function botReply(userText: string, turn: number): string {+ if (/\b(hi|hey|hello)\b/i.test(userText)) return 'Hey! Ask me anything about this demo.';+ if (userText.endsWith('?')) return 'Good question — try scrolling the log while you type.';+ return REPLIES[turn % REPLIES.length];+}++// A short opening conversation so the log is not empty on load.+export const SEED: { from: Sender; text: string }[] = [+ { from: 'bot', text: 'Welcome to the chat demo.' },+ { from: 'bot', text: 'This log is a virtualized ListView; the field below is a TextInput.' },+ { from: 'me', text: 'Nice — how do I send a message?' },+ { from: 'bot', text: 'Type below and press Enter, or click Send.' },+];diff --git a/examples/chat/src/main.ts b/examples/chat/src/main.tsnew file mode 100644index 000000000..0cf96defa--- /dev/null+++ b/examples/chat/src/main.ts@@ -0,0 +1,9 @@+// Chat — the clearest showcase for two UI widgets working together: a virtualized+// message log (createListView, recycling ~10 entities for the whole history) and+// an editable composer (createTextInput) with a Send button. Enter or Send appends+// your message and a canned bot reply, and the list auto-scrolls to the newest.+import { addStartupSystem } from 'esengine';++import { buildSystem } from './systems/build';++addStartupSystem(buildSystem);diff --git a/examples/chat/src/state.ts b/examples/chat/src/state.tsnew file mode 100644index 000000000..cc8bcaf08--- /dev/null+++ b/examples/chat/src/state.ts@@ -0,0 +1,14 @@+import type { ListViewHandle, ArrayDataSource, TextInputHandle } from 'esengine';++import type { Message } from './config';++export const state = {+ list: null as ListViewHandle<Message> | null,+ // The backing store: list.data is the readonly DataSource view; mutations+ // (append) live on ArrayDataSource.+ messages: null as ArrayDataSource<Message> | null,+ input: null as TextInputHandle | null,+ nextId: 0,+ botTurn: 0,+ built: false,+};diff --git a/examples/chat/src/systems/build.ts b/examples/chat/src/systems/build.tsnew file mode 100644index 000000000..b97e673b9--- /dev/null+++ b/examples/chat/src/systems/build.ts@@ -0,0 +1,162 @@+import {+ defineSystem, Res, GetWorld,+ UIEvents,+ UIVisual, Text,+ uiPlugin,+ createListView, createButton, createTextInput,+ ArrayDataSource,+ spawnUIEntity,+ themeColors, px,+ UIPositionType, TextVerticalAlign, TextAlign,+} from 'esengine';+import type {+ Entity, World, Color, UIEventQueue, UIVisualData, TextData,+ ListItemTemplate,+} from 'esengine';++import {+ CHAT_W, CHAT_H, ROW_H, ROW_SPACING, BUBBLE_W, RIGHT_GUTTER,+ COMPOSER_H, SEND_W, INPUT_W,+ ME_BUBBLE, BOT_BUBBLE, BUBBLE_TEXT,+ botReply, SEED,+ type Message, type Sender,+} from '../config';+import { state } from '../state';++// One row pools BOTH a left (them) and a right (you) bubble, pinned at create+// time; bind() just enables the sender's side and fills its label. Only UIVisual+// + Text are mutated per bind — never layout — so recycling stays cheap.+interface Side { bubble: Entity; label: Entity; }+const rowSides = new Map<Entity, { me: Side; bot: Side }>();++const LIST_BG: Color = { r: 0.11, g: 0.11, b: 0.13, a: 1 };++export const buildSystem = defineSystem(+ [Res(UIEvents), GetWorld()],+ (events: UIEventQueue, world: World) => {+ if (state.built) return;+ const messagesSlot = world.findEntityByName('MessagesSlot');+ const composerRow = world.findEntityByName('ComposerRow');+ if (messagesSlot === null || composerRow === null) return;+ state.built = true;++ const c = themeColors();++ const messages = new ArrayDataSource<Message>([]);+ state.messages = messages;++ const makeSide = (w: World, row: Entity, mine: boolean): Side => {+ const bubble = spawnUIEntity({+ world: w, parent: row,+ node: {+ position: UIPositionType.Absolute,+ insetLeft: px(mine ? CHAT_W - BUBBLE_W - RIGHT_GUTTER : 12),+ insetTop: px(0),+ width: px(BUBBLE_W),+ height: px(ROW_H - ROW_SPACING),+ },+ visual: { color: mine ? ME_BUBBLE : BOT_BUBBLE, enabled: false },+ });+ const label = spawnUIEntity({+ world: w, parent: bubble,+ node: {+ position: UIPositionType.Absolute,+ insetLeft: px(12), insetRight: px(12), insetTop: px(0), insetBottom: px(0),+ },+ text: {+ content: '', fontSize: 14, color: BUBBLE_TEXT,+ align: mine ? TextAlign.Right : TextAlign.Left,+ verticalAlign: TextVerticalAlign.Middle, wordWrap: true,+ },+ });+ return { bubble, label };+ };++ const rowTemplate: ListItemTemplate<Message> = {+ create: (w, parent) => {+ const row = spawnUIEntity({ world: w, parent });+ rowSides.set(row, { me: makeSide(w, row, true), bot: makeSide(w, row, false) });+ return row;+ },+ bind: (row, msg) => {+ const sides = rowSides.get(row);+ if (!sides) return;+ const on = msg.from === 'me' ? sides.me : sides.bot;+ const off = msg.from === 'me' ? sides.bot : sides.me;+ setVisible(world, on.bubble, true);+ setVisible(world, off.bubble, false);+ setText(world, on.label, msg.text);+ setText(world, off.label, '');+ },+ };++ state.list = createListView<Message>({+ host: uiPlugin,+ world, parent: messagesSlot,+ viewportSize: { x: CHAT_W, y: CHAT_H },+ background: { color: LIST_BG },+ data: messages,+ layout: { itemHeight: ROW_H, spacing: ROW_SPACING },+ item: rowTemplate,+ });++ // Composer: a fixed-width TextInput + a primary Send button, side by side.+ state.input = createTextInput({+ world, events, parent: composerRow,+ node: { width: px(INPUT_W), height: px(COMPOSER_H) },+ placeholder: 'Type a message and press Enter…',+ fontSize: 14,+ onSubmit: send,+ });++ createButton({+ world, events, parent: composerRow,+ node: { width: px(SEND_W), height: px(COMPOSER_H) },+ states: {+ normal: { color: c.primary },+ hover: { color: c.primary },+ pressed: { color: c.primary },+ },+ text: { content: 'Send', color: c.onPrimary, fontSize: 14 },+ onClick: send,+ });++ for (const m of SEED) append(m.from, m.text);+ },+ { name: 'BuildSystem' },+);++/** Append a message and keep the newest in view. */+function append(from: Sender, text: string): void {+ const messages = state.messages;+ if (!messages) return;+ messages.append([{ id: state.nextId++, from, text }]);+ state.list?.scrollToIndex(messages.getCount() - 1);+}++/** Send the composed text, then let the canned bot answer. */+function send(): void {+ const input = state.input;+ if (!input || !state.messages) return;+ const text = input.getValue().trim();+ if (!text) return;+ append('me', text);+ input.setValue('');+ append('bot', botReply(text, state.botTurn++));+}++function setVisible(world: World, entity: Entity, on: boolean): void {+ if (!world.valid(entity) || !world.has(entity, UIVisual)) return;+ const v = world.get(entity, UIVisual) as UIVisualData;+ if (v.enabled === on) return;+ v.enabled = on;+ world.insert(entity, UIVisual, v);+}++function setText(world: World, entity: Entity, content: string): void {+ if (!world.valid(entity) || !world.has(entity, Text)) return;+ const t = world.get(entity, Text) as TextData;+ if (t.content === content) return;+ t.content = content;+ world.insert(entity, Text, t);+}diff --git a/examples/chat/tsconfig.json b/examples/chat/tsconfig.jsonnew file mode 100644index 000000000..0a8528b29--- /dev/null+++ b/examples/chat/tsconfig.json@@ -0,0 +1,22 @@+{+ "compilerOptions": {+ "target": "ES2020",+ "module": "ESNext",+ "moduleResolution": "bundler",+ "strict": true,+ "esModuleInterop": true,+ "skipLibCheck": true,+ "forceConsistentCasingInFileNames": true,+ "declaration": false,+ "outDir": "./dist",+ "rootDir": ".",+ "baseUrl": ".",+ "paths": {+ "esengine": ["./.esengine/sdk/index.d.ts"],+ "esengine/wasm": ["./.esengine/sdk/wasm.d.ts"],+ "@esengine/editor": ["./.esengine/editor/index.d.ts"]+ }+ },+ "include": ["src/**/*"],+ "exclude": ["node_modules"]+}