webgl_clipping_advanced.html 10 KB

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