SVGRenderer.js 12 KB

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