forked from joshmarinacci/webxr-experiments
-
Notifications
You must be signed in to change notification settings - Fork 0
/
vrmanager.js
103 lines (84 loc) · 3.19 KB
/
vrmanager.js
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
function printError(err) {
console.log(err)
}
export const VR_DETECTED = "detected"
export const VR_CONNECTED = "connected"
export const VR_DISCONNECTED = "disconnected"
export const VR_PRESENTCHANGE = "presentchange"
export const VR_ACTIVATED = "activated"
export default class VRManager {
constructor(renderer) {
this.device = null
this.renderer = renderer
if(!this.renderer) throw new Error("VR Manager requires a valid ThreeJS renderer instance")
this.listeners = {}
if ('xr' in navigator) {
console.log("has webxr")
navigator.xr.requestDevice().then((device) => {
device.supportsSession({immersive: true, exclusive: true /* DEPRECATED */})
.then(() => {
this.device = device
this.fire(VR_DETECTED,{})
})
.catch(printError);
}).catch(printError);
} else if ('getVRDisplays' in navigator) {
console.log("has webvr")
window.addEventListener( 'vrdisplayconnect', ( event ) => {
this.device = event.display
this.fire(VR_CONNECTED)
}, false );
window.addEventListener( 'vrdisplaydisconnect', ( event ) => {
this.fire(VR_DISCONNECTED)
}, false );
window.addEventListener( 'vrdisplaypresentchange', ( event ) => {
this.fire(VR_PRESENTCHANGE)
}, false );
window.addEventListener( 'vrdisplayactivate', ( event ) => {
this.device = event.display
this.device.requestPresent([{source:this.renderer.domElement}])
this.fire(VR_ACTIVATED)
}, false );
navigator.getVRDisplays()
.then( ( displays ) => {
console.log("vr scanned")
if ( displays.length > 0 ) {
// showEnterVR( displays[ 0 ] );
console.log("found vr",displays[0])
this.device = displays[0]
this.fire(VR_DETECTED,{})
} else {
console.log("no vr at all")
// showVRNotFound();
}
} ).catch(printError);
} else {
// no vr
console.log("no vr at all")
}
}
addEventListener(type, cb) {
if(!this.listeners[type]) this.listeners[type] = []
this.listeners[type].push(cb)
}
fire(type,evt) {
if(!evt) evt = {}
evt.type = type
if(!this.listeners[type]) this.listeners[type] = []
this.listeners[type].forEach(cb => cb(evt))
}
enterVR() {
if(!this.device) {
console.warn("tried to connect VR on an invalid device")
return
}
console.log("entering VR")
const prom = this.renderer.vr.setDevice( this.device );
console.log('promise is',prom)
if(this.device.isPresenting) {
this.device.exitPresent()
} else {
this.device.requestPresent([{source: this.renderer.domElement}]);
}
}
}