@directivegames/genesys.sdk 3.2.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 (181) hide show
  1. package/README.md +60 -0
  2. package/dist/src/asset-pack/eslint.config.js +43 -0
  3. package/dist/src/asset-pack/scripts/postinstall.js +64 -0
  4. package/dist/src/asset-pack/src/index.js +1 -0
  5. package/dist/src/core/cli.js +306 -0
  6. package/dist/src/core/common.js +324 -0
  7. package/dist/src/core/index.js +6 -0
  8. package/dist/src/core/tools/build-project.js +450 -0
  9. package/dist/src/core/tools/index.js +2 -0
  10. package/dist/src/core/tools/new-asset-pack.js +150 -0
  11. package/dist/src/core/tools/new-project.js +292 -0
  12. package/dist/src/core/types.js +1 -0
  13. package/dist/src/dependencies.js +82 -0
  14. package/dist/src/electron/IpcSerializableError.js +38 -0
  15. package/dist/src/electron/api.js +7 -0
  16. package/dist/src/electron/backend/actions.js +56 -0
  17. package/dist/src/electron/backend/handler.js +441 -0
  18. package/dist/src/electron/backend/logging.js +41 -0
  19. package/dist/src/electron/backend/main.js +315 -0
  20. package/dist/src/electron/backend/menu.js +208 -0
  21. package/dist/src/electron/backend/state.js +201 -0
  22. package/dist/src/electron/backend/tools/const.js +9 -0
  23. package/dist/src/electron/backend/tools/file-server.js +383 -0
  24. package/dist/src/electron/backend/tools/open-project.js +261 -0
  25. package/dist/src/electron/backend/window.js +161 -0
  26. package/dist/src/templates/eslint.config.js +43 -0
  27. package/dist/src/templates/scripts/genesys/build-project.js +42 -0
  28. package/dist/src/templates/scripts/genesys/calc-bounding-box.js +205 -0
  29. package/dist/src/templates/scripts/genesys/common.js +36 -0
  30. package/dist/src/templates/scripts/genesys/const.js +9 -0
  31. package/dist/src/templates/scripts/genesys/dev/dump-default-scene.js +8 -0
  32. package/dist/src/templates/scripts/genesys/dev/generate-manifest.js +116 -0
  33. package/dist/src/templates/scripts/genesys/dev/launcher.js +39 -0
  34. package/dist/src/templates/scripts/genesys/dev/storage-provider.js +188 -0
  35. package/dist/src/templates/scripts/genesys/dev/update-template-scenes.js +67 -0
  36. package/dist/src/templates/scripts/genesys/doc-server.js +12 -0
  37. package/dist/src/templates/scripts/genesys/genesys-mcp.js +413 -0
  38. package/dist/src/templates/scripts/genesys/mcp/doc-tools.js +70 -0
  39. package/dist/src/templates/scripts/genesys/mcp/editor-functions.js +123 -0
  40. package/dist/src/templates/scripts/genesys/mcp/editor-tools.js +51 -0
  41. package/dist/src/templates/scripts/genesys/mcp/get-scene-state.js +26 -0
  42. package/dist/src/templates/scripts/genesys/mcp/run-subprocess.js +23 -0
  43. package/dist/src/templates/scripts/genesys/mcp/search-actors.js +703 -0
  44. package/dist/src/templates/scripts/genesys/mcp/search-assets.js +296 -0
  45. package/dist/src/templates/scripts/genesys/mcp/utils.js +234 -0
  46. package/dist/src/templates/scripts/genesys/misc.js +32 -0
  47. package/dist/src/templates/scripts/genesys/mock.js +5 -0
  48. package/dist/src/templates/scripts/genesys/place-actors.js +112 -0
  49. package/dist/src/templates/scripts/genesys/post-install.js +25 -0
  50. package/dist/src/templates/scripts/genesys/remove-engine-comments.js +113 -0
  51. package/dist/src/templates/scripts/genesys/storageProvider.js +146 -0
  52. package/dist/src/templates/scripts/genesys/validate-prefabs.js +115 -0
  53. package/dist/src/templates/src/index.js +20 -0
  54. package/dist/src/templates/src/templates/firstPerson/src/auto-imports.js +1 -0
  55. package/dist/src/templates/src/templates/firstPerson/src/game.js +30 -0
  56. package/dist/src/templates/src/templates/firstPerson/src/player.js +60 -0
  57. package/dist/src/templates/src/templates/fps/src/auto-imports.js +1 -0
  58. package/dist/src/templates/src/templates/fps/src/game.js +30 -0
  59. package/dist/src/templates/src/templates/fps/src/player.js +64 -0
  60. package/dist/src/templates/src/templates/fps/src/weapon.js +62 -0
  61. package/dist/src/templates/src/templates/freeCamera/src/auto-imports.js +1 -0
  62. package/dist/src/templates/src/templates/freeCamera/src/game.js +30 -0
  63. package/dist/src/templates/src/templates/freeCamera/src/player.js +43 -0
  64. package/dist/src/templates/src/templates/sideScroller/src/auto-imports.js +1 -0
  65. package/dist/src/templates/src/templates/sideScroller/src/const.js +43 -0
  66. package/dist/src/templates/src/templates/sideScroller/src/game.js +103 -0
  67. package/dist/src/templates/src/templates/sideScroller/src/level-generator.js +249 -0
  68. package/dist/src/templates/src/templates/sideScroller/src/player.js +105 -0
  69. package/dist/src/templates/src/templates/thirdPerson/src/auto-imports.js +1 -0
  70. package/dist/src/templates/src/templates/thirdPerson/src/game.js +30 -0
  71. package/dist/src/templates/src/templates/thirdPerson/src/player.js +63 -0
  72. package/dist/src/templates/src/templates/vehicle/src/auto-imports.js +1 -0
  73. package/dist/src/templates/src/templates/vehicle/src/base-vehicle.js +122 -0
  74. package/dist/src/templates/src/templates/vehicle/src/game.js +33 -0
  75. package/dist/src/templates/src/templates/vehicle/src/mesh-vehicle.js +189 -0
  76. package/dist/src/templates/src/templates/vehicle/src/player.js +102 -0
  77. package/dist/src/templates/src/templates/vehicle/src/primitive-vehicle.js +259 -0
  78. package/dist/src/templates/src/templates/vehicle/src/ui-hints.js +100 -0
  79. package/dist/src/templates/src/templates/vr-game/src/auto-imports.js +1 -0
  80. package/dist/src/templates/src/templates/vr-game/src/game.js +55 -0
  81. package/dist/src/templates/src/templates/vr-game/src/sample-vr-actor.js +29 -0
  82. package/dist/src/templates/vite.config.js +46 -0
  83. package/package.json +176 -0
  84. package/scripts/post-install.ts +143 -0
  85. package/src/asset-pack/.gitattributes +89 -0
  86. package/src/asset-pack/eslint.config.js +45 -0
  87. package/src/asset-pack/gitignore +11 -0
  88. package/src/asset-pack/scripts/postinstall.ts +81 -0
  89. package/src/asset-pack/src/index.ts +0 -0
  90. package/src/asset-pack/tsconfig.json +34 -0
  91. package/src/templates/.cursor/mcp.json +20 -0
  92. package/src/templates/.cursorignore +2 -0
  93. package/src/templates/.gitattributes +89 -0
  94. package/src/templates/.vscode/settings.json +6 -0
  95. package/src/templates/AGENTS.md +86 -0
  96. package/src/templates/CLAUDE.md +1 -0
  97. package/src/templates/README.md +24 -0
  98. package/src/templates/eslint.config.js +45 -0
  99. package/src/templates/gitignore +11 -0
  100. package/src/templates/index.html +34 -0
  101. package/src/templates/pnpm-lock.yaml +3676 -0
  102. package/src/templates/scripts/genesys/build-project.ts +51 -0
  103. package/src/templates/scripts/genesys/calc-bounding-box.ts +272 -0
  104. package/src/templates/scripts/genesys/common.ts +46 -0
  105. package/src/templates/scripts/genesys/const.ts +9 -0
  106. package/src/templates/scripts/genesys/dev/dump-default-scene.ts +11 -0
  107. package/src/templates/scripts/genesys/dev/generate-manifest.ts +146 -0
  108. package/src/templates/scripts/genesys/dev/launcher.ts +46 -0
  109. package/src/templates/scripts/genesys/dev/storage-provider.ts +229 -0
  110. package/src/templates/scripts/genesys/dev/update-template-scenes.ts +84 -0
  111. package/src/templates/scripts/genesys/doc-server.ts +16 -0
  112. package/src/templates/scripts/genesys/genesys-mcp.ts +526 -0
  113. package/src/templates/scripts/genesys/mcp/doc-tools.ts +86 -0
  114. package/src/templates/scripts/genesys/mcp/editor-functions.ts +151 -0
  115. package/src/templates/scripts/genesys/mcp/editor-tools.ts +73 -0
  116. package/src/templates/scripts/genesys/mcp/get-scene-state.ts +35 -0
  117. package/src/templates/scripts/genesys/mcp/run-subprocess.ts +30 -0
  118. package/src/templates/scripts/genesys/mcp/search-actors.ts +858 -0
  119. package/src/templates/scripts/genesys/mcp/search-assets.ts +380 -0
  120. package/src/templates/scripts/genesys/mcp/utils.ts +281 -0
  121. package/src/templates/scripts/genesys/misc.ts +42 -0
  122. package/src/templates/scripts/genesys/mock.ts +6 -0
  123. package/src/templates/scripts/genesys/place-actors.ts +179 -0
  124. package/src/templates/scripts/genesys/post-install.ts +30 -0
  125. package/src/templates/scripts/genesys/prefab.schema.json +85 -0
  126. package/src/templates/scripts/genesys/remove-engine-comments.ts +135 -0
  127. package/src/templates/scripts/genesys/run-mcp-inspector.bat +5 -0
  128. package/src/templates/scripts/genesys/storageProvider.ts +182 -0
  129. package/src/templates/scripts/genesys/validate-prefabs.ts +138 -0
  130. package/src/templates/src/index.ts +22 -0
  131. package/src/templates/src/templates/firstPerson/assets/default.genesys-scene +166 -0
  132. package/src/templates/src/templates/firstPerson/src/auto-imports.ts +0 -0
  133. package/src/templates/src/templates/firstPerson/src/game.ts +39 -0
  134. package/src/templates/src/templates/firstPerson/src/player.ts +63 -0
  135. package/src/templates/src/templates/fps/assets/default.genesys-scene +9460 -0
  136. package/src/templates/src/templates/fps/assets/models/SM_Beam_400.glb +0 -0
  137. package/src/templates/src/templates/fps/assets/models/SM_ChamferCube.glb +0 -0
  138. package/src/templates/src/templates/fps/assets/models/SM_Floor_Thick_400x400.glb +0 -0
  139. package/src/templates/src/templates/fps/assets/models/SM_Floor_Thick_400x400_Orange.glb +0 -0
  140. package/src/templates/src/templates/fps/assets/models/SM_Floor_Thin_400x400.glb +0 -0
  141. package/src/templates/src/templates/fps/assets/models/SM_Floor_Thin_400x400_Orange.glb +0 -0
  142. package/src/templates/src/templates/fps/assets/models/SM_Ramp_400x400.glb +0 -0
  143. package/src/templates/src/templates/fps/assets/models/SM_Rifle.glb +0 -0
  144. package/src/templates/src/templates/fps/assets/models/SM_Wall_Thin_400x200.glb +0 -0
  145. package/src/templates/src/templates/fps/assets/models/SM_Wall_Thin_400x200_Orange.glb +0 -0
  146. package/src/templates/src/templates/fps/assets/models/SM_Wall_Thin_400x400.glb +0 -0
  147. package/src/templates/src/templates/fps/assets/models/SM_Wall_Thin_400x400_Orange.glb +0 -0
  148. package/src/templates/src/templates/fps/src/auto-imports.ts +0 -0
  149. package/src/templates/src/templates/fps/src/game.ts +39 -0
  150. package/src/templates/src/templates/fps/src/player.ts +69 -0
  151. package/src/templates/src/templates/fps/src/weapon.ts +54 -0
  152. package/src/templates/src/templates/freeCamera/assets/default.genesys-scene +166 -0
  153. package/src/templates/src/templates/freeCamera/src/auto-imports.ts +0 -0
  154. package/src/templates/src/templates/freeCamera/src/game.ts +39 -0
  155. package/src/templates/src/templates/freeCamera/src/player.ts +45 -0
  156. package/src/templates/src/templates/sideScroller/assets/default.genesys-scene +122 -0
  157. package/src/templates/src/templates/sideScroller/src/auto-imports.ts +0 -0
  158. package/src/templates/src/templates/sideScroller/src/const.ts +46 -0
  159. package/src/templates/src/templates/sideScroller/src/game.ts +122 -0
  160. package/src/templates/src/templates/sideScroller/src/level-generator.ts +361 -0
  161. package/src/templates/src/templates/sideScroller/src/player.ts +125 -0
  162. package/src/templates/src/templates/thirdPerson/assets/default.genesys-scene +166 -0
  163. package/src/templates/src/templates/thirdPerson/src/auto-imports.ts +0 -0
  164. package/src/templates/src/templates/thirdPerson/src/game.ts +39 -0
  165. package/src/templates/src/templates/thirdPerson/src/player.ts +61 -0
  166. package/src/templates/src/templates/vehicle/assets/default.genesys-scene +226 -0
  167. package/src/templates/src/templates/vehicle/assets/models/cyberTruck/chassis.glb +0 -0
  168. package/src/templates/src/templates/vehicle/assets/models/cyberTruck/wheel.glb +0 -0
  169. package/src/templates/src/templates/vehicle/src/auto-imports.ts +0 -0
  170. package/src/templates/src/templates/vehicle/src/base-vehicle.ts +145 -0
  171. package/src/templates/src/templates/vehicle/src/game.ts +43 -0
  172. package/src/templates/src/templates/vehicle/src/mesh-vehicle.ts +191 -0
  173. package/src/templates/src/templates/vehicle/src/player.ts +109 -0
  174. package/src/templates/src/templates/vehicle/src/primitive-vehicle.ts +266 -0
  175. package/src/templates/src/templates/vehicle/src/ui-hints.ts +101 -0
  176. package/src/templates/src/templates/vr-game/assets/default.genesys-scene +247 -0
  177. package/src/templates/src/templates/vr-game/src/auto-imports.ts +1 -0
  178. package/src/templates/src/templates/vr-game/src/game.ts +66 -0
  179. package/src/templates/src/templates/vr-game/src/sample-vr-actor.ts +26 -0
  180. package/src/templates/tsconfig.json +35 -0
  181. package/src/templates/vite.config.ts +52 -0
@@ -0,0 +1,380 @@
1
+ import * as fs from 'fs';
2
+ import * as path from 'path';
3
+
4
+ import * as ENGINE from 'genesys.js';
5
+ import { zodToJsonSchema } from 'zod-to-json-schema';
6
+
7
+ import { BoundingBoxSchema, fetchBoundingBoxData } from '../calc-bounding-box.js';
8
+ import { ENGINE_PREFIX, JS_CLASSES_DIR_NAME, PROJECT_PREFIX, SCENE_EXTENSION } from '../const.js';
9
+ import { StorageProvider } from '../storageProvider.js';
10
+
11
+ import { populateClassesInfo } from './search-actors.js';
12
+ import { conditionallyRegisterGameClasses } from './utils.js';
13
+ import { isSubclass } from './utils.js';
14
+
15
+
16
+ // TODO: make it consistent to AssetType in genesys.ai
17
+ export enum AssetType {
18
+ Model = 'model',
19
+ Texture = 'texture',
20
+ HDRI = 'hdri',
21
+ Video = 'video',
22
+ Audio = 'audio',
23
+ Json = 'json',
24
+ Scene = 'scene',
25
+ Prefab = 'prefab',
26
+ Material = 'material',
27
+ SourceCode = 'sourcecode',
28
+ JsClass = 'jsclass',
29
+ }
30
+
31
+ const modelTypes = ['.glb', '.gltf'];
32
+
33
+ export const assetDescriptions: Record<AssetType, string> = {
34
+ [AssetType.Model]: '3D model files',
35
+ [AssetType.Texture]: 'Texture files',
36
+ [AssetType.HDRI]: 'HDRI files',
37
+ [AssetType.Video]: 'Video files',
38
+ [AssetType.Audio]: 'Audio files',
39
+ [AssetType.Scene]: 'Scenes, also known as levels, are generally used to represent distinct, playable areas in the game.',
40
+ [AssetType.Prefab]: 'Prefabs are actors that are prebuilt with components and can be placed in the scene directly. They generally extend Javascript classes to achieve more visual complex behavior.',
41
+ [AssetType.Material]: 'Material files',
42
+ [AssetType.SourceCode]: 'Source code files, including TypeScript and JavaScript files.',
43
+ [AssetType.JsClass]: 'JavaScript classes, which are actors that are implemented in code (Javascript). They contain visual and audio components, logics, or anything as they are implemented in code. They are often used directly in the scene, they also be used as a prefab base. Always consider this when placing things in the scene.',
44
+ [AssetType.Json]: 'JSON files, which are used to store data in a structured format.',
45
+ };
46
+
47
+ const assetTypeToExtensions: Record<AssetType, string[]> = {
48
+ [AssetType.Model]: modelTypes,
49
+ [AssetType.Texture]: ['.png', '.jpg', '.jpeg', '.gif', '.bmp', '.tiff', '.ico', '.webp'],
50
+ [AssetType.HDRI]: ['.hdr', '.exr'],
51
+ [AssetType.Video]: ['.mp4', '.webm', '.mov', '.avi', '.mkv'],
52
+ [AssetType.Audio]: ['.mp3', '.wav', '.ogg', '.m4a', '.aac'],
53
+ [AssetType.Scene]: [SCENE_EXTENSION],
54
+ [AssetType.Prefab]: ['.prefab.json'],
55
+ [AssetType.Material]: ['.material.json'],
56
+ [AssetType.SourceCode]: ['.ts', '.js', '.tsx', '.jsx'],
57
+ [AssetType.JsClass]: [],
58
+ [AssetType.Json]: ['.json'],
59
+ };
60
+
61
+ interface AssetPopulationOptions {
62
+ peek?: boolean; // if true, only populate the basic metadata, such as name and description
63
+ }
64
+
65
+ const findAssetType = (filePath: string) => {
66
+ if (filePath.includes(JS_CLASSES_DIR_NAME)) {
67
+ return AssetType.JsClass;
68
+ }
69
+
70
+ const extension = path.extname(filePath).toLowerCase();
71
+ for (const [assetType, extensions] of Object.entries(assetTypeToExtensions)) {
72
+ // make sure .json is checked last
73
+ if (assetType === AssetType.Json) {
74
+ continue;
75
+ }
76
+
77
+ if (extensions.includes(extension)) {
78
+ return assetType as AssetType;
79
+ }
80
+ }
81
+
82
+ if (assetTypeToExtensions[AssetType.Json].includes(extension)) {
83
+ return AssetType.Json;
84
+ }
85
+
86
+ return undefined;
87
+ };
88
+
89
+ export interface Metadata {
90
+ [key: string]: any;
91
+ }
92
+
93
+ export interface AssetsInfo {
94
+ metadataDescription: Record<string, any>;
95
+ assets: Record<string, Metadata>;
96
+ }
97
+
98
+
99
+
100
+ /**
101
+ * Recursively iterates a given directory and returns an array of all file paths
102
+ * that match the accepted types.
103
+ * @param dir The directory to iterate.
104
+ * @param acceptedTypes Array of accepted types.
105
+ * @returns An array of file paths.
106
+ */
107
+ export async function searchForAssets(
108
+ dirs: string[],
109
+ acceptedTypes: AssetType[] = [],
110
+ searchKeywords: string[] = []
111
+ ): Promise<AssetsInfo> {
112
+ for (const dir of dirs) {
113
+ if (!dir.startsWith(ENGINE.PROJECT_PATH_PREFIX) && !dir.startsWith(ENGINE.ENGINE_PATH_PREFIX)) {
114
+ throw new Error(`Directory ${dir} is not a valid project or engine directory`);
115
+ }
116
+ }
117
+
118
+ // make sure the game is built and classes are registered
119
+ await conditionallyRegisterGameClasses();
120
+
121
+ const acceptedExtensions = acceptedTypes.map(type => assetTypeToExtensions[type]).flat();
122
+ const getAll = acceptedTypes.length === 0;
123
+ const files = dirs.map(dir => collectFiles(dir, { getAll, acceptedExtensions })).flat();
124
+
125
+ // handle js classes in a special way.
126
+ if (getAll || acceptedTypes.includes(AssetType.JsClass)) {
127
+ const jsClasses = dirs.map(dir => {
128
+ const prefix = dir.includes(PROJECT_PREFIX) ? ENGINE.Prefix.GAME : (dir.includes(ENGINE_PREFIX) ? ENGINE.Prefix.ENGINE : '');
129
+ const registeredClasses = ENGINE.ClassRegistry.getRegistry();
130
+ const actorClasses = Array.from(registeredClasses.entries()).filter(
131
+ ([className, classCtor]) => className.startsWith(prefix) && isSubclass(classCtor, ENGINE.Actor) && !isSubclass(classCtor, ENGINE.BaseGameLoop));
132
+ return actorClasses.map(([key]) => `${JS_CLASSES_DIR_NAME}/${key}`);
133
+ });
134
+ files.push(...jsClasses.flat());
135
+ }
136
+
137
+ // convert file paths to unix paths
138
+ const assetPaths: string[] = files.map(filePath => filePath.replace(/\\/g, '/'));
139
+
140
+ // only peeking for basic metadata when searching assets to reduce the amount of data transferred
141
+ const result: AssetsInfo = await populateAssets(assetPaths, { peek: true });
142
+
143
+ // filter assets as we rely on not only names, but the metadata as well, to filter them
144
+ filterAssets(result, searchKeywords);
145
+
146
+ return result;
147
+ }
148
+
149
+
150
+ /**
151
+ * Gets the assets info with metadata for the given asset paths.
152
+ * @param assetPaths The paths of the assets to populate. It must be retrieved from `searchForAssets` function.
153
+ * @param options population options, such as `peek` to only populate basic metadata.
154
+ * @returns A promise that resolves to the assets info with metadata.
155
+ */
156
+ export async function populateAssets(
157
+ assetPaths: string[],
158
+ options: AssetPopulationOptions
159
+ ): Promise<AssetsInfo> {
160
+
161
+ const result: AssetsInfo = {
162
+ metadataDescription: {},
163
+ assets: assetPaths.reduce((acc, assetPath) => {
164
+ acc[assetPath] = {type: findAssetType(assetPath)};
165
+ return acc;
166
+ }, {} as Record<string, Metadata>)
167
+ };
168
+
169
+ await populateModels(result, options);
170
+ await populateJsClasses(result, options);
171
+
172
+ return result;
173
+ }
174
+
175
+
176
+ function collectFiles(
177
+ dir: string,
178
+ options: {
179
+ getAll: boolean;
180
+ acceptedExtensions: string[];
181
+ }
182
+ ): string[] {
183
+ let results: string[] = [];
184
+ const storageProvider = new StorageProvider();
185
+ const actualDir = storageProvider.getFullPath(dir);
186
+ const list = fs.readdirSync(actualDir);
187
+ // Normalize accepted extensions to lower case for case-insensitive comparison
188
+ const normalizedExtensions = options.acceptedExtensions.map(ext => ext.toLowerCase());
189
+ list.forEach((file) => {
190
+ const filePath = path.join(dir, file);
191
+ const actualFilePath = storageProvider.getFullPath(filePath);
192
+ const stat = fs.statSync(actualFilePath);
193
+ if (stat && stat.isDirectory()) {
194
+ results = results.concat(collectFiles(filePath, options));
195
+ } else {
196
+ let shouldKeep = false;
197
+ if (options.getAll) {
198
+ shouldKeep = true;
199
+ }
200
+ else {
201
+ const fileName = path.basename(filePath).toLowerCase();
202
+ if (normalizedExtensions.some((ext) => fileName.endsWith(ext))) {
203
+ shouldKeep = true;
204
+ }
205
+ }
206
+ if (shouldKeep) {
207
+ results.push(filePath);
208
+ }
209
+ }
210
+ });
211
+ return results;
212
+ }
213
+
214
+
215
+ function filterAssets(assets: AssetsInfo, searchKeywords: string[] = []) {
216
+ // if searchKeywords is not empty, filter the result
217
+ if (searchKeywords.length > 0) {
218
+ const rule = (filePath: string, metadata: any) => {
219
+ for (const keyword of searchKeywords) {
220
+ const kw = keyword.toLowerCase();
221
+
222
+ // if the file path contains any of the search keywords, return true
223
+ if (filePath.toLowerCase().includes(kw)) {
224
+ return true;
225
+ }
226
+
227
+ // if the file metadata values contains any of the search keywords, return true
228
+ if (Object.values(metadata).some((metadataValue: any) => {
229
+ return JSON.stringify(metadataValue).toLowerCase().includes(kw);
230
+ })) {
231
+ return true;
232
+ }
233
+ }
234
+ return false;
235
+ };
236
+
237
+ assets.assets = Object.fromEntries(
238
+ Object.entries(assets.assets).filter(([filePath, metadata]) => rule(filePath, metadata))
239
+ );
240
+ }
241
+ }
242
+
243
+ async function populateModels(assets: AssetsInfo, options: AssetPopulationOptions) {
244
+ if (Object.values(assets.assets).some(asset => asset.type === AssetType.Model)) {
245
+ await populateModelsMetadata(assets);
246
+ if (!options?.peek) {
247
+ await populateBoundingBoxes(assets);
248
+ }
249
+ }
250
+ }
251
+
252
+ async function populateModelsMetadata(assets: AssetsInfo): Promise<void> {
253
+ // read manifest.json, and populate the result with the file details
254
+ const manifest: Record<string, Record<string, string>> = {};
255
+ const storageProvider = new StorageProvider();
256
+ for (const dir of [ENGINE.PROJECT_PATH_PREFIX, ENGINE.ENGINE_PATH_PREFIX]) {
257
+ const assetsManifest = path.join(dir, 'assets', 'manifest.json');
258
+ Object.assign(manifest, await storageProvider.downloadFileAsJson<any>(ENGINE.AssetPath.fromString(assetsManifest)));
259
+ }
260
+
261
+ let metadataDescription: Record<string, any> = {};
262
+ if (manifest) {
263
+ // populate metadata description if it exists
264
+ metadataDescription = manifest['$metadata_description'] ?? {};
265
+
266
+ // populate the result with the file details
267
+ for (const [filePath, targetMetadata] of Object.entries(assets.assets)) {
268
+ const metadata = manifest[filePath];
269
+ if (metadata !== undefined && metadata !== null && metadata.constructor == Object) {
270
+ Object.assign(targetMetadata, metadata);
271
+ }
272
+ }
273
+ }
274
+
275
+ assets.metadataDescription[AssetType.Model] = {
276
+ ...assets.metadataDescription[AssetType.Model],
277
+ ...metadataDescription,
278
+ };
279
+ }
280
+
281
+ async function populateBoundingBoxes(assets: AssetsInfo) {
282
+ const modelFiles = Object.keys(assets.assets).filter(filePath =>
283
+ modelTypes.includes(path.extname(filePath).toLowerCase())
284
+ );
285
+
286
+ // split model files into two groups - engine and project
287
+ const engineModelFiles = modelFiles.filter(filePath =>
288
+ filePath.startsWith(ENGINE.ENGINE_PATH_PREFIX)
289
+ );
290
+ const projectModelFiles = modelFiles.filter(filePath =>
291
+ filePath.startsWith(ENGINE.PROJECT_PATH_PREFIX)
292
+ );
293
+
294
+ const update = async (root: string, modelFiles: string[]) => {
295
+ const manifestFile = path.join(root, 'assets', 'bounding_box.json');
296
+ const storageProvider = new StorageProvider();
297
+ const gltfPaths: {[key: string]: string} = {};
298
+ for (const filePath of modelFiles) {
299
+ gltfPaths[filePath] = storageProvider.getFullPath(filePath);
300
+ }
301
+ const boundingBoxes = await fetchBoundingBoxData(storageProvider.getFullPath(manifestFile), gltfPaths);
302
+ for (const [filePath, boundingBox] of Object.entries(boundingBoxes)) {
303
+ assets.assets[filePath]['boundingBox'] = boundingBox;
304
+ }
305
+ };
306
+
307
+ if (engineModelFiles.length > 0) {
308
+ await update(ENGINE.ENGINE_PATH_PREFIX, engineModelFiles);
309
+ }
310
+
311
+ if (projectModelFiles.length > 0) {
312
+ await update(ENGINE.PROJECT_PATH_PREFIX, projectModelFiles);
313
+ }
314
+
315
+ if (engineModelFiles.length > 0 || projectModelFiles.length > 0) {
316
+ // also populate the metadata description for bounding box
317
+ const boundingBoxSchema = zodToJsonSchema(BoundingBoxSchema, 'BoundingBoxSchema');
318
+ const properties = (boundingBoxSchema as any).definitions.BoundingBoxSchema.properties;
319
+ const boundingBoxDescription: Record<string, string> = {};
320
+ for (const key in properties) {
321
+ if (properties[key].description) {
322
+ boundingBoxDescription[key] = properties[key].description;
323
+ }
324
+ }
325
+ const metadataDescription = {
326
+ boundingBox: {
327
+ description: 'The bounding box info of model assets',
328
+ properties: boundingBoxDescription,
329
+ }
330
+ };
331
+ assets.metadataDescription[AssetType.Model] = {
332
+ ...assets.metadataDescription[AssetType.Model],
333
+ ...metadataDescription
334
+ };
335
+ }
336
+ }
337
+
338
+ async function populateJsClasses(assets: AssetsInfo, options: AssetPopulationOptions): Promise<void> {
339
+ const jsClassNames: Record<string, string> = {};
340
+ for (const [filePath, metadata] of Object.entries(assets.assets)) {
341
+ if (filePath.includes(JS_CLASSES_DIR_NAME)) {
342
+ jsClassNames[filePath] = path.basename(filePath);
343
+ }
344
+ }
345
+
346
+ if (Object.keys(jsClassNames).length === 0) {
347
+ return;
348
+ }
349
+ const result = await populateClassesInfo({
350
+ classesToSearch: Object.values(jsClassNames),
351
+ includeConstructorParams: !options?.peek
352
+ });
353
+
354
+ if (result.actors
355
+ && Object.keys(result.actors).length > 0
356
+ && result.metadataDescription
357
+ && Object.keys(result.metadataDescription).length > 0) {
358
+
359
+ assets.metadataDescription[AssetType.JsClass] = result.metadataDescription;
360
+ }
361
+
362
+ for (const [filePath, metadata] of Object.entries(assets.assets)) {
363
+ if (filePath in jsClassNames) {
364
+ const className = jsClassNames[filePath];
365
+ const actorInfo = result.actors[className];
366
+ if (actorInfo) {
367
+ metadata.jsClassName = actorInfo.className;
368
+ if (!options?.peek) {
369
+ metadata.jsClassFilePath = actorInfo.filePath;
370
+ metadata.jsClassConstructorParams = actorInfo.constructorParams ?? [];
371
+ metadata.jsClassCanPopulateFromJson = actorInfo.canPopulateFromJson ?? false;
372
+ }
373
+ metadata.jsClassDescription = actorInfo.description ?? '';
374
+ } else {
375
+ console.warn(`Actor class ${className} not found in classes info for file ${filePath}`);
376
+ }
377
+ }
378
+ }
379
+ }
380
+
@@ -0,0 +1,281 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+
4
+ import * as ENGINE from 'genesys.js';
5
+ import * as THREE from 'three';
6
+ import { type GLTF } from 'three/examples/jsm/loaders/GLTFLoader.js';
7
+
8
+ import { isDev } from '../common.js';
9
+ import { mockBrowserEnvironment } from '../mock.js';
10
+ import { getResolvedPath, StorageProvider } from '../storageProvider.js';
11
+
12
+ import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
13
+
14
+ const fileServerPort = !isDev ? 4000 : 4001;
15
+
16
+ mockBrowserEnvironment();
17
+
18
+ class ResourceManagerSkippingLoadingGLTF extends ENGINE.ResourceManager {
19
+ public override async loadModel(path: ENGINE.AssetPath): Promise<GLTF | null> {
20
+ return null;
21
+ }
22
+ }
23
+
24
+ export const fixUpClassName = (className: string) => {
25
+ const allClasses = ENGINE.ClassRegistry.getRegistry();
26
+
27
+ if (allClasses.has(className)) {
28
+ return className;
29
+ }
30
+
31
+ const gameClassName = ENGINE.Prefix.GAME + className;
32
+ if (allClasses.has(gameClassName)) {
33
+ return gameClassName;
34
+ }
35
+
36
+ const engineClassName = ENGINE.Prefix.ENGINE + className;
37
+ if (allClasses.has(engineClassName)) {
38
+ return engineClassName;
39
+ }
40
+
41
+ throw new Error(`Class ${className} not found`);
42
+ };
43
+
44
+ export interface LoadWorldOptions {
45
+ readonly?: boolean;
46
+ skipLoadingGLTF?: boolean;
47
+ }
48
+
49
+ export async function loadWorld(scenePath: string, options: LoadWorldOptions = {}) {
50
+ const storageProvider = new StorageProvider();
51
+ const cleanUp = ENGINE.projectContext({ project: 'local-project', storageProvider: storageProvider });
52
+
53
+ const sceneFile = scenePath;
54
+
55
+ let world: ENGINE.World | null = null;
56
+
57
+ let originalResourceManager = null;
58
+ if (!options.skipLoadingGLTF) {
59
+ originalResourceManager = ENGINE.resourceManager;
60
+ ENGINE.setResourceManager(new ResourceManagerSkippingLoadingGLTF());
61
+ }
62
+
63
+ try {
64
+ world = new ENGINE.World(defaultWorldOptions);
65
+ const worldData = await storageProvider.downloadFileAsJson<any>(ENGINE.AssetPath.fromString(sceneFile));
66
+
67
+ // wait for all gltf mesh components to load, should probably move this into engine.
68
+ const actors = world.getActors(ENGINE.Actor);
69
+ const promises = actors.map(actor => actor.waitForComponentsToLoad());
70
+ await Promise.all(promises);
71
+
72
+ await ENGINE.WorldSerializer.loadWorld(world, worldData);
73
+ } catch (error) {
74
+ cleanUp();
75
+ throw new Error(`Failed to load world from ${sceneFile}: ${error instanceof Error ? error.message : error}`);
76
+ } finally {
77
+ if (originalResourceManager) {
78
+ ENGINE.setResourceManager(originalResourceManager);
79
+ }
80
+ }
81
+
82
+ return {
83
+ world: world,
84
+ [Symbol.dispose]() {
85
+ if (!options.readonly && world) {
86
+ const worldData = world.asExportedObject();
87
+ fs.writeFileSync(storageProvider.getFullPath(sceneFile), JSON.stringify(worldData, null, 2));
88
+ }
89
+ cleanUp();
90
+ }
91
+ };
92
+ }
93
+
94
+ export const defaultWorldOptions = {
95
+ rendererDomElement: document.createElement('div'),
96
+ gameContainer: document.createElement('div'),
97
+ backgroundColor: 0x2E2E2E,
98
+ physicsOptions: {
99
+ engine: ENGINE.PhysicsEngine.Rapier,
100
+ gravity: ENGINE.MathHelpers.makeVector({ up: -9.81 }),
101
+ },
102
+ navigationOptions: {
103
+ engine: ENGINE.NavigationEngine.RecastNavigation,
104
+ },
105
+ useManifold: true
106
+ };
107
+
108
+ export function mcpLogger(server: McpServer): Disposable {
109
+ const originalConsoleLog = console.log;
110
+ const originalConsoleWarn = console.warn;
111
+ const originalConsoleError = console.error;
112
+
113
+ // it seems sendLoggingMessage isn't picked up by cursor as of 2025 July 17th,
114
+ // The log can't be found in any of the output channels, or in cursor logs
115
+ // for now we log to stderr, which is supported by MCP
116
+ // https://modelcontextprotocol.io/docs/tools/debugging#implementing-logging
117
+ const sendLogToClient = false;
118
+
119
+ console.log = (...args: any[]) => {
120
+ originalConsoleError('[MCP Info]: ', ...args);
121
+ if (sendLogToClient) {
122
+ server.server.sendLoggingMessage({ level: 'info', data: args.join(' ') });
123
+ }
124
+ };
125
+ console.warn = (...args: any[]) => {
126
+ originalConsoleError('[MCP Warning]: ', ...args);
127
+ if (sendLogToClient) {
128
+ server.server.sendLoggingMessage({ level: 'warning', data: args.join(' ') });
129
+ }
130
+ };
131
+ console.error = (...args: any[]) => {
132
+ originalConsoleError('[MCP Error]: ', ...args);
133
+ if (sendLogToClient) {
134
+ server.server.sendLoggingMessage({ level: 'error', data: args.join(' ') });
135
+ }
136
+ };
137
+
138
+ return {
139
+ [Symbol.dispose]() {
140
+ console.log = originalConsoleLog;
141
+ console.warn = originalConsoleWarn;
142
+ console.error = originalConsoleError;
143
+ }
144
+ };
145
+ }
146
+
147
+ export function isSubclass(child: Function | null | undefined, parent: Function): boolean {
148
+ if (typeof child !== 'function' || typeof parent !== 'function') return false;
149
+ let proto: any = child;
150
+ while (proto) {
151
+ if (proto === parent) return true;
152
+ proto = Object.getPrototypeOf(proto);
153
+ }
154
+ return false;
155
+ }
156
+
157
+ async function buildProject() {
158
+ const url = `http://localhost:${fileServerPort}/api/build-project`;
159
+ const options = {
160
+ method: 'POST'
161
+ };
162
+ const response = await fetch(url, options);
163
+ if (!response.ok) {
164
+ throw new Error(`Failed to rebuild game.js: ${response.statusText}`);
165
+ }
166
+ const result = await response.json();
167
+ return result;
168
+ }
169
+
170
+ export async function registerGameClasses(): Promise<void> {
171
+ const bundlePath = ENGINE.AssetPath.fromString(ENGINE.AssetPath.join(ENGINE.PROJECT_PATH_PREFIX, '.dist', 'game.js'));
172
+ const storageProvider = new StorageProvider();
173
+ storageProvider.resolvePath(bundlePath);
174
+ try {
175
+ const buildProjectResult = await buildProject();
176
+
177
+ const bundleFullPath = getResolvedPath(bundlePath);
178
+ if (!fs.existsSync(bundleFullPath)) {
179
+ throw new Error(`bundle file not found at ${bundleFullPath}, please make sure build project is successful, buildProject result: ${JSON.stringify(buildProjectResult)}`);
180
+ }
181
+
182
+ const bundleText = fs.readFileSync(bundleFullPath, 'utf8');
183
+ const injectedDependencies = (mod: string) => {
184
+ if (mod === 'genesys.js') return ENGINE;
185
+ if (mod === 'three') return THREE;
186
+ throw new Error(`Unknown module: ${mod}`);
187
+ };
188
+
189
+ ENGINE.ClassRegistry.clearGameClasses();
190
+ // Create a module-like object to simulate CommonJS environment
191
+ const moduleObj = { exports: {} };
192
+ const run = new Function('require', 'module', bundleText);
193
+ run(injectedDependencies, moduleObj);
194
+
195
+ // Apply any exports to the global scope if needed
196
+ if (moduleObj.exports && typeof moduleObj.exports === 'object') {
197
+ Object.assign(window, moduleObj.exports);
198
+ }
199
+ } catch (error) {
200
+ console.error('Error registering game classes', error);
201
+ }
202
+ }
203
+
204
+ export function isClassRegistered(className: string): boolean {
205
+ return ENGINE.ClassRegistry.getRegistry().has(className);
206
+ }
207
+
208
+ export async function registerGameClassesIfAnyNotRegistered(classNamesToCheck: string[]): Promise<void> {
209
+ const validNames = classNamesToCheck.filter((className) => className.startsWith(ENGINE.Prefix.GAME) || className.startsWith(ENGINE.Prefix.ENGINE));
210
+ if (validNames.some(className => !isClassRegistered(className))) {
211
+ await registerGameClasses();
212
+ }
213
+ }
214
+
215
+ export async function conditionallyRegisterGameClasses(): Promise<void> {
216
+ const storageProvider = new StorageProvider();
217
+
218
+ const bundlePath = ENGINE.AssetPath.fromString(ENGINE.AssetPath.join(ENGINE.PROJECT_PATH_PREFIX, '.dist', 'game.js'));
219
+ storageProvider.resolvePath(bundlePath);
220
+
221
+ const srcDir = ENGINE.AssetPath.fromString(ENGINE.AssetPath.join(ENGINE.PROJECT_PATH_PREFIX, 'src'));
222
+ storageProvider.resolvePath(srcDir);
223
+
224
+ // Check if .dist/game.js exists
225
+ if (!fs.existsSync(bundlePath.getResolvedPath())) {
226
+ // If game.js doesn't exist, we need to register classes
227
+ await registerGameClasses();
228
+ return;
229
+ }
230
+
231
+ const bundleFileStats = fs.statSync(getResolvedPath(bundlePath));
232
+ const bundleFileTimestamp = bundleFileStats.mtime.getTime();
233
+ console.log('bundleFileTimestamp:', new Date(bundleFileTimestamp));
234
+
235
+ // Check if src directory exists
236
+ if (!fs.existsSync(getResolvedPath(srcDir))) {
237
+ console.log('No src directory, no need to register classes');
238
+ return; // No src directory, nothing to check
239
+ }
240
+
241
+ // Recursively find all js, jsx, ts, tsx files in src directory
242
+ const sourceFiles = findSourceFiles(getResolvedPath(srcDir));
243
+
244
+ // Check if any source file is newer than game.js
245
+ for (const sourceFile of sourceFiles) {
246
+ const sourceStats = fs.statSync(sourceFile);
247
+ const sourceTime = sourceStats.mtime.getTime();
248
+
249
+ if (sourceTime > bundleFileTimestamp) {
250
+ // Found a newer source file, register classes and return
251
+ console.log(`Found a newer source file, ${sourceFile}, timestamp ${new Date(sourceTime)}, registering classes`);
252
+ await registerGameClasses();
253
+ return;
254
+ }
255
+ }
256
+
257
+ console.log('No newer source files found, no need to register classes');
258
+ }
259
+
260
+ function findSourceFiles(dir: string): string[] {
261
+ const sourceFiles: string[] = [];
262
+ const entries = fs.readdirSync(dir, { withFileTypes: true });
263
+
264
+ for (const entry of entries) {
265
+ const fullPath = path.join(dir, entry.name);
266
+
267
+ if (entry.isDirectory()) {
268
+ // Recursively search subdirectories
269
+ sourceFiles.push(...findSourceFiles(fullPath));
270
+ } else if (entry.isFile()) {
271
+ // Check if file has one of the target extensions
272
+ const ext = path.extname(entry.name).toLowerCase();
273
+ if (['.js', '.jsx', '.ts', '.tsx'].includes(ext)) {
274
+ sourceFiles.push(fullPath);
275
+ }
276
+ }
277
+ }
278
+
279
+ return sourceFiles;
280
+ }
281
+
@@ -0,0 +1,42 @@
1
+ import path from 'path';
2
+
3
+ import * as ENGINE from 'genesys.js';
4
+
5
+ import { getProjectRoot } from './common.js';
6
+ import { isSubclass } from './mcp/utils.js';
7
+ import { fixUpClassName, registerGameClasses } from './mcp/utils.js';
8
+ import { StorageProvider } from './storageProvider.js';
9
+
10
+
11
+ export async function generateCode(className: string, filePath: string, baseClassName: string): Promise<boolean> {
12
+ try {
13
+ baseClassName = fixUpClassName(baseClassName);
14
+ }
15
+ catch (error) {
16
+ // if the base class name is not found, register all game classes and try again
17
+ await registerGameClasses();
18
+ baseClassName = fixUpClassName(baseClassName);
19
+ }
20
+
21
+ using context = ENGINE.scopedProjectContext({project: 'mcp-project', storageProvider: new StorageProvider()});
22
+
23
+ const testIsSubclass = (childName: string, parent: Function) => {
24
+ const child = ENGINE.ClassRegistry.getRegistry().get(childName);
25
+ if (!child) {
26
+ return false;
27
+ }
28
+ return isSubclass(child, parent);
29
+ };
30
+
31
+ const fullFilePath = path.isAbsolute(filePath) ? filePath : path.join(getProjectRoot(), filePath);
32
+
33
+ let fileGenerated = false;
34
+ const isSubclassOfActor = testIsSubclass(baseClassName, ENGINE.Actor);
35
+ if (isSubclassOfActor) {
36
+ await ENGINE.WorldCommands.generateActorTemplateFile(className, fullFilePath, baseClassName);
37
+ fileGenerated = true;
38
+ }
39
+
40
+ return fileGenerated;
41
+ }
42
+