webgl_clipping_advanced.html 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>three.js webgl - clipping planes - advanced</title>
  5. <meta charset="utf-8">
  6. <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
  7. <link type="text/css" rel="stylesheet" href="main.css">
  8. </head>
  9. <body>
  10. <script type="module">
  11. import * as THREE from '../build/three.module.js';
  12. import Stats from './jsm/libs/stats.module.js';
  13. import { GUI } from './jsm/libs/dat.gui.module.js';
  14. import { OrbitControls } from './jsm/controls/OrbitControls.js';
  15. function planesFromMesh( vertices, indices ) {
  16. // creates a clipping volume from a convex triangular mesh
  17. // specified by the arrays 'vertices' and 'indices'
  18. const n = indices.length / 3,
  19. result = new Array( n );
  20. for ( let i = 0, j = 0; i < n; ++ i, j += 3 ) {
  21. const a = vertices[ indices[ j ] ],
  22. b = vertices[ indices[ j + 1 ] ],
  23. c = vertices[ indices[ j + 2 ] ];
  24. result[ i ] = new THREE.Plane().
  25. setFromCoplanarPoints( a, b, c );
  26. }
  27. return result;
  28. }
  29. function createPlanes( n ) {
  30. // creates an array of n uninitialized plane objects
  31. const result = new Array( n );
  32. for ( let i = 0; i !== n; ++ i )
  33. result[ i ] = new THREE.Plane();
  34. return result;
  35. }
  36. function assignTransformedPlanes( planesOut, planesIn, matrix ) {
  37. // sets an array of existing planes to transformed 'planesIn'
  38. for ( let i = 0, n = planesIn.length; i !== n; ++ i )
  39. planesOut[ i ].copy( planesIn[ i ] ).applyMatrix4( matrix );
  40. }
  41. function cylindricalPlanes( n, innerRadius ) {
  42. const result = createPlanes( n );
  43. for ( let i = 0; i !== n; ++ i ) {
  44. const plane = result[ i ],
  45. angle = i * Math.PI * 2 / n;
  46. plane.normal.set(
  47. Math.cos( angle ), 0, Math.sin( angle ) );
  48. plane.constant = innerRadius;
  49. }
  50. return result;
  51. }
  52. const planeToMatrix = ( function () {
  53. // creates a matrix that aligns X/Y to a given plane
  54. // temporaries:
  55. const xAxis = new THREE.Vector3(),
  56. yAxis = new THREE.Vector3(),
  57. trans = new THREE.Vector3();
  58. return function planeToMatrix( plane ) {
  59. const zAxis = plane.normal,
  60. matrix = new THREE.Matrix4();
  61. // Hughes & Moeller '99
  62. // "Building an Orthonormal Basis from a Unit Vector."
  63. if ( Math.abs( zAxis.x ) > Math.abs( zAxis.z ) ) {
  64. yAxis.set( - zAxis.y, zAxis.x, 0 );
  65. } else {
  66. yAxis.set( 0, - zAxis.z, zAxis.y );
  67. }
  68. xAxis.crossVectors( yAxis.normalize(), zAxis );
  69. plane.coplanarPoint( trans );
  70. return matrix.set(
  71. xAxis.x, yAxis.x, zAxis.x, trans.x,
  72. xAxis.y, yAxis.y, zAxis.y, trans.y,
  73. xAxis.z, yAxis.z, zAxis.z, trans.z,
  74. 0, 0, 0, 1 );
  75. };
  76. } )();
  77. // A regular tetrahedron for the clipping volume:
  78. const Vertices = [
  79. new THREE.Vector3( + 1, 0, + Math.SQRT1_2 ),
  80. new THREE.Vector3( - 1, 0, + Math.SQRT1_2 ),
  81. new THREE.Vector3( 0, + 1, - Math.SQRT1_2 ),
  82. new THREE.Vector3( 0, - 1, - Math.SQRT1_2 )
  83. ],
  84. Indices = [
  85. 0, 1, 2, 0, 2, 3, 0, 3, 1, 1, 3, 2
  86. ],
  87. Planes = planesFromMesh( Vertices, Indices ),
  88. PlaneMatrices = Planes.map( planeToMatrix ),
  89. GlobalClippingPlanes = cylindricalPlanes( 5, 2.5 ),
  90. Empty = Object.freeze( [] );
  91. let camera, scene, renderer, startTime, stats,
  92. object, clipMaterial,
  93. volumeVisualization,
  94. globalClippingPlanes;
  95. function init() {
  96. camera = new THREE.PerspectiveCamera(
  97. 36, window.innerWidth / window.innerHeight, 0.25, 16 );
  98. camera.position.set( 0, 1.5, 3 );
  99. scene = new THREE.Scene();
  100. // Lights
  101. scene.add( new THREE.AmbientLight( 0xffffff, 0.3 ) );
  102. const spotLight = new THREE.SpotLight( 0xffffff, 0.5 );
  103. spotLight.angle = Math.PI / 5;
  104. spotLight.penumbra = 0.2;
  105. spotLight.position.set( 2, 3, 3 );
  106. spotLight.castShadow = true;
  107. spotLight.shadow.camera.near = 3;
  108. spotLight.shadow.camera.far = 10;
  109. spotLight.shadow.mapSize.width = 1024;
  110. spotLight.shadow.mapSize.height = 1024;
  111. scene.add( spotLight );
  112. const dirLight = new THREE.DirectionalLight( 0xffffff, 0.5 );
  113. dirLight.position.set( 0, 2, 0 );
  114. dirLight.castShadow = true;
  115. dirLight.shadow.camera.near = 1;
  116. dirLight.shadow.camera.far = 10;
  117. dirLight.shadow.camera.right = 1;
  118. dirLight.shadow.camera.left = - 1;
  119. dirLight.shadow.camera.top = 1;
  120. dirLight.shadow.camera.bottom = - 1;
  121. dirLight.shadow.mapSize.width = 1024;
  122. dirLight.shadow.mapSize.height = 1024;
  123. scene.add( dirLight );
  124. // Geometry
  125. clipMaterial = new THREE.MeshPhongMaterial( {
  126. color: 0xee0a10,
  127. shininess: 100,
  128. side: THREE.DoubleSide,
  129. // Clipping setup:
  130. clippingPlanes: createPlanes( Planes.length ),
  131. clipShadows: true
  132. } );
  133. object = new THREE.Group();
  134. const geometry = new THREE.BoxGeometry( 0.18, 0.18, 0.18 );
  135. for ( let z = - 2; z <= 2; ++ z )
  136. for ( let y = - 2; y <= 2; ++ y )
  137. for ( let x = - 2; x <= 2; ++ x ) {
  138. const mesh = new THREE.Mesh( geometry, clipMaterial );
  139. mesh.position.set( x / 5, y / 5, z / 5 );
  140. mesh.castShadow = true;
  141. object.add( mesh );
  142. }
  143. scene.add( object );
  144. const planeGeometry = new THREE.PlaneGeometry( 3, 3, 1, 1 ),
  145. color = new THREE.Color();
  146. volumeVisualization = new THREE.Group();
  147. volumeVisualization.visible = false;
  148. for ( let i = 0, n = Planes.length; i !== n; ++ i ) {
  149. const material = new THREE.MeshBasicMaterial( {
  150. color: color.setHSL( i / n, 0.5, 0.5 ).getHex(),
  151. side: THREE.DoubleSide,
  152. opacity: 0.2,
  153. transparent: true,
  154. // clip to the others to show the volume (wildly
  155. // intersecting transparent planes look bad)
  156. clippingPlanes: clipMaterial.clippingPlanes.
  157. filter( function ( _, j ) {
  158. return j !== i;
  159. } )
  160. // no need to enable shadow clipping - the plane
  161. // visualization does not cast shadows
  162. } );
  163. const mesh = new THREE.Mesh( planeGeometry, material );
  164. mesh.matrixAutoUpdate = false;
  165. volumeVisualization.add( mesh );
  166. }
  167. scene.add( volumeVisualization );
  168. const ground = new THREE.Mesh( planeGeometry,
  169. new THREE.MeshPhongMaterial( {
  170. color: 0xa0adaf, shininess: 10 } ) );
  171. ground.rotation.x = - Math.PI / 2;
  172. ground.scale.multiplyScalar( 3 );
  173. ground.receiveShadow = true;
  174. scene.add( ground );
  175. // Renderer
  176. const container = document.body;
  177. renderer = new THREE.WebGLRenderer();
  178. renderer.shadowMap.enabled = true;
  179. renderer.setPixelRatio( window.devicePixelRatio );
  180. renderer.setSize( window.innerWidth, window.innerHeight );
  181. window.addEventListener( 'resize', onWindowResize );
  182. container.appendChild( renderer.domElement );
  183. // Clipping setup:
  184. globalClippingPlanes = createPlanes( GlobalClippingPlanes.length );
  185. renderer.clippingPlanes = Empty;
  186. renderer.localClippingEnabled = true;
  187. // Stats
  188. stats = new Stats();
  189. container.appendChild( stats.dom );
  190. // Controls
  191. const controls = new OrbitControls( camera, renderer.domElement );
  192. controls.minDistance = 1;
  193. controls.maxDistance = 8;
  194. controls.target.set( 0, 1, 0 );
  195. controls.update();
  196. // GUI
  197. const gui = new GUI(),
  198. folder = gui.addFolder( "Local Clipping" ),
  199. props = {
  200. get 'Enabled'() {
  201. return renderer.localClippingEnabled;
  202. },
  203. set 'Enabled'( v ) {
  204. renderer.localClippingEnabled = v;
  205. if ( ! v ) volumeVisualization.visible = false;
  206. },
  207. get 'Shadows'() {
  208. return clipMaterial.clipShadows;
  209. },
  210. set 'Shadows'( v ) {
  211. clipMaterial.clipShadows = v;
  212. },
  213. get 'Visualize'() {
  214. return volumeVisualization.visible;
  215. },
  216. set 'Visualize'( v ) {
  217. if ( renderer.localClippingEnabled )
  218. volumeVisualization.visible = v;
  219. }
  220. };
  221. folder.add( props, 'Enabled' );
  222. folder.add( props, 'Shadows' );
  223. folder.add( props, 'Visualize' ).listen();
  224. gui.addFolder( "Global Clipping" ).
  225. add( {
  226. get 'Enabled'() {
  227. return renderer.clippingPlanes !== Empty;
  228. },
  229. set 'Enabled'( v ) {
  230. renderer.clippingPlanes = v ?
  231. globalClippingPlanes : Empty;
  232. }
  233. }, "Enabled" );
  234. // Start
  235. startTime = Date.now();
  236. }
  237. function onWindowResize() {
  238. camera.aspect = window.innerWidth / window.innerHeight;
  239. camera.updateProjectionMatrix();
  240. renderer.setSize( window.innerWidth, window.innerHeight );
  241. }
  242. function setObjectWorldMatrix( object, matrix ) {
  243. // set the orientation of an object based on a world matrix
  244. const parent = object.parent;
  245. scene.updateMatrixWorld();
  246. object.matrix.copy( parent.matrixWorld ).invert();
  247. object.applyMatrix4( matrix );
  248. }
  249. const transform = new THREE.Matrix4(),
  250. tmpMatrix = new THREE.Matrix4();
  251. function animate() {
  252. const currentTime = Date.now(),
  253. time = ( currentTime - startTime ) / 1000;
  254. requestAnimationFrame( animate );
  255. object.position.y = 1;
  256. object.rotation.x = time * 0.5;
  257. object.rotation.y = time * 0.2;
  258. object.updateMatrix();
  259. transform.copy( object.matrix );
  260. const bouncy = Math.cos( time * .5 ) * 0.5 + 0.7;
  261. transform.multiply(
  262. tmpMatrix.makeScale( bouncy, bouncy, bouncy ) );
  263. assignTransformedPlanes(
  264. clipMaterial.clippingPlanes, Planes, transform );
  265. const planeMeshes = volumeVisualization.children;
  266. for ( let i = 0, n = planeMeshes.length; i !== n; ++ i ) {
  267. tmpMatrix.multiplyMatrices( transform, PlaneMatrices[ i ] );
  268. setObjectWorldMatrix( planeMeshes[ i ], tmpMatrix );
  269. }
  270. transform.makeRotationY( time * 0.1 );
  271. assignTransformedPlanes( globalClippingPlanes, GlobalClippingPlanes, transform );
  272. stats.begin();
  273. renderer.render( scene, camera );
  274. stats.end();
  275. }
  276. init();
  277. animate();
  278. </script>
  279. </body>
  280. </html>