-
Notifications
You must be signed in to change notification settings - Fork 101
/
generate-code.ts
2617 lines (2314 loc) · 83.1 KB
/
generate-code.ts
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
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { Nullable } from '@babylonjs/core/types'
import camelCase from 'lodash.camelcase'
import { exit } from 'process'
/**
* To debug code generation use the launch config in VS Code - "Generate Code (debug)"
* Also, remove "type": "module" in package.json for ERR_UNKNOWN_FILE_EXTENSION errors.
*/
import path, { dirname } from 'path'
import {
ClassDeclaration,
CodeBlockWriter,
ConstructorDeclaration,
EnumDeclaration,
FormatCodeSettings,
FunctionDeclaration,
GetAccessorDeclaration,
ImportDeclaration,
ImportDeclarationStructure,
InterfaceDeclaration,
JSDoc,
MethodDeclaration,
MethodSignature,
ModuleDeclaration,
ModuleDeclarationKind,
Node,
OptionalKind,
ParameterDeclaration,
Project,
PropertyDeclaration,
PropertySignature,
PropertySignatureStructure,
Scope,
SetAccessorDeclaration,
SourceFile,
SyntaxKind,
ts,
Type,
VariableDeclaration,
VariableDeclarationKind,
VariableStatement,
WriterFunction,
Writers,
} from 'ts-morph'
import { fileURLToPath } from 'url'
import { CreateInfo, CreationType, GeneratedParameter } from '../src/codeGenerationDescriptors'
import { InstanceMetadataParameter } from '../src/CreatedInstance'
const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)
const REACT_RECONCILER_CREATED_INSTANCE_METADATA = 'CreatedInstanceMetadata'
const PROPERTY_UPDATE_INTERFACE = 'PropertyUpdate'
const CLASS_NAME_PREFIX = 'Fiber'
type ClassNameSpaceTuple = {
classDeclaration: ClassDeclaration
moduleDeclaration: GeneratedModuleDeclaration
}
const addedClassDeclarationsMap = new Map<string, ClassDeclaration>()
// issues #137, 148,
const fullySpecified = (moduleSpecifier: string): string => `${moduleSpecifier}.js`
// to set onXXX properties. via onXXX.add(() => void). TODO: use TypeGuards.isTypeReferenceNode(...) and check type
const OBSERVABLE_PATTERN: RegExp = /^BabylonjsCoreObservable<.*>$/
const GENERATE_KEBAB_ACCESSORS = true // test for Vector3 only currently
/**
* These are required parameters that we defer to after instantion (JSX.IntrinsicElements marked as optional)
* LifecycleHandler and delay creation will handle these not being set (ie: look at PhysicsImposter constructor!)
*/
const LATE_BOUND_CONSTRUCTOR_PARAMETERS: Map<string, string[]> = new Map<string, string[]>([
['PhysicsImpostor', ['object']],
['PhysicsAggregate', ['transformNode']],
['ShadowGenerator', ['light']],
['CascadedShadowGenerator', ['light']],
['Sprite', ['manager']],
])
console.log('ver:', ts.version)
const CONFLICT_INTRINSIC_ELEMENTS = ['Button', 'Ellipse', 'Image', 'Line', 'Polygon', 'Text']
const ALL_CUSTOM_PROPS = [
'AbstractMeshCustomProps',
'ADTCustomProps',
'CameraCustomProps',
'Control2DCustomProps',
'Control3DCustomProps',
'CustomProps',
'GizmoCustomProps',
'GlowLayerCustomProps',
'MaterialCustomProps',
'ShadowGeneratorCustomProps',
'VirtualKeyboardCustomProps',
'VRExperienceHelperCustomProps',
]
// would be good to check JSX.IntrinsicElements with 'keyof', but it's erased at runtime (doesn't work on dynamic strings)
// fixes TS warning: Property 'polygon' must be of type SVGProps<SVGPolygonElement>, but here has type..., so we are skipping to generate polygon for now.
// TypeScript has some issues being worked on to address local instead of `global`
const classToIntrinsic = (className: string): string => {
return CONFLICT_INTRINSIC_ELEMENTS.indexOf(className) >= 0
? `'babylon-${camelCase(className)}'`
: camelCase(className)
}
// NOTE: 'strings' are what are available for NPM import for 'Component', while JSX.IntrinsicElements are global (for now).
// Both are created the same way as host components by react-reconciler
const REACT_EXPORTS: Set<string> = new Set<string>()
let INTRINSIC_ELEMENTS: InterfaceDeclaration
const _hostElementMap: Set<string> = new Set<string>()
/**
*
* @param className may not exist with an underlying 'type'. ie: Box, Sphere
* @param factoryTypeDeclaration
*/
const addHostElement = (className: string, babylonjsClassDeclaration: ClassDeclaration): void => {
if (!REACT_EXPORTS.has(className)) {
REACT_EXPORTS.add(className)
_hostElementMap.add(className) // prevent duplicates
const { intersectionType } = Writers
const moduleDeclaration = getModuleDeclarationFromDeclaration(babylonjsClassDeclaration)
let classPropIntersection = intersectionType(
intersectionType(
`${CLASS_NAME_PREFIX}${babylonjsClassDeclaration.getName()}Props`,
`${CLASS_NAME_PREFIX}${className}PropsCtor`
),
`BabylonNode<${moduleDeclaration.importAlias}>`
)
// adding props that are not original babylonjs
if (additionalCustomProps[`${CLASS_NAME_PREFIX}${className}`]) {
classPropIntersection = intersectionType(
classPropIntersection,
additionalCustomProps[`${CLASS_NAME_PREFIX}${className}`]
)
}
INTRINSIC_ELEMENTS.addProperty({
name: classToIntrinsic(className),
type: classPropIntersection,
})
}
}
// const addCustomHostElement = (className: string, type: string): void => {
// if (REACT_EXPORTS.has(className)) {
// console.error('Found existing export:', className); // would happen in BabylonJS added class with same name
// return;
// }
// REACT_EXPORTS.add(className);
// INTRINSIC_ELEMENTS.addProperty({
// name: classToIntrinsic(className),
// type
// } as OptionalKind<PropertySignatureStructure>)
// }
const monkeyPatchInterfaces: Map<string, InterfaceDeclaration[]> = new Map<
string,
InterfaceDeclaration[]
>()
const enumMap: Map<string, string> = new Map<string, string>()
let ENUMS_LIST: string[] = []
const PROPS_EXPORTS: string[] = [] // used to put all props in single import.
/**
* CustomProps not from @babylonjs/* modules, but custom for this project (used when not applied to entire inheritance chain).
*/
const additionalCustomProps: Record<string, string> = {
[`${CLASS_NAME_PREFIX}AbstractMesh`]: 'AbstractMeshCustomProps', // not including dervived.
[`${CLASS_NAME_PREFIX}AdvancedDynamicTexture`]: 'ADTCustomProps',
[`${CLASS_NAME_PREFIX}GlowLayer`]: 'GlowLayerCustomProps',
[`${CLASS_NAME_PREFIX}VirtualKeyboard`]: 'VirtualKeyboardCustomProps',
}
// These are the base/factory classes we used to generate everything.
let classesOfInterest: Map<String, ClassNameSpaceTuple | undefined> = new Map<
String,
ClassNameSpaceTuple | undefined
>()
const classesToGenerate: String[] = [
// always needed
'TransformNode',
'AbstractMesh',
'Mesh',
'AbstractScene',
'Scene',
// decides what is generated (useful to remove some to speed up debugging)
'Camera',
'Material',
'Light',
'Control',
'Control3D',
'GUI3DManager',
'ThinTexture',
'AdvancedDynamicTexture',
'ShadowGenerator',
'CascadedShadowGenerator',
'EnvironmentHelper',
'PhysicsImpostor',
'PhysicsAggregate',
'VRExperienceHelper',
'DynamicTerrain',
'EffectLayer',
'Behavior', // TODO: remove this and use interface
'PointsCloudSystem',
'PostProcessRenderPipeline',
'PostProcess',
'UtilityLayerRenderer',
'Gizmo',
'GizmoManager',
'EngineView',
'Viewport',
'Layer',
'MaterialPluginBase',
'SpriteManager',
'Sprite',
'Sound',
]
let MeshBuilderVariableDeclaration: Nullable<VariableDeclaration> = null
classesToGenerate.forEach((className) => classesOfInterest.set(className, undefined))
const readonlyPropertiesToGenerate: Map<string, ClassNameSpaceTuple> = new Map<
string,
ClassNameSpaceTuple
>()
/**
* In babylon.js, Behavior is a interface, not a class.
* Each specific behavior is a separated class.
* Add it to classesOfInterest if className includes keyword.
*/
const classesOfKeywordInterest = ['Behavior']
type GeneratedModuleDeclaration = {
moduleSpecifier: string
className: string
importAlias: string
}
type FileModuleDeclaration = {
hostComponent: boolean // used to generate factory
sourceFile: SourceFile // needed since we use filePath as key for top-level dictionary
moduleDeclaration: GeneratedModuleDeclaration
}
const importDeclarationMap: Map<string, Map<string, FileModuleDeclaration[]>> = new Map<
string,
Map<string, FileModuleDeclaration[]>
>()
const capitalize = (value: string) => {
if (!value || value.length === 0) {
return value
}
return value.charAt(0).toUpperCase() + value.substring(1).toLowerCase()
}
/**
* TODO: fix this so, that classes with acronyms are properly formatted (I think _ does this).
* ie: VRExperienceHelper -> vrExperienceHelper, PBRMaterial -> pbrMaterial
*
* @param value
*/
const getModuleDeclarationFromDeclaration = (
declaration: ClassDeclaration | VariableDeclaration
): GeneratedModuleDeclaration => {
const sourceFile = declaration.getSourceFile()
const match = sourceFile.getFilePath().match(`node_modules/(.*)${sourceFile.getExtension()}`)
const className = declaration.getName()!
let moduleSpecifier: string
let classAlias: string
if (match === null || match.length < 2) {
if (className !== 'DynamicTerrain') {
throw new Error('Unknown (not from @babylonjs) class being generated:' + className)
}
// '../src/extensions/DynamicTerrain.ts' == sourceFile.getFilePath();
classAlias = 'ExtensionsDynamicTerrain'
moduleSpecifier = './extensions/DynamicTerrain'
} else {
moduleSpecifier = fullySpecified(match[1]!)
const packageName = moduleSpecifier.substr(
0,
moduleSpecifier.indexOf('/', '@babylonjs/'.length)
)
// ie: '@babylonjs/core' -> BabylonjsCore
const aliasPrefix = packageName
.substring('@'.length)
.split('/')
.map((x) => capitalize(x))
.join('')
classAlias = `${aliasPrefix}${className}`
}
return {
moduleSpecifier,
className,
importAlias: classAlias,
}
}
const addNamedImportToFile = (
moduleDeclaration: GeneratedModuleDeclaration,
targets: SourceFile[],
isHostComponent: boolean
): void => {
targets.forEach((file) => {
const fileKey = file.getFilePath()
if (!importDeclarationMap.has(fileKey)) {
const fileMap: Map<string, FileModuleDeclaration[]> = new Map<
string,
FileModuleDeclaration[]
>()
importDeclarationMap.set(fileKey, fileMap)
}
const existingFileMap: Map<string, FileModuleDeclaration[]> = importDeclarationMap.get(fileKey)!
if (!existingFileMap.has(moduleDeclaration.moduleSpecifier)) {
existingFileMap.set(moduleDeclaration.moduleSpecifier, [])
}
const declarationList: FileModuleDeclaration[] = existingFileMap.get(
moduleDeclaration.moduleSpecifier
)!
const match = declarationList.find(
(i) => i.moduleDeclaration.className === moduleDeclaration.className
)
if (match === undefined) {
declarationList.push({
hostComponent: isHostComponent,
sourceFile: file,
moduleDeclaration,
})
} else {
match.hostComponent = match.hostComponent || isHostComponent
}
})
}
/**
*
* Would comvert something like BabylonjsCore
*
* @param input
*/
const reduceToImport = (input: string): string => {
let result = input
while (result.endsWith('[]')) {
result = result.substr(0, result.length - 2)
}
return result
}
const createTypeFromText = (
typeText: string,
targetFiles: SourceFile[],
customPattern?: RegExp
): string => {
// ^<> for generics. ',)' for parameter lists, ';' for types, '|' for unions
const pattern: RegExp = /import\(\"([^\"]+)\"\)\.([^<>,;\|) ]+)/
let match = typeText.match(customPattern || pattern)
while (match !== null && match.length === 3) {
const importLocation = match[1]
const importClassName = match[2]
if (importClassName.endsWith(' ')) {
console.error('match', match)
}
const pathMatch = importLocation.match(/node_modules\/(.*)/)
if (pathMatch !== null && pathMatch.length === 2) {
const moduleSpecifier = fullySpecified(pathMatch[1]!)
const packageName = moduleSpecifier.substr(
0,
moduleSpecifier.indexOf('/', '@babylonjs/'.length)
)
// ie: '@babylonjs/core' -> BabylonjsCore
const aliasPrefix = packageName
.substr(1)
.split('/')
.map((x) => capitalize(x))
.join('')
const classAlias = `${aliasPrefix}${importClassName}`
const importAlias = reduceToImport(classAlias)
const className = reduceToImport(importClassName)
const moduleDeclaration: GeneratedModuleDeclaration = {
moduleSpecifier,
className,
importAlias: importAlias,
}
// This is only to skip unused enumerations like SimplificationType.QUADRATIC.
// We need to trim out the enum value itself when present, but for now we can skip.
if (classAlias.indexOf('.') === -1) {
addNamedImportToFile(moduleDeclaration, targetFiles, false)
}
typeText = typeText.replace(match[0], classAlias)
match = typeText.match(pattern)
}
}
// enumerations are missing imports. getText() just uses TypeChecker#typeToString
// this converts ie: 'boolean | Space' to 'boolean | BabylonjsCoreSpace', which matches imports
typeText
.split('|')
.map((t) => t.trim())
.forEach((value) => {
const enumIndex = ENUMS_LIST.indexOf(value)
if (enumIndex >= 0) {
const regex: RegExp = new RegExp(`(^${value}|${value}$)`, 'gi')
typeText = typeText.replace(regex, enumMap.get(value)!)
}
})
return typeText
}
/**
* If has interest file, add it's class info to classesOfInterest.
* @param classDeclaration
* @param sourceFiles
*/
const addSourceClass = (classDeclaration: ClassDeclaration, sourceFiles: SourceFile[]) => {
const className = classDeclaration.getName()
if (className === undefined) {
return
}
const findByKeyword = classesOfKeywordInterest.some((keyword) => className.includes(keyword))
if (classesOfInterest.has(className) || findByKeyword) {
const moduleDeclaration = getModuleDeclarationFromDeclaration(classDeclaration)
addNamedImportToFile(moduleDeclaration, sourceFiles, true)
classesOfInterest.set(className, {
classDeclaration,
moduleDeclaration,
})
}
}
const addProject = (packageNames: string[], files: string[], sourceFiles: SourceFile[]): void => {
const project = new Project({})
packageNames.forEach((packageName) => {
// workspaces are hoisted to root (./node_modules)
const fullPath = path.join(__dirname, '../../../node_modules', packageName, '/**/*.d.ts')
console.log('adding package:', fullPath)
project.addSourceFilesAtPaths(fullPath)
})
files.forEach((file) => {
project.addSourceFilesAtPaths(path.join(__dirname, file))
})
project.getSourceFiles().forEach((sourceFile: SourceFile) => {
sourceFile.getClasses().forEach((classDeclaration: ClassDeclaration) => {
addSourceClass(classDeclaration, sourceFiles)
})
sourceFile.getVariableDeclarations().forEach((variableDeclaration: VariableDeclaration) => {
if (variableDeclaration.getName() === 'MeshBuilder') {
MeshBuilderVariableDeclaration = variableDeclaration
}
})
sourceFile.getModules().forEach((ns: ModuleDeclaration) => {
ns.getInterfaces().forEach((interfaceDeclaration: InterfaceDeclaration) => {
if (
interfaceDeclaration.getName() === 'Scene' &&
interfaceDeclaration
.getProperties()
.find((prop) => prop.getName() === 'onBeforePhysicsObservable')
) {
// adding Scene monkey patch only for now (babylonjs/core/Physics/physicsEngineComponent), but could find way to do all.
monkeyPatchInterfaces.set(interfaceDeclaration.getName(), [interfaceDeclaration])
}
if (
interfaceDeclaration.getName() === 'AbstractMesh' &&
interfaceDeclaration.getProperties().find((prop) => prop.getName() === 'instancedBuffers')
) {
monkeyPatchInterfaces.set(interfaceDeclaration.getName(), [interfaceDeclaration])
}
})
ns.getClasses().forEach((classDeclaration: ClassDeclaration) => {
addSourceClass(classDeclaration, sourceFiles)
})
})
const fullyQualifiedPattern: RegExp = /\"([^\"]+)\"\.([^<>,;\|) ]+)/
sourceFile.getEnums().forEach((enumDeclaration: EnumDeclaration) => {
if (!enumDeclaration || enumDeclaration.getType().getSymbol() === undefined) {
console.log('UNDEF enumdeclaration?')
} else {
const fqn: string = enumDeclaration.getType().getSymbol()!.getFullyQualifiedName()
const translatedType = createTypeFromText(fqn, sourceFiles, fullyQualifiedPattern)
enumMap.set(enumDeclaration.getName(), translatedType)
}
})
})
}
const addMetadata = (
classDeclaration: ClassDeclaration,
originalClassDeclaration?: ClassDeclaration,
metadata?: InstanceMetadataParameter
) => {
const createInfoProperty = classDeclaration.addProperty({
name: 'Metadata',
type: REACT_RECONCILER_CREATED_INSTANCE_METADATA,
scope: Scope.Public,
isStatic: true,
isReadonly: true,
})
let metadataClone = metadata === undefined ? {} : { ...metadata }
let propertyInit = {
...metadataClone,
className: classDeclaration.getName()!,
}
createInfoProperty.setInitializer(JSON.stringify(propertyInit, null, 2))
}
const createdFactoryClasses: string[] = []
/**
* Create host element from class declaration static (creation) methods
*/
const createFactoryClass = (
fromClassName: string,
declarations: Record<string, MethodDeclaration | FunctionDeclaration>,
prefix: string,
metadata: InstanceMetadataParameter,
generatedCodeSourceFile: SourceFile,
generatedPropsSourceFile: SourceFile
) => {
for (const methodName of Object.keys(declarations)) {
const method = declarations[methodName]
if ((methodName && methodName.startsWith('Create')) || methodName.startsWith('Extrude')) {
let factoryType: string = methodName.startsWith('Create')
? methodName.substring('Create'.length)
: methodName // ie: ExtrudePolygon, ExtrudeShape & ExtrudeShapeCustom
factoryType = prefix + factoryType
createdFactoryClasses.push(factoryType)
// [0] is always the ClassDeclaration (at least for MeshBuilder and AdvancedDynamicTexture factory methods)
const hostClassName = (
method.getReturnType().getSymbol()!.getDeclarations()[0] as ClassDeclaration
).getName()!
const classDeclarationType =
addedClassDeclarationsMap.get(hostClassName) ??
classesOfInterest.get(hostClassName)!.classDeclaration!
addHostElement(factoryType, classDeclarationType)
let newClassDeclaration: ClassDeclaration = addClassDeclarationFromFactoryMethod(
generatedCodeSourceFile,
factoryType,
classDeclarationType,
method
)
addCreateInfoFromFactoryMethod(
method,
camelCase(fromClassName),
methodName,
newClassDeclaration,
'@babylonjs/core',
generatedCodeSourceFile,
generatedPropsSourceFile
)
// console.log(` > create info: ${fromClassName}.${methodName}`);
addMetadata(newClassDeclaration, undefined /* no original class */, metadata)
}
}
console.log(
`${fromClassName} Factory - ${createdFactoryClasses
.sort((a, b) => a.localeCompare(b))
.map((c) => classToIntrinsic(c).replace(/['\u2019]/g, ''))
.join(', ')}`
)
}
const addClassDeclarationFromFactoryMethod = (
generatedCodeSourceFile: SourceFile,
className: string,
classDeclaration: ClassDeclaration,
factoryMethod: MethodDeclaration | FunctionDeclaration,
extra?: (cd: ClassDeclaration) => void
) => {
const newClassDeclaration = generatedCodeSourceFile.addClass({
name: `${CLASS_NAME_PREFIX}${className}`,
isExported: true,
})
// const newClassModuleDeclaration = getModuleDeclarationFromClassDeclaration(classDeclaration);
if (extra !== undefined) {
extra(newClassDeclaration)
}
// We don't need to inherit anything, also collides with property declarations
// cameraClassDeclaration.setExtends(`${ClassNamesPrefix}${baseClass!.getName()}`)
let jsDocs: JSDoc[] = factoryMethod.getJsDocs()
const generatedComment = 'This code has been generated'
if (jsDocs.length > 0) {
// .compilerNode.comment was getComment() - seems broken
newClassDeclaration.addJsDoc(jsDocs[0].compilerNode.comment + '\n\n' + generatedComment)
} else {
newClassDeclaration.addJsDoc(generatedComment)
}
const propsHandlersPropertyName = 'propsHandlers'
const propsHandlerBaseName = classDeclaration.getName()
newClassDeclaration.addProperty({
name: propsHandlersPropertyName,
type: `PropsHandler<${CLASS_NAME_PREFIX}${propsHandlerBaseName}Props>[]`, // xxx
scope: Scope.Private,
})
// NOTE: remove <T, U> of ${newClassModuleDeclaration.importAlias}
newClassDeclaration.addImplements(
`HasPropsHandlers<${CLASS_NAME_PREFIX}${propsHandlerBaseName}Props>`
)
const newConstructor: ConstructorDeclaration = newClassDeclaration.addConstructor()
newConstructor.setBodyText((writer: CodeBlockWriter) => {
writer.writeLine(`this.${propsHandlersPropertyName} = [`)
const propsHandlers: string[] = []
let handlerClassDeclaration: ClassDeclaration | undefined = classDeclaration
while (handlerClassDeclaration) {
propsHandlers.push(
`new ${CLASS_NAME_PREFIX}${handlerClassDeclaration.getName()}PropsHandler()`
)
handlerClassDeclaration = handlerClassDeclaration.getBaseClass()
}
writer.writeLine(propsHandlers.join('\n,'))
writer.writeLine('];')
})
let getPropsHandlersMethod = newClassDeclaration.addMethod({
name: 'getPropsHandlers',
returnType: `PropsHandler<${CLASS_NAME_PREFIX}${propsHandlerBaseName}Props>[]`,
})
getPropsHandlersMethod.setBodyText((writer) => {
writer.writeLine('return this.propsHandlers;')
})
let addPropertyHandlerMethod = newClassDeclaration.addMethod({
name: 'addPropsHandler',
returnType: 'void',
})
addPropertyHandlerMethod.addParameter({
name: 'propHandler',
type: `PropsHandler<${CLASS_NAME_PREFIX}${propsHandlerBaseName}Props>`,
})
addPropertyHandlerMethod.setBodyText((writer) => {
writer.writeLine('this.propsHandlers.push(propHandler);')
})
return newClassDeclaration
}
const includeAsConstructorParameter = (parameterType: string): boolean => {
// there is two cases: scene:Scene, sceneOrEngine: Scene|Engine
return !parameterType.includes('BabylonjsCoreScene') /* provided by reconciler */
}
const getExpandedPropsFromParameter = (
parameter: ParameterDeclaration,
targetFiles: SourceFile[]
): GeneratedParameter[] => {
const props: GeneratedParameter[] = []
parameter
.getType()
.getSymbol()!
.getMembers()
.forEach((member) => {
let propertyName = member.getName()
let internalType = member.getTypeAtLocation(member.getValueDeclaration()!)
let propertyType = createTypeFromText(internalType.getText(), targetFiles)
// let questionToken2 = (member.getValueDeclaration()!.compilerNode as any).questionToken;
let questionToken = (member.compilerSymbol.valueDeclaration as any).questionToken
props.push({
name: propertyName,
type: propertyType,
optional: questionToken !== undefined,
})
})
return props
}
const parameterShouldBeExpanded = (parameter: ParameterDeclaration): boolean => {
const name = parameter.getName()!
const parameterType: string = createTypeFromText(parameter.getType().getText(), [])
return (
name === 'options' &&
!parameterType.startsWith('Babylonjs') &&
parameter.getType().getSymbol() !== undefined &&
parameter.getType().getSymbol()!.getMembers().length > 0
)
}
const addCreateInfoFromFactoryMethod = (
method: MethodDeclaration | FunctionDeclaration,
classMapKey: string,
factoryMethod: string,
targetClass: ClassDeclaration,
namespace: string,
generatedCodeSourceFile: SourceFile,
generatedPropsSourceFile: SourceFile
): void => {
let methodParameters: GeneratedParameter[] = []
const typeProperties: OptionalKind<PropertySignatureStructure>[] = []
method.getParameters().forEach((createMethodParameter: ParameterDeclaration) => {
const parameterName: string | undefined = createMethodParameter.getName()
if (parameterName === undefined) {
return
}
const parameterType: string = createTypeFromText(createMethodParameter.getType().getText(), [
generatedCodeSourceFile,
generatedPropsSourceFile,
])
const optional: boolean = createMethodParameter.isOptional()
let generatedParameter: GeneratedParameter = {
name: parameterName,
type: parameterType,
optional,
}
if (parameterShouldBeExpanded(createMethodParameter)) {
let specialProperties: GeneratedParameter[] = getExpandedPropsFromParameter(
createMethodParameter,
[generatedCodeSourceFile, generatedPropsSourceFile]
)
generatedParameter.type = specialProperties
specialProperties.forEach((prop) => {
typeProperties.push({
type: prop.type as string,
name: prop.name,
hasQuestionToken: true, // 'options' are always optional from constructor point of view (enforced in IntrinsicType, 'CreateInfo' only generates warnings)
})
})
} else if (includeAsConstructorParameter(parameterType)) {
typeProperties.push({
name: parameterName,
type: parameterType,
hasQuestionToken: optional,
})
}
methodParameters.push(generatedParameter)
})
const createInfoProperty = targetClass.addProperty({
name: 'CreateInfo',
scope: Scope.Public,
isStatic: true,
isReadonly: true,
})
let value: CreateInfo = {
creationType: CreationType.FactoryMethod,
libraryLocation: classMapKey,
namespace,
factoryMethod: factoryMethod,
parameters: methodParameters,
}
createInfoProperty.setInitializer(JSON.stringify(value, null, 2))
writeTypeAlias(generatedPropsSourceFile, `${targetClass.getName()}PropsCtor`, typeProperties)
}
/**
* get some methods from babylonjs class
* @param classDeclaration
*/
const getInstanceSetMethods = (classDeclaration: ClassDeclaration): MethodDeclaration[] => {
let instanceSetMethods: MethodDeclaration[] = []
classDeclaration.getInstanceMethods().forEach((methodDeclaration: MethodDeclaration) => {
const methodName = methodDeclaration.getName()
// TODO: add ?
if (
methodName.startsWith('set') ||
methodName.startsWith('add') ||
methodName.startsWith('enable') ||
methodName === 'translate'
) {
instanceSetMethods.push(methodDeclaration)
}
})
return instanceSetMethods
}
function addReadonlyClasses(
classDeclaration: ClassDeclaration,
property: PropertyDeclaration | GetAccessorDeclaration
): void {
if (property.getType().isClass() === true) {
const typeClassDeclarations: ClassDeclaration[] | undefined = property
.getType()
?.getSymbol()
?.getDeclarations() as ClassDeclaration[]
const className =
typeClassDeclarations !== undefined && typeClassDeclarations.length === 1
? typeClassDeclarations[0].getName()
: undefined
if (className !== undefined && className.endsWith('Configuration')) {
const classNamespaceTuple: ClassNameSpaceTuple = {
classDeclaration: typeClassDeclarations[0],
moduleDeclaration: getModuleDeclarationFromDeclaration(typeClassDeclarations[0]),
}
console.log(
` >> adding ${classDeclaration.getName()!}.${property.getName()} (read-only) property type '${typeClassDeclarations[0].getName()}'`
)
readonlyPropertiesToGenerate.set(typeClassDeclarations[0].getName()!, classNamespaceTuple)
}
}
}
/**
* get props from babylonjs class
* @param classDeclaration
*/
const getInstanceProperties = (
classDeclaration: ClassDeclaration
): (PropertyDeclaration | SetAccessorDeclaration)[] => {
let result: (PropertyDeclaration | SetAccessorDeclaration)[] = []
classDeclaration.getSetAccessors().forEach((acc) => result.push(acc))
classDeclaration.getGetAccessors().forEach((acc) => {
// This is how we add ImageProcessingConfiguration.
addReadonlyClasses(classDeclaration, acc)
})
// for conditional breakpoints on class: classDeclaration.getName() === "Control";
classDeclaration.getProperties().forEach((property) => {
let propertyName = property.getName()
if (propertyName[0] === '_') {
// console.log(` > skipping ${className}.${propertyName} (private/hidden)`)
return
}
if (property.isStatic()) {
// console.log(` > skipping ${className}.${propertyName} (static)`)
return
}
if (property.isReadonly()) {
// This is how we add class configurations like PBRClearCoatConfiguration
// console.log(` > skipping ${classDeclaration.getName()}.${propertyName} (read-only)`)
addReadonlyClasses(classDeclaration, property)
return
}
// add conditional breakpoint to inspect properties. ie: propertyName==='customShaderNameResolve'
result.push(property)
})
return result
}
/**
* Returns null for methods we should be ignoring (no parameters or getters)
* @param methodDeclaration
* @param targetFiles
*/
const getMethodType = (
methodDeclaration: MethodDeclaration | MethodSignature,
targetFiles: SourceFile[]
): string | null => {
const methodName = methodDeclaration.getName()
if (methodName.startsWith('get')) {
return null
}
const params: ParameterDeclaration[] = methodDeclaration.getParameters()
if (params.length === 0) {
return null
}
let paramTypes: string[] = []
params.forEach((param) => {
let type: string = createTypeFromText(param.getType().getText(), targetFiles)
const questionToken = param.hasQuestionToken() ? '?' : ''
const paramName: string | undefined = param.getName()
paramTypes.push(`${paramName}${questionToken}: ${type}`)
})
const returnType =
methodDeclaration.getReturnType().getText() === 'void'
? 'void'
: createTypeFromText(methodDeclaration.getReturnType().getText(), targetFiles)
return `(${paramTypes.join(', ')}) => ${returnType}`
}
const writeMethodAsUpdateFunction = (
propsProperties: OptionalKind<PropertySignatureStructure>[],
method: MethodDeclaration | MethodSignature,
type: string
): void => {
const methodName = method.getName()
// tempting to put the method signature here instead of 'any', but we need to be able to call it like:
// <camera setTarget={} /> and TODO: figure out how with ie: ((target?: BabylonjsCoreVector3) => void;!!)
propsProperties.push({
name: methodName,
type: 'any',
hasQuestionToken: true,
})
}
type PropertySignatureStructurePlusIsSetAccessor = PropertySignatureStructure & {
isSetAccessor: boolean
}
/**
* Returns false when a property has already been declared (ie: a subclass will override a method and create duplicates).
* side-effect is to update the propsProperties list.
*/
const writePropertyAsUpdateFunction = (
propsProperties: OptionalKind<PropertySignatureStructurePlusIsSetAccessor>[],
type: string,
propertyName: string,
isSetAccessor: boolean,
addedProperties: Set<String>
): boolean => {
// doesn't really matter if it's 'optional', as nothing is forcing JavaScript users to follow your conventions.
// const isOptional = property.getQuestionTokenNode();
// TODO: We need to ensure this is for entire hierarchy. ie: 'name' will be saved multiple times on object creation
if (addedProperties.has(propertyName)) {
console.log(
' >> skipping already existing property (ie: was overridden like Mesh.scaling): ',
propertyName
)
return false
}
addedProperties.add(propertyName)
// console.log(` >> including Mesh.${propertyName} (${type}))`)
// /^BabylonjsCoreObservable<.*>$/.test(type)
// cannot set observable types from React. TODO: track and remove added observables on unmount.
const propsType = OBSERVABLE_PATTERN.test(type) ? 'any' : type
propsProperties.push({
name: propertyName,
type: propsType,
hasQuestionToken: true,
isSetAccessor,
})
if (!isSetAccessor && GENERATE_KEBAB_ACCESSORS && propsType === 'BabylonjsCoreVector3') {
;['x', 'y', 'z'].forEach((prop) => {
propsProperties.push({
name: `'${propertyName}-${prop}'`,