OutlineEffect.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  1. ( function () {
  2. /**
  3. * Reference: https://en.wikipedia.org/wiki/Cel_shading
  4. *
  5. * API
  6. *
  7. * 1. Traditional
  8. *
  9. * const effect = new OutlineEffect( renderer );
  10. *
  11. * function render() {
  12. *
  13. * effect.render( scene, camera );
  14. *
  15. * }
  16. *
  17. * 2. VR compatible
  18. *
  19. * const effect = new OutlineEffect( renderer );
  20. * let renderingOutline = false;
  21. *
  22. * scene.onAfterRender = function () {
  23. *
  24. * if ( renderingOutline ) return;
  25. *
  26. * renderingOutline = true;
  27. *
  28. * effect.renderOutline( scene, camera );
  29. *
  30. * renderingOutline = false;
  31. *
  32. * };
  33. *
  34. * function render() {
  35. *
  36. * renderer.render( scene, camera );
  37. *
  38. * }
  39. *
  40. * // How to set default outline parameters
  41. * new OutlineEffect( renderer, {
  42. * defaultThickness: 0.01,
  43. * defaultColor: [ 0, 0, 0 ],
  44. * defaultAlpha: 0.8,
  45. * defaultKeepAlive: true // keeps outline material in cache even if material is removed from scene
  46. * } );
  47. *
  48. * // How to set outline parameters for each material
  49. * material.userData.outlineParameters = {
  50. * thickness: 0.01,
  51. * color: [ 0, 0, 0 ]
  52. * alpha: 0.8,
  53. * visible: true,
  54. * keepAlive: true
  55. * };
  56. */
  57. class OutlineEffect {
  58. constructor( renderer, parameters = {} ) {
  59. this.enabled = true;
  60. const defaultThickness = parameters.defaultThickness !== undefined ? parameters.defaultThickness : 0.003;
  61. const defaultColor = new THREE.Color().fromArray( parameters.defaultColor !== undefined ? parameters.defaultColor : [ 0, 0, 0 ] );
  62. const defaultAlpha = parameters.defaultAlpha !== undefined ? parameters.defaultAlpha : 1.0;
  63. const defaultKeepAlive = parameters.defaultKeepAlive !== undefined ? parameters.defaultKeepAlive : false; // object.material.uuid -> outlineMaterial or
  64. // object.material[ n ].uuid -> outlineMaterial
  65. // save at the outline material creation and release
  66. // if it's unused removeThresholdCount frames
  67. // unless keepAlive is true.
  68. const cache = {};
  69. const removeThresholdCount = 60; // outlineMaterial.uuid -> object.material or
  70. // outlineMaterial.uuid -> object.material[ n ]
  71. // save before render and release after render.
  72. const originalMaterials = {}; // object.uuid -> originalOnBeforeRender
  73. // save before render and release after render.
  74. const originalOnBeforeRenders = {}; //this.cache = cache; // for debug
  75. const uniformsOutline = {
  76. outlineThickness: {
  77. value: defaultThickness
  78. },
  79. outlineColor: {
  80. value: defaultColor
  81. },
  82. outlineAlpha: {
  83. value: defaultAlpha
  84. }
  85. };
  86. const vertexShader = [ '#include <common>', '#include <uv_pars_vertex>', '#include <displacementmap_pars_vertex>', '#include <fog_pars_vertex>', '#include <morphtarget_pars_vertex>', '#include <skinning_pars_vertex>', '#include <logdepthbuf_pars_vertex>', '#include <clipping_planes_pars_vertex>', 'uniform float outlineThickness;', 'vec4 calculateOutline( vec4 pos, vec3 normal, vec4 skinned ) {', ' float thickness = outlineThickness;', ' const float ratio = 1.0;', // TODO: support outline thickness ratio for each vertex
  87. ' vec4 pos2 = projectionMatrix * modelViewMatrix * vec4( skinned.xyz + normal, 1.0 );', // NOTE: subtract pos2 from pos because THREE.BackSide objectNormal is negative
  88. ' vec4 norm = normalize( pos - pos2 );', ' return pos + norm * thickness * pos.w * ratio;', '}', 'void main() {', ' #include <uv_vertex>', ' #include <beginnormal_vertex>', ' #include <morphnormal_vertex>', ' #include <skinbase_vertex>', ' #include <skinnormal_vertex>', ' #include <begin_vertex>', ' #include <morphtarget_vertex>', ' #include <skinning_vertex>', ' #include <displacementmap_vertex>', ' #include <project_vertex>', ' vec3 outlineNormal = - objectNormal;', // the outline material is always rendered with THREE.BackSide
  89. ' gl_Position = calculateOutline( gl_Position, outlineNormal, vec4( transformed, 1.0 ) );', ' #include <logdepthbuf_vertex>', ' #include <clipping_planes_vertex>', ' #include <fog_vertex>', '}' ].join( '\n' );
  90. const fragmentShader = [ '#include <common>', '#include <fog_pars_fragment>', '#include <logdepthbuf_pars_fragment>', '#include <clipping_planes_pars_fragment>', 'uniform vec3 outlineColor;', 'uniform float outlineAlpha;', 'void main() {', ' #include <clipping_planes_fragment>', ' #include <logdepthbuf_fragment>', ' gl_FragColor = vec4( outlineColor, outlineAlpha );', ' #include <tonemapping_fragment>', ' #include <encodings_fragment>', ' #include <fog_fragment>', ' #include <premultiplied_alpha_fragment>', '}' ].join( '\n' );
  91. function createMaterial() {
  92. return new THREE.ShaderMaterial( {
  93. type: 'OutlineEffect',
  94. uniforms: THREE.UniformsUtils.merge( [ THREE.UniformsLib[ 'fog' ], THREE.UniformsLib[ 'displacementmap' ], uniformsOutline ] ),
  95. vertexShader: vertexShader,
  96. fragmentShader: fragmentShader,
  97. side: THREE.BackSide
  98. } );
  99. }
  100. function getOutlineMaterialFromCache( originalMaterial ) {
  101. let data = cache[ originalMaterial.uuid ];
  102. if ( data === undefined ) {
  103. data = {
  104. material: createMaterial(),
  105. used: true,
  106. keepAlive: defaultKeepAlive,
  107. count: 0
  108. };
  109. cache[ originalMaterial.uuid ] = data;
  110. }
  111. data.used = true;
  112. return data.material;
  113. }
  114. function getOutlineMaterial( originalMaterial ) {
  115. const outlineMaterial = getOutlineMaterialFromCache( originalMaterial );
  116. originalMaterials[ outlineMaterial.uuid ] = originalMaterial;
  117. updateOutlineMaterial( outlineMaterial, originalMaterial );
  118. return outlineMaterial;
  119. }
  120. function isCompatible( object ) {
  121. const geometry = object.geometry;
  122. let hasNormals = false;
  123. if ( object.geometry !== undefined ) {
  124. if ( geometry.isBufferGeometry ) {
  125. hasNormals = geometry.attributes.normal !== undefined;
  126. } else {
  127. hasNormals = true; // the renderer always produces a normal attribute for Geometry
  128. }
  129. }
  130. return object.isMesh === true && object.material !== undefined && hasNormals === true;
  131. }
  132. function setOutlineMaterial( object ) {
  133. if ( isCompatible( object ) === false ) return;
  134. if ( Array.isArray( object.material ) ) {
  135. for ( let i = 0, il = object.material.length; i < il; i ++ ) {
  136. object.material[ i ] = getOutlineMaterial( object.material[ i ] );
  137. }
  138. } else {
  139. object.material = getOutlineMaterial( object.material );
  140. }
  141. originalOnBeforeRenders[ object.uuid ] = object.onBeforeRender;
  142. object.onBeforeRender = onBeforeRender;
  143. }
  144. function restoreOriginalMaterial( object ) {
  145. if ( isCompatible( object ) === false ) return;
  146. if ( Array.isArray( object.material ) ) {
  147. for ( let i = 0, il = object.material.length; i < il; i ++ ) {
  148. object.material[ i ] = originalMaterials[ object.material[ i ].uuid ];
  149. }
  150. } else {
  151. object.material = originalMaterials[ object.material.uuid ];
  152. }
  153. object.onBeforeRender = originalOnBeforeRenders[ object.uuid ];
  154. }
  155. function onBeforeRender( renderer, scene, camera, geometry, material ) {
  156. const originalMaterial = originalMaterials[ material.uuid ]; // just in case
  157. if ( originalMaterial === undefined ) return;
  158. updateUniforms( material, originalMaterial );
  159. }
  160. function updateUniforms( material, originalMaterial ) {
  161. const outlineParameters = originalMaterial.userData.outlineParameters;
  162. material.uniforms.outlineAlpha.value = originalMaterial.opacity;
  163. if ( outlineParameters !== undefined ) {
  164. if ( outlineParameters.thickness !== undefined ) material.uniforms.outlineThickness.value = outlineParameters.thickness;
  165. if ( outlineParameters.color !== undefined ) material.uniforms.outlineColor.value.fromArray( outlineParameters.color );
  166. if ( outlineParameters.alpha !== undefined ) material.uniforms.outlineAlpha.value = outlineParameters.alpha;
  167. }
  168. if ( originalMaterial.displacementMap ) {
  169. material.uniforms.displacementMap.value = originalMaterial.displacementMap;
  170. material.uniforms.displacementScale.value = originalMaterial.displacementScale;
  171. material.uniforms.displacementBias.value = originalMaterial.displacementBias;
  172. }
  173. }
  174. function updateOutlineMaterial( material, originalMaterial ) {
  175. if ( material.name === 'invisible' ) return;
  176. const outlineParameters = originalMaterial.userData.outlineParameters;
  177. material.fog = originalMaterial.fog;
  178. material.toneMapped = originalMaterial.toneMapped;
  179. material.premultipliedAlpha = originalMaterial.premultipliedAlpha;
  180. material.displacementMap = originalMaterial.displacementMap;
  181. if ( outlineParameters !== undefined ) {
  182. if ( originalMaterial.visible === false ) {
  183. material.visible = false;
  184. } else {
  185. material.visible = outlineParameters.visible !== undefined ? outlineParameters.visible : true;
  186. }
  187. material.transparent = outlineParameters.alpha !== undefined && outlineParameters.alpha < 1.0 ? true : originalMaterial.transparent;
  188. if ( outlineParameters.keepAlive !== undefined ) cache[ originalMaterial.uuid ].keepAlive = outlineParameters.keepAlive;
  189. } else {
  190. material.transparent = originalMaterial.transparent;
  191. material.visible = originalMaterial.visible;
  192. }
  193. if ( originalMaterial.wireframe === true || originalMaterial.depthTest === false ) material.visible = false;
  194. if ( originalMaterial.clippingPlanes ) {
  195. material.clipping = true;
  196. material.clippingPlanes = originalMaterial.clippingPlanes;
  197. material.clipIntersection = originalMaterial.clipIntersection;
  198. material.clipShadows = originalMaterial.clipShadows;
  199. }
  200. material.version = originalMaterial.version; // update outline material if necessary
  201. }
  202. function cleanupCache() {
  203. let keys; // clear originialMaterials
  204. keys = Object.keys( originalMaterials );
  205. for ( let i = 0, il = keys.length; i < il; i ++ ) {
  206. originalMaterials[ keys[ i ] ] = undefined;
  207. } // clear originalOnBeforeRenders
  208. keys = Object.keys( originalOnBeforeRenders );
  209. for ( let i = 0, il = keys.length; i < il; i ++ ) {
  210. originalOnBeforeRenders[ keys[ i ] ] = undefined;
  211. } // remove unused outlineMaterial from cache
  212. keys = Object.keys( cache );
  213. for ( let i = 0, il = keys.length; i < il; i ++ ) {
  214. const key = keys[ i ];
  215. if ( cache[ key ].used === false ) {
  216. cache[ key ].count ++;
  217. if ( cache[ key ].keepAlive === false && cache[ key ].count > removeThresholdCount ) {
  218. delete cache[ key ];
  219. }
  220. } else {
  221. cache[ key ].used = false;
  222. cache[ key ].count = 0;
  223. }
  224. }
  225. }
  226. this.render = function ( scene, camera ) {
  227. let renderTarget;
  228. let forceClear = false;
  229. if ( arguments[ 2 ] !== undefined ) {
  230. console.warn( 'THREE.OutlineEffect.render(): the renderTarget argument has been removed. Use .setRenderTarget() instead.' );
  231. renderTarget = arguments[ 2 ];
  232. }
  233. if ( arguments[ 3 ] !== undefined ) {
  234. console.warn( 'THREE.OutlineEffect.render(): the forceClear argument has been removed. Use .clear() instead.' );
  235. forceClear = arguments[ 3 ];
  236. }
  237. if ( renderTarget !== undefined ) renderer.setRenderTarget( renderTarget );
  238. if ( forceClear ) renderer.clear();
  239. if ( this.enabled === false ) {
  240. renderer.render( scene, camera );
  241. return;
  242. }
  243. const currentAutoClear = renderer.autoClear;
  244. renderer.autoClear = this.autoClear;
  245. renderer.render( scene, camera );
  246. renderer.autoClear = currentAutoClear;
  247. this.renderOutline( scene, camera );
  248. };
  249. this.renderOutline = function ( scene, camera ) {
  250. const currentAutoClear = renderer.autoClear;
  251. const currentSceneAutoUpdate = scene.autoUpdate;
  252. const currentSceneBackground = scene.background;
  253. const currentShadowMapEnabled = renderer.shadowMap.enabled;
  254. scene.autoUpdate = false;
  255. scene.background = null;
  256. renderer.autoClear = false;
  257. renderer.shadowMap.enabled = false;
  258. scene.traverse( setOutlineMaterial );
  259. renderer.render( scene, camera );
  260. scene.traverse( restoreOriginalMaterial );
  261. cleanupCache();
  262. scene.autoUpdate = currentSceneAutoUpdate;
  263. scene.background = currentSceneBackground;
  264. renderer.autoClear = currentAutoClear;
  265. renderer.shadowMap.enabled = currentShadowMapEnabled;
  266. };
  267. /*
  268. * See #9918
  269. *
  270. * The following property copies and wrapper methods enable
  271. * OutlineEffect to be called from other *Effect, like
  272. *
  273. * effect = new StereoEffect( new OutlineEffect( renderer ) );
  274. *
  275. * function render () {
  276. *
  277. * effect.render( scene, camera );
  278. *
  279. * }
  280. */
  281. this.autoClear = renderer.autoClear;
  282. this.domElement = renderer.domElement;
  283. this.shadowMap = renderer.shadowMap;
  284. this.clear = function ( color, depth, stencil ) {
  285. renderer.clear( color, depth, stencil );
  286. };
  287. this.getPixelRatio = function () {
  288. return renderer.getPixelRatio();
  289. };
  290. this.setPixelRatio = function ( value ) {
  291. renderer.setPixelRatio( value );
  292. };
  293. this.getSize = function ( target ) {
  294. return renderer.getSize( target );
  295. };
  296. this.setSize = function ( width, height, updateStyle ) {
  297. renderer.setSize( width, height, updateStyle );
  298. };
  299. this.setViewport = function ( x, y, width, height ) {
  300. renderer.setViewport( x, y, width, height );
  301. };
  302. this.setScissor = function ( x, y, width, height ) {
  303. renderer.setScissor( x, y, width, height );
  304. };
  305. this.setScissorTest = function ( boolean ) {
  306. renderer.setScissorTest( boolean );
  307. };
  308. this.setRenderTarget = function ( renderTarget ) {
  309. renderer.setRenderTarget( renderTarget );
  310. };
  311. }
  312. }
  313. THREE.OutlineEffect = OutlineEffect;
  314. } )();