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.

22.6 KB
Raw Blame
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
 * @file  check-project-settings.mjs — a project setting reaches everything, or says why not.
 *
 * A setting like "this layer resolves by depth" is only as real as its
 * least-remembered site. The 2.5D depth mask was declared in the manifest,
 * parsed, shown in Project Settings, and sent to the play realm — and reached
 * neither the edit viewport nor ANY exported build, because the editor and the
 * export each restate the list of settings by hand. It looked right in Play and
 * shipped wrong, which is the one failure this file exists to make impossible.
 *
 * So the derivation lives once (pipeline/src/project/runtimeConfig.ts) and this
 * checks that every field of it is actually carried by each consumer:
 *
 *   parse     the manifest reader (format.ts) has a branch for the feature — that
 *             reader is a WHITELIST, so a field that persists and has no branch
 *             looks completely inert
 *   editor    applied to the edit session, so authoring shows what ships
 *   play      forwarded into the play realm
 *   packaged  written into a shipped build
 *   authoring a CREATOR can set it, and this says where
 *
 * A field that legitimately cannot reach one of them declares that HERE, with a
 * reason. The point is not that everything reaches everywhere; it is that a gap
 * is a sentence somebody wrote, not an omission nobody noticed.
 *
 * `authoring` is the one that is not about transport. The four above ask whether
 * a value SURVIVES the trip; that question was green for `msaaSamples` while the
 * only way to set it was to hand-edit project.esproject, because nothing here
 * asked whether a human could reach it at all. So it answers a different
 * question, and it has its own vocabulary:
 *
 *   ui        a row in the settings registry — the id is named and checked. That a
 *             row EXISTS, not that it writes: a control bound to nothing but React
 *             state passes here and fails check-mutator-parity, which is the half
 *             that asks whether a person's edit reaches the project
 *   manual    deliberately manifest-only (advanced, or edited as a file), + why
 *   internal  not creator-authored: derived, or a machine's business, + why
 *   owed      creator-facing, reachable from no editor surface. Debt, recorded
 *             as debt — an entry leaves by growing a UI, never by being explained
 *
 * No answer is not an option: a setting nobody decided about fails here.
 */
import { readFileSync, existsSync } from 'node:fs';
import { execFileSync } from 'node:child_process';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const read = (rel) => readFileSync(path.join(ROOT, rel), 'utf8');

const RUNTIME_CONFIG = 'pipeline/src/project/runtimeConfig.ts';
const FORMAT = 'pipeline/src/project/format.ts';
const STORE = 'desktop/src/project/ProjectStore.ts';
/** Where a project setting becomes a row a creator can see. */
const SETTINGS = 'desktop/src/settings/projectSettings.ts';
/** The rows built from a block's own keys live beside it; they count as the same surface. */
const SETTINGS_FILES = [SETTINGS, 'desktop/src/settings/qualitySettings.ts', 'desktop/src/settings/runtimeSettings.ts'];

/**
 * Where each field of RuntimeProjectConfig has to show up, and the reason when
 * it deliberately does not. `null` = must be carried; a string = a declared gap,
 * printed by `--list` so the gaps stay visible rather than becoming folklore.
 */
const DECLARED_GAPS = {
  qualityModeNamed: {
    parse: 'read off the quality block in place, whether its mode is one parseQualityConfig keeps; it is no manifest key of its own',
    editor: 'the settings row reads the block as written (rawQuality), which says the same thing',
  },
  achievements: {
    editor: 'nothing unlocks one while a scene is being authored — edit mode runs no '
      + 'gameplay, so the set is checked in Play and in a shipped build',
  },
  steamAppId: {
    editor: 'edit mode is not a shipped game — a Steam client is brought up by the '
      + 'runtime, and Play rehearses that with the local provider',
    play: 'Play is not launched by Steam, so a client would refuse the ownership '
      + 'check; the local provider is what a rehearsal can honestly use',
  },
  physicsEnabled: {
    editor: 'edit mode does not simulate — bodies are authored, not stepped',
  },
  physics3dBackend: {
    editor: 'edit mode does not simulate — see physicsEnabled',
  },
  physicsConfig: {
    editor: 'edit mode does not simulate — see physicsEnabled',
  },
  colorSpace: {
    editor: 'boot-fixed — shaders compile against it, so the settings page asks '
      + 'for a reload rather than applying live (EngineHost.resolveColorSpace)',
  },
  renderBackend: {
    editor: 'the viewport runs the developer\'s own `renderer.backend` setting: which '
      + 'GPU a machine can drive is not the project\'s to decide, and a canvas cannot '
      + 'change context type once one is acquired',
    play: 'the play realm boots on the editor\'s own context; the two backends are held '
      + 'equal by the pixel gates (`verify-render --backend webgpu`) rather than by Play',
  },
  screenFit: {
    editor: 'the device preview reads it through projectSeams, not by applying it '
      + 'to the edit camera (the editor view is a free zoom by design)',
  },
  quality: {
    editor: 'the edit viewport stays at authored quality; Play previews the selected '
      + 'device tier and dynamic resolution through the same packaged app options',
  },
  uiThemeColors: {
    editor: 'applied together with uiTheme (one applyWidgetTheme call takes both)',
  },
  runtime: {
    editor: 'the edit viewport keeps the engine\'s own timeouts, budgets and frame limits so authoring behaves the same in every project; '
      + 'Play and a shipped build run under the declared values (initRuntime applies them before the first load)',
  },
};

/** The feature branch in the manifest parser each field is read from. */
const PARSE_KEY = {
  qualityModeNamed: 'r.quality',
  achievements: 'p.achievements',
  steamAppId: 'dt.steam',
  physicsEnabled: 'p.enabled',
  physicsConfig: 'physics',
  physics3dBackend: 'backend3d',
  physics3dWorld: 'world3d',
  audioConfig: 'parseAudioProjectConfig',
  runtime: 'parseRuntimeBuildConfig',
  uiTheme: 'u.theme',
  uiThemeColors: 'u.colors',
  ySortLayers: 'r.ySortLayers',
  depthLayers: 'r.depthLayers',
  colorSpace: 'r.colorSpace',
  outputTransform: 'r.outputTransform',
  renderBackend: 'r.backend',
  screenFit: 'r.cameraScaleMode',
  msaaSamples: 'r.msaa',
  quality: 'r.quality',
};

/**
 * How a CREATOR sets each field — see the header for the four answers. `ui` names
 * the settings-registry id, which is looked for in that file rather than trusted:
 * a claim of "there is a UI" that nobody checked is the same as no UI.
 */
const AUTHORING = {
  qualityModeNamed: { internal: 'derived from the quality block; the setting an author touches is `quality`' },
  achievements: { ui: 'project.packaging.achievements' },
  steamAppId: { ui: 'project.packaging.desktop.steam.appId' },
  physicsEnabled: { ui: 'project.physics.enabled' },
  physics3dBackend: { ui: 'project.physics.backend3d' },
  physics3dWorld: { ui: ['project.physics.world3d.'] },
  physicsConfig: { ui: ['project.physics.gravityX', 'project.physics.gravityY', 'project.physics.fixedTimestep'] },
  audioConfig: { ui: ['project.audio.maxVoices', 'project.audio.buses', 'project.audio.effects'] },
  runtime: { ui: ['project.runtime.'] },
  uiTheme: { ui: 'project.ui.theme' },
  uiThemeColors: { ui: 'project.ui.color.' },
  ySortLayers: { ui: 'project.rendering.ySortLayers' },
  depthLayers: { ui: 'project.rendering.depthLayers' },
  colorSpace: { ui: 'project.rendering.colorSpace' },
  outputTransform: { ui: 'project.rendering.outputTransform' },
  msaaSamples: { ui: 'project.rendering.msaa' },
  quality: { ui: 'project.rendering.quality' },
  renderBackend: { ui: 'project.rendering.backend' },
  screenFit: { ui: 'project.display.cameraFit' },
};

/** Field names of the RuntimeProjectConfig interface, in declaration order. */
function runtimeConfigFields(src) {
  const body = src.slice(src.indexOf('export interface RuntimeProjectConfig {'));
  const end = body.indexOf('\n}');
  return [...body.slice(0, end).matchAll(/^ {2}(\w+):/gm)].map((m) => m[1]);
}

const runtimeSrc = read(RUNTIME_CONFIG);
const formatSrc = read(FORMAT);
const storeSrc = read(STORE);
const settingsSrc = SETTINGS_FILES.map(read).join(String.fromCharCode(10));
const fields = runtimeConfigFields(runtimeSrc);

if (fields.length === 0) {
  console.error('check-project-settings: could not read RuntimeProjectConfig — has it moved?');
  process.exit(1);
}

// The consumers, each as "does this text carry the field". Deliberately textual:
// the alternative is importing the editor's module graph into a lint script.
const editorApplyAt = storeSrc.indexOf('private applyEditorRuntimeConfig');
const editorApply = storeSrc.slice(editorApplyAt, storeSrc.indexOf('\n  }\n', editorApplyAt));
const playPayload = storeSrc.slice(
  storeSrc.indexOf('playPayload()'),
  storeSrc.indexOf('audioFeature()'),
);
const packagedFields = runtimeSrc.slice(runtimeSrc.indexOf('export function packagedRuntimeFields'));

const inPackagedSlice = (f) => packagedFields.includes(`rc.${f}`);
const CONSUMERS = {
  parse: (f) => formatSrc.includes(PARSE_KEY[f] ?? f),
  editor: (f) => editorApply.includes(`rc.${f}`),
  // Either named in the payload, or carried by the packaged slice it spreads.
  play: (f) => playPayload.includes(`rc.${f}`)
    || (inPackagedSlice(f) && playPayload.includes('packagedRuntimeFields')),
  packaged: inPackagedSlice,
};

/**
 * The authoring answer for one field, as a problem string or null. Kept apart
 * from CONSUMERS because it is not the same question: those ask whether a value
 * survives a trip, this asks whether anybody can set it in the first place.
 */
function authoringProblem(field) {
  const answer = AUTHORING[field];
  if (!answer) {
    return `${field} says nothing about authoring — declare one of ui / manual / internal `
      + `in tools/check-project-settings.mjs (AUTHORING.${field}), or record it as owed`;
  }
  const [kind] = Object.keys(answer);
  if (kind === 'manual' || kind === 'internal' || kind === 'owed') {
    return answer[kind] ? null : `${field} declares "${kind}" with no reason`;
  }
  if (kind !== 'ui') return `${field} declares an unknown authoring kind "${kind}"`;
  const ids = Array.isArray(answer.ui) ? answer.ui : [answer.ui];
  // A trailing dot is a PREFIX, for the ids built in a loop (`project.ui.color.
  // ${role}`); anything else must appear quoted, because a bare substring test
  // let `project.rendering.msaaX` satisfy a claim about `project.rendering.msaa`.
  const missing = ids.filter((id) => (id.endsWith('.')
    ? !settingsSrc.includes(id)
    : !settingsSrc.includes(`'${id}'`)));
  return missing.length
    ? `${field} claims a settings row (${missing.join(', ')}) that ${SETTINGS} does not register`
    : null;
}

const problems = [];
const gaps = [];
const owed = [];
for (const field of fields) {
  for (const [role, carries] of Object.entries(CONSUMERS)) {
    const declared = DECLARED_GAPS[field]?.[role];
    const carried = carries(field);
    if (declared) {
      gaps.push(`  ${field} → ${role}: ${declared}`);
      // A declared gap that is now carried anyway is stale bookkeeping, not an error.
      continue;
    }
    if (!carried) {
      problems.push(
        `${field} never reaches "${role}". Either carry it there, or declare the gap `
        + `with a reason in tools/check-project-settings.mjs (DECLARED_GAPS.${field}.${role}).`,
      );
    }
  }
  const authoring = authoringProblem(field);
  if (authoring) problems.push(authoring);
  if (AUTHORING[field]?.owed) owed.push(`  ${field} → ${AUTHORING[field].owed}`);
  // A field nobody parses is a field a manifest can hold and nothing will read.
  if (!PARSE_KEY[field]) {
    problems.push(`${field} has no PARSE_KEY entry — say which manifest branch reads it.`);
  }
}


/**
 * The blocks inside a RuntimeProjectConfig field. A field passing the transport questions above says nothing about the keys it holds: `quality`
 * has one row for its level and thirty keys. Each block's keys are read from its interface and must say how a creator reaches them.
 *
 * `ui` is the settings id, looked for in the settings sources; an id built in a loop from the key (`project.rendering.quality.${row.key}`)
 * counts when its prefix is built that way and the key is named. `manual` and `internal` carry a reason; `owed` is debt.
 */
const BLOCKS = [
  {
    name: 'QualityConfig', file: 'sdk/src/render/quality.ts',
    keys: {
      mode: { ui: 'project.rendering.quality' },
      targetFps: { ui: 'project.rendering.qualityTargetFps' },
      dynamicResolution: { ui: 'project.rendering.dynamicResolution' },
      asyncShaderCompile: { ui: 'project.rendering.quality.asyncShaderCompile' },
      prewarmShaders: { ui: 'project.rendering.quality.prewarmShaders' },
      prewarmTimeoutMs: { ui: 'project.rendering.quality.prewarmTimeoutMs' },
      renderOnDemand: { ui: 'project.rendering.quality.renderOnDemand' },
      power: { ui: 'project.rendering.quality.power' },
      renderOnDemandTail: { ui: 'project.rendering.quality.renderOnDemandTail' },
      profiles: { ui: 'project.rendering.quality.renderScale' },
      deviceRules: { ui: 'project.rendering.qualityDeviceRules' },
    },
  },
  {
    name: 'QualityProfile', file: 'sdk/src/render/quality.ts',
    keys: {
      renderScale: { ui: 'project.rendering.quality.renderScale' },
      minRenderScale: { ui: 'project.rendering.quality.minRenderScale' },
      msaaSamples: { ui: 'project.rendering.quality.msaaSamples' },
      antialiasing: { ui: 'project.rendering.quality.antialiasing' },
      shadowAtlasSize: { ui: 'project.rendering.quality.shadowAtlasSize' },
      shadowCellSize: { ui: 'project.rendering.quality.shadowCellSize' },
      shadowCascades: { ui: 'project.rendering.quality.shadowCascades' },
      shadowDistance: { ui: 'project.rendering.quality.shadowDistance' },
      detailScale: { ui: 'project.rendering.quality.detailScale' },
      particleLimit: { ui: 'project.rendering.quality.particleLimit' },
      planarReflectionScale: { ui: 'project.rendering.quality.planarReflectionScale' },
      planarReflectionMaxSize: { ui: 'project.rendering.quality.planarReflectionMaxSize' },
      planarReflectionUpdatesPerSecond: { ui: 'project.rendering.quality.planarReflectionUpdatesPerSecond' },
      depthPrepass: { ui: 'project.rendering.quality.depthPrepass' },
      postProcess: { ui: 'project.rendering.quality.postProcess' },
      ssao: { ui: 'project.rendering.quality.effects' },
      waterWaves: { ui: 'project.rendering.quality.waterWaves' },
      waterRippleCells: { ui: 'project.rendering.quality.waterRippleCells' },
      waterDisplacement: { ui: 'project.rendering.quality.waterDisplacement' },
      waterMirror: { ui: 'project.rendering.quality.waterMirror' },
      waterCaustics: { ui: 'project.rendering.quality.waterCaustics' },
      shelterMaskSize: { ui: 'project.rendering.quality.shelterMaskSize' },
      shadowSoftSamples: { ui: 'project.rendering.quality.shadowSoftSamples' },
      lighting: { ui: 'project.rendering.quality.lighting' },
      dynamicGIReduced: { ui: 'project.rendering.quality.dynamicGIReduced' },
      drawCallBudget: { ui: 'project.rendering.quality.drawCallBudget' },
      textureStreaming: { ui: 'project.rendering.quality.textureStreaming' },
      textureStreamingBudget: { ui: 'project.rendering.quality.textureStreamingBudget' },
      skipEffects: { ui: 'project.rendering.quality.effects' },
    },
  },
  {
    name: 'RuntimeBuildConfig', file: 'sdk/src/defaults.ts',
    keys: Object.fromEntries([
      'sceneTransitionDuration', 'sceneTransitionColor', 'defaultFontFamily', 'maxDeltaTime', 'maxFixedSteps', 'textCanvasSize',
      'assetLoadTimeout', 'assetFailureCooldown', 'textureCacheBudget', 'audioCacheBudget', 'retainedBudget', 'multiTouch',
    ].map((k) => [k, { ui: `project.runtime.${k}` }])),
  },
];

/** The member names of an interface, from its source text. */
function interfaceKeys(src, name) {
  const at = src.indexOf(`export interface ${name} {`);
  if (at < 0) return null;
  const body = src.slice(at);
  const end = body.indexOf(String.fromCharCode(10) + '}');
  return [...body.slice(0, end).matchAll(/^ {4}(\w+)\??:/gm)].map((m) => m[1]);
}

/** Whether a settings id is registered: quoted as it stands, or built in a loop from its last segment under the same prefix. */
function rowRegistered(id) {
  if (settingsSrc.includes(`'${id}'`)) return true;
  const dot = id.lastIndexOf('.');
  const prefix = id.slice(0, dot + 1);
  const key = id.slice(dot + 1);
  return settingsSrc.includes(`\`${prefix}\${`) && settingsSrc.includes(`'${key}'`);
}

for (const block of BLOCKS) {
  const keys = interfaceKeys(read(block.file), block.name);
  if (!keys) { problems.push(`${block.name}: not found in ${block.file} — has it moved?`); continue; }
  for (const key of keys) {
    const answer = block.keys[key];
    if (!answer) {
      problems.push(`${block.name}.${key} says nothing about authoring — add it to BLOCKS in tools/check-project-settings.mjs `
        + 'with the settings row that sets it, or a manual / internal reason, or record it as owed');
      continue;
    }
    if (answer.ui && !rowRegistered(answer.ui)) problems.push(`${block.name}.${key} claims the row ${answer.ui}, which no settings file registers`);
    if (answer.owed) owed.push(`  ${block.name}.${key} → ${answer.owed}`);
    if ((answer.manual || answer.internal) === '') problems.push(`${block.name}.${key} declares a reason that is empty`);
  }
  for (const key of Object.keys(block.keys)) {
    if (!keys.includes(key)) problems.push(`${block.name}.${key} is declared here and no longer in the interface — remove the entry`);
  }
}

/**
 * Settings a creator can WRITE that are not RuntimeProjectConfig fields, so the
 * transport questions above never see them. An authoring surface proves only
 * that a value can be written; this asks whether anything CONSUMES it, and
 * refuses to let a `metadata-only` one be described as changing a build.
 */
const CONSUMPTION = {
  spineVersion: {
    kind: 'metadata-only',
    why: 'the runtimes a package carries are detected from its own skeletons '
      + '(sideModuleScan → detectSpineVersion) and decided per runtime by the Spine rows; nothing reads this field',
    /**
     * The readers that are not the settings UI. An agent tool's
     * description promised "the build bundles that runtime", which matches no
     * BUILD_PROMISE pattern — enumerating the ways to lie does not work. So the
     * rule is the row's: wherever it is described, it says what it does not do.
     */
    describedIn: ['desktop/shared/toolCatalog.mjs'],
  },
};
/** An absolute promise about what a build produces. Not the word "ships": the
 *  disclaimer has to be allowed to use it ("does not change what ships"). */
const BUILD_PROMISE = /and no other|package weighs|构建只会携带|决定了.*包体/;
const DISCLAIMS = /does not change what ships|不会改变最终打包/;
const MESSAGES = 'desktop/src/i18n/messages/settings.ts';
const messages = existsSync(path.join(ROOT, MESSAGES)) ? read(MESSAGES) : '';
/** Every tracked line naming `needle` under `dirs`, as `<path>:<line>`. */
function grep(needle, dirs) {
  try {
    return execFileSync('git', ['grep', '-nw', '--', needle, ...dirs],
      { cwd: ROOT, encoding: 'utf8' }).split('\n').filter(Boolean)
      .filter((l) => !l.includes('.generated.'));
  } catch {
    return []; // git grep exits 1 when nothing matches
  }
}
for (const [field, decl] of Object.entries(CONSUMPTION)) {
  if (!decl.why) problems.push(`${field} declares "${decl.kind}" consumption with no reason`);
  if (decl.kind !== 'metadata-only' && decl.kind !== 'unavailable') continue;
  // Ground truth against the declaration: a field that GAINS a reader must stop
  // calling itself metadata-only, or the note outlives the fact it described.
  // FORMAT declares the field's own type, which is not a reading of it.
  const readers = grep(field, ['sdk/src', 'pipeline/src']).filter((l) => !l.startsWith(FORMAT));
  if (readers.length) {
    problems.push(`${field} declares "${decl.kind}" but ${readers.length} site(s) now read it`
      + ` (${readers[0]}) — say what consumes it instead.`);
  }
  if (!messages) continue;
  for (const key of decl.saidBy ?? []) {
    const at = messages.indexOf(`'${key}'`);
    if (at < 0) { problems.push(`${field}: no message "${key}" to check what a creator is told`); continue; }
    const said = messages.slice(at, at + 700);
    if (BUILD_PROMISE.test(said)) {
      problems.push(`${field} is ${decl.kind}, and "${key}" promises a creator it decides what a build ships`);
    }
  }
  const dk = decl.disclaimedBy;
  const at = dk ? messages.indexOf(`'${dk}'`) : -1;
  if (dk && (at < 0 || !DISCLAIMS.test(messages.slice(at, at + 700)))) {
    problems.push(`${field} is ${decl.kind} and "${dk}" never says so — a row that reads like`
      + ' every other one is read as one that takes effect like every other one.');
  }
  for (const rel of decl.describedIn ?? []) {
    if (!existsSync(path.join(ROOT, rel))) {
      problems.push(`${field}: ${rel} is declared to describe it and is not there`);
      continue;
    }
    const text = read(rel);
    let from = text.indexOf(field);
    if (from < 0) {
      problems.push(`${field}: ${rel} is declared to describe it and never names it`);
      continue;
    }
    while (from >= 0) {
      if (!DISCLAIMS.test(text.slice(from, from + 400))) {
        const line = text.slice(0, from).split('\n').length;
        problems.push(`${field} is ${decl.kind}, and ${rel}:${line} describes it without saying so`
          + ' — a reader told what a setting is and not told it does nothing assumes it does something.');
      }
      from = text.indexOf(field, from + 1);
    }
  }
}

if (process.argv.includes('--list')) {
  console.log(`project settings (${fields.length}): ${fields.join(', ')}`);
  for (const [f, d] of Object.entries(CONSUMPTION)) console.log(`  consumption: ${f} — ${d.kind} (${d.why})`);
  if (gaps.length) console.log(`declared gaps:\n${gaps.join('\n')}`);
  if (owed.length) console.log(`owed — creator-facing, authorable from no editor surface:\n${owed.join('\n')}`);
}

if (problems.length) {
  console.error('check-project-settings: a project setting does not reach a consumer.\n');
  for (const p of problems) console.error(`  - ${p}`);
  process.exit(1);
}

console.log(`check-project-settings: ${fields.length} settings, ${gaps.length} declared gaps,`
  + ` ${owed.length} owed an authoring surface (--list names them) — ok`);