Repository navigation
Expand file tree
/
Copy pathGodotCompiler.ts
More file actions
931 lines (840 loc) · 34.4 KB
/
Copy pathGodotCompiler.ts
File metadata and controls
931 lines (840 loc) · 34.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
import type { Vector3 } from '../types';
/**
* HoloScript → Godot GDScript Compiler
*
* Translates a HoloComposition AST into a Godot 4[0] GDScript file
* that builds the scene tree programmatically via _ready().
*
* Emits:
* - extends Node3D script
* - _ready() for scene construction
* - MeshInstance3D, CollisionShape3D, RigidBody3D, Light3D, Camera3D
* - AudioStreamPlayer3D, Area3D (zones), Timer (timelines)
* - UI via CanvasLayer + Control nodes
*
* @version 1.0.0
*/
import type {
HoloComposition,
HoloObjectDecl,
HoloSpatialGroup,
HoloLight,
HoloEnvironment,
HoloCamera,
HoloTimeline,
HoloAudio,
HoloZone,
HoloUI,
HoloTransition,
HoloEffects,
HoloValue,
} from '../parser/HoloCompositionTypes';
import { CompilerBase } from './CompilerBase';
import { compileAcousticTrait } from './godot-acoustic-bus';
import { ANSCapabilityPath, type ANSCapabilityPathValue } from '@holoscript/core-types/ans';
import {
compileDomainBlocks,
compileMaterialBlock,
compilePhysicsBlock,
compileParticleBlock,
compilePostProcessingBlock,
compileAudioSourceBlock,
compileWeatherBlock,
materialToGodot,
physicsToGodot,
particlesToGodot,
postProcessingToGodot,
audioSourceToGodot,
weatherToGodot,
compileNarrativeBlock,
narrativeToGodot,
compilePaymentBlock,
paymentToGodot,
compileHealthcareBlock,
healthcareToGodot,
compileRoboticsBlock,
roboticsToGodot,
compileIoTBlock,
iotToGodot,
compileDataVizBlock,
datavizToGodot,
compileEducationBlock,
educationToGodot,
compileMusicBlock,
musicToGodot,
compileArchitectureBlock,
architectureToGodot,
compileWeb3Block,
web3ToGodot,
compileProceduralBlock,
proceduralToGodot,
compileRenderingBlock,
renderingToGodot,
compileNavigationBlock,
navigationToGodot,
compileInputBlock,
inputToGodot,
} from './DomainBlockCompilerMixin';
export interface GodotCompilerOptions {
className?: string;
indent?: string;
godotVersion?: '4.0' | '4.1' | '4.2' | '4.3';
/** When set, emits a `# Provenance Hash:` banner (compile-time overhead bench / Paper 10). */
provenanceHash?: string;
}
export class GodotCompiler extends CompilerBase {
protected readonly compilerName = 'GodotCompiler';
protected override getRequiredCapability(): ANSCapabilityPathValue {
return ANSCapabilityPath.GODOT;
}
private options: Required<GodotCompilerOptions>;
private lines: string[] = [];
private indentLevel: number = 0;
constructor(options: GodotCompilerOptions = {}) {
super();
this.options = {
className: options.className || 'GeneratedScene',
indent: options.indent || '\t',
godotVersion: options.godotVersion || '4.3',
provenanceHash: options.provenanceHash ?? '',
};
}
compile(composition: HoloComposition, agentToken: string, outputPath?: string): string {
// ─── Agent Identity Verification ───────────────────────────────────────
this.validateCompilerAccess(agentToken, outputPath);
// ───────────────────────────────────────────────────────────────────────
// Objects (and an environment) written inside `scene` blocks are built the
// same way as top-level ones, as children of this node. Everything _ready()
// builds is a variable in that one function: objects, and also lights, groups,
// sounds, zones, the camera, the environment and the UI, plus the variables
// an object derives from its name (`X_mat`, `X_shape`, ...). A scene object
// that would declare a variable already declared there is left out and named
// in a WARNING below; the variables are read off what _ready() writes.
const scenes = this.flattenScenes(composition, (name) => this.sanitizeName(name), {
reserved: (content) => this.readyVariables(content),
of: (obj) => this.variablesDeclaredBy(() => this.compileObject(obj, 'self')),
});
composition = scenes.composition;
this.lines = [];
this.indentLevel = 0;
this.emit(`# Auto-generated by HoloScript GodotCompiler`);
this.emit(
`# Source: composition "${this.escapeStringValue(composition.name as string, 'GDScript')}"`
);
this.emit(`# Target: Godot ${this.options.godotVersion}`);
this.emit(`# Do not edit manually — regenerate from .holo source`);
if (this.options.provenanceHash) {
this.emit(`# Provenance Hash: ${this.options.provenanceHash}`);
}
for (const warning of this.sceneWarnings(scenes, 'GDScript')) {
this.emit(`# WARNING: ${warning}`);
}
this.emit('');
this.emit('extends Node3D');
this.emit(`class_name ${this.options.className}`);
this.emit('');
// State variables
if (composition.state) {
this.emit('# === State ===');
for (const prop of composition.state.properties) {
const gdVal = this.toGDScriptValue(prop.value);
this.emit(`var ${this.escapeStringValue(prop.key as string, 'GDScript')} = ${gdVal}`);
}
this.emit('');
}
// Ready function
this.emit('func _ready():');
this.indentLevel++;
this.compileReady(composition);
this.indentLevel--;
this.emit('');
// Timeline functions
if (composition.timelines) {
for (const tl of composition.timelines) {
this.compileTimeline(tl);
}
}
// Transition functions
if (composition.transitions) {
for (const tr of composition.transitions) {
this.compileTransition(tr);
}
}
// Effects (as comments)
if (composition.effects) {
this.compileEffects(composition.effects);
}
// v4.2: Domain Blocks (materials, physics, particles, post-processing, audio, weather)
this.compileGodotDomainBlocks(composition);
return this.lines.join('\n');
}
/**
* The body of _ready(), part by part; every variable a part declares lives in
* that one function. compile() writes each part. readyVariables() passes a
* `part` that reads what each one declares instead, so the parts are listed
* here only, and a part added later is counted too.
*/
private compileReady(
composition: HoloComposition,
part: (by: string, compile: () => void) => void = (_by, compile) => compile()
): void {
// Environment
const environment = composition.environment;
if (environment) {
part('the environment', () => this.compileEnvironment(environment));
}
// Lights
if (composition.lights) {
for (const light of composition.lights) {
part('a light', () => this.compileLight(light));
}
}
// Camera
const camera = composition.camera;
if (camera) {
part('the camera', () => this.compileCamera(camera));
}
// Objects
if (composition.objects) {
for (const obj of composition.objects) {
part('another object', () => this.compileObject(obj, 'self'));
}
}
// Spatial groups
if (composition.spatialGroups) {
for (const group of composition.spatialGroups) {
part('a group', () => this.compileSpatialGroup(group, 'self'));
}
}
// Audio
if (composition.audio) {
for (const audio of composition.audio) {
part('a sound', () => this.compileAudio(audio));
}
}
// Zones
if (composition.zones) {
for (const zone of composition.zones) {
part('a zone', () => this.compileZone(zone));
}
}
// Timelines
if (composition.timelines) {
for (const tl of composition.timelines) {
if (tl.autoplay) {
part('a timeline', () => this.emit(`_play_${this.sanitizeName(tl.name)}()`));
}
}
}
// UI
const ui = composition.ui;
if (ui) {
part('the UI overlay', () => this.compileUI(ui));
}
}
/**
* Every variable _ready() declares for `content`, each with plain words for the
* part that declares it. Read off what each part writes, so a variable a part
* derives from a name (`X_mat`, `X_shape`, `X_acoustic_bus_idx`) counts as well
* as the name's own. State variables, timelines and transitions belong to the
* class, not to _ready(): a variable there with the same name only shadows one,
* which GDScript warns about but loads.
*/
private readyVariables(content: HoloComposition): Map<string, string> {
const variables = new Map<string, string>();
this.compileReady(content, (by, compile) => {
for (const name of this.variablesDeclaredBy(compile)) {
if (!variables.has(name)) variables.set(name, by);
}
});
return variables;
}
/** The variables `compile` declares, read off the lines it writes; those lines are dropped. */
private variablesDeclaredBy(compile: () => void): string[] {
const { lines, indentLevel } = this;
this.lines = [];
try {
compile();
return this.lines.flatMap((line) => /^\s*var\s+(\w+)/.exec(line)?.[1] ?? []);
} finally {
this.lines = lines;
this.indentLevel = indentLevel;
}
}
private compileGodotDomainBlocks(composition: HoloComposition): void {
const domainBlocks = composition.domainBlocks ?? [];
if (domainBlocks.length === 0) return;
this.emit('');
this.emit('# === v4.2 Domain Blocks ===');
let blockIdx = 0;
const compiled = compileDomainBlocks(
domainBlocks,
{
material: (block) => {
const mat = compileMaterialBlock(block);
return materialToGodot(mat, `db${blockIdx++}`);
},
physics: (block) => {
const phys = compilePhysicsBlock(block);
return physicsToGodot(phys, `db${blockIdx++}`);
},
vfx: (block) => {
const ps = compileParticleBlock(block);
return particlesToGodot(ps, `db${blockIdx++}`);
},
postfx: (block) => {
const pp = compilePostProcessingBlock(block);
return postProcessingToGodot(pp);
},
audio: (block) => {
const audio = compileAudioSourceBlock(block);
return audioSourceToGodot(audio, `db${blockIdx++}`);
},
weather: (block) => {
const weather = compileWeatherBlock(block);
return weatherToGodot(weather);
},
narrative: (block) => {
const narr = compileNarrativeBlock(block);
return narrativeToGodot(narr);
},
payment: (block) => {
const pay = compilePaymentBlock(block);
return paymentToGodot(pay);
},
healthcare: (block) => {
const h = compileHealthcareBlock(block);
return healthcareToGodot(h);
},
robotics: (block) => {
const r = compileRoboticsBlock(block);
return roboticsToGodot(r);
},
iot: (block) => iotToGodot(compileIoTBlock(block)),
dataviz: (block) => datavizToGodot(compileDataVizBlock(block)),
education: (block) => educationToGodot(compileEducationBlock(block)),
music: (block) => musicToGodot(compileMusicBlock(block)),
architecture: (block) => architectureToGodot(compileArchitectureBlock(block)),
web3: (block) => web3ToGodot(compileWeb3Block(block)),
procedural: (block) => proceduralToGodot(compileProceduralBlock(block)),
rendering: (block) => renderingToGodot(compileRenderingBlock(block)),
navigation: (block) => navigationToGodot(compileNavigationBlock(block)),
input: (block) => inputToGodot(compileInputBlock(block)),
},
(block) =>
`# Domain block: ${block.domain}/${block.keyword} "${this.escapeStringValue(block.name as string, 'GDScript')}"`
);
for (const line of compiled) {
for (const l of line.split('\n')) {
this.emit(l);
}
}
}
private compileEnvironment(env: HoloEnvironment): void {
this.emit('# === Environment ===');
for (const prop of env.properties) {
if (prop.key === 'preset' || prop.key === 'skybox') {
this.emit(`var env = WorldEnvironment.new()`);
this.emit(`env.environment = Environment.new()`);
this.emit(`env.environment.background_mode = Environment.BG_SKY`);
this.emit(`add_child(env)`);
} else if (prop.key === 'fog' && typeof prop.value === 'object') {
const fog = prop.value as Record<string, any>;
this.emit(`# Fog settings`);
if (fog.color) this.emit(`# fog_color: ${fog.color}`);
if (fog.near !== undefined) this.emit(`# fog_near: ${fog.near}`);
if (fog.far !== undefined) this.emit(`# fog_far: ${fog.far}`);
} else if (prop.key === 'ambient_light') {
this.emit(`# Ambient light intensity: ${prop.value}`);
}
}
this.emit('');
}
private compileLight(light: HoloLight): void {
const varName = this.sanitizeName(light.name);
this.emit(`# Light: ${this.escapeStringValue(light.name as string, 'GDScript')}`);
const typeMap: Record<string, string> = {
directional: 'DirectionalLight3D',
point: 'OmniLight3D',
spot: 'SpotLight3D',
};
const gdType = typeMap[light.lightType] || 'DirectionalLight3D';
this.emit(`var ${varName} = ${gdType}.new()`);
this.emit(`${varName}.name = "${this.escapeStringValue(light.name as string, 'GDScript')}"`);
for (const prop of light.properties) {
if (prop.key === 'color') {
this.emit(`${varName}.light_color = ${this.toColor(prop.value)}`);
} else if (prop.key === 'intensity') {
this.emit(`${varName}.light_energy = ${prop.value}`);
} else if (prop.key === 'position' && Array.isArray(prop.value)) {
this.emit(`${varName}.position = ${this.toVector3(prop.value)}`);
} else if (prop.key === 'cast_shadow' || prop.key === 'castShadow') {
this.emit(`${varName}.shadow_enabled = ${prop.value}`);
} else if (prop.key === 'distance') {
this.emit(`${varName}.omni_range = ${prop.value}`);
}
}
this.emit(`add_child(${varName})`);
this.emit('');
}
private compileCamera(camera: HoloCamera): void {
this.emit('# === Camera ===');
this.emit('var cam = Camera3D.new()');
const fov = this.findProp(camera.properties, 'fov');
if (fov) this.emit(`cam.fov = ${fov}`);
const pos = this.findProp(camera.properties, 'position');
if (pos) this.emit(`cam.position = ${this.toVector3(pos)}`);
const lookAt =
this.findProp(camera.properties, 'look_at') || this.findProp(camera.properties, 'lookAt');
if (lookAt) this.emit(`cam.look_at(${this.toVector3(lookAt)})`);
const near = this.findProp(camera.properties, 'near');
if (near) this.emit(`cam.near = ${near}`);
const far = this.findProp(camera.properties, 'far');
if (far) this.emit(`cam.far = ${far}`);
this.emit('cam.current = true');
this.emit('add_child(cam)');
this.emit('');
}
private compileObject(obj: HoloObjectDecl, parentVar: string): void {
const varName = this.sanitizeName(obj.name);
const meshType = this.findObjProp(obj, 'mesh') || this.findObjProp(obj, 'type') || 'cube';
const isText = meshType === 'text';
const isModel = !!this.findObjProp(obj, 'model') || !!this.findObjProp(obj, 'src');
const isSparkles = meshType === 'sparkles';
const isLight = ['directional', 'point', 'spot', 'hemisphere', 'ambient', 'area'].includes(
meshType as string
);
this.emit(`# Object: ${this.escapeStringValue(obj.name as string, 'GDScript')}`);
if (isLight) {
const lightMap: Record<string, string> = {
directional: 'DirectionalLight3D',
point: 'OmniLight3D',
spot: 'SpotLight3D',
};
this.emit(`var ${varName} = ${lightMap[meshType as string] || 'DirectionalLight3D'}.new()`);
} else if (isText) {
this.emit(`var ${varName} = Label3D.new()`);
const text = this.findObjProp(obj, 'text');
if (text) this.emit(`${varName}.text = "${text}"`);
const fontSize = this.findObjProp(obj, 'font_size');
if (fontSize) this.emit(`${varName}.font_size = ${Math.round((fontSize as number) * 100)}`);
const color = this.findObjProp(obj, 'color');
if (color) this.emit(`${varName}.modulate = ${this.toColor(color)}`);
} else if (isModel) {
const src = this.findObjProp(obj, 'model') || this.findObjProp(obj, 'src');
this.emit(`var ${varName} = load("res://models/${src}.glb").instantiate()`);
} else if (isSparkles) {
this.emit(`var ${varName} = GPUParticles3D.new()`);
} else {
// Physics body wrapper if needed
const hasPhysics = obj.traits?.some((t) => t.name === 'physics' || t.name === 'grabbable');
if (hasPhysics) {
this.emit(`var ${varName}_body = RigidBody3D.new()`);
this.emit(
`${varName}_body.name = "${this.escapeStringValue(obj.name as string, 'GDScript')}"`
);
}
this.emit(`var ${varName} = MeshInstance3D.new()`);
const meshMap: Record<string, string> = {
sphere: 'SphereMesh',
box: 'BoxMesh',
cube: 'BoxMesh',
cylinder: 'CylinderMesh',
cone: 'CylinderMesh',
plane: 'PlaneMesh',
torus: 'TorusMesh',
capsule: 'CapsuleMesh',
};
const gdMesh = meshMap[meshType as string] || 'BoxMesh';
this.emit(`${varName}.mesh = ${gdMesh}.new()`);
// Size
const size = this.findObjProp(obj, 'size');
if (size && gdMesh === 'BoxMesh' && Array.isArray(size)) {
this.emit(`${varName}.mesh.size = ${this.toVector3(size)}`);
} else if (typeof size === 'number' && gdMesh === 'PlaneMesh') {
this.emit(`${varName}.mesh.size = Vector2(${size}, ${size})`);
}
// Material
const material = this.findObjProp(obj, 'material');
if (material && typeof material === 'object') {
const mat = material as Record<string, any>;
this.emit(`var ${varName}_mat = StandardMaterial3D.new()`);
if (mat.color) this.emit(`${varName}_mat.albedo_color = ${this.toColor(mat.color)}`);
if (mat.roughness !== undefined) this.emit(`${varName}_mat.roughness = ${mat.roughness}`);
if (mat.metalness !== undefined) this.emit(`${varName}_mat.metallic = ${mat.metalness}`);
if (mat.emissive) {
this.emit(`${varName}_mat.emission_enabled = true`);
this.emit(`${varName}_mat.emission = ${this.toColor(mat.emissive)}`);
}
if (mat.transmission) {
this.emit(`${varName}_mat.transparency = BaseMaterial3D.TRANSPARENCY_ALPHA`);
}
this.emit(`${varName}.material_override = ${varName}_mat`);
}
// Collider
const hasCollider = obj.traits?.some(
(t) => t.name === 'collidable' || t.name === 'physics' || t.name === 'grabbable'
);
if (hasCollider && !hasPhysics) {
this.emit(`var ${varName}_static = StaticBody3D.new()`);
this.emit(`var ${varName}_shape = CollisionShape3D.new()`);
this.emit(`${varName}_shape.shape = ${varName}.mesh.create_convex_shape()`);
this.emit(`${varName}_static.add_child(${varName}_shape)`);
this.emit(`${varName}_static.add_child(${varName})`);
}
if (hasPhysics) {
this.emit(`var ${varName}_shape = CollisionShape3D.new()`);
this.emit(`${varName}_shape.shape = ${varName}.mesh.create_convex_shape()`);
this.emit(`${varName}_body.add_child(${varName}_shape)`);
this.emit(`${varName}_body.add_child(${varName})`);
}
}
this.emit(`${varName}.name = "${this.escapeStringValue(obj.name as string, 'GDScript')}"`);
// Position, rotation, scale
const pos = this.findObjProp(obj, 'position');
if (pos) this.emit(`${varName}.position = ${this.toVector3(pos)}`);
const rot = this.findObjProp(obj, 'rotation');
if (rot && Array.isArray(rot)) {
this.emit(`${varName}.rotation_degrees = ${this.toVector3(rot)}`);
}
const scale = this.findObjProp(obj, 'scale');
if (scale) this.emit(`${varName}.scale = ${this.toVector3(scale)}`);
// Add to parent
const hasPhysics = obj.traits?.some((t) => t.name === 'physics' || t.name === 'grabbable');
if (hasPhysics) {
this.emit(`${parentVar}.add_child(${varName}_body)`);
} else {
this.emit(`${parentVar}.add_child(${varName})`);
}
// Expanded trait handling
if (obj.traits) {
for (const trait of obj.traits) {
const tn = trait.name;
// Skip traits already handled inline
if (tn === 'collidable' || tn === 'physics' || tn === 'grabbable') continue;
// Environment Understanding
if (tn === 'plane_detection') {
this.emit(`# @plane_detection — use XRServer plane detection`);
} else if (tn === 'mesh_detection') {
this.emit(`# @mesh_detection — use XRServer mesh tracking`);
} else if (tn === 'anchor' || tn === 'persistent_anchor' || tn === 'shared_anchor') {
this.emit(`# @${tn} — XRAnchor3D`);
} else if (tn === 'occlusion') {
this.emit(`# @occlusion — Environment3D occlusion`);
} else if (tn === 'light_estimation') {
this.emit(`# @light_estimation — XR light estimation`);
}
// Physics Expansion
else if (tn === 'cloth') {
this.emit(`var ${varName}_soft = SoftBody3D.new()`);
this.emit(
`${varName}_soft.name = "${this.escapeStringValue(obj.name as string, 'GDScript')}_cloth"`
);
this.emit(`# @cloth — configure SoftBody3D stiffness/damping`);
} else if (tn === 'wind') {
this.emit(`# @wind — use GPUParticles3D attractor or custom force`);
} else if (tn === 'fluid') {
this.emit(`# @fluid — custom SPH/particle fluid simulation`);
} else if (tn === 'destruction') {
this.emit(`# @destruction — pre-fractured mesh swap on impact`);
} else if (tn === 'rope' || tn === 'chain') {
this.emit(`# @${tn} — use PinJoint3D chain or custom solver`);
}
// Spatial Audio
else if (tn === 'reverb_zone') {
this.emit(`var ${varName}_reverb = AudioEffectReverb.new()`);
this.emit(`# @reverb_zone — add to AudioBus`);
} else if (tn === 'audio_material' || tn === 'audio_occlusion' || tn === 'audio_portal') {
// E-G16: real Godot acoustic bus + AudioEffect chain (module-first), not a comment.
const acoustic = compileAcousticTrait(
tn,
(trait.config || {}) as Record<string, unknown>,
varName
);
if (acoustic) {
for (const line of acoustic.lines) this.emit(line);
}
} else if (tn === 'ambisonics' || tn === 'hrtf' || tn === 'head_tracked_audio') {
// Not yet modeled as DSP — kept as an honest config-preserving comment.
this.emit(`# @${tn} — spatial audio: ${JSON.stringify(trait.config || {})}`);
}
// Volumetric Content
else if (
tn === 'gaussian_splat' ||
tn === 'nerf' ||
tn === 'volumetric_video' ||
tn === 'point_cloud' ||
tn === 'photogrammetry'
) {
this.emit(`# @${tn} — volumetric renderer: ${JSON.stringify(trait.config || {})}`);
}
// Accessibility
else if (
tn === 'accessible' ||
tn === 'alt_text' ||
tn === 'screen_reader' ||
tn === 'high_contrast' ||
tn === 'motion_reduced' ||
tn === 'magnifiable'
) {
this.emit(`# @${tn} — accessibility: ${JSON.stringify(trait.config || {})}`);
}
// Input Modalities
else if (
tn === 'eye_tracking' ||
tn === 'hand_tracking' ||
tn === 'body_tracking' ||
tn === 'face_tracking' ||
tn === 'controller'
) {
this.emit(`# @${tn} — XR input: ${JSON.stringify(trait.config || {})}`);
}
// V43 AI/XR Traits
else if (tn === 'spatial_persona') {
this.emit(`# @spatial_persona — visionOS-specific; use custom avatar scene for Godot`);
} else if (tn === 'shareplay') {
this.emit(`# @shareplay — multiplayer via ENetMultiplayerPeer or WebSocketPeer`);
} else if (tn === 'object_tracking') {
this.emit(`# @object_tracking — use XRTracker or custom vision-based tracker`);
} else if (tn === 'scene_reconstruction') {
this.emit(`# @scene_reconstruction — use XRServer environment mesh`);
} else if (tn === 'eye_tracked' || tn === 'eye_hand_fusion') {
this.emit(`# @${tn} — use XRPositionalTracker for eye/hand data`);
} else if (
tn === 'controlnet' ||
tn === 'ai_texture_gen' ||
tn === 'diffusion_realtime' ||
tn === 'ai_upscaling' ||
tn === 'ai_inpainting'
) {
this.emit(`# @${tn} — AI generation: route to external inference or GDExtension`);
} else if (tn === 'neural_link' || tn === 'neural_forge') {
this.emit(`# @${tn} — neural interface: ${JSON.stringify(trait.config || {})}`);
} else if (tn === 'embedding_search' || tn === 'ai_npc_brain' || tn === 'vector_db') {
this.emit(`# @${tn} — knowledge/AI: integrate via HTTP or GDExtension`);
} else if (tn === 'vision' || tn === 'ai_vision' || tn === 'spatial_awareness') {
this.emit(`# @${tn} — computer vision: use OpenCV GDExtension or XRServer`);
} else if (tn === 'neural_animation') {
this.emit(`# @neural_animation — motion matching via AnimationTree + custom solver`);
}
// Catch-all
else {
this.emit(`# @${tn}: ${JSON.stringify(trait.config || {})}`);
}
}
}
// Children
if (obj.children) {
for (const child of obj.children) {
this.compileObject(child, varName);
}
}
this.emit('');
}
private compileSpatialGroup(group: HoloSpatialGroup, parentVar: string): void {
const varName = this.sanitizeName(group.name);
this.emit(`# Spatial Group: ${this.escapeStringValue(group.name as string, 'GDScript')}`);
this.emit(`var ${varName} = Node3D.new()`);
this.emit(`${varName}.name = "${this.escapeStringValue(group.name as string, 'GDScript')}"`);
for (const prop of group.properties) {
if (prop.key === 'position' && Array.isArray(prop.value)) {
this.emit(`${varName}.position = ${this.toVector3(prop.value)}`);
}
}
this.emit(`${parentVar}.add_child(${varName})`);
for (const obj of group.objects) {
this.compileObject(obj, varName);
}
if (group.groups) {
for (const sub of group.groups) {
this.compileSpatialGroup(sub, varName);
}
}
this.emit('');
}
private compileAudio(audio: HoloAudio): void {
const varName = this.sanitizeName(audio.name);
const spatial = audio.properties.find((p) => p.key === 'spatial')?.value;
this.emit(`# Audio: ${this.escapeStringValue(audio.name as string, 'GDScript')}`);
if (spatial) {
this.emit(`var ${varName} = AudioStreamPlayer3D.new()`);
} else {
this.emit(`var ${varName} = AudioStreamPlayer.new()`);
}
this.emit(`${varName}.name = "${this.escapeStringValue(audio.name as string, 'GDScript')}"`);
for (const prop of audio.properties) {
if (prop.key === 'src' || prop.key === 'source') {
this.emit(`${varName}.stream = load("res://audio/${prop.value}")`);
} else if (prop.key === 'volume') {
this.emit(`${varName}.volume_db = linear_to_db(${prop.value})`);
} else if (prop.key === 'position' && Array.isArray(prop.value)) {
this.emit(`${varName}.position = ${this.toVector3(prop.value)}`);
} else if (prop.key === 'distance') {
this.emit(`${varName}.max_distance = ${prop.value}`);
}
}
const loop = audio.properties.find((p) => p.key === 'loop')?.value;
this.emit(`add_child(${varName})`);
this.emit(`${varName}.play()`);
if (loop) {
this.emit(`${varName}.finished.connect(func(): ${varName}.play())`);
}
this.emit('');
}
private compileZone(zone: HoloZone): void {
const varName = this.sanitizeName(zone.name);
this.emit(`# Zone: ${this.escapeStringValue(zone.name as string, 'GDScript')}`);
this.emit(`var ${varName} = Area3D.new()`);
this.emit(`${varName}.name = "${this.escapeStringValue(zone.name as string, 'GDScript')}"`);
const shape = zone.properties.find((p) => p.key === 'shape')?.value;
this.emit(`var ${varName}_shape = CollisionShape3D.new()`);
if (shape === 'box') {
this.emit(`${varName}_shape.shape = BoxShape3D.new()`);
const size = zone.properties.find((p) => p.key === 'size')?.value;
if (size && Array.isArray(size)) {
this.emit(`${varName}_shape.shape.size = ${this.toVector3(size)}`);
}
} else if (shape === 'sphere') {
this.emit(`${varName}_shape.shape = SphereShape3D.new()`);
const radius = zone.properties.find((p) => p.key === 'radius')?.value;
if (radius) this.emit(`${varName}_shape.shape.radius = ${radius}`);
}
this.emit(`${varName}.add_child(${varName}_shape)`);
const pos = zone.properties.find((p) => p.key === 'position')?.value;
if (pos) this.emit(`${varName}.position = ${this.toVector3(pos)}`);
// Connect handlers
for (const handler of zone.handlers) {
if (handler.event === 'on_enter') {
this.emit(
`${varName}.body_entered.connect(func(body): print("${this.escapeStringValue(zone.name as string, 'GDScript')}: enter"))`
);
} else if (handler.event === 'on_exit') {
this.emit(
`${varName}.body_exited.connect(func(body): print("${this.escapeStringValue(zone.name as string, 'GDScript')}: exit"))`
);
}
}
this.emit(`add_child(${varName})`);
this.emit('');
}
private compileTimeline(tl: HoloTimeline): void {
const varName = this.sanitizeName(tl.name);
this.emit(`func _play_${varName}():`);
this.indentLevel++;
this.emit(`var tween = create_tween()`);
if (tl.loop) {
this.emit(`tween.set_loops()`);
}
for (const entry of tl.entries) {
if (entry.action.kind === 'animate') {
this.emit(
`tween.tween_callback(func(): pass) # animate "${entry.action.target}" at ${entry.time}s`
);
for (const [key, value] of Object.entries(entry.action.properties)) {
this.emit(`# ${key}: ${JSON.stringify(value)}`);
}
} else if (entry.action.kind === 'emit') {
this.emit(
`tween.tween_callback(func(): print("Event: ${entry.action.event}")).set_delay(${entry.time})`
);
} else if (entry.action.kind === 'call') {
this.emit(
`tween.tween_callback(func(): ${entry.action.method}()).set_delay(${entry.time})`
);
}
}
this.indentLevel--;
this.emit('');
}
private compileTransition(tr: HoloTransition): void {
const varName = this.sanitizeName(tr.name);
this.emit(`func ${varName}():`);
this.indentLevel++;
const target = tr.properties.find((p) => p.key === 'target')?.value;
const effect = tr.properties.find((p) => p.key === 'effect')?.value;
const duration = tr.properties.find((p) => p.key === 'duration')?.value;
this.emit(`# Transition: ${effect} (${duration}s)`);
if (target) {
this.emit(`get_tree().change_scene_to_file("res://scenes/${target}.tscn")`);
}
this.indentLevel--;
this.emit('');
}
private compileEffects(effects: HoloEffects): void {
this.emit('# === Post-Processing (configure via WorldEnvironment) ===');
for (const effect of effects.effects) {
this.emit(`# Effect: ${effect.effectType} — ${JSON.stringify(effect.properties)}`);
}
this.emit('');
}
private compileUI(ui: HoloUI): void {
this.emit('# === UI Overlay ===');
this.emit('var ui_layer = CanvasLayer.new()');
this.emit('ui_layer.name = "HoloUI"');
this.emit('add_child(ui_layer)');
this.emit('');
for (const el of ui.elements) {
const varName = this.sanitizeName(el.name);
const elType = el.properties.find((p) => p.key === 'type')?.value;
this.emit(`# UI: ${this.escapeStringValue(el.name as string, 'GDScript')} (${elType})`);
if (elType === 'text') {
this.emit(`var ${varName} = Label.new()`);
const text = el.properties.find((p) => p.key === 'text')?.value;
if (text) this.emit(`${varName}.text = "${text}"`);
} else if (elType === 'progress') {
this.emit(`var ${varName} = ProgressBar.new()`);
} else if (elType === 'panel') {
this.emit(`var ${varName} = Panel.new()`);
} else {
this.emit(`var ${varName} = Control.new()`);
}
this.emit(`${varName}.name = "${this.escapeStringValue(el.name as string, 'GDScript')}"`);
const pos = el.properties.find((p) => p.key === 'position')?.value;
if (pos && Array.isArray(pos)) {
this.emit(`${varName}.position = Vector2(${pos[0]}, ${pos[1]})`);
}
const size = el.properties.find((p) => p.key === 'size')?.value;
if (size && Array.isArray(size)) {
this.emit(`${varName}.size = Vector2(${size[0]}, ${size[1]})`);
}
this.emit(`ui_layer.add_child(${varName})`);
this.emit('');
}
}
// ─── Helpers ───────────────────────────────────────────────────────────
private emit(line: string): void {
this.lines.push(this.options.indent.repeat(this.indentLevel) + line);
}
private sanitizeName(name: string): string {
return name.replace(/[^a-zA-Z0-9_]/g, '_');
}
private toVector3(arr: HoloValue): string {
if (Array.isArray(arr) && arr.length >= 3) {
return `Vector3(${arr[0]}, ${arr[1]}, ${arr[2]})`;
}
return `Vector3(${arr}, ${arr}, ${arr})`;
}
private toColor(value: HoloValue): string {
if (typeof value === 'string' && value.startsWith('#')) {
return `Color.html("${value}")`;
}
return `Color.WHITE`;
}
private toGDScriptValue(value: HoloValue): string {
if (typeof value === 'number') return `${value}`;
if (typeof value === 'boolean') return value ? 'true' : 'false';
if (typeof value === 'string') return `"${this.escapeStringValue(value, 'GDScript')}"`;
if (value === null) return 'null';
if (Array.isArray(value)) return `[${value.map((v) => this.toGDScriptValue(v)).join(', ')}]`;
return 'null';
}
private findProp(
props: Array<{ key: string; value: HoloValue }>,
key: string
): HoloValue | undefined {
return props?.find((p) => p.key === key)?.value;
}
private findObjProp(obj: HoloObjectDecl, key: string): HoloValue | undefined {
return obj.properties?.find((p) => p.key === key)?.value;
}
}