webgl_clipping_advanced.html 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>three.js webgl - clipping planes</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. var n = indices.length / 3,
  19. result = new Array( n );
  20. for ( var i = 0, j = 0; i < n; ++ i, j += 3 ) {
  21. var 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. var result = new Array( n );
  32. for ( var 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 ( var i = 0, n = planesIn.length; i !== n; ++ i )
  39. planesOut[ i ].copy( planesIn[ i ] ).applyMatrix4( matrix );
  40. }
  41. function cylindricalPlanes( n, innerRadius ) {
  42. var result = createPlanes( n );
  43. for ( var i = 0; i !== n; ++ i ) {
  44. var 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. var planeToMatrix = ( function () {
  53. // creates a matrix that aligns X/Y to a given plane
  54. // temporaries:
  55. var xAxis = new THREE.Vector3(),
  56. yAxis = new THREE.Vector3(),
  57. trans = new THREE.Vector3();
  58. return function planeToMatrix( plane ) {
  59. var 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. var 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, 3.5 ),
  90. Empty = Object.freeze( [] );
  91. var 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( 0x505050 ) );
  102. var spotLight = new THREE.SpotLight( 0xffffff );
  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. var dirLight = new THREE.DirectionalLight( 0x55505a, 1 );
  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. var geometry = new THREE.BoxBufferGeometry( 0.18, 0.18, 0.18 );
  135. for ( var z = - 2; z <= 2; ++ z )
  136. for ( var y = - 2; y <= 2; ++ y )
  137. for ( var x = - 2; x <= 2; ++ x ) {
  138. var 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. var planeGeometry =
  145. new THREE.PlaneBufferGeometry( 3, 3, 1, 1 ),
  146. color = new THREE.Color();
  147. volumeVisualization = new THREE.Group();
  148. volumeVisualization.visible = false;
  149. for ( var i = 0, n = Planes.length; i !== n; ++ i ) {
  150. var material = new THREE.MeshBasicMaterial( {
  151. color: color.setHSL( i / n, 0.5, 0.5 ).getHex(),
  152. side: THREE.DoubleSide,
  153. opacity: 0.2,
  154. transparent: true,
  155. // clip to the others to show the volume (wildly
  156. // intersecting transparent planes look bad)
  157. clippingPlanes: clipMaterial.clippingPlanes.
  158. filter( function ( _, j ) {
  159. return j !== i;
  160. } )
  161. // no need to enable shadow clipping - the plane
  162. // visualization does not cast shadows
  163. } );
  164. volumeVisualization.add(
  165. new THREE.Mesh( planeGeometry, material ) );
  166. }
  167. scene.add( volumeVisualization );
  168. var ground = new THREE.Mesh( planeGeometry,
  169. new THREE.MeshPhongMaterial( {
  170. color: 0xa0adaf, shininess: 150 } ) );
  171. ground.rotation.x = - Math.PI / 2;
  172. ground.scale.multiplyScalar( 3 );
  173. ground.receiveShadow = true;
  174. scene.add( ground );
  175. // Renderer
  176. var 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, false );
  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. var controls = new OrbitControls( camera, renderer.domElement );
  192. controls.target.set( 0, 1, 0 );
  193. controls.update();
  194. // GUI
  195. var gui = new GUI(),
  196. folder = gui.addFolder( "Local Clipping" ),
  197. props = {
  198. get 'Enabled'() {
  199. return renderer.localClippingEnabled;
  200. },
  201. set 'Enabled'( v ) {
  202. renderer.localClippingEnabled = v;
  203. if ( ! v ) volumeVisualization.visible = false;
  204. },
  205. get 'Shadows'() {
  206. return clipMaterial.clipShadows;
  207. },
  208. set 'Shadows'( v ) {
  209. clipMaterial.clipShadows = v;
  210. },
  211. get 'Visualize'() {
  212. return volumeVisualization.visible;
  213. },
  214. set 'Visualize'( v ) {
  215. if ( renderer.localClippingEnabled )
  216. volumeVisualization.visible = v;
  217. }
  218. };
  219. folder.add( props, 'Enabled' );
  220. folder.add( props, 'Shadows' );
  221. folder.add( props, 'Visualize' ).listen();
  222. gui.addFolder( "Global Clipping" ).
  223. add( {
  224. get 'Enabled'() {
  225. return renderer.clippingPlanes !== Empty;
  226. },
  227. set 'Enabled'( v ) {
  228. renderer.clippingPlanes = v ?
  229. globalClippingPlanes : Empty;
  230. }
  231. }, "Enabled" );
  232. // Start
  233. startTime = Date.now();
  234. }
  235. function onWindowResize() {
  236. camera.aspect = window.innerWidth / window.innerHeight;
  237. camera.updateProjectionMatrix();
  238. renderer.setSize( window.innerWidth, window.innerHeight );
  239. }
  240. function setObjectWorldMatrix( object, matrix ) {
  241. // set the orientation of an object based on a world matrix
  242. var parent = object.parent;
  243. scene.updateMatrixWorld();
  244. object.matrix.getInverse( parent.matrixWorld );
  245. object.applyMatrix4( matrix );
  246. }
  247. var transform = new THREE.Matrix4(),
  248. tmpMatrix = new THREE.Matrix4();
  249. function animate() {
  250. var currentTime = Date.now(),
  251. time = ( currentTime - startTime ) / 1000;
  252. requestAnimationFrame( animate );
  253. object.position.y = 1;
  254. object.rotation.x = time * 0.5;
  255. object.rotation.y = time * 0.2;
  256. object.updateMatrix();
  257. transform.copy( object.matrix );
  258. var bouncy = Math.cos( time * .5 ) * 0.5 + 0.7;
  259. transform.multiply(
  260. tmpMatrix.makeScale( bouncy, bouncy, bouncy ) );
  261. assignTransformedPlanes(
  262. clipMaterial.clippingPlanes, Planes, transform );
  263. var planeMeshes = volumeVisualization.children;
  264. for ( var i = 0, n = planeMeshes.length; i !== n; ++ i ) {
  265. tmpMatrix.multiplyMatrices( transform, PlaneMatrices[ i ] );
  266. setObjectWorldMatrix( planeMeshes[ i ], tmpMatrix );
  267. }
  268. transform.makeRotationY( time * 0.1 );
  269. assignTransformedPlanes(
  270. globalClippingPlanes, GlobalClippingPlanes, transform );
  271. stats.begin();
  272. renderer.render( scene, camera );
  273. stats.end();
  274. }
  275. init();
  276. animate();
  277. </script>
  278. </body>
  279. </html>