webgl_postprocessing_pixel.html 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>three.js webgl - post processing - pixelation</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 - post processing - pixelation">
  8. <meta property="og:type" content="website">
  9. <meta property="og:url" content="https://threejs.org/examples/webgl_postprocessing_pixel.html">
  10. <meta property="og:image" content="https://threejs.org/examples/screenshots/webgl_postprocessing_pixel.jpg">
  11. <link type="text/css" rel="stylesheet" href="main.css">
  12. </head>
  13. <body>
  14. <div id="info">
  15. <a href="https://threejs.org" target="_blank" rel="noopener">three.js</a> - Pixelation pass with optional single pixel outlines by
  16. <a href="https://github.com/KodyJKing" target="_blank" rel="noopener">Kody King</a><br /><br />
  17. </div>
  18. <div id="container"></div>
  19. <script type="importmap">
  20. {
  21. "imports": {
  22. "three": "../build/three.module.js",
  23. "three/addons/": "./jsm/"
  24. }
  25. }
  26. </script>
  27. <script type="module">
  28. import * as THREE from 'three';
  29. import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
  30. import { EffectComposer } from 'three/addons/postprocessing/EffectComposer.js';
  31. import { RenderPixelatedPass } from 'three/addons/postprocessing/RenderPixelatedPass.js';
  32. import { OutputPass } from 'three/addons/postprocessing/OutputPass.js';
  33. import { GUI } from 'three/addons/libs/lil-gui.module.min.js';
  34. let camera, scene, renderer, composer, controls, crystalMesh, timer;
  35. let gui, params;
  36. init();
  37. function init() {
  38. const aspectRatio = window.innerWidth / window.innerHeight;
  39. camera = new THREE.OrthographicCamera( - aspectRatio, aspectRatio, 1, - 1, 0.1, 10 );
  40. camera.position.y = 2 * Math.tan( Math.PI / 6 );
  41. camera.position.z = 2;
  42. scene = new THREE.Scene();
  43. scene.background = new THREE.Color( 0x151729 );
  44. timer = new THREE.Timer();
  45. timer.connect( document );
  46. renderer = new THREE.WebGLRenderer();
  47. renderer.shadowMap.enabled = true;
  48. //renderer.setPixelRatio( window.devicePixelRatio );
  49. renderer.setSize( window.innerWidth, window.innerHeight );
  50. renderer.setAnimationLoop( animate );
  51. document.body.appendChild( renderer.domElement );
  52. composer = new EffectComposer( renderer );
  53. const renderPixelatedPass = new RenderPixelatedPass( 6, scene, camera );
  54. composer.addPass( renderPixelatedPass );
  55. const outputPass = new OutputPass();
  56. composer.addPass( outputPass );
  57. window.addEventListener( 'resize', onWindowResize );
  58. controls = new OrbitControls( camera, renderer.domElement );
  59. controls.maxZoom = 2;
  60. // gui
  61. gui = new GUI();
  62. params = { pixelSize: 6, normalEdgeStrength: .3, depthEdgeStrength: .4, snapping: true, pixelAlignedPanning: true, pixelAlignedObjects: true, rotationSnap: 15, cameraRotationSnap: 9, cameraZoomSnap: 0.1 };
  63. gui.add( params, 'pixelSize' ).min( 1 ).max( 16 ).step( 1 )
  64. .onChange( () => {
  65. renderPixelatedPass.setPixelSize( params.pixelSize );
  66. } );
  67. gui.add( renderPixelatedPass, 'normalEdgeStrength' ).min( 0 ).max( 2 ).step( .05 );
  68. gui.add( renderPixelatedPass, 'depthEdgeStrength' ).min( 0 ).max( 1 ).step( .05 );
  69. const snappingControl = gui.add( params, 'snapping' ).name( 'Enable Pixel Snapping' );
  70. const snappingFolder = gui.addFolder( 'Snapping' ).close();
  71. snappingControl.onChange( enabled => snappingFolder.controllers.forEach( c => c.enable( enabled ) ) );
  72. snappingFolder.add( params, 'pixelAlignedPanning' );
  73. snappingFolder.add( params, 'pixelAlignedObjects' );
  74. snappingFolder.add( params, 'rotationSnap' ).min( 0 ).max( 90 ).step( 1 ).name( 'rotationSnap (deg, 0 = off)' );
  75. snappingFolder.add( params, 'cameraRotationSnap' ).min( 0 ).max( 90 ).step( 1 ).name( 'cameraRotationSnap (deg, 0 = off)' );
  76. snappingFolder.add( params, 'cameraZoomSnap' ).min( 0 ).max( 1 ).step( .05 ).name( 'cameraZoomSnap (0 = off)' );
  77. // textures
  78. const loader = new THREE.TextureLoader();
  79. const texChecker = pixelTexture( loader.load( 'textures/checker.png' ) );
  80. const texChecker2 = pixelTexture( loader.load( 'textures/checker.png' ) );
  81. texChecker.repeat.set( 3, 3 );
  82. texChecker2.repeat.set( 1.5, 1.5 );
  83. // meshes
  84. const boxMaterial = new THREE.MeshPhongMaterial( { map: texChecker2 } );
  85. function addBox( boxSideLength, x, z, rotation ) {
  86. const mesh = new THREE.Mesh( new THREE.BoxGeometry( boxSideLength, boxSideLength, boxSideLength ), boxMaterial );
  87. mesh.castShadow = true;
  88. mesh.receiveShadow = true;
  89. mesh.rotation.y = rotation;
  90. mesh.position.y = boxSideLength / 2;
  91. mesh.position.set( x, boxSideLength / 2 + .0001, z );
  92. scene.add( mesh );
  93. return mesh;
  94. }
  95. addBox( .4, 0, 0, Math.PI / 4 );
  96. addBox( .5, - .5, - .5, Math.PI / 4 );
  97. const planeSideLength = 2;
  98. const planeMesh = new THREE.Mesh(
  99. new THREE.PlaneGeometry( planeSideLength, planeSideLength ),
  100. new THREE.MeshPhongMaterial( { map: texChecker } )
  101. );
  102. planeMesh.receiveShadow = true;
  103. planeMesh.rotation.x = - Math.PI / 2;
  104. scene.add( planeMesh );
  105. const radius = .2;
  106. const geometry = new THREE.IcosahedronGeometry( radius );
  107. crystalMesh = new THREE.Mesh(
  108. geometry,
  109. new THREE.MeshPhongMaterial( {
  110. color: 0x68b7e9,
  111. emissive: 0x4f7e8b,
  112. shininess: 10,
  113. specular: 0xffffff
  114. } )
  115. );
  116. crystalMesh.receiveShadow = true;
  117. crystalMesh.castShadow = true;
  118. scene.add( crystalMesh );
  119. // lights
  120. scene.add( new THREE.AmbientLight( 0x757f8e, 3 ) );
  121. const directionalLight = new THREE.DirectionalLight( 0xfffecd, 1.5 );
  122. directionalLight.position.set( 100, 100, 100 );
  123. directionalLight.castShadow = true;
  124. directionalLight.shadow.mapSize.set( 2048, 2048 );
  125. scene.add( directionalLight );
  126. const spotLight = new THREE.SpotLight( 0xffc100, 10, 10, Math.PI / 16, .02, 2 );
  127. spotLight.position.set( 2, 2, 0 );
  128. const target = spotLight.target;
  129. scene.add( target );
  130. target.position.set( 0, 0, 0 );
  131. spotLight.castShadow = true;
  132. scene.add( spotLight );
  133. }
  134. function onWindowResize() {
  135. const aspectRatio = window.innerWidth / window.innerHeight;
  136. camera.left = - aspectRatio;
  137. camera.right = aspectRatio;
  138. camera.updateProjectionMatrix();
  139. renderer.setSize( window.innerWidth, window.innerHeight );
  140. composer.setSize( window.innerWidth, window.innerHeight );
  141. }
  142. function animate() {
  143. timer.update();
  144. const t = timer.getElapsed();
  145. // Quantize the pulsing glow to a few discrete brightness levels to match the pixelated aesthetic
  146. const brightnessLevels = 6;
  147. crystalMesh.material.emissiveIntensity =
  148. Math.round( ( Math.sin( t * 3 ) * .5 + .5 ) * ( brightnessLevels - 1 ) ) / ( brightnessLevels - 1 );
  149. crystalMesh.position.y = .7 + Math.sin( t * 2 ) * .05;
  150. crystalMesh.rotation.y = stopGoEased( t, 6, 8 ) * 2 * Math.PI;
  151. const rendererSize = renderer.getSize( new THREE.Vector2() );
  152. const aspectRatio = rendererSize.x / rendererSize.y;
  153. const pixelsPerScreenWidth = Math.floor( rendererSize.x / params[ 'pixelSize' ] );
  154. const pixelsPerScreenHeight = Math.floor( rendererSize.y / params[ 'pixelSize' ] );
  155. // The top-level 'snapping' checkbox gates every individual snapping effect at once
  156. const snapping = params[ 'snapping' ];
  157. // Remember the camera's true (unsnapped) transform so OrbitControls interaction is unaffected by snapping
  158. const cameraPosition = camera.position.clone();
  159. const cameraQuaternion = camera.quaternion.clone();
  160. const cameraZoom = camera.zoom;
  161. // Snap the camera's rotation and scale first, so the translation snap below derives its pixel grid
  162. // and screen-space basis from the already-snapped orientation and zoom
  163. if ( snapping && ( params[ 'cameraRotationSnap' ] > 0 || params[ 'cameraZoomSnap' ] > 0 ) ) {
  164. pixelAlignCamera( camera, controls.target, params[ 'cameraRotationSnap' ], params[ 'cameraZoomSnap' ] );
  165. }
  166. if ( snapping && params[ 'pixelAlignedPanning' ] ) {
  167. pixelAlignFrustum( camera, aspectRatio, pixelsPerScreenWidth, pixelsPerScreenHeight );
  168. } else if ( camera.left != - aspectRatio || camera.top != 1.0 ) {
  169. // Reset the Camera Frustum if it has been modified
  170. camera.left = - aspectRatio;
  171. camera.right = aspectRatio;
  172. camera.top = 1.0;
  173. camera.bottom = - 1.0;
  174. camera.updateProjectionMatrix();
  175. }
  176. // Remember the crystal's true (unsnapped) transform so its bulk movement is unaffected by snapping.
  177. // We snapshot the euler rotation (not the quaternion) because that's what drives the spin: restoring
  178. // the quaternion would let three.js re-derive a gimbal-equivalent euler and corrupt the y rotation.
  179. const crystalPosition = crystalMesh.position.clone();
  180. const crystalRotation = crystalMesh.rotation.clone();
  181. if ( snapping && params[ 'pixelAlignedObjects' ] ) {
  182. // Snap the moving objects to the screen-space pixel grid so they don't shimmer when pixelated
  183. const worldScreenWidth = ( ( camera.right - camera.left ) / camera.zoom );
  184. const worldScreenHeight = ( ( camera.top - camera.bottom ) / camera.zoom );
  185. pixelAlignObject( crystalMesh, camera, worldScreenWidth / pixelsPerScreenWidth,
  186. worldScreenHeight / pixelsPerScreenHeight );
  187. }
  188. if ( snapping && params[ 'rotationSnap' ] > 0 ) {
  189. // Snap the moving objects' rotation to the nearest camera-relative euler increment
  190. snapObjectRotation( crystalMesh, camera, params[ 'rotationSnap' ] );
  191. }
  192. composer.render();
  193. // Restore the true transforms after rendering so the next frame's motion builds on the real trajectory
  194. crystalMesh.position.copy( crystalPosition );
  195. crystalMesh.rotation.copy( crystalRotation );
  196. camera.position.copy( cameraPosition );
  197. camera.quaternion.copy( cameraQuaternion );
  198. camera.zoom = cameraZoom;
  199. camera.updateProjectionMatrix();
  200. }
  201. // Helper functions
  202. function pixelTexture( texture ) {
  203. texture.minFilter = THREE.NearestFilter;
  204. texture.magFilter = THREE.NearestFilter;
  205. texture.generateMipmaps = false;
  206. texture.wrapS = THREE.RepeatWrapping;
  207. texture.wrapT = THREE.RepeatWrapping;
  208. texture.colorSpace = THREE.SRGBColorSpace;
  209. return texture;
  210. }
  211. function easeInOutCubic( x ) {
  212. return x ** 2 * 3 - x ** 3 * 2;
  213. }
  214. function linearStep( x, edge0, edge1 ) {
  215. const w = edge1 - edge0;
  216. const m = 1 / w;
  217. const y0 = - m * edge0;
  218. return THREE.MathUtils.clamp( y0 + m * x, 0, 1 );
  219. }
  220. function stopGoEased( x, downtime, period ) {
  221. const cycle = ( x / period ) | 0;
  222. const tween = x - cycle * period;
  223. const linStep = easeInOutCubic( linearStep( tween, downtime, period ) );
  224. return cycle + linStep;
  225. }
  226. function pixelAlignCamera( camera, target, rotationIncrementDegrees, zoomIncrement ) {
  227. // Snap the camera's orbit to the nearest increment of azimuth/polar angle around the target. Working
  228. // in spherical coordinates (rather than snapping the euler angles) keeps the orbit translation locked
  229. // onto the target and guarantees a roll-free orientation, since we re-aim with lookAt and world up.
  230. if ( rotationIncrementDegrees > 0 ) {
  231. const increment = THREE.MathUtils.degToRad( rotationIncrementDegrees );
  232. const offset = new THREE.Vector3().subVectors( camera.position, target );
  233. const spherical = new THREE.Spherical().setFromVector3( offset );
  234. spherical.theta = Math.round( spherical.theta / increment ) * increment;
  235. spherical.phi = Math.round( spherical.phi / increment ) * increment;
  236. spherical.makeSafe();
  237. offset.setFromSpherical( spherical );
  238. camera.position.copy( target ).add( offset );
  239. camera.up.set( 0.0, 1.0, 0.0 );
  240. camera.lookAt( target );
  241. }
  242. // Snap the camera's zoom to the nearest increment so the pixel grid stays a stable size while scaling
  243. if ( zoomIncrement > 0 ) {
  244. camera.zoom = Math.max( zoomIncrement, Math.round( camera.zoom / zoomIncrement ) * zoomIncrement );
  245. camera.updateProjectionMatrix();
  246. }
  247. }
  248. function pixelAlignFrustum( camera, aspectRatio, pixelsPerScreenWidth, pixelsPerScreenHeight ) {
  249. // 0. Get Pixel Grid Units
  250. const worldScreenWidth = ( ( camera.right - camera.left ) / camera.zoom );
  251. const worldScreenHeight = ( ( camera.top - camera.bottom ) / camera.zoom );
  252. const pixelWidth = worldScreenWidth / pixelsPerScreenWidth;
  253. const pixelHeight = worldScreenHeight / pixelsPerScreenHeight;
  254. // 1. Project the current camera position along its local rotation bases
  255. const camPos = new THREE.Vector3(); camera.getWorldPosition( camPos );
  256. const camRot = new THREE.Quaternion(); camera.getWorldQuaternion( camRot );
  257. const camRight = new THREE.Vector3( 1.0, 0.0, 0.0 ).applyQuaternion( camRot );
  258. const camUp = new THREE.Vector3( 0.0, 1.0, 0.0 ).applyQuaternion( camRot );
  259. const camPosRight = camPos.dot( camRight );
  260. const camPosUp = camPos.dot( camUp );
  261. // 2. Find how far along its position is along these bases in pixel units
  262. const camPosRightPx = camPosRight / pixelWidth;
  263. const camPosUpPx = camPosUp / pixelHeight;
  264. // 3. Find the fractional pixel units and convert to world units
  265. const fractX = camPosRightPx - Math.round( camPosRightPx );
  266. const fractY = camPosUpPx - Math.round( camPosUpPx );
  267. // 4. Add fractional world units to the left/right top/bottom to align with the pixel grid
  268. camera.left = - aspectRatio - ( fractX * pixelWidth );
  269. camera.right = aspectRatio - ( fractX * pixelWidth );
  270. camera.top = 1.0 - ( fractY * pixelHeight );
  271. camera.bottom = - 1.0 - ( fractY * pixelHeight );
  272. camera.updateProjectionMatrix();
  273. }
  274. function pixelAlignObject( object, camera, pixelWidth, pixelHeight ) {
  275. // 1. Build the camera's orthonormal screen-space basis
  276. const camRot = new THREE.Quaternion(); camera.getWorldQuaternion( camRot );
  277. const camRight = new THREE.Vector3( 1.0, 0.0, 0.0 ).applyQuaternion( camRot );
  278. const camUp = new THREE.Vector3( 0.0, 1.0, 0.0 ).applyQuaternion( camRot );
  279. const camForward = new THREE.Vector3( 0.0, 0.0, - 1.0 ).applyQuaternion( camRot );
  280. // 2. Decompose the object's world position onto that basis
  281. const pos = object.position;
  282. const posRight = pos.dot( camRight );
  283. const posUp = pos.dot( camUp );
  284. const posForward = pos.dot( camForward );
  285. // 3. Snap the screen-space (right/up) components to the pixel grid, leaving depth untouched
  286. const snappedRight = Math.round( posRight / pixelWidth ) * pixelWidth;
  287. const snappedUp = Math.round( posUp / pixelHeight ) * pixelHeight;
  288. // 4. Recompose the world position from the snapped basis components
  289. pos.set( 0, 0, 0 );
  290. pos.addScaledVector( camRight, snappedRight );
  291. pos.addScaledVector( camUp, snappedUp );
  292. pos.addScaledVector( camForward, posForward );
  293. }
  294. function snapObjectRotation( object, camera, incrementDegrees ) {
  295. const increment = THREE.MathUtils.degToRad( incrementDegrees );
  296. // 1. Express the object's rotation relative to the camera
  297. const camRot = new THREE.Quaternion(); camera.getWorldQuaternion( camRot );
  298. const relative = camRot.clone().invert().multiply( object.quaternion );
  299. // 2. Snap each euler axis (in camera space) to the nearest increment
  300. const euler = new THREE.Euler().setFromQuaternion( relative );
  301. euler.x = Math.round( euler.x / increment ) * increment;
  302. euler.y = Math.round( euler.y / increment ) * increment;
  303. euler.z = Math.round( euler.z / increment ) * increment;
  304. // 3. Convert back to a world-space rotation
  305. relative.setFromEuler( euler );
  306. object.quaternion.copy( camRot.multiply( relative ) );
  307. }
  308. </script>
  309. </body>
  310. </html>
粤ICP备19079148号