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.

11.5 KB
Raw Blame
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
 * Scene Report — a worked example of an Estella editor plugin.
 *
 * It shows the three contribution kinds a plugin usually needs, and the two rules
 * that matter:
 *
 *   - Register through `ctx`, never through a global. Every registration is
 *     attributed to this plugin, which is what lets the editor unload or reload it
 *     cleanly (try editing this file — the editor recompiles and re-activates it).
 *
 *   - Mutate the scene through `ctx.scene`. Those writes go through the editor's
 *     command layer, so they land in the undo history and survive Play → Stop.
 *     Reaching around it to the live engine would lose both.
 *
 * Written in TypeScript with no build step: the editor compiles it, and the typings
 * come from `.esengine/plugins/.types/editor-api.d.ts`, which the editor keeps in
 * sync with itself (see tsconfig.json next to this file).
 */
import { definePlugin, type PluginContext } from '@estella/editor-api';

/** Count entities and how often each component type appears. */
function summarize(ctx: PluginContext): { entities: number; components: Map<string, number> } {
  const components = new Map<string, number>();
  let entities = 0;
  const walk = (nodes: ReturnType<PluginContext['scene']['getSceneTree']>): void => {
    for (const node of nodes) {
      entities++;
      for (const type of ctx.scene.getEntity(node.id)?.components ?? []) {
        components.set(type, (components.get(type) ?? 0) + 1);
      }
      if (node.children?.length) walk(node.children);
    }
  };
  walk(ctx.scene.getSceneTree());
  return { entities, components };
}

export default definePlugin({
  activate(ctx: PluginContext) {
    // — A command. Lands in the command palette and in the Tools menu; its label,
    //   shortcut, and enablement all come from this one declaration. —
    ctx.commands.register({
      id: 'estella.scene-report.logSummary',
      title: { en: 'Log Scene Summary', 'zh-CN': '输出场景摘要' },
      category: { en: 'Scene Report', 'zh-CN': '场景报告' },
      menu: 'tools',
      run: () => {
        const { entities, components } = summarize(ctx);
        ctx.log.info(`${entities} entities, ${components.size} distinct component types`);
        ctx.ui.toast(`Scene has ${entities} entities`, 'info');
      },
    });

    // — A command that WRITES. One transact() call is one undo step, however many
    //   edits it makes: ⌘Z takes all of it back together. —
    ctx.commands.register({
      id: 'estella.scene-report.nameUnnamed',
      title: { en: 'Name Unnamed Entities', 'zh-CN': '命名未命名实体' },
      category: { en: 'Scene Report', 'zh-CN': '场景报告' },
      menu: 'tools',
      isEnabled: () => ctx.scene.getSceneTree().length > 0,
      run: () => {
        ctx.scene.transact('Name Unnamed Entities', () => {
          let n = 0;
          for (const node of ctx.scene.getSceneTree()) {
            if (/^entity$/i.test(node.name)) ctx.scene.renameEntity(node.id, `Entity ${++n}`);
          }
        });
      },
    });

    // — A setting. Appears under Settings ▸ Plugins ▸ Scene Report. —
    ctx.settings.register({
      id: 'estella.scene-report.showComponents',
      type: 'boolean',
      default: true,
      label: { en: 'Show component breakdown', 'zh-CN': '显示组件明细' },
      description: {
        en: 'List component counts in the Scene Report panel.',
        'zh-CN': '在场景报告面板中列出组件数量。',
      },
    });

    // — A panel. `mount` gets a plain host element and returns its teardown; the
    //   editor owns the tab, the dirty dot, the error boundary, and pop-out. Style
    //   against the editor's CSS variables and it matches the surrounding chrome. —
    ctx.panels.register({
      id: 'estella.scene-report.panel',
      title: { en: 'Scene Report', 'zh-CN': '场景报告' },
      placement: 'bottom',
      mount: (host) => {
        const root = document.createElement('div');
        root.style.cssText = 'padding:10px;display:flex;flex-direction:column;gap:8px;font-size:11px;color:var(--text)';
        host.append(root);

        const render = (): void => {
          const { entities, components } = summarize(ctx);
          const showComponents = ctx.settings.get<boolean>('estella.scene-report.showComponents') ?? true;
          const selection = ctx.scene.getSelection();
          const selected = selection != null ? ctx.scene.getEntity(selection) : null;

          root.replaceChildren();
          const line = (label: string, value: string): void => {
            const row = document.createElement('div');
            row.style.cssText = 'display:flex;gap:8px';
            const k = document.createElement('span');
            k.style.cssText = 'color:var(--text-dim);min-width:110px';
            k.textContent = label;
            const v = document.createElement('span');
            v.style.cssText = 'color:var(--text-hi);font-weight:600';
            v.textContent = value;
            row.append(k, v);
            root.append(row);
          };

          line('Entities', String(entities));
          line('Scene', ctx.project.currentScene() ?? '—');
          line('Selected', selected ? `${selected.name} (${selected.components.length} components)` : '—');
          if (showComponents) {
            const list = [...components].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]));
            for (const [type, count] of list) line(`  ${type}`, String(count));
          }
        };

        render();
        // Re-render on the events that change what's displayed. Both handlers are
        // retracted when the plugin unloads, so no listener outlives it.
        const offSelection = ctx.events.on('selectionChanged', render);
        const offScene = ctx.events.on('sceneChanged', render);
        return () => {
          offSelection.dispose();
          offScene.dispose();
        };
      },
    });

    // — An inspector section. It renders through the editor's own property UI, so it
    //   looks native without any styling; `write` receives edits to the rows it
    //   built, and wrapping the scene write in transact() makes it one undo step. —
    ctx.inspector.register({
      kind: 'component',
      id: 'transform-report',
      component: 'Transform',
      title: { en: 'Scene Report', 'zh-CN': '场景报告' },
      build: (entity, ui) => {
        const e = ctx.scene.getEntity(entity);
        ui.info({ en: 'Components', 'zh-CN': '组件数' }, String(e?.components.length ?? 0));
        ui.info({ en: 'Children', 'zh-CN': '子实体' }, String(countChildren(ctx, entity)));
        ui.text('label', { en: 'Report label', 'zh-CN': '报告标签' }, e?.name ?? '');
      },
      action: {
        label: { en: 'Log', 'zh-CN': '输出' },
        run: (entity) => ctx.log.info(`entity ${entity}: ${ctx.scene.getEntity(entity)?.name}`),
      },
      // Renaming through ctx.scene means the edit is undoable like any other.
      write: (entity, key, value) => {
        if (key === 'label') ctx.scene.transact('Rename from Scene Report', () => ctx.scene.renameEntity(entity, String(value)));
      },
    });

    // — A viewport overlay. Coordinates are WORLD space and the host projects them,
    //   so this gizmo tracks the scene through pan and zoom with no camera math. —
    ctx.overlays.register({
      id: 'selection-ring',
      render: (g) => {
        const id = ctx.scene.getSelection();
        if (id == null) return;
        const p = ctx.scene.getFieldValue(id, 'Transform', 'position');
        if (!Array.isArray(p)) return;
        const at = { x: p[0], y: p[1] };
        // A world-unit radius, so the ring scales with the scene rather than
        // staying a fixed number of pixels.
        g.circle(at, 48, { color: 'var(--star)', width: 1.5, dashed: true });
        g.line({ x: at.x - 64, y: at.y }, { x: at.x + 64, y: at.y }, { color: 'var(--star)', opacity: 0.5 });
        g.text({ x: at.x + 52, y: at.y + 52 }, ctx.scene.getEntity(id)?.name ?? '', { fontSize: 11 });
      },
    });

    // — A viewport tool. Armed via its command; while armed it gets first refusal on
    //   every stroke, and picking any built-in tool disarms it. —
    let dragFrom: { x: number; y: number } | null = null;
    ctx.overlays.register({
      id: 'measure-line',
      render: (g) => {
        if (!dragFrom || !dragTo) return;
        g.line(dragFrom, dragTo, { color: '#e0a35a', width: 2 });
        const dx = dragTo.x - dragFrom.x;
        const dy = dragTo.y - dragFrom.y;
        g.text(dragTo, `${Math.hypot(dx, dy).toFixed(1)} wu`, { color: '#e0a35a' });
      },
    });
    let dragTo: { x: number; y: number } | null = null;
    ctx.tools.register({
      id: 'estella.scene-report.measure',
      title: { en: 'Measure', 'zh-CN': '测距' },
      onPointerDown: (p, tc) => {
        // Pointer input arrives in viewport space, the same space ctx.viewport
        // projects from — no conversion needed.
        dragFrom = ctx.viewport.viewportToWorld(p.x, p.y);
        dragTo = dragFrom;
        tc.capture(p.pointerId);
        return true; // claim the stroke
      },
      onPointerMove: (p) => {
        if (dragFrom) dragTo = ctx.viewport.viewportToWorld(p.x, p.y);
      },
      onPointerUp: (p, tc) => {
        tc.release(p.pointerId);
        if (dragFrom && dragTo) {
          ctx.log.info(`measured ${Math.hypot(dragTo.x - dragFrom.x, dragTo.y - dragFrom.y).toFixed(2)} world units`);
        }
        dragFrom = dragTo = null;
      },
      cancel: () => {
        dragFrom = dragTo = null;
      },
    });
    ctx.commands.register({
      id: 'estella.scene-report.measureTool',
      title: { en: 'Measure Tool', 'zh-CN': '测距工具' },
      category: { en: 'Scene Report', 'zh-CN': '场景报告' },
      menu: 'tools',
      isChecked: () => ctx.tools.activeId() === 'estella.scene-report.measure',
      run: () =>
        ctx.tools.activate(
          ctx.tools.activeId() === 'estella.scene-report.measure' ? null : 'estella.scene-report.measure',
        ),
    });

    // — An entity template. The host builds the prefab from these component specs,
    //   so it appears in the Create picker beside the built-in ones. —
    ctx.entities.registerTemplate({
      id: 'estella.scene-report.marker',
      label: { en: 'Report Marker', 'zh-CN': '报告标记' },
      category: 'Scripts',
      keywords: ['report', 'marker'],
      components: [{ type: 'Transform' }, { type: 'Marker', data: { type: 'report' } }],
    });

    // — A context-menu row. `when` hides it for targets it doesn't apply to, and the
    //   host drops the separator with it, so the menu never shows a stray divider. —
    ctx.contextMenus.register({
      id: 'estella.scene-report.logEntity',
      location: 'outliner/item',
      label: { en: 'Log to Scene Report', 'zh-CN': '输出到场景报告' },
      when: (target) => target.entity != null,
      run: (target) => ctx.log.info(`outliner: ${ctx.scene.getEntity(target.entity!)?.name}`),
    });

    ctx.log.info('scene report ready');
  },
});

/** Direct children of an entity, from the scene tree. */
function countChildren(ctx: PluginContext, entity: number): number {
  const find = (nodes: ReturnType<PluginContext['scene']['getSceneTree']>): number | null => {
    for (const n of nodes) {
      if (n.id === entity) return n.children?.length ?? 0;
      const hit = n.children ? find(n.children) : null;
      if (hit !== null) return hit;
    }
    return null;
  };
  return find(ctx.scene.getSceneTree()) ?? 0;
}