Skip to content

Commit

Permalink
Fix Camera typings add missing parameter for attachControl #3
Browse files Browse the repository at this point in the history
  • Loading branch information
brianzinn committed Oct 10, 2021
1 parent c8532a9 commit 54ca1ba
Show file tree
Hide file tree
Showing 8 changed files with 66 additions and 86 deletions.
7 changes: 3 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@
"prebuild": "rimraf dist",
"build": "cross-env NODE_ENV=production rollup -c",
"start": "tsc-watch --onSuccess \"rollup -c\"",
"deploy-docs": "ts-node tools/gh-pages-publish",
"generate-code": "ts-node -P tools/tsconfig.generate.json tools/generate-code.ts",
"unit-test": "cross-env TS_NODE_PROJECT=\"test/tsconfig.json\" mocha --require ts-node/register --require esm \"test/**/*.spec.{js,jsx,ts,tsx}\"",
"test": "npm run unit-test",
Expand All @@ -48,7 +47,7 @@
"@types/lodash.camelcase": "^4.3.6",
"@types/mocha": "^8.2.0",
"@types/node": "^14.14.10",
"@types/react": "^17.0.0",
"@types/react": "^17.0.27",
"@types/react-reconciler": "^0.18.0",
"@types/sinon": "^9.0.10",
"@typescript-eslint/eslint-plugin": "^4.29.1",
Expand All @@ -60,8 +59,8 @@
"lodash.camelcase": "^4.3.0",
"mocha": "8.1.3",
"nyc": "^15.1.0",
"react": "^17.0.1",
"react-dom": "^17.0.1",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"rimraf": "^3.0.2",
"rollup": "^2.0.6",
"rollup-plugin-terser": "^7.0.2",
Expand Down
29 changes: 27 additions & 2 deletions src/CustomProps.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,10 +75,22 @@ export type VRExperienceHelperCustomProps = {
/**
* Custom Gizmo props used for declaratively attaching.
*/
export type GizmoCustomProps = {
export type GizmoCustomProps = {
/**
* Attach to nearest node (as opposed to a restricting mesh)
*/
attachGizmoToNode?: boolean
/**
* Attach to nearest node
*/
attachGizmoToMesh?: boolean
/**
* Do not automatically attach to a mesh/node
*/
skipAutoAttach?: boolean
/**
* Try to set 'gizmoLayer' automatically.
*/
skipUtilityLayerAttach?: boolean
} & CustomProps;

Expand All @@ -87,7 +99,20 @@ export type VRExperienceHelperCustomProps = {
* These are more useful when applicalbe to only part of the inheritance chain.
*/

/**
* Currently only extra prop for controlling attaching camera
*/
export type CameraCustomProps = {
/**
* Passed through when attachControl(..) is called. Defines whether event caught by the controls should call preventdefault()
* (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
*/
noPreventDefault?: boolean
}

/**
* Same functionality as Advanced Dynamic Texture factory method "createForMesh" (and for first parent mesh).
*/
export type ADTCustomProps = {
/**
* Only applicable for AdvanceDynamicTexture to attach to a mesh. ADT.CreateForMesh(parent, ...)
Expand Down Expand Up @@ -119,4 +144,4 @@ export type VirtualKeyboardCustomProps = {
/**
* A union of all CustomProps as a convenience typing and easier maintenance in other areas of code (ie: CreatedInstance and HostConfig)
*/
export type AnyCustomProps = CustomProps & (AbstractMeshCustomProps & ADTCustomProps & Control3DCustomProps & GizmoCustomProps & GlowLayerCustomProps & VirtualKeyboardCustomProps & ShadowGeneratorCustomProps & MaterialCustomProps)
export type AnyCustomProps = CustomProps & (AbstractMeshCustomProps & ADTCustomProps & CameraCustomProps & Control3DCustomProps & GizmoCustomProps & GlowLayerCustomProps & VirtualKeyboardCustomProps & ShadowGeneratorCustomProps & MaterialCustomProps)
3 changes: 2 additions & 1 deletion src/customHosts/CameraLifecycleListener.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@ import { Camera } from '@babylonjs/core/Cameras/camera.js';

import BaseLifecycleListener from './BaseLifecycleListener';
import { CreatedInstance } from '../CreatedInstance';
import { FiberCameraProps } from '../generatedProps';

export default class CameraLifecycleListener extends BaseLifecycleListener<Camera, any> {
export default class CameraLifecycleListener extends BaseLifecycleListener<Camera, FiberCameraProps> {

onParented(parent: CreatedInstance<any>, child: CreatedInstance<any>): any {
super.onParented(parent, child);
Expand Down
2 changes: 1 addition & 1 deletion src/customHosts/GizmoLifecycleListener.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { CreatedInstance } from '../CreatedInstance';
import { GizmoCustomProps } from '../CustomProps';
import BaseLifecycleListener from './BaseLifecycleListener';

export default class GizmoLifecycleListener extends BaseLifecycleListener<Gizmo, any> {
export default class GizmoLifecycleListener extends BaseLifecycleListener<Gizmo, GizmoCustomProps> {
onMount(instance: CreatedInstance<Gizmo>) {
const gizmo = instance.hostInstance!;
const gizmoProps: GizmoCustomProps = instance.customProps;
Expand Down
3 changes: 2 additions & 1 deletion src/customHosts/GizmoManagerLifecycleListener.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { GizmoManager } from '@babylonjs/core/Gizmos/gizmoManager.js';

import { CreatedInstance } from '../CreatedInstance';
import { FiberGizmoManagerProps } from '../generatedProps';
import BaseLifecycleListener from './BaseLifecycleListener';

export default class GizmoManagerLifecycleListener extends BaseLifecycleListener<GizmoManager, any> {
export default class GizmoManagerLifecycleListener extends BaseLifecycleListener<GizmoManager, FiberGizmoManagerProps> {

onChildAdded(child: CreatedInstance<any>, parent: CreatedInstance<any>): void {
const gizmoManager: GizmoManager = parent.hostInstance! as GizmoManager;
Expand Down
4 changes: 2 additions & 2 deletions src/generatedProps.ts
Original file line number Diff line number Diff line change
Expand Up @@ -230,7 +230,7 @@ import { VolumeBasedPanel as BabylonjsGuiVolumeBasedPanel } from "@babylonjs/gui
import { GUI3DManager as BabylonjsGuiGUI3DManager } from "@babylonjs/gui/3D/gui3DManager.js";
import { FluentMaterial as BabylonjsGuiFluentMaterial } from "@babylonjs/gui/3D/materials/fluentMaterial.js";
import { Key, ReactNode, Ref } from "react";
import { AbstractMeshCustomProps, ADTCustomProps, Control3DCustomProps, CustomProps, GizmoCustomProps, GlowLayerCustomProps, MaterialCustomProps, ShadowGeneratorCustomProps, VirtualKeyboardCustomProps, VRExperienceHelperCustomProps } from "./CustomProps";
import { AbstractMeshCustomProps, ADTCustomProps, CameraCustomProps, Control3DCustomProps, CustomProps, GizmoCustomProps, GlowLayerCustomProps, MaterialCustomProps, ShadowGeneratorCustomProps, VirtualKeyboardCustomProps, VRExperienceHelperCustomProps } from "./CustomProps";
import { DynamicTerrain as ExtensionsDynamicTerrain } from "./extensions/DynamicTerrain";

export type BabylonNode<T> = {
Expand Down Expand Up @@ -708,7 +708,7 @@ export type FiberCameraProps = {
'upVector-y'?: number;
'upVector-z'?: number;
viewport?: BabylonjsCoreViewport;
} & FiberNodeProps;
} & FiberNodeProps & CameraCustomProps;
export type FiberCameraPropsCtor = {
name: string;
position: BabylonjsCoreVector3;
Expand Down
51 changes: 29 additions & 22 deletions tools/generate-code.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ console.log('ver:', ts.version);

const CONFLICT_INTRINSIC_ELEMENTS = ['Button', 'Ellipse', 'Image', 'Line', 'Polygon'];

const ALL_CUSTOM_PROPS = ['AbstractMeshCustomProps', 'ADTCustomProps', 'Control3DCustomProps', 'CustomProps', 'GizmoCustomProps', 'GlowLayerCustomProps', 'MaterialCustomProps', 'ShadowGeneratorCustomProps', 'VirtualKeyboardCustomProps', 'VRExperienceHelperCustomProps'];
const ALL_CUSTOM_PROPS = ['AbstractMeshCustomProps', 'ADTCustomProps', 'CameraCustomProps', '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.
Expand Down Expand Up @@ -117,7 +117,7 @@ const addHostElement = (className: string, babylonjsClassDeclaration: ClassDecla

INTRINSIC_ELEMENTS.addProperty({
name: classToIntrinsic(className),
type: classPropIntersection
type: classPropIntersection
});
}
}
Expand Down Expand Up @@ -800,7 +800,7 @@ const writePropertyAsUpdateFunction = (propsProperties: OptionalKind<PropertySig
})

if (GENERATE_KEBAB_ACCESSORS && propsType === 'BabylonjsCoreVector3') {
['x','y','z'].forEach(prop => {
['x', 'y', 'z'].forEach(prop => {
propsProperties.push({
name: `'${propertyName}-${prop}'`,
type: 'number',
Expand All @@ -827,7 +827,6 @@ const createClassDeclaration = (classDeclaration: ClassDeclaration, rootBaseClas

const importedClassDeclaration = getModuleDeclarationFromClassDeclaration(classDeclaration);
addNamedImportToFile(importedClassDeclaration, [generatedCodeSourceFile, generatedPropsSourceFile], true);

addPropsAndHandlerClasses(generatedCodeSourceFile, generatedPropsSourceFile, className, importedClassDeclaration, getInstanceProperties(classDeclaration), getInstanceSetMethods(classDeclaration), baseClass, customProps);

const newClassDeclaration = generatedCodeSourceFile.addClass({
Expand Down Expand Up @@ -961,7 +960,7 @@ const isQuestionToken = (node: Node<ts.Node>): boolean => {
* It probably looks like we should just pass along the ClassDeclaration...
*/
const addPropsAndHandlerClasses = (generatedCodeSourceFile: SourceFile, generatedPropsSourceFile: SourceFile, classNameToGenerate: string, babylonClassDeclaration: GeneratedModuleDeclaration, propertiesToAdd: (PropertyDeclaration | PropertySignature | SetAccessorDeclaration)[], setMethods: (MethodDeclaration | MethodSignature)[], baseClass: ClassDeclaration | undefined, customProps: string = 'CustomProps'): void => {
// console.log('addpropshandlers1:', classNameToGenerate, babylonClassDeclaration.className, babylonClassDeclaration.importAlias);
// console.log('addpropshandlers1:', classNameToGenerate, babylonClassDeclaration.className, babylonClassDeclaration.importAlias, baseClass?.getName(), customProps);

const typeProperties: OptionalKind<PropertySignatureStructure>[] = []

Expand Down Expand Up @@ -1009,7 +1008,7 @@ const addPropsAndHandlerClasses = (generatedCodeSourceFile: SourceFile, generate
})
monkeyPatchInterface.getMethods().forEach(method => {
const type = getMethodType(method, [generatedCodeSourceFile, generatedPropsSourceFile]);

if (type === null) {
return; // skip
}
Expand Down Expand Up @@ -1073,7 +1072,7 @@ const addPropsAndHandlerClasses = (generatedCodeSourceFile: SourceFile, generate
});

if (GENERATE_KEBAB_ACCESSORS && type === 'BabylonjsCoreVector3') {
['x','y','z'].forEach(prop => {
['x', 'y', 'z'].forEach(prop => {
propsToCheck.push({
name: `${propertyName}-${prop}`,
type: 'number',
Expand Down Expand Up @@ -1197,27 +1196,35 @@ const addPropsAndHandlerClasses = (generatedCodeSourceFile: SourceFile, generate
}
})

// this is temporary, where we give ALL classes these CustomProps. Will be addressed (ideally we leave intersectsWith here 'undefined' and add ONLY valid props)
const intersectsWith = baseClass === undefined ? customProps : baseClass.getName();
const intersectsWith: string[] = [];
// TODO: probably need something here only whe base case is reached?
// const intersectsWith = baseClass === undefined ? customProps : baseClass.getName();
if (baseClass !== undefined) {
intersectsWith.push(baseClass.getName()!);
if (customProps === `${classNameToGenerate}CustomProps`) {
intersectsWith.push(customProps);
}
} else {
intersectsWith.push(customProps);
}

const propsClassName = `${CLASS_NAME_PREFIX}${classNameToGenerate}Props`;

PROPS_EXPORTS.push(propsClassName);
writeTypeAlias(generatedPropsSourceFile, propsClassName, typeProperties.sort((a, b) =>
writeTypeAlias(generatedPropsSourceFile, propsClassName, typeProperties.sort((a, b) =>
(a.name.startsWith('\'') ? a.name.substr(1) : a.name).localeCompare(b.name.startsWith('\'') ? b.name.substr(1) : b.name)
), intersectsWith);
}

const writeTypeAlias = (file: SourceFile, name: string, typeProperties: OptionalKind<PropertySignatureStructure>[], intersectsWith?: string): void => {
const writeTypeAlias = (file: SourceFile, name: string, typeProperties: OptionalKind<PropertySignatureStructure>[], intersectsWith: string[] = []): void => {
const { intersectionType, objectType } = Writers;

// bad hack to get custom props through. will address soon...
const intersectsWithType = (intersectsWith === undefined)
? undefined
: ALL_CUSTOM_PROPS.indexOf(intersectsWith) !== -1 ? intersectsWith : `${CLASS_NAME_PREFIX}${intersectsWith}Props`;
const intersectsWithTypes = intersectsWith.map(i => ALL_CUSTOM_PROPS.indexOf(i) !== -1 ? i : `${CLASS_NAME_PREFIX}${i}Props`)

const propertiesObject = objectType({ properties: typeProperties })
const aliasType: WriterFunction = (intersectsWithType !== undefined)
? intersectionType(propertiesObject, intersectsWithType)
const aliasType: WriterFunction = (intersectsWithTypes.length > 0)
? intersectionType(propertiesObject, intersectsWithTypes[0], ...intersectsWithTypes.slice(1))
: propertiesObject

file.addTypeAlias({
Expand Down Expand Up @@ -1390,7 +1397,7 @@ const createClassesInheritedFrom = (generatedCodeSourceFile: SourceFile, generat
derivedClassesOrdered.forEach((derivedClassDeclaration: ClassDeclaration) => {
addHostElement(derivedClassDeclaration.getName()!, derivedClassDeclaration);

const newClassDeclaration = createClassDeclaration(derivedClassDeclaration, baseClassDeclaration, generatedCodeSourceFile, generatedPropsSourceFile, extra, customProps ? customProps(derivedClassDeclaration): undefined);
const newClassDeclaration = createClassDeclaration(derivedClassDeclaration, baseClassDeclaration, generatedCodeSourceFile, generatedPropsSourceFile, extra, customProps ? customProps(derivedClassDeclaration) : undefined);
addCreateInfoFromConstructor(derivedClassDeclaration, newClassDeclaration, classNamespaceTuple.moduleDeclaration, generatedCodeSourceFile, generatedPropsSourceFile);

// AdvancedDynamicTexture has different metadata than other ThinTexture derived classes.
Expand Down Expand Up @@ -1550,7 +1557,7 @@ const generateCode = async () => {

// This includes Node, which is base class for ie: Camera, Mesh, etc. (inheriting from Node would add new things like TextureDome)
createClassesDerivedFrom(generatedCodeSourceFile, generatedPropsSourceFile, classesOfInterest.get("TransformNode")!, { isNode: true }, undefined);
createClassesInheritedFrom(generatedCodeSourceFile, generatedPropsSourceFile, classesOfInterest.get("AbstractMesh")!, () => ({isNode: true, acceptsMaterials: true, isMesh: true}));
createClassesInheritedFrom(generatedCodeSourceFile, generatedPropsSourceFile, classesOfInterest.get("AbstractMesh")!, () => ({ isNode: true, acceptsMaterials: true, isMesh: true }));

const extra = (newClassDeclaration: ClassDeclaration, originalClassDeclaration: ClassDeclaration) => {
// consider having targetable as metadata.
Expand All @@ -1577,7 +1584,7 @@ const generateCode = async () => {
};

if (classesOfInterest.get("Camera") !== undefined) {
createClassesInheritedFrom(generatedCodeSourceFile, generatedPropsSourceFile, classesOfInterest.get("Camera")!, () => ({ isCamera: true, isNode: true }), extra);
createClassesInheritedFrom(generatedCodeSourceFile, generatedPropsSourceFile, classesOfInterest.get("Camera")!, () => ({ isCamera: true, isNode: true }), extra, undefined, () => ('CameraCustomProps'));
}

if (classesOfInterest.get("MeshBuilder") !== undefined) {
Expand Down Expand Up @@ -1676,7 +1683,7 @@ const generateCode = async () => {
}

if (classesOfInterest.get("Gizmo")) {
createClassesInheritedFrom(generatedCodeSourceFile, generatedPropsSourceFile, classesOfInterest.get("Gizmo")!, () => ({isGizmo: true}), undefined, undefined, () => "GizmoCustomProps");
createClassesInheritedFrom(generatedCodeSourceFile, generatedPropsSourceFile, classesOfInterest.get("Gizmo")!, () => ({ isGizmo: true }), undefined, undefined, () => "GizmoCustomProps");
}

console.log('Adding single classes:');
Expand All @@ -1687,7 +1694,7 @@ const generateCode = async () => {
createSingleClass("DynamicTerrain", generatedCodeSourceFile, generatedPropsSourceFile, undefined, { acceptsMaterials: true });
createSingleClass("PointsCloudSystem", generatedCodeSourceFile, generatedPropsSourceFile);
createSingleClass("Viewport", generatedCodeSourceFile, generatedPropsSourceFile);
createSingleClass("UtilityLayerRenderer", generatedCodeSourceFile, generatedPropsSourceFile, undefined, { isUtilityLayerRenderer: true})
createSingleClass("UtilityLayerRenderer", generatedCodeSourceFile, generatedPropsSourceFile, undefined, { isUtilityLayerRenderer: true })

// These "delay creation" we want to also not generate constructors?
createSingleClass("ShadowGenerator", generatedCodeSourceFile, generatedPropsSourceFile, undefined, { delayCreation: true, isShadowGenerator: true }, () => { return; }, 'ShadowGeneratorCustomProps');
Expand Down Expand Up @@ -1813,7 +1820,7 @@ const generateCode = async () => {

console.log('saving created content...')

const saveFile = async(file: SourceFile): Promise<void> => {
const saveFile = async (file: SourceFile): Promise<void> => {
const formatCodeSettings: FormatCodeSettings = {
newLineCharacter: '\n',
indentSize: 2,
Expand Down
53 changes: 0 additions & 53 deletions tools/gh-pages-publish.ts

This file was deleted.

0 comments on commit 54ca1ba

Please sign in to comment.