SVGRenderer.js 12 KB

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