webxr_xr_dragging_custom_depth.html 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>three.js xr - dragging with custom depth shader</title>
  5. <meta charset="utf-8">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
  7. <link type="text/css" rel="stylesheet" href="main.css">
  8. </head>
  9. <body>
  10. <div id="info">
  11. <a href="https://threejs.org" target="_blank" rel="noopener">three.js</a> xr - dragging
  12. </div>
  13. <script type="importmap">
  14. {
  15. "imports": {
  16. "three": "../build/three.module.js",
  17. "three/addons/": "./jsm/"
  18. }
  19. }
  20. </script>
  21. <script type="module">
  22. import * as THREE from 'three';
  23. import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
  24. import { XRButton } from 'three/addons/webxr/XRButton.js';
  25. import { XRControllerModelFactory } from 'three/addons/webxr/XRControllerModelFactory.js';
  26. let container;
  27. let camera, scene, renderer;
  28. let controller1, controller2;
  29. let controllerGrip1, controllerGrip2;
  30. let isDepthSupplied = false;
  31. let raycaster;
  32. const intersected = [];
  33. const tempMatrix = new THREE.Matrix4();
  34. let controls, group;
  35. init();
  36. animate();
  37. function init() {
  38. container = document.createElement( 'div' );
  39. document.body.appendChild( container );
  40. scene = new THREE.Scene();
  41. scene.background = new THREE.Color( 0x808080 );
  42. camera = new THREE.PerspectiveCamera( 50, window.innerWidth / window.innerHeight, 0.1, 10 );
  43. camera.position.set( 0, 1.6, 3 );
  44. controls = new OrbitControls( camera, container );
  45. controls.target.set( 0, 1.6, 0 );
  46. controls.update();
  47. const floorGeometry = new THREE.PlaneGeometry( 6, 6 );
  48. const floorMaterial = new THREE.ShadowMaterial( { opacity: 0.25, blending: THREE.CustomBlending, transparent: false } );
  49. const floor = new THREE.Mesh( floorGeometry, floorMaterial );
  50. floor.rotation.x = - Math.PI / 2;
  51. floor.receiveShadow = true;
  52. scene.add( floor );
  53. scene.add( new THREE.HemisphereLight( 0xbcbcbc, 0xa5a5a5, 3 ) );
  54. const light = new THREE.DirectionalLight( 0xffffff, 3 );
  55. light.position.set( 0, 6, 0 );
  56. light.castShadow = true;
  57. light.shadow.camera.top = 3;
  58. light.shadow.camera.bottom = - 3;
  59. light.shadow.camera.right = 3;
  60. light.shadow.camera.left = - 3;
  61. light.shadow.mapSize.set( 4096, 4096 );
  62. scene.add( light );
  63. group = new THREE.Group();
  64. scene.add( group );
  65. const geometries = [
  66. new THREE.BoxGeometry( 0.2, 0.2, 0.2 ),
  67. new THREE.ConeGeometry( 0.2, 0.2, 64 ),
  68. new THREE.CylinderGeometry( 0.2, 0.2, 0.2, 64 ),
  69. new THREE.IcosahedronGeometry( 0.2, 8 ),
  70. new THREE.TorusGeometry( 0.2, 0.04, 64, 32 )
  71. ];
  72. for ( let i = 0; i < 50; i ++ ) {
  73. const geometry = geometries[ Math.floor( Math.random() * geometries.length ) ];
  74. const material = new THREE.ShaderMaterial( {
  75. vertexShader: /* glsl */`
  76. varying vec3 vNormal;
  77. varying vec2 vUv;
  78. void main() {
  79. vNormal = normalize(normalMatrix * normal);
  80. vUv = uv;
  81. gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
  82. }
  83. `,
  84. fragmentShader: /* glsl */`
  85. uniform vec3 diffuseColor;
  86. uniform float roughness;
  87. uniform float metalness;
  88. uniform float emissive;
  89. varying vec3 vNormal;
  90. varying vec2 vUv;
  91. uniform sampler2DArray depthColor;
  92. uniform float depthWidth;
  93. uniform float depthHeight;
  94. #define saturate( a ) clamp( a, 0.0, 1.0 )
  95. float Depth_GetCameraDepthInMeters(const sampler2DArray depthTexture,
  96. const vec2 depthUv, int arrayIndex) {
  97. return texture(depthColor, vec3(depthUv.x, depthUv.y, arrayIndex)).r;
  98. }
  99. float Depth_GetOcclusion(const sampler2DArray depthTexture, const vec2 depthUv, float assetDepthM, int arrayIndex) {
  100. float depthMm = Depth_GetCameraDepthInMeters(depthTexture, depthUv, arrayIndex);
  101. const float kDepthTolerancePerM = 0.001;
  102. return clamp(1.0 -
  103. 0.5 * (depthMm - assetDepthM) /
  104. (kDepthTolerancePerM * assetDepthM) +
  105. 0.5, 0.0, 1.0);
  106. }
  107. float Depth_GetBlurredOcclusionAroundUV(const sampler2DArray depthTexture, const vec2 uv, float assetDepthM, int arrayIndex) {
  108. // Kernel used:
  109. // 0 4 7 4 0
  110. // 4 16 26 16 4
  111. // 7 26 41 26 7
  112. // 4 16 26 16 4
  113. // 0 4 7 4 0
  114. const float kKernelTotalWeights = 269.0;
  115. float sum = 0.0;
  116. const float kOcclusionBlurAmount = 0.0005;
  117. vec2 blurriness =
  118. vec2(kOcclusionBlurAmount, kOcclusionBlurAmount /** u_DepthAspectRatio*/);
  119. float current = 0.0;
  120. current += Depth_GetOcclusion(
  121. depthTexture, uv + vec2(-1.0, -2.0) * blurriness, assetDepthM, arrayIndex);
  122. current += Depth_GetOcclusion(
  123. depthTexture, uv + vec2(+1.0, -2.0) * blurriness, assetDepthM, arrayIndex);
  124. current += Depth_GetOcclusion(
  125. depthTexture, uv + vec2(-1.0, +2.0) * blurriness, assetDepthM, arrayIndex);
  126. current += Depth_GetOcclusion(
  127. depthTexture, uv + vec2(+1.0, +2.0) * blurriness, assetDepthM, arrayIndex);
  128. current += Depth_GetOcclusion(
  129. depthTexture, uv + vec2(-2.0, +1.0) * blurriness, assetDepthM, arrayIndex);
  130. current += Depth_GetOcclusion(
  131. depthTexture, uv + vec2(+2.0, +1.0) * blurriness, assetDepthM, arrayIndex);
  132. current += Depth_GetOcclusion(
  133. depthTexture, uv + vec2(-2.0, -1.0) * blurriness, assetDepthM, arrayIndex);
  134. current += Depth_GetOcclusion(
  135. depthTexture, uv + vec2(+2.0, -1.0) * blurriness, assetDepthM, arrayIndex);
  136. sum += current * 4.0;
  137. current = 0.0;
  138. current += Depth_GetOcclusion(
  139. depthTexture, uv + vec2(-2.0, -0.0) * blurriness, assetDepthM, arrayIndex);
  140. current += Depth_GetOcclusion(
  141. depthTexture, uv + vec2(+2.0, +0.0) * blurriness, assetDepthM, arrayIndex);
  142. current += Depth_GetOcclusion(
  143. depthTexture, uv + vec2(+0.0, +2.0) * blurriness, assetDepthM, arrayIndex);
  144. current += Depth_GetOcclusion(
  145. depthTexture, uv + vec2(-0.0, -2.0) * blurriness, assetDepthM, arrayIndex);
  146. sum += current * 7.0;
  147. current = 0.0;
  148. current += Depth_GetOcclusion(
  149. depthTexture, uv + vec2(-1.0, -1.0) * blurriness, assetDepthM, arrayIndex);
  150. current += Depth_GetOcclusion(
  151. depthTexture, uv + vec2(+1.0, -1.0) * blurriness, assetDepthM, arrayIndex);
  152. current += Depth_GetOcclusion(
  153. depthTexture, uv + vec2(-1.0, +1.0) * blurriness, assetDepthM, arrayIndex);
  154. current += Depth_GetOcclusion(
  155. depthTexture, uv + vec2(+1.0, +1.0) * blurriness, assetDepthM, arrayIndex);
  156. sum += current * 16.0;
  157. current = 0.0;
  158. current += Depth_GetOcclusion(
  159. depthTexture, uv + vec2(+0.0, +1.0) * blurriness, assetDepthM, arrayIndex);
  160. current += Depth_GetOcclusion(
  161. depthTexture, uv + vec2(-0.0, -1.0) * blurriness, assetDepthM, arrayIndex);
  162. current += Depth_GetOcclusion(
  163. depthTexture, uv + vec2(-1.0, -0.0) * blurriness, assetDepthM, arrayIndex);
  164. current += Depth_GetOcclusion(
  165. depthTexture, uv + vec2(+1.0, +0.0) * blurriness, assetDepthM, arrayIndex);
  166. sum += current * 26.0;
  167. sum += Depth_GetOcclusion(depthTexture, uv, assetDepthM, arrayIndex) * 41.0;
  168. return sum / kKernelTotalWeights;
  169. }
  170. void main() {
  171. vec3 normal = normalize(vNormal);
  172. vec3 diffuse = diffuseColor;
  173. float specularIntensity = pow(max(dot(normal, normalize(vec3(0, 0, 1))), 0.0), 64.0);
  174. vec3 specular = vec3(specularIntensity) * mix(vec3(0.04), diffuse, metalness);
  175. gl_FragColor = vec4(diffuse * (1.0 - specular) + specular, 1.0) * (1.0 + emissive);
  176. if (depthWidth > 0.0) {
  177. int arrayIndex = 0;
  178. vec2 depthUv;
  179. if (gl_FragCoord.x>=depthWidth) {
  180. arrayIndex = 1;
  181. depthUv = vec2((gl_FragCoord.x-depthWidth)/depthWidth, gl_FragCoord.y/depthHeight);
  182. } else {
  183. depthUv = vec2(gl_FragCoord.x/depthWidth, gl_FragCoord.y/depthHeight);
  184. }
  185. float assetDepthM = gl_FragCoord.z;
  186. float occlusion = Depth_GetBlurredOcclusionAroundUV(depthColor, depthUv, assetDepthM, arrayIndex);
  187. float depthMm = Depth_GetCameraDepthInMeters(depthColor, depthUv, arrayIndex);
  188. float absDistance = abs(assetDepthM - depthMm);
  189. float v = 0.0025;
  190. absDistance = saturate(v - absDistance) / v;
  191. gl_FragColor.rgb += vec3(absDistance * 2.0, absDistance * 2.0, absDistance * 12.0);
  192. gl_FragColor = mix(gl_FragColor, vec4(0.0, 0.0, 0.0, 0.0), occlusion * 0.7);
  193. }
  194. }
  195. `,
  196. uniforms: {
  197. diffuseColor: { value: new THREE.Color( Math.random() * 0xffffff ) },
  198. roughness: { value: 0.7 },
  199. metalness: { value: 0.0 },
  200. emissive: { value: 0.0 },
  201. depthWidth: { value: 0.0 },
  202. depthHeight: { value: 0.0 },
  203. depthColor: { value: new THREE.Texture() }
  204. }
  205. } );
  206. const object = new THREE.Mesh( geometry, material );
  207. object.position.x = Math.random() * 4 - 2;
  208. object.position.y = Math.random() * 2;
  209. object.position.z = Math.random() * 4 - 2;
  210. object.rotation.x = Math.random() * 2 * Math.PI;
  211. object.rotation.y = Math.random() * 2 * Math.PI;
  212. object.rotation.z = Math.random() * 2 * Math.PI;
  213. object.scale.setScalar( Math.random() + 0.5 );
  214. group.add( object );
  215. }
  216. //
  217. renderer = new THREE.WebGLRenderer( { antialias: true } );
  218. renderer.setPixelRatio( window.devicePixelRatio );
  219. renderer.setSize( window.innerWidth, window.innerHeight );
  220. renderer.shadowMap.enabled = true;
  221. renderer.xr.enabled = true;
  222. container.appendChild( renderer.domElement );
  223. document.body.appendChild( XRButton.createButton( renderer, {
  224. 'optionalFeatures': [ 'depth-sensing' ],
  225. 'depthSensing': { 'usagePreference': [ 'gpu-optimized' ], 'dataFormatPreference': [] }
  226. } ) );
  227. // controllers
  228. controller1 = renderer.xr.getController( 0 );
  229. controller1.addEventListener( 'selectstart', onSelectStart );
  230. controller1.addEventListener( 'selectend', onSelectEnd );
  231. scene.add( controller1 );
  232. controller2 = renderer.xr.getController( 1 );
  233. controller2.addEventListener( 'selectstart', onSelectStart );
  234. controller2.addEventListener( 'selectend', onSelectEnd );
  235. scene.add( controller2 );
  236. const controllerModelFactory = new XRControllerModelFactory();
  237. controllerGrip1 = renderer.xr.getControllerGrip( 0 );
  238. controllerGrip1.add( controllerModelFactory.createControllerModel( controllerGrip1 ) );
  239. scene.add( controllerGrip1 );
  240. controllerGrip2 = renderer.xr.getControllerGrip( 1 );
  241. controllerGrip2.add( controllerModelFactory.createControllerModel( controllerGrip2 ) );
  242. scene.add( controllerGrip2 );
  243. //
  244. const geometry = new THREE.BufferGeometry().setFromPoints( [ new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( 0, 0, - 1 ) ] );
  245. const line = new THREE.Line( geometry );
  246. line.name = 'line';
  247. line.scale.z = 5;
  248. controller1.add( line.clone() );
  249. controller2.add( line.clone() );
  250. raycaster = new THREE.Raycaster();
  251. //
  252. window.addEventListener( 'resize', onWindowResize );
  253. }
  254. function onWindowResize() {
  255. camera.aspect = window.innerWidth / window.innerHeight;
  256. camera.updateProjectionMatrix();
  257. renderer.setSize( window.innerWidth, window.innerHeight );
  258. }
  259. function onSelectStart( event ) {
  260. const controller = event.target;
  261. const intersections = getIntersections( controller );
  262. if ( intersections.length > 0 ) {
  263. const intersection = intersections[ 0 ];
  264. const object = intersection.object;
  265. object.material.uniforms.emissive.value = 1;
  266. controller.attach( object );
  267. controller.userData.selected = object;
  268. }
  269. controller.userData.targetRayMode = event.data.targetRayMode;
  270. }
  271. function onSelectEnd( event ) {
  272. const controller = event.target;
  273. if ( controller.userData.selected !== undefined ) {
  274. const object = controller.userData.selected;
  275. object.material.uniforms.emissive.value = 0;
  276. group.attach( object );
  277. controller.userData.selected = undefined;
  278. }
  279. }
  280. function getIntersections( controller ) {
  281. controller.updateMatrixWorld();
  282. tempMatrix.identity().extractRotation( controller.matrixWorld );
  283. raycaster.ray.origin.setFromMatrixPosition( controller.matrixWorld );
  284. raycaster.ray.direction.set( 0, 0, - 1 ).applyMatrix4( tempMatrix );
  285. return raycaster.intersectObjects( group.children, false );
  286. }
  287. function intersectObjects( controller ) {
  288. // Do not highlight in mobile-ar
  289. if ( controller.userData.targetRayMode === 'screen' ) return;
  290. // Do not highlight when already selected
  291. if ( controller.userData.selected !== undefined ) return;
  292. const line = controller.getObjectByName( 'line' );
  293. const intersections = getIntersections( controller );
  294. if ( intersections.length > 0 ) {
  295. const intersection = intersections[ 0 ];
  296. const object = intersection.object;
  297. object.material.uniforms.emissive.value = 1;
  298. intersected.push( object );
  299. line.scale.z = intersection.distance;
  300. } else {
  301. line.scale.z = 5;
  302. }
  303. }
  304. function cleanIntersected() {
  305. while ( intersected.length ) {
  306. const object = intersected.pop();
  307. object.material.uniforms.emissive.value = 0;
  308. }
  309. }
  310. //
  311. function animate() {
  312. renderer.setAnimationLoop( render );
  313. }
  314. function render() {
  315. if ( renderer.xr.hasDepthSensing() && ! isDepthSupplied ) {
  316. group.children.forEach( child => {
  317. child.material.uniforms.depthColor.value = renderer.xr.getDepthTexture();
  318. child.material.uniforms.depthWidth.value = 1680;
  319. child.material.uniforms.depthHeight.value = 1760;
  320. isDepthSupplied = true;
  321. } );
  322. } else if ( ! renderer.xr.hasDepthSensing() && isDepthSupplied ) {
  323. group.children.forEach( child => {
  324. child.material.uniforms.depthWidth.value = 0;
  325. child.material.uniforms.depthHeight.value = 0;
  326. isDepthSupplied = false;
  327. } );
  328. }
  329. cleanIntersected();
  330. intersectObjects( controller1 );
  331. intersectObjects( controller2 );
  332. renderer.render( scene, camera );
  333. }
  334. </script>
  335. </body>
  336. </html>