SVGRenderer.js 12 KB

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