SVGRenderer.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556
  1. import {
  2. Box2,
  3. Camera,
  4. Color,
  5. Matrix3,
  6. Matrix4,
  7. Object3D,
  8. SRGBColorSpace,
  9. Vector3
  10. } from 'three';
  11. import { Projector } from '../renderers/Projector.js';
  12. import { RenderableFace } from '../renderers/Projector.js';
  13. import { RenderableLine } from '../renderers/Projector.js';
  14. import { RenderableSprite } from '../renderers/Projector.js';
  15. class SVGObject extends Object3D {
  16. constructor( node ) {
  17. super();
  18. this.isSVGObject = true;
  19. this.node = node;
  20. }
  21. }
  22. class SVGRenderer {
  23. constructor() {
  24. let _renderData, _elements, _lights,
  25. _svgWidth, _svgHeight, _svgWidthHalf, _svgHeightHalf,
  26. _v1, _v2, _v3,
  27. _svgNode,
  28. _pathCount = 0,
  29. _precision = null,
  30. _quality = 1,
  31. _currentPath, _currentStyle;
  32. const _this = this,
  33. _clipBox = new Box2(),
  34. _elemBox = new Box2(),
  35. _color = new Color(),
  36. _diffuseColor = new Color(),
  37. _ambientLight = new Color(),
  38. _directionalLights = new Color(),
  39. _pointLights = new Color(),
  40. _clearColor = new Color(),
  41. _vector3 = new Vector3(), // Needed for PointLight
  42. _centroid = new Vector3(),
  43. _normal = new Vector3(),
  44. _normalViewMatrix = new Matrix3(),
  45. _viewMatrix = new Matrix4(),
  46. _viewProjectionMatrix = new Matrix4(),
  47. _svgPathPool = [],
  48. _projector = new Projector(),
  49. _svg = document.createElementNS( 'http://www.w3.org/2000/svg', 'svg' );
  50. this.domElement = _svg;
  51. this.autoClear = true;
  52. this.sortObjects = true;
  53. this.sortElements = true;
  54. this.overdraw = 0.5;
  55. this.outputColorSpace = SRGBColorSpace;
  56. this.info = {
  57. render: {
  58. vertices: 0,
  59. faces: 0
  60. }
  61. };
  62. this.setQuality = function ( quality ) {
  63. switch ( quality ) {
  64. case 'high': _quality = 1; break;
  65. case 'low': _quality = 0; break;
  66. }
  67. };
  68. this.setClearColor = function ( color ) {
  69. _clearColor.set( color );
  70. };
  71. this.setPixelRatio = function () {};
  72. this.setSize = function ( width, height ) {
  73. _svgWidth = width; _svgHeight = height;
  74. _svgWidthHalf = _svgWidth / 2; _svgHeightHalf = _svgHeight / 2;
  75. _svg.setAttribute( 'viewBox', ( - _svgWidthHalf ) + ' ' + ( - _svgHeightHalf ) + ' ' + _svgWidth + ' ' + _svgHeight );
  76. _svg.setAttribute( 'width', _svgWidth );
  77. _svg.setAttribute( 'height', _svgHeight );
  78. _clipBox.min.set( - _svgWidthHalf, - _svgHeightHalf );
  79. _clipBox.max.set( _svgWidthHalf, _svgHeightHalf );
  80. };
  81. this.getSize = function () {
  82. return {
  83. width: _svgWidth,
  84. height: _svgHeight
  85. };
  86. };
  87. this.setPrecision = function ( precision ) {
  88. _precision = precision;
  89. };
  90. function removeChildNodes() {
  91. _pathCount = 0;
  92. while ( _svg.childNodes.length > 0 ) {
  93. _svg.removeChild( _svg.childNodes[ 0 ] );
  94. }
  95. }
  96. function convert( c ) {
  97. return _precision !== null ? c.toFixed( _precision ) : c;
  98. }
  99. this.clear = function () {
  100. removeChildNodes();
  101. _svg.style.backgroundColor = _clearColor.getStyle( _this.outputColorSpace );
  102. };
  103. this.render = function ( scene, camera ) {
  104. if ( camera instanceof Camera === false ) {
  105. console.error( 'THREE.SVGRenderer.render: camera is not an instance of Camera.' );
  106. return;
  107. }
  108. const background = scene.background;
  109. if ( background && background.isColor ) {
  110. removeChildNodes();
  111. _svg.style.backgroundColor = background.getStyle( _this.outputColorSpace );
  112. } else if ( this.autoClear === true ) {
  113. this.clear();
  114. }
  115. _this.info.render.vertices = 0;
  116. _this.info.render.faces = 0;
  117. _viewMatrix.copy( camera.matrixWorldInverse );
  118. _viewProjectionMatrix.multiplyMatrices( camera.projectionMatrix, _viewMatrix );
  119. _renderData = _projector.projectScene( scene, camera, this.sortObjects, this.sortElements );
  120. _elements = _renderData.elements;
  121. _lights = _renderData.lights;
  122. _normalViewMatrix.getNormalMatrix( camera.matrixWorldInverse );
  123. calculateLights( _lights );
  124. // reset accumulated path
  125. _currentPath = '';
  126. _currentStyle = '';
  127. for ( let e = 0, el = _elements.length; e < el; e ++ ) {
  128. const element = _elements[ e ];
  129. const material = element.material;
  130. if ( material === undefined || material.opacity === 0 ) continue;
  131. _elemBox.makeEmpty();
  132. if ( element instanceof RenderableSprite ) {
  133. _v1 = element;
  134. _v1.x *= _svgWidthHalf; _v1.y *= - _svgHeightHalf;
  135. renderSprite( _v1, element, material );
  136. } else if ( element instanceof RenderableLine ) {
  137. _v1 = element.v1; _v2 = element.v2;
  138. _v1.positionScreen.x *= _svgWidthHalf; _v1.positionScreen.y *= - _svgHeightHalf;
  139. _v2.positionScreen.x *= _svgWidthHalf; _v2.positionScreen.y *= - _svgHeightHalf;
  140. _elemBox.setFromPoints( [ _v1.positionScreen, _v2.positionScreen ] );
  141. if ( _clipBox.intersectsBox( _elemBox ) === true ) {
  142. renderLine( _v1, _v2, material );
  143. }
  144. } else if ( element instanceof RenderableFace ) {
  145. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3;
  146. if ( _v1.positionScreen.z < - 1 || _v1.positionScreen.z > 1 ) continue;
  147. if ( _v2.positionScreen.z < - 1 || _v2.positionScreen.z > 1 ) continue;
  148. if ( _v3.positionScreen.z < - 1 || _v3.positionScreen.z > 1 ) continue;
  149. _v1.positionScreen.x *= _svgWidthHalf; _v1.positionScreen.y *= - _svgHeightHalf;
  150. _v2.positionScreen.x *= _svgWidthHalf; _v2.positionScreen.y *= - _svgHeightHalf;
  151. _v3.positionScreen.x *= _svgWidthHalf; _v3.positionScreen.y *= - _svgHeightHalf;
  152. if ( this.overdraw > 0 ) {
  153. expand( _v1.positionScreen, _v2.positionScreen, this.overdraw );
  154. expand( _v2.positionScreen, _v3.positionScreen, this.overdraw );
  155. expand( _v3.positionScreen, _v1.positionScreen, this.overdraw );
  156. }
  157. _elemBox.setFromPoints( [
  158. _v1.positionScreen,
  159. _v2.positionScreen,
  160. _v3.positionScreen
  161. ] );
  162. if ( _clipBox.intersectsBox( _elemBox ) === true ) {
  163. renderFace3( _v1, _v2, _v3, element, material );
  164. }
  165. }
  166. }
  167. flushPath(); // just to flush last svg:path
  168. scene.traverseVisible( function ( object ) {
  169. if ( object.isSVGObject ) {
  170. _vector3.setFromMatrixPosition( object.matrixWorld );
  171. _vector3.applyMatrix4( _viewProjectionMatrix );
  172. if ( _vector3.z < - 1 || _vector3.z > 1 ) return;
  173. const x = _vector3.x * _svgWidthHalf;
  174. const y = - _vector3.y * _svgHeightHalf;
  175. const node = object.node;
  176. node.setAttribute( 'transform', 'translate(' + x + ',' + y + ')' );
  177. _svg.appendChild( node );
  178. }
  179. } );
  180. };
  181. function calculateLights( lights ) {
  182. _ambientLight.setRGB( 0, 0, 0 );
  183. _directionalLights.setRGB( 0, 0, 0 );
  184. _pointLights.setRGB( 0, 0, 0 );
  185. for ( let l = 0, ll = lights.length; l < ll; l ++ ) {
  186. const light = lights[ l ];
  187. const lightColor = light.color;
  188. if ( light.isAmbientLight ) {
  189. _ambientLight.r += lightColor.r;
  190. _ambientLight.g += lightColor.g;
  191. _ambientLight.b += lightColor.b;
  192. } else if ( light.isDirectionalLight ) {
  193. _directionalLights.r += lightColor.r;
  194. _directionalLights.g += lightColor.g;
  195. _directionalLights.b += lightColor.b;
  196. } else if ( light.isPointLight ) {
  197. _pointLights.r += lightColor.r;
  198. _pointLights.g += lightColor.g;
  199. _pointLights.b += lightColor.b;
  200. }
  201. }
  202. }
  203. function calculateLight( lights, position, normal, color ) {
  204. for ( let l = 0, ll = lights.length; l < ll; l ++ ) {
  205. const light = lights[ l ];
  206. const lightColor = light.color;
  207. if ( light.isDirectionalLight ) {
  208. const lightPosition = _vector3.setFromMatrixPosition( light.matrixWorld ).normalize();
  209. let amount = normal.dot( lightPosition );
  210. if ( amount <= 0 ) continue;
  211. amount *= light.intensity;
  212. color.r += lightColor.r * amount;
  213. color.g += lightColor.g * amount;
  214. color.b += lightColor.b * amount;
  215. } else if ( light.isPointLight ) {
  216. const lightPosition = _vector3.setFromMatrixPosition( light.matrixWorld );
  217. let amount = normal.dot( _vector3.subVectors( lightPosition, position ).normalize() );
  218. if ( amount <= 0 ) continue;
  219. amount *= light.distance == 0 ? 1 : 1 - Math.min( position.distanceTo( lightPosition ) / light.distance, 1 );
  220. if ( amount == 0 ) continue;
  221. amount *= light.intensity;
  222. color.r += lightColor.r * amount;
  223. color.g += lightColor.g * amount;
  224. color.b += lightColor.b * amount;
  225. }
  226. }
  227. }
  228. function renderSprite( v1, element, material ) {
  229. let scaleX = element.scale.x * _svgWidthHalf;
  230. let scaleY = element.scale.y * _svgHeightHalf;
  231. if ( material.isPointsMaterial ) {
  232. scaleX *= material.size;
  233. scaleY *= material.size;
  234. }
  235. const path = 'M' + convert( v1.x - scaleX * 0.5 ) + ',' + convert( v1.y - scaleY * 0.5 ) + 'h' + convert( scaleX ) + 'v' + convert( scaleY ) + 'h' + convert( - scaleX ) + 'z';
  236. let style = '';
  237. if ( material.isSpriteMaterial || material.isPointsMaterial ) {
  238. style = 'fill:' + material.color.getStyle( _this.outputColorSpace ) + ';fill-opacity:' + material.opacity;
  239. }
  240. addPath( style, path );
  241. }
  242. function renderLine( v1, v2, material ) {
  243. const path = 'M' + convert( v1.positionScreen.x ) + ',' + convert( v1.positionScreen.y ) + 'L' + convert( v2.positionScreen.x ) + ',' + convert( v2.positionScreen.y );
  244. if ( material.isLineBasicMaterial ) {
  245. let style = 'fill:none;stroke:' + material.color.getStyle( _this.outputColorSpace ) + ';stroke-opacity:' + material.opacity + ';stroke-width:' + material.linewidth + ';stroke-linecap:' + material.linecap;
  246. if ( material.isLineDashedMaterial ) {
  247. style = style + ';stroke-dasharray:' + material.dashSize + ',' + material.gapSize;
  248. }
  249. addPath( style, path );
  250. }
  251. }
  252. function renderFace3( v1, v2, v3, element, material ) {
  253. _this.info.render.vertices += 3;
  254. _this.info.render.faces ++;
  255. const path = 'M' + convert( v1.positionScreen.x ) + ',' + convert( v1.positionScreen.y ) + 'L' + convert( v2.positionScreen.x ) + ',' + convert( v2.positionScreen.y ) + 'L' + convert( v3.positionScreen.x ) + ',' + convert( v3.positionScreen.y ) + 'z';
  256. let style = '';
  257. if ( material.isMeshBasicMaterial ) {
  258. _color.copy( material.color );
  259. if ( material.vertexColors ) {
  260. _color.multiply( element.color );
  261. }
  262. } else if ( material.isMeshLambertMaterial || material.isMeshPhongMaterial || material.isMeshStandardMaterial ) {
  263. _diffuseColor.copy( material.color );
  264. if ( material.vertexColors ) {
  265. _diffuseColor.multiply( element.color );
  266. }
  267. _color.copy( _ambientLight );
  268. _centroid.copy( v1.positionWorld ).add( v2.positionWorld ).add( v3.positionWorld ).divideScalar( 3 );
  269. calculateLight( _lights, _centroid, element.normalModel, _color );
  270. _color.multiply( _diffuseColor ).add( material.emissive );
  271. } else if ( material.isMeshNormalMaterial ) {
  272. _normal.copy( element.normalModel ).applyMatrix3( _normalViewMatrix ).normalize();
  273. _color.setRGB( _normal.x, _normal.y, _normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  274. }
  275. if ( material.wireframe ) {
  276. style = 'fill:none;stroke:' + _color.getStyle( _this.outputColorSpace ) + ';stroke-opacity:' + material.opacity + ';stroke-width:' + material.wireframeLinewidth + ';stroke-linecap:' + material.wireframeLinecap + ';stroke-linejoin:' + material.wireframeLinejoin;
  277. } else {
  278. style = 'fill:' + _color.getStyle( _this.outputColorSpace ) + ';fill-opacity:' + material.opacity;
  279. }
  280. addPath( style, path );
  281. }
  282. // Hide anti-alias gaps
  283. function expand( v1, v2, pixels ) {
  284. let x = v2.x - v1.x, y = v2.y - v1.y;
  285. const det = x * x + y * y;
  286. if ( det === 0 ) return;
  287. const idet = pixels / Math.sqrt( det );
  288. x *= idet; y *= idet;
  289. v2.x += x; v2.y += y;
  290. v1.x -= x; v1.y -= y;
  291. }
  292. function addPath( style, path ) {
  293. if ( _currentStyle === style ) {
  294. _currentPath += path;
  295. } else {
  296. flushPath();
  297. _currentStyle = style;
  298. _currentPath = path;
  299. }
  300. }
  301. function flushPath() {
  302. if ( _currentPath ) {
  303. _svgNode = getPathNode( _pathCount ++ );
  304. _svgNode.setAttribute( 'd', _currentPath );
  305. _svgNode.setAttribute( 'style', _currentStyle );
  306. _svg.appendChild( _svgNode );
  307. }
  308. _currentPath = '';
  309. _currentStyle = '';
  310. }
  311. function getPathNode( id ) {
  312. if ( _svgPathPool[ id ] == null ) {
  313. _svgPathPool[ id ] = document.createElementNS( 'http://www.w3.org/2000/svg', 'path' );
  314. if ( _quality == 0 ) {
  315. _svgPathPool[ id ].setAttribute( 'shape-rendering', 'crispEdges' ); //optimizeSpeed
  316. }
  317. return _svgPathPool[ id ];
  318. }
  319. return _svgPathPool[ id ];
  320. }
  321. }
  322. }
  323. export { SVGObject, SVGRenderer };