SVGRenderer.js 12 KB

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