OutlineEffect.js 13 KB

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