SVGRenderer.js 12 KB

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