Renderer.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895
  1. import Animation from './Animation.js';
  2. import RenderObjects from './RenderObjects.js';
  3. import Attributes from './Attributes.js';
  4. import Geometries from './Geometries.js';
  5. import Info from './Info.js';
  6. import Pipelines from './Pipelines.js';
  7. import Bindings from './Bindings.js';
  8. import RenderLists from './RenderLists.js';
  9. import RenderContexts from './RenderContexts.js';
  10. import Textures from './Textures.js';
  11. import Background from './Background.js';
  12. import Nodes from './nodes/Nodes.js';
  13. import { Scene, Frustum, Matrix4, Vector2, Vector3, Vector4, Color, DoubleSide, BackSide, FrontSide, SRGBColorSpace, NoToneMapping } from 'three';
  14. const _scene = new Scene();
  15. const _drawingBufferSize = new Vector2();
  16. const _screen = new Vector4();
  17. const _frustum = new Frustum();
  18. const _projScreenMatrix = new Matrix4();
  19. const _vector3 = new Vector3();
  20. class Renderer {
  21. constructor( backend ) {
  22. this.isRenderer = true;
  23. // public
  24. this.domElement = backend.getDomElement();
  25. this.backend = backend;
  26. this.autoClear = true;
  27. this.autoClearColor = true;
  28. this.autoClearDepth = true;
  29. this.autoClearStencil = true;
  30. this.outputColorSpace = SRGBColorSpace;
  31. this.toneMapping = NoToneMapping;
  32. this.toneMappingExposure = 1.0;
  33. this.sortObjects = true;
  34. this.depth = true;
  35. this.stencil = true;
  36. // internals
  37. this._pixelRatio = 1;
  38. this._width = this.domElement.width;
  39. this._height = this.domElement.height;
  40. this._viewport = new Vector4( 0, 0, this._width, this._height );
  41. this._scissor = new Vector4( 0, 0, this._width, this._height );
  42. this._scissorTest = false;
  43. this._info = null;
  44. this._properties = null;
  45. this._attributes = null;
  46. this._geometries = null;
  47. this._nodes = null;
  48. this._bindings = null;
  49. this._objects = null;
  50. this._pipelines = null;
  51. this._renderLists = null;
  52. this._renderContexts = null;
  53. this._textures = null;
  54. this._background = null;
  55. this._animation = new Animation();
  56. this._currentRenderContext = null;
  57. this._lastRenderContext = null;
  58. this._opaqueSort = null;
  59. this._transparentSort = null;
  60. this._clearAlpha = 1;
  61. this._clearColor = new Color( 0x000000 );
  62. this._clearDepth = 1;
  63. this._clearStencil = 0;
  64. this._renderTarget = null;
  65. this._currentActiveCubeFace = 0;
  66. this._initialized = false;
  67. this._initPromise = null;
  68. // backwards compatibility
  69. this.shadowMap = {
  70. enabled: false,
  71. type: null
  72. };
  73. this.xr = {
  74. enabled: false
  75. };
  76. }
  77. async init() {
  78. if ( this._initialized ) {
  79. throw new Error( 'Renderer: Backend has already been initialized.' );
  80. }
  81. if ( this._initPromise !== null ) {
  82. return this._initPromise;
  83. }
  84. this._initPromise = new Promise( async ( resolve, reject ) => {
  85. const backend = this.backend;
  86. try {
  87. await backend.init( this );
  88. } catch ( error ) {
  89. reject( error );
  90. return;
  91. }
  92. this._info = new Info();
  93. this._nodes = new Nodes( this, backend );
  94. this._attributes = new Attributes( backend );
  95. this._background = new Background( this, this._nodes );
  96. this._geometries = new Geometries( this._attributes, this._info );
  97. this._textures = new Textures( backend, this._info );
  98. this._pipelines = new Pipelines( backend, this._nodes );
  99. this._bindings = new Bindings( backend, this._nodes, this._textures, this._attributes, this._pipelines, this._info );
  100. this._objects = new RenderObjects( this, this._nodes, this._geometries, this._pipelines, this._bindings, this._info );
  101. this._renderLists = new RenderLists();
  102. this._renderContexts = new RenderContexts();
  103. //
  104. this._animation.setNodes( this._nodes );
  105. this._animation.start();
  106. this._initialized = true;
  107. resolve();
  108. } );
  109. return this._initPromise;
  110. }
  111. get coordinateSystem() {
  112. return this.backend.coordinateSystem;
  113. }
  114. async compile( /*scene, camera*/ ) {
  115. console.warn( 'THREE.Renderer: .compile() is not implemented yet.' );
  116. }
  117. async render( scene, camera ) {
  118. if ( this._initialized === false ) await this.init();
  119. // preserve render tree
  120. const nodeFrame = this._nodes.nodeFrame;
  121. const previousRenderId = nodeFrame.renderId;
  122. const previousRenderState = this._currentRenderContext;
  123. //
  124. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  125. const renderTarget = this._renderTarget;
  126. const renderContext = this._renderContexts.get( scene, camera, renderTarget );
  127. const activeCubeFace = this._activeCubeFace;
  128. this._currentRenderContext = renderContext;
  129. nodeFrame.renderId ++;
  130. //
  131. const coordinateSystem = this.coordinateSystem;
  132. if ( camera.coordinateSystem !== coordinateSystem ) {
  133. camera.coordinateSystem = coordinateSystem;
  134. camera.updateProjectionMatrix();
  135. }
  136. //
  137. if ( this._animation.isAnimating === false ) nodeFrame.update();
  138. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  139. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  140. if ( this._info.autoReset === true ) this._info.reset();
  141. this._info.render.frame ++;
  142. //
  143. let viewport = this._viewport;
  144. let scissor = this._scissor;
  145. let pixelRatio = this._pixelRatio;
  146. if ( renderTarget !== null ) {
  147. viewport = renderTarget.viewport;
  148. scissor = renderTarget.scissor;
  149. pixelRatio = 1;
  150. }
  151. this.getDrawingBufferSize( _drawingBufferSize );
  152. _screen.set( 0, 0, _drawingBufferSize.width, _drawingBufferSize.height );
  153. const minDepth = ( viewport.minDepth === undefined ) ? 0 : viewport.minDepth;
  154. const maxDepth = ( viewport.maxDepth === undefined ) ? 1 : viewport.maxDepth;
  155. renderContext.viewportValue.copy( viewport ).multiplyScalar( pixelRatio ).floor();
  156. renderContext.viewportValue.minDepth = minDepth;
  157. renderContext.viewportValue.maxDepth = maxDepth;
  158. renderContext.viewport = renderContext.viewportValue.equals( _screen ) === false;
  159. renderContext.scissorValue.copy( scissor ).multiplyScalar( pixelRatio ).floor();
  160. renderContext.scissor = this._scissorTest && renderContext.scissorValue.equals( _screen ) === false;
  161. renderContext.depth = this.depth;
  162. renderContext.stencil = this.stencil;
  163. //
  164. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  165. //
  166. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  167. _frustum.setFromProjectionMatrix( _projScreenMatrix, coordinateSystem );
  168. const renderList = this._renderLists.get( scene, camera );
  169. renderList.init();
  170. this._projectObject( scene, camera, 0, renderList );
  171. renderList.finish();
  172. if ( this.sortObjects === true ) {
  173. renderList.sort( this._opaqueSort, this._transparentSort );
  174. }
  175. //
  176. if ( renderTarget !== null ) {
  177. this._textures.updateRenderTarget( renderTarget );
  178. const renderTargetData = this._textures.get( renderTarget );
  179. renderContext.texture = renderTargetData.texture;
  180. renderContext.depthTexture = renderTargetData.depthTexture;
  181. } else {
  182. renderContext.texture = null;
  183. renderContext.depthTexture = null;
  184. }
  185. renderContext.activeCubeFace = activeCubeFace;
  186. //
  187. this._nodes.updateScene( sceneRef );
  188. //
  189. this._background.update( sceneRef, renderList, renderContext );
  190. //
  191. this.backend.beginRender( renderContext );
  192. // process render lists
  193. const opaqueObjects = renderList.opaque;
  194. const transparentObjects = renderList.transparent;
  195. const lightsNode = renderList.lightsNode;
  196. if ( opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  197. if ( transparentObjects.length > 0 ) this._renderObjects( transparentObjects, camera, sceneRef, lightsNode );
  198. // finish render pass
  199. this.backend.finishRender( renderContext );
  200. // restore render tree
  201. nodeFrame.renderId = previousRenderId;
  202. this._currentRenderContext = previousRenderState;
  203. this._lastRenderContext = renderContext;
  204. //
  205. sceneRef.onAfterRender( this, scene, camera, renderTarget );
  206. }
  207. setAnimationLoop( callback ) {
  208. if ( this._initialized === false ) this.init();
  209. const animation = this._animation;
  210. animation.setAnimationLoop( callback );
  211. ( callback === null ) ? animation.stop() : animation.start();
  212. }
  213. getArrayBuffer( attribute ) { // @deprecated, r155
  214. console.warn( 'THREE.Renderer: getArrayBuffer() is deprecated. Use getArrayBufferAsync() instead.' );
  215. return this.getArrayBufferAsync( attribute );
  216. }
  217. async getArrayBufferAsync( attribute ) {
  218. return await this.backend.getArrayBufferAsync( attribute );
  219. }
  220. getContext() {
  221. return this._context;
  222. }
  223. getPixelRatio() {
  224. return this._pixelRatio;
  225. }
  226. getDrawingBufferSize( target ) {
  227. return target.set( this._width * this._pixelRatio, this._height * this._pixelRatio ).floor();
  228. }
  229. getSize( target ) {
  230. return target.set( this._width, this._height );
  231. }
  232. setPixelRatio( value = 1 ) {
  233. this._pixelRatio = value;
  234. this.setSize( this._width, this._height, false );
  235. }
  236. setDrawingBufferSize( width, height, pixelRatio ) {
  237. this._width = width;
  238. this._height = height;
  239. this._pixelRatio = pixelRatio;
  240. this.domElement.width = Math.floor( width * pixelRatio );
  241. this.domElement.height = Math.floor( height * pixelRatio );
  242. this.setViewport( 0, 0, width, height );
  243. if ( this._initialized ) this.backend.updateSize();
  244. }
  245. setSize( width, height, updateStyle = true ) {
  246. this._width = width;
  247. this._height = height;
  248. this.domElement.width = Math.floor( width * this._pixelRatio );
  249. this.domElement.height = Math.floor( height * this._pixelRatio );
  250. if ( updateStyle === true ) {
  251. this.domElement.style.width = width + 'px';
  252. this.domElement.style.height = height + 'px';
  253. }
  254. this.setViewport( 0, 0, width, height );
  255. if ( this._initialized ) this.backend.updateSize();
  256. }
  257. setOpaqueSort( method ) {
  258. this._opaqueSort = method;
  259. }
  260. setTransparentSort( method ) {
  261. this._transparentSort = method;
  262. }
  263. getScissor( target ) {
  264. const scissor = this._scissor;
  265. target.x = scissor.x;
  266. target.y = scissor.y;
  267. target.width = scissor.width;
  268. target.height = scissor.height;
  269. return target;
  270. }
  271. setScissor( x, y, width, height ) {
  272. const scissor = this._scissor;
  273. if ( x.isVector4 ) {
  274. scissor.copy( x );
  275. } else {
  276. scissor.set( x, y, width, height );
  277. }
  278. }
  279. getScissorTest() {
  280. return this._scissorTest;
  281. }
  282. setScissorTest( boolean ) {
  283. this._scissorTest = boolean;
  284. }
  285. getViewport( target ) {
  286. return target.copy( this._viewport );
  287. }
  288. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  289. const viewport = this._viewport;
  290. if ( x.isVector4 ) {
  291. viewport.copy( x );
  292. } else {
  293. viewport.set( x, y, width, height );
  294. }
  295. viewport.minDepth = minDepth;
  296. viewport.maxDepth = maxDepth;
  297. }
  298. getClearColor( target ) {
  299. return target.copy( this._clearColor );
  300. }
  301. setClearColor( color, alpha = 1 ) {
  302. this._clearColor.set( color );
  303. this._clearAlpha = alpha;
  304. }
  305. getClearAlpha() {
  306. return this._clearAlpha;
  307. }
  308. setClearAlpha( alpha ) {
  309. this._clearAlpha = alpha;
  310. }
  311. getClearDepth() {
  312. return this._clearDepth;
  313. }
  314. setClearDepth( depth ) {
  315. this._clearDepth = depth;
  316. }
  317. getClearStencil() {
  318. return this._clearStencil;
  319. }
  320. setClearStencil( stencil ) {
  321. this._clearStencil = stencil;
  322. }
  323. clear( color = true, depth = true, stencil = true ) {
  324. const renderContext = this._currentRenderContext || this._lastRenderContext;
  325. if ( renderContext ) this.backend.clear( renderContext, color, depth, stencil );
  326. }
  327. clearColor() {
  328. this.clear( true, false, false );
  329. }
  330. clearDepth() {
  331. this.clear( false, true, false );
  332. }
  333. clearStencil() {
  334. this.clear( false, false, true );
  335. }
  336. dispose() {
  337. this._objects.dispose();
  338. this._properties.dispose();
  339. this._pipelines.dispose();
  340. this._nodes.dispose();
  341. this._bindings.dispose();
  342. this._info.dispose();
  343. this._renderLists.dispose();
  344. this._renderContexts.dispose();
  345. this._textures.dispose();
  346. this.setRenderTarget( null );
  347. this.setAnimationLoop( null );
  348. }
  349. setRenderTarget( renderTarget, activeCubeFace = 0 ) {
  350. this._renderTarget = renderTarget;
  351. this._activeCubeFace = activeCubeFace;
  352. }
  353. getRenderTarget() {
  354. return this._renderTarget;
  355. }
  356. async compute( computeNodes ) {
  357. if ( this._initialized === false ) await this.init();
  358. const backend = this.backend;
  359. const pipelines = this._pipelines;
  360. const bindings = this._bindings;
  361. const nodes = this._nodes;
  362. const computeList = Array.isArray( computeNodes ) ? computeNodes : [ computeNodes ];
  363. backend.beginCompute( computeNodes );
  364. for ( const computeNode of computeList ) {
  365. // onInit
  366. if ( pipelines.has( computeNode ) === false ) {
  367. const dispose = () => {
  368. computeNode.removeEventListener( 'dispose', dispose );
  369. pipelines.delete( computeNode );
  370. bindings.delete( computeNode );
  371. nodes.delete( computeNode );
  372. };
  373. computeNode.addEventListener( 'dispose', dispose );
  374. //
  375. computeNode.onInit( { renderer: this } );
  376. }
  377. nodes.updateForCompute( computeNode );
  378. bindings.updateForCompute( computeNode );
  379. const computeBindings = bindings.getForCompute( computeNode );
  380. const computePipeline = pipelines.getForCompute( computeNode, computeBindings );
  381. backend.compute( computeNodes, computeNode, computeBindings, computePipeline );
  382. }
  383. backend.finishCompute( computeNodes );
  384. }
  385. hasFeature( name ) {
  386. return this.backend.hasFeature( name );
  387. }
  388. copyFramebufferToTexture( framebufferTexture ) {
  389. const renderContext = this._currentRenderContext || this._lastRenderContext;
  390. this._textures.updateTexture( framebufferTexture );
  391. this.backend.copyFramebufferToTexture( framebufferTexture, renderContext );
  392. }
  393. readRenderTargetPixelsAsync( renderTarget, x, y, width, height ) {
  394. return this.backend.copyTextureToBuffer( renderTarget.texture, x, y, width, height );
  395. }
  396. _projectObject( object, camera, groupOrder, renderList ) {
  397. if ( object.visible === false ) return;
  398. const visible = object.layers.test( camera.layers );
  399. if ( visible ) {
  400. if ( object.isGroup ) {
  401. groupOrder = object.renderOrder;
  402. } else if ( object.isLOD ) {
  403. if ( object.autoUpdate === true ) object.update( camera );
  404. } else if ( object.isLight ) {
  405. renderList.pushLight( object );
  406. } else if ( object.isSprite ) {
  407. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  408. if ( this.sortObjects === true ) {
  409. _vector3.setFromMatrixPosition( object.matrixWorld ).applyMatrix4( _projScreenMatrix );
  410. }
  411. const geometry = object.geometry;
  412. const material = object.material;
  413. if ( material.visible ) {
  414. renderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  415. }
  416. }
  417. } else if ( object.isLineLoop ) {
  418. console.error( 'THREE.Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.' );
  419. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  420. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  421. const geometry = object.geometry;
  422. const material = object.material;
  423. if ( this.sortObjects === true ) {
  424. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  425. _vector3
  426. .copy( geometry.boundingSphere.center )
  427. .applyMatrix4( object.matrixWorld )
  428. .applyMatrix4( _projScreenMatrix );
  429. }
  430. if ( Array.isArray( material ) ) {
  431. const groups = geometry.groups;
  432. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  433. const group = groups[ i ];
  434. const groupMaterial = material[ group.materialIndex ];
  435. if ( groupMaterial && groupMaterial.visible ) {
  436. renderList.push( object, geometry, groupMaterial, groupOrder, _vector3.z, group );
  437. }
  438. }
  439. } else if ( material.visible ) {
  440. renderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  441. }
  442. }
  443. }
  444. }
  445. const children = object.children;
  446. for ( let i = 0, l = children.length; i < l; i ++ ) {
  447. this._projectObject( children[ i ], camera, groupOrder, renderList );
  448. }
  449. }
  450. _renderObjects( renderList, camera, scene, lightsNode ) {
  451. // process renderable objects
  452. for ( let i = 0, il = renderList.length; i < il; i ++ ) {
  453. const renderItem = renderList[ i ];
  454. // @TODO: Add support for multiple materials per object. This will require to extract
  455. // the material from the renderItem object and pass it with its group data to _renderObject().
  456. const { object, geometry, material, group } = renderItem;
  457. if ( camera.isArrayCamera ) {
  458. const cameras = camera.cameras;
  459. for ( let j = 0, jl = cameras.length; j < jl; j ++ ) {
  460. const camera2 = cameras[ j ];
  461. if ( object.layers.test( camera2.layers ) ) {
  462. const vp = camera2.viewport;
  463. const minDepth = ( vp.minDepth === undefined ) ? 0 : vp.minDepth;
  464. const maxDepth = ( vp.maxDepth === undefined ) ? 1 : vp.maxDepth;
  465. const viewportValue = this._currentRenderContext.viewportValue;
  466. viewportValue.copy( vp ).multiplyScalar( this._pixelRatio ).floor();
  467. viewportValue.minDepth = minDepth;
  468. viewportValue.maxDepth = maxDepth;
  469. this.backend.updateViewport( this._currentRenderContext );
  470. this._renderObject( object, scene, camera2, geometry, material, group, lightsNode );
  471. }
  472. }
  473. } else {
  474. this._renderObject( object, scene, camera, geometry, material, group, lightsNode );
  475. }
  476. }
  477. }
  478. _renderObject( object, scene, camera, geometry, material, group, lightsNode ) {
  479. material = scene.overrideMaterial !== null ? scene.overrideMaterial : material;
  480. //
  481. object.onBeforeRender( this, scene, camera, geometry, material, group );
  482. material.onBeforeRender( this, scene, camera, geometry, material, group );
  483. //
  484. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  485. material.side = BackSide;
  486. this._renderObjectDirect( object, material, scene, camera, lightsNode, 'backSide' ); // create backSide pass id
  487. material.side = FrontSide;
  488. this._renderObjectDirect( object, material, scene, camera, lightsNode ); // use default pass id
  489. material.side = DoubleSide;
  490. } else {
  491. this._renderObjectDirect( object, material, scene, camera, lightsNode );
  492. }
  493. //
  494. object.onAfterRender( this, scene, camera, geometry, material, group );
  495. }
  496. _renderObjectDirect( object, material, scene, camera, lightsNode, passId ) {
  497. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, passId );
  498. //
  499. this._nodes.updateBefore( renderObject );
  500. //
  501. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  502. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  503. //
  504. this._nodes.updateForRender( renderObject );
  505. this._geometries.updateForRender( renderObject );
  506. this._bindings.updateForRender( renderObject );
  507. this._pipelines.updateForRender( renderObject );
  508. //
  509. this.backend.draw( renderObject, this._info );
  510. }
  511. }
  512. export default Renderer;