@craft_eco/craft-mcp 0.1.34 → 0.1.35-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. package/README.md +2 -2
  2. package/bin/craft-mcp.mjs +11 -2
  3. package/dist-server/core/http-utils.mjs +11 -0
  4. package/dist-server/game-workflow/asset-formats.mjs +1 -1
  5. package/dist-server/game-workflow/bundle-files.mjs +19 -0
  6. package/dist-server/game-workflow/bundle-template.mjs +5 -0
  7. package/dist-server/game-workflow/context-state.mjs +1 -1
  8. package/dist-server/game-workflow/draft-archive.mjs +61 -0
  9. package/dist-server/game-workflow/draft-binding-migration.mjs +73 -0
  10. package/dist-server/game-workflow/draft-uploads.mjs +258 -75
  11. package/dist-server/game-workflow/native-context.mjs +4 -1
  12. package/dist-server/game-workflow/project-bundles.mjs +17 -6
  13. package/dist-server/game-workflow/projects.mjs +4 -0
  14. package/dist-server/game-workflow/template-refresh.mjs +430 -0
  15. package/dist-server/integrations/distribution-targets.mjs +2 -0
  16. package/dist-server/integrations/files.mjs +30 -2
  17. package/dist-server/integrations/fixed-launcher.mjs +4 -4
  18. package/dist-server/integrations/install.mjs +5 -5
  19. package/dist-server/integrations/installation-state.mjs +6 -7
  20. package/dist-server/integrations/launcher-start.mjs +12 -8
  21. package/dist-server/integrations/opencode-config.mjs +1 -1
  22. package/dist-server/integrations/project-setup.mjs +0 -1
  23. package/dist-server/integrations/runtime-candidate.mjs +8 -12
  24. package/dist-server/integrations/runtime-gc.mjs +20 -21
  25. package/dist-server/integrations/runtime.mjs +7 -3
  26. package/dist-server/integrations/updates.mjs +64 -27
  27. package/dist-server/launcher.mjs +39 -14
  28. package/dist-server/mcp/login-page.mjs +2 -2
  29. package/dist-server/mcp/server.mjs +10 -12
  30. package/dist-server/mcp/update-session.mjs +3 -3
  31. package/dist-server/upstream/{craft-aigc.mjs → craft-platform.mjs} +40 -115
  32. package/dist-server/upstream/draft-audit.mjs +51 -0
  33. package/dist-server/upstream/draft-transport.mjs +184 -0
  34. package/package.json +3 -3
  35. package/resources/craft-update/SKILL.md +2 -0
  36. package/resources/targets/claude/js/js/bundle.json +15 -9
  37. package/resources/targets/claude/js/target.json +8 -6
  38. package/resources/targets/claude/js3d/js3d/bundle.json +21 -10
  39. package/resources/targets/claude/js3d/target.json +14 -7
  40. package/resources/targets/codebuddy/js/js/bundle.json +15 -9
  41. package/resources/targets/codebuddy/js/target.json +8 -6
  42. package/resources/targets/codebuddy/js3d/js3d/bundle.json +21 -10
  43. package/resources/targets/codebuddy/js3d/target.json +14 -7
  44. package/resources/targets/codex/js/js/bundle.json +15 -9
  45. package/resources/targets/codex/js/target.json +8 -6
  46. package/resources/targets/codex/js3d/js3d/bundle.json +21 -10
  47. package/resources/targets/codex/js3d/target.json +14 -7
  48. package/resources/targets/comate/js/js/bundle.json +15 -9
  49. package/resources/targets/comate/js/target.json +8 -6
  50. package/resources/targets/comate/js3d/js3d/bundle.json +21 -10
  51. package/resources/targets/comate/js3d/target.json +14 -7
  52. package/resources/targets/cursor/js/js/bundle.json +15 -9
  53. package/resources/targets/cursor/js/target.json +8 -6
  54. package/resources/targets/cursor/js3d/js3d/bundle.json +21 -10
  55. package/resources/targets/cursor/js3d/target.json +14 -7
  56. package/resources/targets/dsh/js/js/bundle.json +15 -9
  57. package/resources/targets/dsh/js/target.json +8 -6
  58. package/resources/targets/dsh/js3d/js3d/bundle.json +21 -10
  59. package/resources/targets/dsh/js3d/target.json +14 -7
  60. package/resources/targets/index.json +56 -56
  61. package/resources/targets/kimi/js/js/bundle.json +15 -9
  62. package/resources/targets/kimi/js/target.json +8 -6
  63. package/resources/targets/kimi/js3d/js3d/bundle.json +21 -10
  64. package/resources/targets/kimi/js3d/target.json +14 -7
  65. package/resources/targets/opencode/js/js/bundle.json +15 -9
  66. package/resources/targets/opencode/js/target.json +8 -6
  67. package/resources/targets/opencode/js3d/js3d/bundle.json +21 -10
  68. package/resources/targets/opencode/js3d/target.json +14 -7
  69. package/resources/targets/qoder/js/js/bundle.json +15 -9
  70. package/resources/targets/qoder/js/target.json +8 -6
  71. package/resources/targets/qoder/js3d/js3d/bundle.json +21 -10
  72. package/resources/targets/qoder/js3d/target.json +14 -7
  73. package/resources/targets/qoder-cn/js/js/bundle.json +15 -9
  74. package/resources/targets/qoder-cn/js/target.json +8 -6
  75. package/resources/targets/qoder-cn/js3d/js3d/bundle.json +21 -10
  76. package/resources/targets/qoder-cn/js3d/target.json +14 -7
  77. package/resources/targets/qwen/js/js/bundle.json +15 -9
  78. package/resources/targets/qwen/js/target.json +8 -6
  79. package/resources/targets/qwen/js3d/js3d/bundle.json +21 -10
  80. package/resources/targets/qwen/js3d/target.json +14 -7
  81. package/resources/targets/trae/js/js/bundle.json +15 -9
  82. package/resources/targets/trae/js/target.json +8 -6
  83. package/resources/targets/trae/js3d/js3d/bundle.json +21 -10
  84. package/resources/targets/trae/js3d/target.json +14 -7
  85. package/resources/targets/workbuddy/js/js/bundle.json +15 -9
  86. package/resources/targets/workbuddy/js/target.json +8 -6
  87. package/resources/targets/workbuddy/js3d/js3d/bundle.json +21 -10
  88. package/resources/targets/workbuddy/js3d/target.json +14 -7
  89. package/resources/targets/zcode/js/js/bundle.json +15 -9
  90. package/resources/targets/zcode/js/target.json +8 -6
  91. package/resources/targets/zcode/js3d/js3d/bundle.json +21 -10
  92. package/resources/targets/zcode/js3d/target.json +14 -7
  93. package/resources/templates/js/materialize_paths.json +9 -0
  94. package/resources/templates/js/project/package.json +1 -0
  95. package/resources/templates/js/project/runtime/lightgame/1.1.0/platform/platform-capture-dom.mjs +176 -0
  96. package/resources/templates/js/project/runtime/lightgame/1.1.0/platform/platform.d.mts +5 -1
  97. package/resources/templates/js/project/runtime/lightgame/1.1.0/platform/platform.mjs +87 -3
  98. package/resources/templates/js/project/runtime/lightgame/1.1.0/release.json +3 -2
  99. package/resources/templates/js/project/scripts/refresh-runtime.mjs +50 -0
  100. package/resources/templates/js3d/materialize_paths.json +9 -0
  101. package/resources/templates/js3d/project/package.json +4 -2
  102. package/resources/templates/js3d/project/runtime/lightgame/1.1.0/platform/platform-capture-dom.mjs +176 -0
  103. package/resources/templates/js3d/project/runtime/lightgame/1.1.0/platform/platform.d.mts +5 -1
  104. package/resources/templates/js3d/project/runtime/lightgame/1.1.0/platform/platform.mjs +87 -3
  105. package/resources/templates/js3d/project/runtime/lightgame/1.1.0/release.json +3 -2
  106. package/resources/templates/js3d/project/scripts/refresh-runtime.mjs +50 -0
  107. package/resources/templates/js3d/project/scripts/skill-modules/gameplay-check/check.mjs +331 -0
  108. package/resources/templates/js3d/project/src/game/capability/core.ts +3 -0
  109. package/resources/templates/js3d/project/src/main.ts +23 -6
  110. package/resources/templates/js3d/project/src/skill-modules/gameplay/core/index.d.mts +92 -0
  111. package/resources/templates/js3d/project/src/skill-modules/gameplay/core/index.mjs +375 -0
  112. package/resources/templates/js3d/project/src/skill-modules/gameplay/installed.json +6 -0
  113. package/dist-server/game-workflow/local-context.mjs +0 -64
@@ -0,0 +1,331 @@
1
+ import { readFile, readdir, stat } from 'node:fs/promises';
2
+ import { dirname, resolve, join, relative } from 'node:path';
3
+ import { pathToFileURL } from 'node:url';
4
+
5
+ /**
6
+ * gameplay 契约机检。
7
+ *
8
+ * 只查“能机械判定”的项:装了哪几组、能力入口在不在、业务代码有没有自己起循环、
9
+ * 业务代码有没有绕过内核直接用定时器。玩法正确性不在这里查。
10
+ */
11
+
12
+ const SKIP_DIRS = new Set(['node_modules', 'dist', '.git', 'skill-modules', 'runtime', 'vendor']);
13
+ const SOURCE_EXT = /\.(ts|tsx|mts|js|mjs|jsx)$/;
14
+ export const RECAST_NAVIGATION_VERSION = '0.43.1';
15
+ // 自写寻路的常见痕迹:类名、函数名、文件名,以及 A* / 距离场的典型写法。只用于提示
16
+ const PATHFINDING = /\b(?:class|function)\s+\w*(?:MinHeap|PriorityQueue|FlowField|PathField|PathFinder|Pathfinder|NavGrid|NavGraph|NavMesh|RouteMap|WaypointGraph)\b|\b(?:findPath|findRoute|computePath|buildPath|calcPath|distanceField|distanceMap|navField|pathField|routeMap|aStar|Astar|dijkstra|openSet|openList|closedSet|bfs|floodFill)\b/;
17
+ const PATHFINDING_FILE = /(?:^|\/)(?:nav|navmesh|nav-grid|navgraph|nav-graph|pathfinding|path-field|pathfield|route-map|routemap|flow-field|flowfield|astar|a-star|grid-map)\.(?:ts|tsx|mts|js|mjs)$/i;
18
+ // 允许的自写(格子规则移动、非地面移动):在文件里写一行 `// gameplay-allow: 原因` 即可跳过提示
19
+ const ALLOW = /gameplay-allow\s*[::]\s*(\S[^\n]*)/;
20
+ // onRender 的回调:内联箭头 / 函数表达式 / 直接传函数名(第四组)都要认,才能判断有没有用插值
21
+ const ON_RENDER = /onRender\s*\(\s*(?:async\s+)?(?:function\s*[\w$]*\s*\(\s*([\w$]*)[^)]*\)|\(\s*([\w$]*)\s*[^)]*\)\s*=>|([\w$]+)\s*=>|([\w$]+)\s*\))/g;
22
+
23
+ /** 这个文件里的 onRender 回调用没用 alpha:true / false,没有回调为 null。按项目整体判断,一个文件里插值、另一个不插也算用了。 */
24
+ function renderUsesAlpha(text) {
25
+ const code = stripComments(text);
26
+ if (/\btime\s*\.\s*alpha\b/.test(code)) return true;
27
+ const used = name => code.split(new RegExp(`\\b${name}\\b`)).length - 1 >= 2;
28
+ let seen = false;
29
+ for (const match of code.matchAll(ON_RENDER)) {
30
+ seen = true;
31
+ const named = match[4];
32
+ if (named) {
33
+ // 传的是函数名:找它在本文件的定义,再看形参有没有被用到
34
+ const def = code.match(new RegExp(
35
+ `(?:function\\s+${named}\\s*\\(\\s*([\\w$]*)`
36
+ + `|(?:const|let|var)\\s+${named}\\s*=\\s*(?:async\\s+)?(?:\\(\\s*([\\w$]*)[^)]*\\)|([\\w$]+))\\s*=>)`));
37
+ if (!def) continue; // 定义在别的文件,判不了就不算数
38
+ const inner = def[1] ?? def[2] ?? def[3];
39
+ if (inner && used(inner)) return true;
40
+ continue;
41
+ }
42
+ const param = match[1] ?? match[2] ?? match[3];
43
+ if (param && used(param)) return true;
44
+ }
45
+ return seen ? false : null;
46
+ }
47
+
48
+ async function walk(dir, files = []) {
49
+ let entries;
50
+ try {
51
+ entries = await readdir(dir, { withFileTypes: true });
52
+ } catch (error) {
53
+ if (error.code === 'ENOENT') return files;
54
+ throw error;
55
+ }
56
+ for (const entry of entries) {
57
+ if (entry.isDirectory()) {
58
+ if (SKIP_DIRS.has(entry.name)) continue;
59
+ await walk(join(dir, entry.name), files);
60
+ } else if (SOURCE_EXT.test(entry.name)) {
61
+ files.push(join(dir, entry.name));
62
+ }
63
+ }
64
+ return files;
65
+ }
66
+
67
+ async function readJson(path) {
68
+ try {
69
+ return JSON.parse(await readFile(path, 'utf8'));
70
+ } catch (error) {
71
+ if (error.code === 'ENOENT') return null;
72
+ throw error;
73
+ }
74
+ }
75
+
76
+ /** 粗略去掉注释,避免注释里的示例代码被当成调用。 */
77
+ const stripComments = text => text.replace(/\/\*[\s\S]*?\*\//g, '').replace(/(^|[^:])\/\/.*$/gm, '$1');
78
+
79
+ /** 只取源代码中的运行时模块引用和调用,不把文字、注释或类型引用当成接线。 */
80
+ function analyzeSource(ts, file, text) {
81
+ const tree = ts.createSourceFile(file, text, ts.ScriptTarget.Latest);
82
+ const imports = [];
83
+ const calls = [];
84
+ const constructors = [];
85
+ const addImport = node => {
86
+ if (node && ts.isStringLiteralLike(node)) imports.push(node.text);
87
+ };
88
+ const memberName = node => {
89
+ if (ts.isIdentifier(node)) return node.text;
90
+ if (ts.isPropertyAccessExpression(node)) return node.name.text;
91
+ if (ts.isElementAccessExpression(node) && ts.isStringLiteralLike(node.argumentExpression)) {
92
+ return node.argumentExpression.text;
93
+ }
94
+ };
95
+ const isTypeOnlyNamed = bindings => bindings && ts.isNamedImports(bindings)
96
+ && bindings.elements.length > 0 && bindings.elements.every(element => element.isTypeOnly);
97
+
98
+ function visit(node) {
99
+ if (ts.isImportDeclaration(node)) {
100
+ const clause = node.importClause;
101
+ if (!clause?.isTypeOnly && (clause?.name || !isTypeOnlyNamed(clause?.namedBindings))) {
102
+ addImport(node.moduleSpecifier);
103
+ }
104
+ } else if (ts.isExportDeclaration(node)) {
105
+ const clause = node.exportClause;
106
+ if (!node.isTypeOnly && !(clause && ts.isNamedExports(clause) && clause.elements.length > 0
107
+ && clause.elements.every(element => element.isTypeOnly))) {
108
+ addImport(node.moduleSpecifier);
109
+ }
110
+ } else if (ts.isCallExpression(node)) {
111
+ const callee = node.expression;
112
+ if (callee.kind === ts.SyntaxKind.ImportKeyword) addImport(node.arguments[0]);
113
+ calls.push({
114
+ name: memberName(callee),
115
+ receiver: callee.expression?.getText(tree),
116
+ stopsLoop: node.arguments[0]?.kind === ts.SyntaxKind.NullKeyword,
117
+ });
118
+ } else if (ts.isNewExpression(node)) {
119
+ constructors.push({ name: memberName(node.expression), receiver: node.expression.expression?.getText(tree) });
120
+ }
121
+ ts.forEachChild(node, visit);
122
+ }
123
+ visit(tree);
124
+ return { imports, calls, constructors };
125
+ }
126
+
127
+ async function exists(path) {
128
+ try {
129
+ await stat(path);
130
+ return true;
131
+ } catch { return false; }
132
+ }
133
+
134
+ export async function checkProject(project) {
135
+ const root = resolve(project);
136
+ const results = [];
137
+
138
+ const record = await readJson(join(root, 'src/skill-modules/gameplay/installed.json'));
139
+ const modules = Array.isArray(record?.modules) ? record.modules : [];
140
+ if (!modules.length) {
141
+ // 构建时也会跑:没装任何组的项目(纯展示、旧模板)不在 gameplay 契约范围内,只提示不阻断
142
+ results.push({ name: 'installed', status: 'warn', detail: '没有装任何 gameplay 组,跳过契约检查' });
143
+ return { project: root, modules, results, failed: false };
144
+ }
145
+
146
+ const missingFiles = [];
147
+ for (const group of modules) {
148
+ if (!(await exists(join(root, `src/skill-modules/gameplay/${group}/index.mjs`)))) missingFiles.push(group);
149
+ }
150
+ results.push(missingFiles.length
151
+ ? { name: 'installed', status: 'fail', detail: `已装组缺文件:${missingFiles.join(', ')},重装一次` }
152
+ : { name: 'installed', status: 'ok', detail: modules.join(', ') });
153
+
154
+ const missingEntries = [];
155
+ for (const group of modules) {
156
+ if (!(await exists(join(root, `src/game/capability/${group}.ts`)))) missingEntries.push(group);
157
+ }
158
+ results.push(missingEntries.length
159
+ ? { name: 'capability', status: 'fail', detail: `缺能力入口 src/game/capability/${missingEntries.join('.ts, ')}.ts;业务只允许从这一层引用能力` }
160
+ : { name: 'capability', status: 'ok', detail: modules.map(group => `src/game/capability/${group}.ts`).join(', ') });
161
+
162
+ const { default: ts } = await import('typescript');
163
+ const files = await walk(join(root, 'src'));
164
+ const capabilityDir = join(root, 'src/game/capability');
165
+ const wired = new Set();
166
+ const loops = new Map([
167
+ ['requestAnimationFrame', []],
168
+ ['setAnimationLoop', []],
169
+ ]);
170
+ const sources = [];
171
+ for (const file of files) {
172
+ const text = await readFile(file, 'utf8');
173
+ const name = relative(root, file).replace(/\\/g, '/');
174
+ const syntax = analyzeSource(ts, file, text);
175
+ sources.push({ name, text, ...syntax });
176
+ if (!name.startsWith('src/game/capability/')) {
177
+ for (const specifier of syntax.imports) {
178
+ if (!specifier.startsWith('./') && !specifier.startsWith('../')) continue;
179
+ wired.add(resolve(dirname(file), specifier).replace(/\.(?:ts|js)$/, ''));
180
+ }
181
+ }
182
+ for (const [loop, names] of loops) {
183
+ if (syntax.calls.some(call => call.name === loop
184
+ && (loop !== 'setAnimationLoop' || (call.receiver && !call.stopsLoop)))) names.push(name);
185
+ }
186
+ }
187
+
188
+ const unused = modules.filter(group => !wired.has(join(capabilityDir, group)));
189
+ results.push(unused.length
190
+ ? { name: 'wired', status: 'warn', detail: `装了但没有接线:${unused.join(', ')};业务代码应从 src/game/capability/<组> 引用,否则这批文件等于白装` }
191
+ : { name: 'wired', status: 'ok', detail: modules.map(group => `capability/${group}`).join(', ') });
192
+
193
+ // 主循环由 Kernel.start 提供(模板预装 core),业务不应再启动浏览器或 Three.js 的循环。
194
+ if (modules.includes('core')) {
195
+ const loopDetails = [...loops].filter(([, names]) => names.length)
196
+ .map(([loop, names]) => `${loop}:${names.join(', ')}`);
197
+ results.push(!loopDetails.length
198
+ ? { name: 'single-loop', status: 'ok', detail: '业务代码没有自起循环(由 Kernel.start 提供)' }
199
+ : { name: 'single-loop', status: 'fail', detail: `业务代码自起循环:${loopDetails.join(';')};主循环只有 Kernel 一处,每帧逻辑改用 kernel.add,渲染改用 kernel.onRender` });
200
+ }
201
+
202
+ const timers = sources.filter(source => source.calls.some(call => call.name === 'setInterval'))
203
+ .map(source => source.name);
204
+ results.push(timers.length
205
+ ? { name: 'no-setInterval', status: 'warn', detail: `业务代码直接用了 setInterval:${timers.join(', ')};定时改走 kernel.every,切场景才会随世界一起清掉` }
206
+ : { name: 'no-setInterval', status: 'ok', detail: '没有直接使用 setInterval' });
207
+
208
+ // 没装任何寻路组却出现寻路写法:大概率是自写了平台已有的能力。只提示,格子规则与非地面移动属于正常自写
209
+ if (!modules.some(group => group === 'nav' || group === 'crowd' || group === 'flowfield')) {
210
+ const skipped = [];
211
+ const pathfinding = sources
212
+ .filter(source => !source.name.startsWith('src/game/capability/'))
213
+ .filter(source => {
214
+ const allowed = ALLOW.test(source.text);
215
+ const hit = PATHFINDING.test(stripComments(source.text)) || PATHFINDING_FILE.test(source.name);
216
+ if (hit && allowed) { skipped.push(source.name); return false; }
217
+ return hit;
218
+ })
219
+ .map(source => source.name);
220
+ if (pathfinding.length) {
221
+ results.push({
222
+ name: 'pathfinding',
223
+ status: 'warn',
224
+ detail: `看起来自己写了寻路:${pathfinding.join(', ')};地面单位绕障碍追目标请按 SKILL.md 的寻路选型改用 nav / crowd / flowfield。`
225
+ + `格子规则移动、飞行等非地面移动确实要自己写的,在文件里写一行 \`// gameplay-allow: 原因\` 即可跳过这条`,
226
+ });
227
+ } else if (skipped.length) {
228
+ results.push({ name: 'pathfinding', status: 'ok', detail: `自写寻路已注明理由:${skipped.join(', ')}` });
229
+ }
230
+ }
231
+
232
+ // 固定步长下不做插值,高刷屏移动会抖。按项目整体看:只要有一处渲染回调用了 alpha 就算做了
233
+ if (modules.includes('core')) {
234
+ const business = sources.filter(source => !source.name.startsWith('src/game/capability/')
235
+ && !source.name.startsWith('src/skill-modules/'));
236
+ const renderFiles = [];
237
+ let anyAlpha = false;
238
+ for (const source of business) {
239
+ const uses = renderUsesAlpha(source.text);
240
+ if (uses === null) continue;
241
+ renderFiles.push(source.name);
242
+ if (uses) anyAlpha = true;
243
+ }
244
+ const moves = business.some(source => source.calls.some(call => call.receiver === 'kernel' && call.name === 'add'));
245
+ if (renderFiles.length) {
246
+ results.push(anyAlpha
247
+ ? { name: 'interpolate', status: 'ok', detail: '渲染回调使用了插值' }
248
+ : moves
249
+ ? { name: 'interpolate', status: 'warn', detail: `onRender 拿到了 alpha 却没用:${renderFiles.join(', ')};固定步长推进时要在 previous → position 之间按 alpha 插值,否则 120Hz 屏上移动会抖` }
250
+ : { name: 'interpolate', status: 'ok', detail: '还没有需要插值的移动实体' });
251
+ }
252
+ }
253
+
254
+ // 装了 random 说明要的是可复现随机;业务里还在用 Math.random 的地方,结果没法复现。纯视觉随机可以忽略,所以只提示
255
+ if (modules.includes('random')) {
256
+ const raw = sources
257
+ .filter(source => !source.name.startsWith('src/game/capability/')
258
+ && source.calls.some(call => call.receiver === 'Math' && call.name === 'random'))
259
+ .map(source => source.name);
260
+ results.push(raw.length
261
+ ? { name: 'random', status: 'warn', detail: `装了 random 但仍在用 Math.random:${raw.join(', ')};刷怪、掉落、暴击这类影响结果的随机改用 Random(可复现),纯视觉的粒子抖动可以忽略这条` }
262
+ : { name: 'random', status: 'ok', detail: '业务代码没有直接使用 Math.random' });
263
+ }
264
+
265
+ if (modules.includes('interact')) {
266
+ const handheld = sources
267
+ .filter(source => source.constructors.some(({ name, receiver }) => name === 'Raycaster'
268
+ && (receiver === undefined || receiver === 'THREE')))
269
+ .map(source => source.name);
270
+ results.push(handheld.length
271
+ ? { name: 'interact-raycast', status: 'warn', detail: `装了 interact 但业务自己 new 了射线:${handheld.join(', ')};交互探测交给 Interact,否则距离预筛与暂停冻结都不生效。非交互用途可以忽略这条` }
272
+ : { name: 'interact-raycast', status: 'ok', detail: '交互探测走 Interact' });
273
+ }
274
+
275
+ if (modules.includes('nav')) {
276
+ const pkg = await readJson(join(root, 'package.json'));
277
+ const version = pkg?.dependencies?.['recast-navigation'] ?? pkg?.devDependencies?.['recast-navigation'];
278
+ results.push(!version
279
+ ? { name: 'nav-dependency', status: 'fail', detail: 'package.json 缺 recast-navigation,重装 nav 组会自动写入,然后 npm install' }
280
+ : version === RECAST_NAVIGATION_VERSION
281
+ ? { name: 'nav-dependency', status: 'ok', detail: `recast-navigation@${version}` }
282
+ : { name: 'nav-dependency', status: 'warn', detail: `项目声明 recast-navigation@${version},nav 按 ${RECAST_NAVIGATION_VERSION} 验证` });
283
+
284
+ const direct = sources
285
+ .filter(source => source.imports.some(specifier => specifier === 'recast-navigation' || specifier.startsWith('recast-navigation/')))
286
+ .map(source => source.name);
287
+ results.push(direct.length
288
+ ? { name: 'nav-direct', status: 'warn', detail: `业务直接引用了 recast-navigation:${direct.join(', ')};绕过 nav 会丢掉米/体素换算和障碍外扩,角色容易嵌进墙` }
289
+ : { name: 'nav-direct', status: 'ok', detail: '寻路走 NavWorld / Crowd' });
290
+ }
291
+
292
+ if (modules.includes('flow')) {
293
+ const manual = sources
294
+ .filter(source => !source.name.startsWith('src/game/capability/')
295
+ && source.calls.some(call => call.receiver === 'kernel' && (call.name === 'pause' || call.name === 'resume')))
296
+ .map(source => source.name);
297
+ results.push(manual.length
298
+ ? { name: 'flow-pause', status: 'warn', detail: `装了 flow 但业务直接调 kernel.pause/resume:${manual.join(', ')};暂停改用 freeze 状态,否则状态栈与暂停会对不上` }
299
+ : { name: 'flow-pause', status: 'ok', detail: '暂停由 flow 的 freeze 状态驱动' });
300
+ }
301
+
302
+ return { project: root, modules, results, failed: results.some(item => item.status === 'fail') };
303
+ }
304
+
305
+ export function formatReport(report) {
306
+ const label = { ok: 'OK ', warn: 'WARN', fail: 'FAIL' };
307
+ const lines = [`[gameplay-check] ${report.project}`];
308
+ for (const item of report.results) lines.push(` ${label[item.status]} ${item.name}: ${item.detail}`);
309
+ lines.push(report.failed ? '[gameplay-check] 未通过' : '[gameplay-check] 通过');
310
+ return lines.join('\n');
311
+ }
312
+
313
+ export async function runCli(args = process.argv.slice(2)) {
314
+ let project;
315
+ for (let index = 0; index < args.length; index++) {
316
+ const flag = args[index];
317
+ const value = args[++index];
318
+ if (!value || value.startsWith('--')) throw new Error(`Missing value for ${flag}`);
319
+ if (flag === '--project') project = value;
320
+ else throw new Error(`Unknown option: ${flag}`);
321
+ }
322
+ if (!project) throw new Error('Usage: check.mjs --project <directory>');
323
+ const report = await checkProject(project);
324
+ console.log(formatReport(report));
325
+ if (report.failed) process.exitCode = 1;
326
+ return report;
327
+ }
328
+
329
+ if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
330
+ runCli().catch(error => { console.error(error.message); process.exitCode = 1; });
331
+ }
@@ -0,0 +1,3 @@
1
+ // 由 gameplay-modules 安装器生成的入口。项目内只从这里引用 core 能力。
2
+ // 换成自己的实现时,把下面一行改成 export * from './core.impl.mjs',业务代码不用动。
3
+ export * from '../../skill-modules/gameplay/core/index.mjs';
@@ -3,6 +3,7 @@ import game from '../configs/game.json';
3
3
  import { connectPreview } from './platform';
4
4
  import './style.css';
5
5
  import { initUiStage } from './display/ui-stage';
6
+ import { Kernel } from './game/capability/core';
6
7
 
7
8
  const container = document.querySelector<HTMLDivElement>('#game')!;
8
9
  const canvas = document.createElement('canvas');
@@ -62,23 +63,39 @@ const resizeObserver = new ResizeObserver(applyViewSize);
62
63
  resizeObserver.observe(container);
63
64
  applyViewSize();
64
65
 
65
- // 在这里使用 Three.js 与浏览器 API 添加场景、输入、资源和游戏逻辑。
66
- let frame = 0;
67
- function render(): void {
66
+ /**
67
+ * 帧循环:全工程只有 Kernel 这一处 requestAnimationFrame(gameplay-modules 的 core 组)。
68
+ * 模拟走固定步长,掉帧不会整体慢放;业务往内核里挂实体、定时器和渲染回调,不自己写循环,
69
+ * 也不用 setTimeout / setInterval。接线规则见 gameplay-modules 的 references/core.md;
70
+ * 业务调用 requestAnimationFrame 或 renderer.setAnimationLoop(fn) 时,gameplay 检查会拦截构建。
71
+ */
72
+ const kernel = new Kernel({ stepSeconds: 1 / 60, maxSubSteps: 5 });
73
+
74
+ function renderFrame(): void {
68
75
  renderer.render(scene, camera);
69
76
  preview.afterRender();
70
- frame = requestAnimationFrame(render);
71
77
  }
72
- render();
78
+ kernel.onRender(renderFrame);
79
+
80
+ // 同步提交首帧,再按平台约定通知就绪,最后才进入循环。
81
+ renderFrame();
73
82
  preview.markReady();
83
+ kernel.start();
84
+
85
+ // 在这里接输入、建场景、登记实体:
86
+ // const world = kernel.add({ update(dt) { /* 只改模拟状态,用 dt 推进 */ } });
87
+ // const unsubscribe = kernel.on('pickup', (target) => { /* ... */ });
74
88
 
75
89
  if (import.meta.hot) {
76
90
  import.meta.hot.accept();
77
91
  import.meta.hot.dispose(() => {
78
- cancelAnimationFrame(frame);
92
+ kernel.dispose();
79
93
  resizeObserver.disconnect();
80
94
  ui.dispose();
81
95
  preview.dispose();
96
+ // 热更新会重跑整个模块:不主动释放上下文,几次之后浏览器会开始回收,
97
+ // 平台把那次回收报成 WebGL 故障(runtime-result 2)。
98
+ renderer.forceContextLoss();
82
99
  renderer.dispose();
83
100
  canvas.remove();
84
101
  });
@@ -0,0 +1,92 @@
1
+ /** 可被世界管理的实体。两个方法都可选:纯逻辑实体不需要 update,也不需要渲染节点。 */
2
+ export interface Entity {
3
+ update?(dt: number): void;
4
+ dispose?(): void;
5
+ }
6
+
7
+ export interface KernelOptions {
8
+ /** 固定步长,默认 1/60 秒。 */
9
+ stepSeconds?: number;
10
+ /** 单帧最多跑几个固定步,默认 5。触到上限时丢弃剩余时间,避免卡顿后连跑。 */
11
+ maxSubSteps?: number;
12
+ /** 单帧参与模拟的最大时长,默认 stepSeconds * maxSubSteps。切后台回来的长帧按它截断。 */
13
+ maxFrameSeconds?: number;
14
+ }
15
+
16
+ export interface KernelTime {
17
+ /** 本帧真实时长(秒,已按 maxFrameSeconds 截断)。 */
18
+ frameSeconds: number;
19
+ /** 累计模拟时间(秒,已乘时间缩放)。 */
20
+ simulated: number;
21
+ /** 累计固定步数。 */
22
+ steps: number;
23
+ /** 渲染插值系数:0 表示刚好在一步的起点,1 表示差一步追上。 */
24
+ alpha: number;
25
+ }
26
+
27
+ export interface TimerHandle {
28
+ readonly id: number;
29
+ cancel(): void;
30
+ }
31
+
32
+ /** Kernel.probe() 的返回值:全是数字与布尔,可直接放进页面探针或 JSON。 */
33
+ export interface KernelProbe {
34
+ running: boolean;
35
+ paused: boolean;
36
+ timeScale: number;
37
+ /** 世界里的实体数。 */
38
+ entities: number;
39
+ /** 待触发的定时器数。 */
40
+ timers: number;
41
+ /** 通过 on() 登记的事件监听数。 */
42
+ listeners: number;
43
+ renderHooks: number;
44
+ /** onBeforeStep + onAfterStep 的数量。 */
45
+ stepHooks: number;
46
+ /** 累计固定步数。 */
47
+ steps: number;
48
+ /** 累计模拟时间(毫秒,已乘时间缩放)。 */
49
+ simulatedMs: number;
50
+ }
51
+
52
+ export declare class Kernel {
53
+ constructor(options?: KernelOptions);
54
+
55
+ readonly stepSeconds: number;
56
+ readonly size: number;
57
+ readonly pending: number;
58
+ readonly paused: boolean;
59
+ readonly timeScale: number;
60
+ readonly time: KernelTime;
61
+ /** 运行状态快照(实体、定时器、监听、暂停、步数),供自动验收读取。 */
62
+ probe(): KernelProbe;
63
+
64
+ add<T extends Entity>(entity: T): T;
65
+ remove(entity: Entity): boolean;
66
+ clear(): void;
67
+
68
+ after(seconds: number, callback: () => void): TimerHandle;
69
+ every(seconds: number, callback: () => void): TimerHandle;
70
+
71
+ on<T = unknown>(name: string, listener: (payload: T) => void): () => void;
72
+ off(name: string, listener: (payload: unknown) => void): void;
73
+ emit<T = unknown>(name: string, payload?: T): void;
74
+ /** 一帧的多个固定步里重复触发时,只派发最后一次。 */
75
+ emitOnce<T = unknown>(name: string, payload?: T, key?: string): void;
76
+
77
+ /** simulatedSeconds 是本帧实际推进的模拟秒数,已含时间缩放。暂停或无固定步时为 0。 */
78
+ onRender(callback: (alpha: number, frameSeconds: number, simulatedSeconds: number) => void): () => void;
79
+ /** 每个固定步开始前调用,早于所有实体。输入层的 sample() 挂这里。clear() 不会清掉。 */
80
+ onBeforeStep(callback: (dt: number) => void): () => void;
81
+ /** 每个固定步结束后调用,晚于实体与定时器。输入层的 endFrame() 挂这里。clear() 不会清掉。 */
82
+ onAfterStep(callback: (dt: number) => void): () => void;
83
+
84
+ start(): this;
85
+ stop(): void;
86
+ pause(): void;
87
+ resume(): void;
88
+ setTimeScale(value: number): void;
89
+ /** 推进一帧。start() 内部调用;测试与自定义驱动器可手动调用。 */
90
+ advance(frameSeconds: number): void;
91
+ dispose(): void;
92
+ }