cocos2d-cli 1.1.1 → 1.1.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.
@@ -1,21 +1,30 @@
1
1
  /**
2
- * create-scene 命令 - 从树形文本结构创建场景文件
2
+ * create-scene 命令 - 从 JSON 结构创建场景文件
3
3
  *
4
- * 示例输入:
5
- * Canvas
6
- * ├─ TopBar (sprite, widget)
7
- * ├─ ScoreLabel (label)
8
- * ├─ LivesContainer
9
- * └─ GoldLabel (label)
10
- * ├─ GameArea
11
- * └─ BottomBar
4
+ * JSON 格式示例:
5
+ * {
6
+ * "name": "Panel",
7
+ * "width": 400,
8
+ * "height": 300,
9
+ * "color": "#ffffff",
10
+ * "components": [
11
+ * { "type": "sprite", "sizeMode": 1 },
12
+ * { "type": "widget", "top": 0, "bottom": 0 }
13
+ * ],
14
+ * "children": [...]
15
+ * }
16
+ *
17
+ * 节点属性:name, width, height, x, y, color, opacity, anchorX, anchorY, rotation, scaleX, scaleY, active
18
+ * 组件属性:type + 各组件特有属性
19
+ *
20
+ * 场景会自动包含 Canvas 和 Main Camera 节点
12
21
  */
13
22
 
14
23
  const fs = require('fs');
15
24
  const path = require('path');
16
- const { Components, generateId, createNodeData } = require('../lib/components');
25
+ const { Components, generateId } = require('../lib/components');
17
26
 
18
- // 支持的组件类型映射
27
+ // 支持的组件类型
19
28
  const COMPONENT_TYPES = {
20
29
  'sprite': 'sprite',
21
30
  'label': 'label',
@@ -28,262 +37,380 @@ const COMPONENT_TYPES = {
28
37
  'particlesystem': 'particleSystem'
29
38
  };
30
39
 
31
- // 渲染组件(一个节点只能有一个)
32
- const RENDER_COMPONENTS = ['sprite', 'label', 'graphics', 'mask', 'richtext', 'particleSystem'];
33
-
34
- // 功能组件(可以和渲染组件共存,也可以多个共存)
35
- const FUNCTIONAL_COMPONENTS = ['button', 'widget', 'layout', 'canvas', 'camera'];
36
-
37
40
  /**
38
- * 校验节点的组件配置
39
- * @returns {object} { valid: boolean, error?: string, warning?: string }
41
+ * 解析颜色字符串 #RRGGBB 或 #RRGGBBAA
40
42
  */
41
- function validateNodeComponents(nodeName, components) {
42
- const renderComps = components.filter(c => RENDER_COMPONENTS.includes(c));
43
+ function parseColor(colorStr) {
44
+ if (!colorStr || typeof colorStr !== 'string') return null;
43
45
 
44
- if (renderComps.length > 1) {
46
+ let hex = colorStr.replace('#', '');
47
+ if (hex.length === 6) {
45
48
  return {
46
- valid: false,
47
- error: `节点 "${nodeName}" 有多个渲染组件 [${renderComps.join(', ')}],Cocos Creator 不支持。
48
-
49
- 解决方法:将渲染组件拆分到子节点:
50
- ${nodeName} (${components.filter(c => !RENDER_COMPONENTS.includes(c)).join(', ') || '无组件'})
51
- └─ ${nodeName}Graphic (${renderComps[0]})
52
-
53
- 渲染组件: sprite, label, graphics, mask, richtext, particle
54
- 功能组件: button, widget, layout, canvas, camera (可多个共存)`
49
+ r: parseInt(hex.substring(0, 2), 16),
50
+ g: parseInt(hex.substring(2, 4), 16),
51
+ b: parseInt(hex.substring(4, 6), 16),
52
+ a: 255
53
+ };
54
+ } else if (hex.length === 8) {
55
+ return {
56
+ r: parseInt(hex.substring(0, 2), 16),
57
+ g: parseInt(hex.substring(2, 4), 16),
58
+ b: parseInt(hex.substring(4, 6), 16),
59
+ a: parseInt(hex.substring(6, 8), 16)
55
60
  };
56
61
  }
57
-
58
- return { valid: true };
62
+ return null;
63
+ }
64
+
65
+ /**
66
+ * 生成 UUID
67
+ */
68
+ function generateUUID() {
69
+ return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
70
+ const r = Math.random() * 16 | 0;
71
+ const v = c === 'x' ? r : (r & 0x3 | 0x8);
72
+ return v.toString(16);
73
+ });
59
74
  }
60
75
 
61
76
  /**
62
- * 递归校验所有节点
77
+ * 解析组件定义
63
78
  */
64
- function validateAllNodes(nodes, path = '') {
65
- const errors = [];
79
+ function parseComponent(compDef) {
80
+ if (typeof compDef === 'string') {
81
+ const type = COMPONENT_TYPES[compDef.toLowerCase()];
82
+ return type ? { type, props: {} } : null;
83
+ }
66
84
 
67
- for (const node of nodes) {
68
- const nodePath = path ? `${path}/${node.name}` : node.name;
69
- const validation = validateNodeComponents(node.name, node.components);
70
-
71
- if (!validation.valid) {
72
- errors.push({ node: nodePath, error: validation.error });
73
- }
85
+ if (typeof compDef === 'object' && compDef.type) {
86
+ const type = COMPONENT_TYPES[compDef.type.toLowerCase()];
87
+ if (!type) return null;
74
88
 
75
- // 递归检查子节点
76
- if (node.children && node.children.length > 0) {
77
- const childErrors = validateAllNodes(node.children, nodePath);
78
- errors.push(...childErrors);
79
- }
89
+ const props = { ...compDef };
90
+ delete props.type;
91
+ return { type, props };
80
92
  }
81
93
 
82
- return errors;
94
+ return null;
83
95
  }
84
96
 
85
97
  /**
86
- * 解析树形文本结构
87
- * 支持格式:
88
- * - 节点名称
89
- * - 节点名称 (组件1, 组件2)
90
- * - 节点名称 #width=100 #height=50 #x=10 #y=20
91
- *
92
- * 树形符号支持:
93
- * ├─ └─ │ 以及 Windows 下可能出现的 ? 乱码形式
98
+ * 应用组件属性
94
99
  */
95
- function parseTreeText(text) {
96
- const lines = text.split('\n').filter(line => line.trim());
97
- const rootNodes = [];
98
- const stack = []; // [{ depth, node }]
99
-
100
- for (const line of lines) {
101
- if (!line.trim()) continue;
102
-
103
- // 计算深度:通过测量前导非内容字符
104
- // Windows 下树形符号可能被编码成 ?? 或 ? ??
105
- // 策略:计算 ?? 或 ├─ 这样的分支标记数量
106
-
107
- let depth = 0;
108
- let contentStart = 0;
109
-
110
- // 首先尝试匹配树形模式
111
- // 模式1: Unicode 树形符号 ├ └
112
- // 模式2: Windows 乱码 ??
113
- const branchPattern = /([├└]─|├|└|\?\?|\?)\s*/g;
114
- const branches = [];
115
- let match;
116
- let lastBranchEnd = 0;
117
-
118
- while ((match = branchPattern.exec(line)) !== null) {
119
- branches.push(match[1]);
120
- lastBranchEnd = match.index + match[0].length;
121
- }
100
+ function applyComponentProps(comp, props) {
101
+ if (!props || !comp) return;
102
+
103
+ const type = comp.__type__;
104
+
105
+ // Widget 特殊处理:根据设置的方向计算 alignFlags
106
+ if (type === 'cc.Widget') {
107
+ const ALIGN = {
108
+ top: 1,
109
+ verticalCenter: 2,
110
+ bottom: 4,
111
+ left: 8,
112
+ horizontalCenter: 16,
113
+ right: 32
114
+ };
115
+ let alignFlags = 0;
122
116
 
123
- if (branches.length > 0) {
124
- // 找到了分支符号,深度 = 分支数量
125
- depth = branches.length;
126
- contentStart = lastBranchEnd;
127
- } else {
128
- // 没有分支符号,检查缩进
129
- for (let i = 0; i < line.length; i++) {
130
- const char = line[i];
131
- if (char !== ' ' && char !== '\t') {
132
- contentStart = i;
133
- break;
134
- }
117
+ for (const dir of ['top', 'bottom', 'left', 'right', 'horizontalCenter', 'verticalCenter']) {
118
+ if (props[dir] !== undefined && props[dir] !== null) {
119
+ alignFlags |= ALIGN[dir];
135
120
  }
136
- depth = Math.floor(contentStart / 4);
137
121
  }
138
-
139
- // 提取节点内容
140
- let content = line.substring(contentStart).trim();
141
122
 
142
- // 清理可能残留的符号(- 和空格)
143
- content = content.replace(/^[\-\s]+/, '').trim();
144
-
145
- if (!content) continue;
146
-
147
- // 解析节点信息
148
- const nodeInfo = parseNodeLine(content);
149
-
150
- // 构建树结构
151
- while (stack.length > depth) {
152
- stack.pop();
153
- }
154
-
155
- const node = {
156
- name: nodeInfo.name,
157
- components: nodeInfo.components,
158
- options: nodeInfo.options,
159
- children: []
160
- };
161
-
162
- if (stack.length === 0) {
163
- rootNodes.push(node);
164
- } else {
165
- stack[stack.length - 1].node.children.push(node);
123
+ if (alignFlags > 0) {
124
+ comp._alignFlags = alignFlags;
166
125
  }
167
-
168
- stack.push({ depth, node });
169
126
  }
170
-
171
- return rootNodes;
172
- }
173
-
174
- /**
175
- * 解析单行节点定义
176
- * 格式:NodeName (comp1, comp2) #key=value
177
- */
178
- function parseNodeLine(line) {
179
- let name = line;
180
- let components = [];
181
- let options = {};
182
-
183
- // 提取组件 (xxx)
184
- const compMatch = line.match(/\(([^)]+)\)/);
185
- if (compMatch) {
186
- name = name.replace(compMatch[0], '').trim();
187
- const compList = compMatch[1].split(',').map(c => c.trim().toLowerCase());
188
- for (const comp of compList) {
189
- if (COMPONENT_TYPES[comp]) {
190
- components.push(COMPONENT_TYPES[comp]);
127
+
128
+ // 通用属性映射
129
+ const propMap = {
130
+ 'sizeMode': '_sizeMode',
131
+ 'fillType': '_fillType',
132
+ 'fillCenter': '_fillCenter',
133
+ 'fillStart': '_fillStart',
134
+ 'fillRange': '_fillRange',
135
+ 'trim': '_isTrimmedMode',
136
+ 'string': '_string',
137
+ 'fontSize': '_fontSize',
138
+ 'lineHeight': '_lineHeight',
139
+ 'horizontalAlign': '_N$horizontalAlign',
140
+ 'verticalAlign': '_N$verticalAlign',
141
+ 'overflow': '_N$overflow',
142
+ 'fontFamily': '_N$fontFamily',
143
+ 'wrap': '_enableWrapText',
144
+ 'alignFlags': '_alignFlags',
145
+ 'left': '_left',
146
+ 'right': '_right',
147
+ 'top': '_top',
148
+ 'bottom': '_bottom',
149
+ 'horizontalCenter': '_horizontalCenter',
150
+ 'verticalCenter': '_verticalCenter',
151
+ 'isAbsLeft': '_isAbsLeft',
152
+ 'isAbsRight': '_isAbsRight',
153
+ 'isAbsTop': '_isAbsTop',
154
+ 'isAbsBottom': '_isAbsBottom',
155
+ 'interactable': '_N$interactable',
156
+ 'transition': '_N$transition',
157
+ 'zoomScale': 'zoomScale',
158
+ 'duration': 'duration',
159
+ 'layoutType': '_N$layoutType',
160
+ 'cellSize': '_N$cellSize',
161
+ 'startAxis': '_N$startAxis',
162
+ 'paddingLeft': '_N$paddingLeft',
163
+ 'paddingRight': '_N$paddingRight',
164
+ 'paddingTop': '_N$paddingTop',
165
+ 'paddingBottom': '_N$paddingBottom',
166
+ 'spacingX': '_N$spacingX',
167
+ 'spacingY': '_N$spacingY',
168
+ 'resize': '_resize',
169
+ 'designResolution': '_designResolution',
170
+ 'fitWidth': '_fitWidth',
171
+ 'fitHeight': '_fitHeight',
172
+ 'orthoSize': '_orthoSize',
173
+ 'backgroundColor': '_backgroundColor',
174
+ 'cullingMask': '_cullingMask',
175
+ 'zoomRatio': '_zoomRatio'
176
+ };
177
+
178
+ if (type === 'cc.Label' && props.string !== undefined) {
179
+ comp._N$string = props.string;
180
+ }
181
+
182
+ for (const [key, value] of Object.entries(props)) {
183
+ const compKey = propMap[key];
184
+ if (compKey) {
185
+ if (key === 'fillCenter' && Array.isArray(value)) {
186
+ comp[compKey] = { "__type__": "cc.Vec2", "x": value[0], "y": value[1] };
187
+ } else if (key === 'cellSize' && Array.isArray(value)) {
188
+ comp[compKey] = { "__type__": "cc.Size", "width": value[0], "height": value[1] };
189
+ } else if (key === 'designResolution' && Array.isArray(value)) {
190
+ comp[compKey] = { "__type__": "cc.Size", "width": value[0], "height": value[1] };
191
+ } else if ((key === 'backgroundColor' || key === 'color') && typeof value === 'string') {
192
+ const color = parseColor(value);
193
+ if (color) {
194
+ comp[compKey] = { "__type__": "cc.Color", ...color };
195
+ }
196
+ } else {
197
+ comp[compKey] = value;
191
198
  }
192
199
  }
193
200
  }
194
-
195
- // 提取选项 #key=value
196
- const optionMatches = name.matchAll(/#(\w+)=([^\s#]+)/g);
197
- for (const match of optionMatches) {
198
- const key = match[1];
199
- let value = match[2];
200
-
201
- // 类型转换
202
- if (/^\d+$/.test(value)) value = parseInt(value);
203
- else if (/^\d+\.\d+$/.test(value)) value = parseFloat(value);
204
- else if (value === 'true') value = true;
205
- else if (value === 'false') value = false;
206
-
207
- options[key] = value;
208
- }
209
- name = name.replace(/#\w+=[^\s#]+/g, '').trim();
210
-
211
- return { name, components, options };
212
201
  }
213
202
 
214
203
  /**
215
- * 生成 UUID(简化版)
204
+ * 创建场景数据结构
216
205
  */
217
- function generateUUID() {
218
- return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
219
- const r = Math.random() * 16 | 0;
220
- const v = c === 'x' ? r : (r & 0x3 | 0x8);
221
- return v.toString(16);
206
+ function createSceneData(nodeDefs, sceneName) {
207
+ const data = [];
208
+
209
+ // 场景 UUID
210
+ const sceneUUID = generateUUID();
211
+ const canvasUUID = generateUUID();
212
+ const cameraUUID = generateUUID();
213
+
214
+ // 索引 0: cc.SceneAsset
215
+ data.push({
216
+ "__type__": "cc.SceneAsset",
217
+ "_name": sceneName || "NewScene",
218
+ "_objFlags": 0,
219
+ "_native": "",
220
+ "scene": { "__id__": 1 }
222
221
  });
223
- }
224
-
225
- /**
226
- * 创建场景文件数据结构(基于模板)
227
- */
228
- function createSceneData(rootNodes, sceneName) {
229
- // 加载模板
230
- const templatePath = path.join(__dirname, '..', '..', 'data', 'scene-template.json');
231
- let data;
232
222
 
233
- try {
234
- const templateContent = fs.readFileSync(templatePath, 'utf8');
235
- data = JSON.parse(templateContent);
236
- } catch (e) {
237
- // 如果模板加载失败,使用内置基础结构
238
- data = createBasicSceneTemplate();
239
- }
240
-
241
- // 设置场景名称
242
- data[0]._name = sceneName || "NewScene";
243
- data[1]._name = sceneName || "NewScene";
244
-
245
- // 生成新的 UUID
246
- data[1]._id = generateUUID();
247
- data[2]._id = generateUUID();
248
- data[3]._id = generateUUID();
223
+ // 索引 1: cc.Scene
224
+ data.push({
225
+ "__type__": "cc.Scene",
226
+ "_name": sceneName || "NewScene",
227
+ "_objFlags": 0,
228
+ "_parent": null,
229
+ "_children": [{ "__id__": 2 }],
230
+ "_active": true,
231
+ "_components": [],
232
+ "_prefab": null,
233
+ "_opacity": 255,
234
+ "_color": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 },
235
+ "_contentSize": { "__type__": "cc.Size", "width": 0, "height": 0 },
236
+ "_anchorPoint": { "__type__": "cc.Vec2", "x": 0, "y": 0 },
237
+ "_trs": { "__type__": "TypedArray", "ctor": "Float64Array", "array": [0, 0, 0, 0, 0, 0, 1, 1, 1, 1] },
238
+ "_is3DNode": true,
239
+ "_groupIndex": 0,
240
+ "groupIndex": 0,
241
+ "autoReleaseAssets": false,
242
+ "_id": sceneUUID
243
+ });
244
+
245
+ // 索引 2: Canvas 节点
246
+ data.push({
247
+ "__type__": "cc.Node",
248
+ "_name": "Canvas",
249
+ "_objFlags": 0,
250
+ "_parent": { "__id__": 1 },
251
+ "_children": [{ "__id__": 3 }], // Main Camera
252
+ "_active": true,
253
+ "_components": [{ "__id__": 5 }, { "__id__": 6 }], // Canvas, Widget
254
+ "_prefab": null,
255
+ "_opacity": 255,
256
+ "_color": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 },
257
+ "_contentSize": { "__type__": "cc.Size", "width": 960, "height": 640 },
258
+ "_anchorPoint": { "__type__": "cc.Vec2", "x": 0.5, "y": 0.5 },
259
+ "_trs": { "__type__": "TypedArray", "ctor": "Float64Array", "array": [480, 320, 0, 0, 0, 0, 1, 1, 1, 1] },
260
+ "_eulerAngles": { "__type__": "cc.Vec3", "x": 0, "y": 0, "z": 0 },
261
+ "_skewX": 0,
262
+ "_skewY": 0,
263
+ "_is3DNode": false,
264
+ "_groupIndex": 0,
265
+ "groupIndex": 0,
266
+ "_id": canvasUUID
267
+ });
268
+
269
+ // 索引 3: Main Camera 节点
270
+ data.push({
271
+ "__type__": "cc.Node",
272
+ "_name": "Main Camera",
273
+ "_objFlags": 0,
274
+ "_parent": { "__id__": 2 },
275
+ "_children": [],
276
+ "_active": true,
277
+ "_components": [{ "__id__": 4 }], // Camera
278
+ "_prefab": null,
279
+ "_opacity": 255,
280
+ "_color": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 },
281
+ "_contentSize": { "__type__": "cc.Size", "width": 0, "height": 0 },
282
+ "_anchorPoint": { "__type__": "cc.Vec2", "x": 0.5, "y": 0.5 },
283
+ "_trs": { "__type__": "TypedArray", "ctor": "Float64Array", "array": [0, 0, 0, 0, 0, 0, 1, 1, 1, 1] },
284
+ "_eulerAngles": { "__type__": "cc.Vec3", "x": 0, "y": 0, "z": 0 },
285
+ "_skewX": 0,
286
+ "_skewY": 0,
287
+ "_is3DNode": false,
288
+ "_groupIndex": 0,
289
+ "groupIndex": 0,
290
+ "_id": cameraUUID
291
+ });
292
+
293
+ // 索引 4: Camera 组件
294
+ data.push({
295
+ "__type__": "cc.Camera",
296
+ "_name": "",
297
+ "_objFlags": 0,
298
+ "node": { "__id__": 3 },
299
+ "_enabled": true,
300
+ "_cullingMask": 4294967295,
301
+ "_clearFlags": 7,
302
+ "_backgroundColor": { "__type__": "cc.Color", "r": 0, "g": 0, "b": 0, "a": 255 },
303
+ "_depth": -1,
304
+ "_zoomRatio": 1,
305
+ "_targetTexture": null,
306
+ "_fov": 60,
307
+ "_orthoSize": 10,
308
+ "_nearClip": 1,
309
+ "_farClip": 4096,
310
+ "_ortho": true,
311
+ "_rect": { "__type__": "cc.Rect", "x": 0, "y": 0, "width": 1, "height": 1 },
312
+ "_renderStages": 1,
313
+ "_alignWithScreen": true,
314
+ "_id": generateId()
315
+ });
316
+
317
+ // 索引 5: Canvas 组件
318
+ data.push({
319
+ "__type__": "cc.Canvas",
320
+ "_name": "",
321
+ "_objFlags": 0,
322
+ "node": { "__id__": 2 },
323
+ "_enabled": true,
324
+ "_designResolution": { "__type__": "cc.Size", "width": 960, "height": 640 },
325
+ "_fitWidth": false,
326
+ "_fitHeight": true,
327
+ "_id": generateId()
328
+ });
329
+
330
+ // 索引 6: Widget 组件 (Canvas)
331
+ data.push({
332
+ "__type__": "cc.Widget",
333
+ "_name": "",
334
+ "_objFlags": 0,
335
+ "node": { "__id__": 2 },
336
+ "_enabled": true,
337
+ "alignMode": 1,
338
+ "_target": null,
339
+ "_alignFlags": 45,
340
+ "_left": 0,
341
+ "_right": 0,
342
+ "_top": 0,
343
+ "_bottom": 0,
344
+ "_verticalCenter": 0,
345
+ "_horizontalCenter": 0,
346
+ "_isAbsLeft": true,
347
+ "_isAbsRight": true,
348
+ "_isAbsTop": true,
349
+ "_isAbsBottom": true,
350
+ "_isAbsHorizontalCenter": true,
351
+ "_isAbsVerticalCenter": true,
352
+ "_originalWidth": 0,
353
+ "_originalHeight": 0,
354
+ "_id": generateId()
355
+ });
249
356
 
250
- // Canvas 节点在索引 2
357
+ // Canvas 节点索引
251
358
  const canvasIndex = 2;
252
- const canvas = data[canvasIndex];
253
359
 
254
- // 递归添加节点
255
- function addNode(nodeDef, parentIndex) {
360
+ // 递归添加用户节点
361
+ function addNode(def, parentIndex) {
256
362
  const nodeIndex = data.length;
257
363
  const uuid = generateUUID();
258
364
 
365
+ // 解析组件
366
+ const compList = (def.components || [])
367
+ .map(parseComponent)
368
+ .filter(Boolean);
369
+
370
+ // 解析颜色
371
+ let color = { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 };
372
+ if (def.color) {
373
+ const parsed = parseColor(def.color);
374
+ if (parsed) {
375
+ color = { "__type__": "cc.Color", ...parsed };
376
+ }
377
+ }
378
+
379
+ // 解析尺寸和位置
380
+ const width = def.width || 0;
381
+ const height = def.height || 0;
382
+ const anchorX = def.anchorX !== undefined ? def.anchorX : 0.5;
383
+ const anchorY = def.anchorY !== undefined ? def.anchorY : 0.5;
384
+ const rotation = def.rotation || 0;
385
+ const scaleX = def.scaleX !== undefined ? def.scaleX : 1;
386
+ const scaleY = def.scaleY !== undefined ? def.scaleY : 1;
387
+
259
388
  // 创建节点
260
389
  const node = {
261
390
  "__type__": "cc.Node",
262
- "_name": nodeDef.name,
391
+ "_name": def.name || 'Node',
263
392
  "_objFlags": 0,
264
393
  "_parent": { "__id__": parentIndex },
265
394
  "_children": [],
266
- "_active": true,
395
+ "_active": def.active !== false,
267
396
  "_components": [],
268
397
  "_prefab": null,
269
- "_opacity": 255,
270
- "_color": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 },
271
- "_contentSize": {
272
- "__type__": "cc.Size",
273
- "width": nodeDef.options.width || 0,
274
- "height": nodeDef.options.height || 0
275
- },
276
- "_anchorPoint": { "__type__": "cc.Vec2", "x": 0.5, "y": 0.5 },
398
+ "_opacity": def.opacity !== undefined ? def.opacity : 255,
399
+ "_color": color,
400
+ "_contentSize": { "__type__": "cc.Size", width, height },
401
+ "_anchorPoint": { "__type__": "cc.Vec2", "x": anchorX, "y": anchorY },
277
402
  "_trs": {
278
403
  "__type__": "TypedArray",
279
404
  "ctor": "Float64Array",
280
405
  "array": [
281
- nodeDef.options.x || 0,
282
- nodeDef.options.y || 0,
283
- 0, 0, 0, 0, 1, 1, 1, 1
406
+ def.x || 0,
407
+ def.y || 0,
408
+ 0, 0, 0,
409
+ rotation * Math.PI / 180,
410
+ 1, scaleX, scaleY, 1
284
411
  ]
285
412
  },
286
- "_eulerAngles": { "__type__": "cc.Vec3", "x": 0, "y": 0, "z": 0 },
413
+ "_eulerAngles": { "__type__": "cc.Vec3", "x": 0, "y": 0, "z": rotation },
287
414
  "_skewX": 0,
288
415
  "_skewY": 0,
289
416
  "_is3DNode": false,
@@ -295,9 +422,10 @@ function createSceneData(rootNodes, sceneName) {
295
422
  data.push(node);
296
423
 
297
424
  // 添加组件
298
- for (const compType of nodeDef.components) {
299
- if (Components[compType]) {
300
- const comp = Components[compType](nodeIndex);
425
+ for (const { type, props } of compList) {
426
+ if (Components[type]) {
427
+ const comp = Components[type](nodeIndex);
428
+ applyComponentProps(comp, props);
301
429
  const compIndex = data.length;
302
430
  data.push(comp);
303
431
  node._components.push({ "__id__": compIndex });
@@ -305,223 +433,63 @@ function createSceneData(rootNodes, sceneName) {
305
433
  }
306
434
 
307
435
  // 更新父节点的 _children
308
- const parent = data[parentIndex];
309
- if (parent && parent._children) {
310
- parent._children.push({ "__id__": nodeIndex });
311
- }
436
+ data[parentIndex]._children.push({ "__id__": nodeIndex });
312
437
 
313
438
  // 递归处理子节点
314
- for (const child of nodeDef.children) {
315
- addNode(child, nodeIndex);
439
+ if (def.children && def.children.length > 0) {
440
+ for (const child of def.children) {
441
+ addNode(child, nodeIndex);
442
+ }
316
443
  }
317
444
 
318
445
  return nodeIndex;
319
446
  }
320
447
 
321
- // 处理输入的节点结构
322
- // 如果第一个节点是 Canvas,把它的子节点添加到模板的 Canvas
323
- if (rootNodes.length > 0 && rootNodes[0].name === 'Canvas') {
324
- // 用户定义了 Canvas 节点,把它的子节点添加到模板的 Canvas
325
- for (const child of rootNodes[0].children) {
326
- addNode(child, canvasIndex);
327
- }
328
- } else {
329
- // 用户定义的是其他节点,直接添加到 Canvas 下
330
- for (const rootNode of rootNodes) {
331
- addNode(rootNode, canvasIndex);
332
- }
448
+ // 支持数组或单个节点
449
+ const nodes = Array.isArray(nodeDefs) ? nodeDefs : [nodeDefs];
450
+
451
+ // 添加用户节点到 Canvas
452
+ for (const nodeDef of nodes) {
453
+ addNode(nodeDef, canvasIndex);
333
454
  }
334
455
 
335
456
  return data;
336
457
  }
337
458
 
338
- /**
339
- * 创建基础场景模板(当模板文件不存在时使用)
340
- */
341
- function createBasicSceneTemplate() {
342
- return [
343
- {
344
- "__type__": "cc.SceneAsset",
345
- "_name": "",
346
- "_objFlags": 0,
347
- "_native": "",
348
- "scene": { "__id__": 1 }
349
- },
350
- {
351
- "__type__": "cc.Scene",
352
- "_objFlags": 0,
353
- "_parent": null,
354
- "_children": [{ "__id__": 2 }],
355
- "_active": true,
356
- "_components": [],
357
- "_prefab": null,
358
- "_opacity": 255,
359
- "_color": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 },
360
- "_contentSize": { "__type__": "cc.Size", "width": 0, "height": 0 },
361
- "_anchorPoint": { "__type__": "cc.Vec2", "x": 0, "y": 0 },
362
- "_trs": { "__type__": "TypedArray", "ctor": "Float64Array", "array": [0, 0, 0, 0, 0, 0, 1, 1, 1, 1] },
363
- "_is3DNode": true,
364
- "_groupIndex": 0,
365
- "groupIndex": 0,
366
- "autoReleaseAssets": false,
367
- "_id": ""
368
- },
369
- {
370
- "__type__": "cc.Node",
371
- "_name": "Canvas",
372
- "_objFlags": 0,
373
- "_parent": { "__id__": 1 },
374
- "_children": [{ "__id__": 3 }],
375
- "_active": true,
376
- "_components": [{ "__id__": 5 }, { "__id__": 6 }],
377
- "_prefab": null,
378
- "_opacity": 255,
379
- "_color": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 },
380
- "_contentSize": { "__type__": "cc.Size", "width": 960, "height": 640 },
381
- "_anchorPoint": { "__type__": "cc.Vec2", "x": 0.5, "y": 0.5 },
382
- "_trs": { "__type__": "TypedArray", "ctor": "Float64Array", "array": [480, 320, 0, 0, 0, 0, 1, 1, 1, 1] },
383
- "_eulerAngles": { "__type__": "cc.Vec3", "x": 0, "y": 0, "z": 0 },
384
- "_skewX": 0,
385
- "_skewY": 0,
386
- "_is3DNode": false,
387
- "_groupIndex": 0,
388
- "groupIndex": 0,
389
- "_id": ""
390
- },
391
- {
392
- "__type__": "cc.Node",
393
- "_name": "Main Camera",
394
- "_objFlags": 0,
395
- "_parent": { "__id__": 2 },
396
- "_children": [],
397
- "_active": true,
398
- "_components": [{ "__id__": 4 }],
399
- "_prefab": null,
400
- "_opacity": 255,
401
- "_color": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 },
402
- "_contentSize": { "__type__": "cc.Size", "width": 0, "height": 0 },
403
- "_anchorPoint": { "__type__": "cc.Vec2", "x": 0.5, "y": 0.5 },
404
- "_trs": { "__type__": "TypedArray", "ctor": "Float64Array", "array": [0, 0, 0, 0, 0, 0, 1, 1, 1, 1] },
405
- "_eulerAngles": { "__type__": "cc.Vec3", "x": 0, "y": 0, "z": 0 },
406
- "_skewX": 0,
407
- "_skewY": 0,
408
- "_is3DNode": false,
409
- "_groupIndex": 0,
410
- "groupIndex": 0,
411
- "_id": ""
412
- },
413
- {
414
- "__type__": "cc.Camera",
415
- "_name": "",
416
- "_objFlags": 0,
417
- "node": { "__id__": 3 },
418
- "_enabled": true,
419
- "_cullingMask": 4294967295,
420
- "_clearFlags": 7,
421
- "_backgroundColor": { "__type__": "cc.Color", "r": 0, "g": 0, "b": 0, "a": 255 },
422
- "_depth": -1,
423
- "_zoomRatio": 1,
424
- "_targetTexture": null,
425
- "_fov": 60,
426
- "_orthoSize": 10,
427
- "_nearClip": 1,
428
- "_farClip": 4096,
429
- "_ortho": true,
430
- "_rect": { "__type__": "cc.Rect", "x": 0, "y": 0, "width": 1, "height": 1 },
431
- "_renderStages": 1,
432
- "_alignWithScreen": true,
433
- "_id": ""
434
- },
435
- {
436
- "__type__": "cc.Canvas",
437
- "_name": "",
438
- "_objFlags": 0,
439
- "node": { "__id__": 2 },
440
- "_enabled": true,
441
- "_designResolution": { "__type__": "cc.Size", "width": 960, "height": 640 },
442
- "_fitWidth": false,
443
- "_fitHeight": true,
444
- "_id": ""
445
- },
446
- {
447
- "__type__": "cc.Widget",
448
- "_name": "",
449
- "_objFlags": 0,
450
- "node": { "__id__": 2 },
451
- "_enabled": true,
452
- "alignMode": 1,
453
- "_target": null,
454
- "_alignFlags": 45,
455
- "_left": 0,
456
- "_right": 0,
457
- "_top": 0,
458
- "_bottom": 0,
459
- "_verticalCenter": 0,
460
- "_horizontalCenter": 0,
461
- "_isAbsLeft": true,
462
- "_isAbsRight": true,
463
- "_isAbsTop": true,
464
- "_isAbsBottom": true,
465
- "_isAbsHorizontalCenter": true,
466
- "_isAbsVerticalCenter": true,
467
- "_originalWidth": 0,
468
- "_originalHeight": 0,
469
- "_id": ""
470
- }
471
- ];
472
- }
473
-
474
459
  function run(args) {
475
460
  if (args.length < 1) {
476
461
  console.log(JSON.stringify({
477
- error: '用法: cocos2.4 create-scene <输出路径.fire> [场景名称]',
478
- hint: '从 stdin 读取树形结构,例如:\n echo "Canvas\\n├─ TopBar (sprite)" | cocos2.4 create-scene assets/scene.fire'
462
+ error: '用法: cocos2d-cli create-scene <输出路径.fire>',
463
+ hint: '从 stdin 读取 JSON 结构生成场景',
464
+ example: 'type scene.json | cocos2d-cli create-scene assets/scene.fire'
479
465
  }));
480
466
  return;
481
467
  }
482
468
 
483
469
  const outputPath = args[0];
484
- const sceneName = args[1] || path.basename(outputPath, '.fire');
470
+ const sceneName = path.basename(outputPath, '.fire');
485
471
 
486
- // 从 stdin 读取树形结构
472
+ // 从 stdin 读取 JSON
487
473
  let input = '';
488
474
 
489
- // 检查是否是管道输入
490
475
  if (!process.stdin.isTTY) {
491
- // 同步读取 stdin(简化处理)
492
- const fs = require('fs');
493
476
  input = fs.readFileSync(0, 'utf8');
494
477
  }
495
478
 
496
479
  if (!input.trim()) {
497
480
  console.log(JSON.stringify({
498
- error: '请通过 stdin 提供场景结构',
499
- example: `echo "Canvas (canvas)\\n├─ TopBar (sprite, widget)\\n│ └─ ScoreLabel (label)" | cocos2.4 create-scene assets/game.fire`
481
+ error: '请通过 stdin 提供 JSON 结构'
500
482
  }));
501
483
  return;
502
484
  }
503
485
 
504
486
  try {
505
- // 解析树形结构
506
- const rootNodes = parseTreeText(input);
507
-
508
- if (rootNodes.length === 0) {
509
- console.log(JSON.stringify({ error: '未能解析出任何节点' }));
510
- return;
511
- }
512
-
513
- // 校验组件配置
514
- const validationErrors = validateAllNodes(rootNodes);
515
- if (validationErrors.length > 0) {
516
- console.log(JSON.stringify({
517
- error: '组件配置错误',
518
- details: validationErrors
519
- }));
520
- return;
521
- }
487
+ // 移除 BOM 并解析 JSON
488
+ input = input.replace(/^\uFEFF/, '').trim();
489
+ const nodeDef = JSON.parse(input);
522
490
 
523
491
  // 生成场景数据
524
- const sceneData = createSceneData(rootNodes, sceneName);
492
+ const sceneData = createSceneData(nodeDef, sceneName);
525
493
 
526
494
  // 确保输出目录存在
527
495
  const outputDir = path.dirname(outputPath);
@@ -533,11 +501,10 @@ function run(args) {
533
501
  fs.writeFileSync(outputPath, JSON.stringify(sceneData, null, 2), 'utf8');
534
502
 
535
503
  // 统计信息
536
- let nodeCount = 0;
537
- let compCount = 0;
504
+ let nodeCount = 0, compCount = 0;
538
505
  for (const item of sceneData) {
539
506
  if (item.__type__ === 'cc.Node') nodeCount++;
540
- else if (item.__type__?.startsWith('cc.') && item.__type__ !== 'cc.Scene' && item.__type__ !== 'cc.SceneAsset') {
507
+ else if (item.__type__?.startsWith('cc.') && !['cc.Scene', 'cc.SceneAsset'].includes(item.__type__)) {
541
508
  compCount++;
542
509
  }
543
510
  }
@@ -546,8 +513,7 @@ function run(args) {
546
513
  success: true,
547
514
  path: outputPath,
548
515
  nodes: nodeCount,
549
- components: compCount,
550
- structure: rootNodes.map(n => n.name)
516
+ components: compCount
551
517
  }));
552
518
 
553
519
  } catch (err) {
@@ -555,4 +521,4 @@ function run(args) {
555
521
  }
556
522
  }
557
523
 
558
- module.exports = { run };
524
+ module.exports = { run };