-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathApp.tsx
387 lines (360 loc) · 11.8 KB
/
App.tsx
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
/**
* Generated with the TypeScript template
* https://github.com/react-native-community/react-native-template-typescript
*
* @format
*/
import React, {
useState,
FunctionComponent,
useEffect,
useCallback,
} from 'react';
import {
SafeAreaView,
StatusBar,
Button,
View,
Text,
ViewProps,
Image,
} from 'react-native';
import {
EngineView,
useEngine,
EngineViewCallbacks,
FontFace,
} from '@babylonjs/react-native';
import {
Scene,
Vector3,
ArcRotateCamera,
Camera,
WebXRSessionManager,
SceneLoader,
TransformNode,
DeviceSourceManager,
DeviceType,
PointerInput,
WebXRTrackingState,
IMouseEvent,
Nullable,
Mesh,
ICanvasRenderingContext,
MeshBuilder,
StandardMaterial,
DynamicTexture,
} from '@babylonjs/core';
import '@babylonjs/loaders';
import Slider from '@react-native-community/slider';
const EngineScreen: FunctionComponent<ViewProps> = (props: ViewProps) => {
const defaultScale = 1;
const enableSnapshots = false;
const engine = useEngine();
const [toggleView, setToggleView] = useState(false);
const [camera, setCamera] = useState<Camera>();
const [rootNode, setRootNode] = useState<TransformNode>();
const [scene, setScene] = useState<Scene>();
const [xrSession, setXrSession] = useState<WebXRSessionManager>();
const [scale, setScale] = useState<number>(defaultScale);
const [snapshotData, setSnapshotData] = useState<string>();
const [engineViewCallbacks, setEngineViewCallbacks] =
useState<EngineViewCallbacks>();
const [trackingState, setTrackingState] = useState<WebXRTrackingState>();
const [mesh, setMesh] = useState<Mesh>();
const [texture, setTexture] = useState<DynamicTexture>();
useEffect(() => {
if (engine) {
const scene = new Scene(engine);
scene.createDefaultCamera(true);
(scene.activeCamera as ArcRotateCamera).beta -= Math.PI / 8;
setCamera(scene.activeCamera!);
scene.createDefaultLight(true);
const rootNode = new TransformNode('Root Container', scene);
setRootNode(rootNode);
setScene(scene);
const deviceSourceManager = new DeviceSourceManager(engine);
const handlePointerInput = (
inputIndex: PointerInput,
previousState: Nullable<number>,
currentState: Nullable<number>,
) => {
if (
inputIndex === PointerInput.Horizontal &&
currentState &&
previousState
) {
rootNode.rotate(
Vector3.Down(),
(currentState - previousState) * 0.005,
);
}
};
deviceSourceManager.onDeviceConnectedObservable.add(device => {
if (device.deviceType === DeviceType.Touch) {
const touch = deviceSourceManager.getDeviceSource(
device.deviceType,
device.deviceSlot,
)!;
touch.onInputChangedObservable.add(touchEvent => {
handlePointerInput(
touchEvent.inputIndex,
touchEvent.previousState,
touchEvent.currentState,
);
});
} else if (device.deviceType === DeviceType.Mouse) {
const mouse = deviceSourceManager.getDeviceSource(
device.deviceType,
device.deviceSlot,
)!;
mouse.onInputChangedObservable.add(mouseEvent => {
if (mouse.getInput(PointerInput.LeftClick)) {
handlePointerInput(
mouseEvent.inputIndex,
mouseEvent.previousState,
mouseEvent.currentState,
);
}
});
}
});
const transformContainer = new TransformNode(
'Transform Container',
scene,
);
transformContainer.parent = rootNode;
transformContainer.scaling.scaleInPlace(0.2);
transformContainer.position.y -= 0.2;
const fontFace = new FontFace(
'droidsans',
'https://raw.githubusercontent.com/CedricGuillemet/dump/master/droidsans.ttf',
);
// san fransisco for ios, roboto for google, for web opensans.
fontFace.load().then(() => {
const plane = MeshBuilder.CreatePlane('testPlane', {size: 0.5}, scene);
const textureWidth = 1024;
const textureHeight = 1024;
const font = `bold 50px monospace`;
const mat = new StandardMaterial('Name', scene);
mat.backFaceCulling = false;
const localTexture = new DynamicTexture(
'testText',
{width: textureWidth, height: textureHeight},
scene,
);
localTexture.drawText(
'TestText',
textureWidth / 10,
textureHeight / 10,
font,
'white',
'transparent',
true,
true,
);
mat.diffuseTexture = localTexture;
setTexture(localTexture);
plane.material = mat;
plane.position.z = 2;
plane.position.y -= 0.5;
setMesh(plane);
});
scene.beforeRender = function () {
setScale(scale => (scale === 300 ? 1 : scale + 1));
};
}
}, [engine]);
// -------------------------------------------------
useEffect(() => {
if (scale && mesh && texture) {
//Situation one: Recreating a mesh each frame to update
// Expectation: a new texture appears on the mesh every frame
// Reality: Nothing seems to appear on the mesh, and eventually the texture seems to be attached to the camera view.
(mesh.material as StandardMaterial).diffuseTexture?.dispose();
const font = `bold 50px monospace`;
let localTexture = new DynamicTexture(
'Updated text ' + scale,
{width: 1024, height: 1024},
scene,
);
localTexture.hasAlpha = true;
localTexture.drawText(
'Updated text ' + scale,
10,
scale,
font,
'white',
'transparent',
true,
true,
);
(mesh.material as StandardMaterial).diffuseTexture = localTexture;
//Situation two: Update texture and measure the text a lot
// Expectation: The texture gets updated with new text in addition to the old text
// Reality: The expectation does happen, but also the memory keeps on climbing and never comes down.
// const canvas = texture.getContext();
// const font = `bold ${scale}px monospace`;
// canvas.font = font;
// // canvas.fillStyle = '#000000';
// let measure;
// for (let index = 0; index < 30; index++) { // In my actual app, I don't have this but I do use measureText in a loop this for loop is here to simulate an extreme scenario
// measure = canvas.measureText(
// 'This is some random text to measure',
// ).width;
// }
// texture.drawText(
// 'Updated text ' + scale + measure,
// 10,
// scale,
// font,
// 'white',
// 'transparent',
// true,
// true,
// );
// (mesh.material as StandardMaterial).diffuseTexture = texture;
}
}, [mesh, scale]);
const trackingStateToString = (
trackingState: WebXRTrackingState | undefined,
): string => {
return trackingState === undefined ? '' : WebXRTrackingState[trackingState];
};
// -------------------------------------------------
const onToggleXr = useCallback(() => {
(async () => {
if (xrSession) {
await xrSession.exitXRAsync();
} else {
if (rootNode !== undefined && scene !== undefined) {
const xr = await scene.createDefaultXRExperienceAsync({
disableDefaultUI: true,
disableTeleportation: true,
});
const session = await xr.baseExperience.enterXRAsync(
'immersive-ar',
'unbounded',
xr.renderTarget,
);
setXrSession(session);
session.onXRSessionEnded.add(() => {
setXrSession(undefined);
setTrackingState(undefined);
});
setTrackingState(xr.baseExperience.camera.trackingState);
xr.baseExperience.camera.onTrackingStateChanged.add(
newTrackingState => {
setTrackingState(newTrackingState);
},
);
// TODO: Figure out why getFrontPosition stopped working
//box.position = (scene.activeCamera as TargetCamera).getFrontPosition(2);
const cameraRay = scene.activeCamera!.getForwardRay(1);
rootNode.position = cameraRay.origin.add(
cameraRay.direction.scale(cameraRay.length),
);
rootNode.rotate(Vector3.Up(), 3.14159);
}
}
})();
}, [rootNode, scene, xrSession]);
const onInitialized = useCallback(
async (engineViewCallbacks: EngineViewCallbacks) => {
setEngineViewCallbacks(engineViewCallbacks);
},
[engine],
);
const onSnapshot = useCallback(async () => {
if (engineViewCallbacks) {
setSnapshotData(
'data:image/jpeg;base64,' + (await engineViewCallbacks.takeSnapshot()),
);
}
}, [engineViewCallbacks]);
return (
<>
<View style={props.style}>
<Button
title="Toggle EngineView"
onPress={() => {
setToggleView(!toggleView);
}}
/>
<Button
title={xrSession ? 'Stop XR' : 'Start XR'}
onPress={onToggleXr}
/>
{!toggleView && (
<View style={{flex: 1}}>
{enableSnapshots && (
<View style={{flex: 1}}>
<Button title={'Take Snapshot'} onPress={onSnapshot} />
<Image style={{flex: 1}} source={{uri: snapshotData}} />
</View>
)}
<EngineView
camera={camera}
onInitialized={onInitialized}
displayFrameRate={true}
/>
<Slider
style={{
position: 'absolute',
minHeight: 50,
margin: 10,
left: 0,
right: 0,
bottom: 0,
}}
minimumValue={50}
maximumValue={200}
step={1}
value={defaultScale}
onValueChange={setScale}
/>
<Text style={{color: 'yellow', position: 'absolute', margin: 3}}>
{trackingStateToString(trackingState)}
</Text>
</View>
)}
{toggleView && (
<View
style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
<Text style={{fontSize: 24}}>EngineView has been removed.</Text>
<Text style={{fontSize: 12}}>
Render loop stopped, but engine is still alive.
</Text>
</View>
)}
</View>
</>
);
};
const App = () => {
const [toggleScreen, setToggleScreen] = useState(false);
return (
<>
<StatusBar barStyle="dark-content" />
<SafeAreaView style={{flex: 1, backgroundColor: 'white'}}>
{!toggleScreen && <EngineScreen style={{flex: 1}} />}
{toggleScreen && (
<View
style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
<Text style={{fontSize: 24}}>EngineScreen has been removed.</Text>
<Text style={{fontSize: 12}}>
Engine has been disposed, and will be recreated.
</Text>
</View>
)}
<Button
title="Toggle EngineScreen"
onPress={() => {
setToggleScreen(!toggleScreen);
}}
/>
</SafeAreaView>
</>
);
};
export default App;