WebGPURenderer.js 26 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148
  1. import { GPUIndexFormat, GPUTextureFormat, GPUFeatureName, GPULoadOp } from './constants.js';
  2. import WebGPUAnimation from './WebGPUAnimation.js';
  3. import WebGPURenderObjects from './WebGPURenderObjects.js';
  4. import WebGPUAttributes from './WebGPUAttributes.js';
  5. import WebGPUGeometries from './WebGPUGeometries.js';
  6. import WebGPUInfo from './WebGPUInfo.js';
  7. import WebGPUProperties from './WebGPUProperties.js';
  8. import WebGPURenderPipelines from './WebGPURenderPipelines.js';
  9. import WebGPUComputePipelines from './WebGPUComputePipelines.js';
  10. import WebGPUBindings from './WebGPUBindings.js';
  11. import WebGPURenderLists from './WebGPURenderLists.js';
  12. import WebGPURenderStates from './WebGPURenderStates.js';
  13. import WebGPUTextures from './WebGPUTextures.js';
  14. import WebGPUBackground from './WebGPUBackground.js';
  15. import WebGPUNodes from './nodes/WebGPUNodes.js';
  16. import WebGPUUtils from './WebGPUUtils.js';
  17. import { Frustum, Matrix4, Vector3, Color, SRGBColorSpace, NoToneMapping, DepthFormat } from 'three';
  18. console.info( 'THREE.WebGPURenderer: Modified Matrix4.makePerspective() and Matrix4.makeOrtographic() to work with WebGPU, see https://github.com/mrdoob/three.js/issues/20276.' );
  19. Matrix4.prototype.makePerspective = function ( left, right, top, bottom, near, far ) {
  20. const te = this.elements;
  21. const x = 2 * near / ( right - left );
  22. const y = 2 * near / ( top - bottom );
  23. const a = ( right + left ) / ( right - left );
  24. const b = ( top + bottom ) / ( top - bottom );
  25. const c = - far / ( far - near );
  26. const d = - far * near / ( far - near );
  27. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  28. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  29. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  30. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  31. return this;
  32. };
  33. Matrix4.prototype.makeOrthographic = function ( left, right, top, bottom, near, far ) {
  34. const te = this.elements;
  35. const w = 1.0 / ( right - left );
  36. const h = 1.0 / ( top - bottom );
  37. const p = 1.0 / ( far - near );
  38. const x = ( right + left ) * w;
  39. const y = ( top + bottom ) * h;
  40. const z = near * p;
  41. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  42. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  43. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = - 1 * p; te[ 14 ] = - z;
  44. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  45. return this;
  46. };
  47. Frustum.prototype.setFromProjectionMatrix = function ( m ) {
  48. const planes = this.planes;
  49. const me = m.elements;
  50. const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  51. const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  52. const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  53. const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  54. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  55. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  56. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  57. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  58. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  59. planes[ 5 ].setComponents( me2, me6, me10, me14 ).normalize();
  60. return this;
  61. };
  62. const _frustum = new Frustum();
  63. const _projScreenMatrix = new Matrix4();
  64. const _vector3 = new Vector3();
  65. class WebGPURenderer {
  66. constructor( parameters = {} ) {
  67. this.isWebGPURenderer = true;
  68. // public
  69. this.domElement = ( parameters.canvas !== undefined ) ? parameters.canvas : this._createCanvasElement();
  70. this.autoClear = true;
  71. this.autoClearColor = true;
  72. this.autoClearDepth = true;
  73. this.autoClearStencil = true;
  74. this.outputColorSpace = SRGBColorSpace;
  75. this.toneMapping = NoToneMapping;
  76. this.toneMappingExposure = 1.0;
  77. this.sortObjects = true;
  78. // internals
  79. this._parameters = Object.assign( {}, parameters );
  80. this._pixelRatio = 1;
  81. this._width = this.domElement.width;
  82. this._height = this.domElement.height;
  83. this._viewport = null;
  84. this._scissor = null;
  85. this._adapter = null;
  86. this._device = null;
  87. this._context = null;
  88. this._colorBuffer = null;
  89. this._depthBuffer = null;
  90. this._info = null;
  91. this._properties = null;
  92. this._attributes = null;
  93. this._geometries = null;
  94. this._nodes = null;
  95. this._bindings = null;
  96. this._objects = null;
  97. this._renderPipelines = null;
  98. this._computePipelines = null;
  99. this._renderLists = null;
  100. this._renderStates = null;
  101. this._textures = null;
  102. this._background = null;
  103. this._animation = new WebGPUAnimation();
  104. this._currentRenderState = null;
  105. this._opaqueSort = null;
  106. this._transparentSort = null;
  107. this._clearAlpha = 1;
  108. this._clearColor = new Color( 0x000000 );
  109. this._clearDepth = 1;
  110. this._clearStencil = 0;
  111. this._renderTarget = null;
  112. this._initialized = false;
  113. // some parameters require default values other than "undefined"
  114. this._parameters.antialias = ( parameters.antialias === true );
  115. if ( this._parameters.antialias === true ) {
  116. this._parameters.sampleCount = ( parameters.sampleCount === undefined ) ? 4 : parameters.sampleCount;
  117. } else {
  118. this._parameters.sampleCount = 1;
  119. }
  120. this._parameters.requiredLimits = ( parameters.requiredLimits === undefined ) ? {} : parameters.requiredLimits;
  121. // backwards compatibility
  122. this.shadow = {
  123. shadowMap: {}
  124. };
  125. }
  126. async init() {
  127. if ( this._initialized === true ) {
  128. throw new Error( 'WebGPURenderer: Device has already been initialized.' );
  129. }
  130. const parameters = this._parameters;
  131. const adapterOptions = {
  132. powerPreference: parameters.powerPreference
  133. };
  134. const adapter = await navigator.gpu.requestAdapter( adapterOptions );
  135. if ( adapter === null ) {
  136. throw new Error( 'WebGPURenderer: Unable to create WebGPU adapter.' );
  137. }
  138. // feature support
  139. const features = Object.values( GPUFeatureName );
  140. const supportedFeatures = [];
  141. for ( const name of features ) {
  142. if ( adapter.features.has( name ) ) {
  143. supportedFeatures.push( name );
  144. }
  145. }
  146. const deviceDescriptor = {
  147. requiredFeatures: supportedFeatures,
  148. requiredLimits: parameters.requiredLimits
  149. };
  150. const device = await adapter.requestDevice( deviceDescriptor );
  151. const context = ( parameters.context !== undefined ) ? parameters.context : this.domElement.getContext( 'webgpu' );
  152. this._adapter = adapter;
  153. this._device = device;
  154. this._context = context;
  155. this._configureContext();
  156. this._info = new WebGPUInfo();
  157. this._properties = new WebGPUProperties();
  158. this._attributes = new WebGPUAttributes( device );
  159. this._geometries = new WebGPUGeometries( this._attributes, this._properties, this._info );
  160. this._textures = new WebGPUTextures( device, this._properties, this._info );
  161. this._utils = new WebGPUUtils( this );
  162. this._nodes = new WebGPUNodes( this, this._properties );
  163. this._objects = new WebGPURenderObjects( this, this._nodes, this._geometries, this._info );
  164. this._computePipelines = new WebGPUComputePipelines( device, this._nodes );
  165. this._renderPipelines = new WebGPURenderPipelines( device, this._nodes, this._utils );
  166. this._bindings = this._renderPipelines.bindings = new WebGPUBindings( device, this._info, this._properties, this._textures, this._renderPipelines, this._computePipelines, this._attributes, this._nodes );
  167. this._renderLists = new WebGPURenderLists();
  168. this._renderStates = new WebGPURenderStates();
  169. this._background = new WebGPUBackground( this, this._properties );
  170. //
  171. this._setupColorBuffer();
  172. this._setupDepthBuffer();
  173. this._animation.setNodes( this._nodes );
  174. this._animation.start();
  175. this._initialized = true;
  176. }
  177. async render( scene, camera ) {
  178. if ( this._initialized === false ) await this.init();
  179. // preserve render tree
  180. const nodeFrame = this._nodes.nodeFrame;
  181. const previousRenderId = nodeFrame.renderId;
  182. const previousRenderState = this._currentRenderState;
  183. //
  184. const renderState = this._renderStates.get( scene, camera );
  185. const renderTarget = this._renderTarget;
  186. this._currentRenderState = renderState;
  187. nodeFrame.renderId ++;
  188. //
  189. if ( this._animation.isAnimating === false ) nodeFrame.update();
  190. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  191. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  192. if ( this._info.autoReset === true ) this._info.reset();
  193. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  194. _frustum.setFromProjectionMatrix( _projScreenMatrix );
  195. const renderList = this._renderLists.get( scene, camera );
  196. renderList.init();
  197. this._projectObject( scene, camera, 0, renderList );
  198. renderList.finish();
  199. if ( this.sortObjects === true ) {
  200. renderList.sort( this._opaqueSort, this._transparentSort );
  201. }
  202. // prepare render pass descriptor
  203. renderState.descriptorGPU = {
  204. colorAttachments: [ {
  205. view: null
  206. } ],
  207. depthStencilAttachment: {
  208. view: null
  209. }
  210. };
  211. const colorAttachment = renderState.descriptorGPU.colorAttachments[ 0 ];
  212. const depthStencilAttachment = renderState.descriptorGPU.depthStencilAttachment;
  213. if ( renderTarget !== null ) {
  214. this._textures.initRenderTarget( renderTarget );
  215. // @TODO: Support RenderTarget with antialiasing.
  216. const renderTargetProperties = this._properties.get( renderTarget );
  217. colorAttachment.view = renderTargetProperties.colorTextureGPU.createView();
  218. depthStencilAttachment.view = renderTargetProperties.depthTextureGPU.createView();
  219. renderState.stencil = renderTarget.depthTexture ? renderTarget.depthTexture.format !== DepthFormat : true;
  220. } else {
  221. if ( this._parameters.antialias === true ) {
  222. colorAttachment.view = this._colorBuffer.createView();
  223. colorAttachment.resolveTarget = this._context.getCurrentTexture().createView();
  224. } else {
  225. colorAttachment.view = this._context.getCurrentTexture().createView();
  226. colorAttachment.resolveTarget = undefined;
  227. }
  228. depthStencilAttachment.view = this._depthBuffer.createView();
  229. }
  230. //
  231. this._nodes.updateEnvironment( scene );
  232. this._nodes.updateFog( scene );
  233. this._nodes.updateBackground( scene );
  234. this._nodes.updateToneMapping();
  235. //
  236. this._background.update( scene, renderList, renderState );
  237. // start render pass
  238. const device = this._device;
  239. renderState.encoderGPU = device.createCommandEncoder( {} );
  240. renderState.currentPassGPU = renderState.encoderGPU.beginRenderPass( renderState.descriptorGPU );
  241. // global rasterization settings for all renderable objects
  242. const vp = this._viewport;
  243. if ( vp !== null ) {
  244. const width = Math.floor( vp.width * this._pixelRatio );
  245. const height = Math.floor( vp.height * this._pixelRatio );
  246. renderState.currentPassGPU.setViewport( vp.x, vp.y, width, height, vp.minDepth, vp.maxDepth );
  247. }
  248. const sc = this._scissor;
  249. if ( sc !== null ) {
  250. const width = Math.floor( sc.width * this._pixelRatio );
  251. const height = Math.floor( sc.height * this._pixelRatio );
  252. renderState.currentPassGPU.setScissorRect( sc.x, sc.y, width, height );
  253. }
  254. // process render lists
  255. const opaqueObjects = renderList.opaque;
  256. const transparentObjects = renderList.transparent;
  257. const lightsNode = renderList.lightsNode;
  258. if ( opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, scene, lightsNode, renderState );
  259. if ( transparentObjects.length > 0 ) this._renderObjects( transparentObjects, camera, scene, lightsNode, renderState );
  260. // finish render pass
  261. renderState.currentPassGPU.end();
  262. device.queue.submit( [ renderState.encoderGPU.finish() ] );
  263. // restore render tree
  264. nodeFrame.renderId = previousRenderId;
  265. this._currentRenderState = previousRenderState;
  266. }
  267. setAnimationLoop( callback ) {
  268. if ( this._initialized === false ) this.init();
  269. const animation = this._animation;
  270. animation.setAnimationLoop( callback );
  271. ( callback === null ) ? animation.stop() : animation.start();
  272. }
  273. async getArrayBuffer( attribute ) {
  274. return await this._attributes.getArrayBuffer( attribute );
  275. }
  276. getContext() {
  277. return this._context;
  278. }
  279. getPixelRatio() {
  280. return this._pixelRatio;
  281. }
  282. getDrawingBufferSize( target ) {
  283. return target.set( this._width * this._pixelRatio, this._height * this._pixelRatio ).floor();
  284. }
  285. getSize( target ) {
  286. return target.set( this._width, this._height );
  287. }
  288. setPixelRatio( value = 1 ) {
  289. this._pixelRatio = value;
  290. this.setSize( this._width, this._height, false );
  291. }
  292. setDrawingBufferSize( width, height, pixelRatio ) {
  293. this._width = width;
  294. this._height = height;
  295. this._pixelRatio = pixelRatio;
  296. this.domElement.width = Math.floor( width * pixelRatio );
  297. this.domElement.height = Math.floor( height * pixelRatio );
  298. this._configureContext();
  299. this._setupColorBuffer();
  300. this._setupDepthBuffer();
  301. }
  302. setSize( width, height, updateStyle = true ) {
  303. this._width = width;
  304. this._height = height;
  305. this.domElement.width = Math.floor( width * this._pixelRatio );
  306. this.domElement.height = Math.floor( height * this._pixelRatio );
  307. if ( updateStyle === true ) {
  308. this.domElement.style.width = width + 'px';
  309. this.domElement.style.height = height + 'px';
  310. }
  311. this._configureContext();
  312. this._setupColorBuffer();
  313. this._setupDepthBuffer();
  314. }
  315. setOpaqueSort( method ) {
  316. this._opaqueSort = method;
  317. }
  318. setTransparentSort( method ) {
  319. this._transparentSort = method;
  320. }
  321. getScissor( target ) {
  322. const scissor = this._scissor;
  323. target.x = scissor.x;
  324. target.y = scissor.y;
  325. target.width = scissor.width;
  326. target.height = scissor.height;
  327. return target;
  328. }
  329. setScissor( x, y, width, height ) {
  330. if ( x === null ) {
  331. this._scissor = null;
  332. } else {
  333. this._scissor = {
  334. x: x,
  335. y: y,
  336. width: width,
  337. height: height
  338. };
  339. }
  340. }
  341. copyFramebufferToRenderTarget( renderTarget ) {
  342. const renderState = this._currentRenderState;
  343. const { encoderGPU, descriptorGPU } = renderState;
  344. const texture = renderTarget.texture;
  345. texture.internalFormat = GPUTextureFormat.BGRA8Unorm;
  346. this._textures.initRenderTarget( renderTarget );
  347. const sourceGPU = this._context.getCurrentTexture();
  348. const destinationGPU = this._textures.getTextureGPU( texture );
  349. renderState.currentPassGPU.end();
  350. encoderGPU.copyTextureToTexture(
  351. {
  352. texture: sourceGPU
  353. },
  354. {
  355. texture: destinationGPU
  356. },
  357. [
  358. texture.image.width,
  359. texture.image.height
  360. ]
  361. );
  362. descriptorGPU.colorAttachments[ 0 ].loadOp = GPULoadOp.Load;
  363. if ( renderState.depth ) descriptorGPU.depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  364. if ( renderState.stencil ) descriptorGPU.depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  365. renderState.currentPassGPU = encoderGPU.beginRenderPass( descriptorGPU );
  366. }
  367. getViewport( target ) {
  368. const viewport = this._viewport;
  369. target.x = viewport.x;
  370. target.y = viewport.y;
  371. target.width = viewport.width;
  372. target.height = viewport.height;
  373. target.minDepth = viewport.minDepth;
  374. target.maxDepth = viewport.maxDepth;
  375. return target;
  376. }
  377. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  378. if ( x === null ) {
  379. this._viewport = null;
  380. } else {
  381. this._viewport = {
  382. x: x,
  383. y: y,
  384. width: width,
  385. height: height,
  386. minDepth: minDepth,
  387. maxDepth: maxDepth
  388. };
  389. }
  390. }
  391. getClearColor( target ) {
  392. return target.copy( this._clearColor );
  393. }
  394. setClearColor( color, alpha = 1 ) {
  395. this._clearColor.set( color );
  396. this._clearAlpha = alpha;
  397. }
  398. getClearAlpha() {
  399. return this._clearAlpha;
  400. }
  401. setClearAlpha( alpha ) {
  402. this._clearAlpha = alpha;
  403. }
  404. getClearDepth() {
  405. return this._clearDepth;
  406. }
  407. setClearDepth( depth ) {
  408. this._clearDepth = depth;
  409. }
  410. getClearStencil() {
  411. return this._clearStencil;
  412. }
  413. setClearStencil( stencil ) {
  414. this._clearStencil = stencil;
  415. }
  416. clear() {
  417. if ( this._background ) this._background.clear();
  418. }
  419. dispose() {
  420. this._objects.dispose();
  421. this._properties.dispose();
  422. this._renderPipelines.dispose();
  423. this._computePipelines.dispose();
  424. this._nodes.dispose();
  425. this._bindings.dispose();
  426. this._info.dispose();
  427. this._renderLists.dispose();
  428. this._renderStates.dispose();
  429. this._textures.dispose();
  430. this.setRenderTarget( null );
  431. this.setAnimationLoop( null );
  432. }
  433. setRenderTarget( renderTarget ) {
  434. this._renderTarget = renderTarget;
  435. }
  436. async compute( ...computeNodes ) {
  437. if ( this._initialized === false ) await this.init();
  438. const device = this._device;
  439. const computePipelines = this._computePipelines;
  440. const cmdEncoder = device.createCommandEncoder( {} );
  441. const passEncoder = cmdEncoder.beginComputePass();
  442. for ( const computeNode of computeNodes ) {
  443. // onInit
  444. if ( computePipelines.has( computeNode ) === false ) {
  445. computeNode.onInit( { renderer: this } );
  446. }
  447. // pipeline
  448. const pipeline = computePipelines.get( computeNode );
  449. passEncoder.setPipeline( pipeline );
  450. // node
  451. //this._nodes.update( computeNode );
  452. // bind group
  453. const bindGroup = this._bindings.getForCompute( computeNode ).group;
  454. this._bindings.update( computeNode );
  455. passEncoder.setBindGroup( 0, bindGroup );
  456. passEncoder.dispatchWorkgroups( computeNode.dispatchCount );
  457. }
  458. passEncoder.end();
  459. device.queue.submit( [ cmdEncoder.finish() ] );
  460. }
  461. getRenderTarget() {
  462. return this._renderTarget;
  463. }
  464. hasFeature( name ) {
  465. if ( this._initialized === false ) {
  466. throw new Error( 'THREE.WebGPURenderer: Renderer must be initialized before testing features.' );
  467. }
  468. //
  469. const features = Object.values( GPUFeatureName );
  470. if ( features.includes( name ) === false ) {
  471. throw new Error( 'THREE.WebGPURenderer: Unknown WebGPU GPU feature: ' + name );
  472. }
  473. //
  474. return this._adapter.features.has( name );
  475. }
  476. _projectObject( object, camera, groupOrder, renderList ) {
  477. if ( object.visible === false ) return;
  478. const visible = object.layers.test( camera.layers );
  479. if ( visible ) {
  480. if ( object.isGroup ) {
  481. groupOrder = object.renderOrder;
  482. } else if ( object.isLOD ) {
  483. if ( object.autoUpdate === true ) object.update( camera );
  484. } else if ( object.isLight ) {
  485. renderList.pushLight( object );
  486. } else if ( object.isSprite ) {
  487. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  488. if ( this.sortObjects === true ) {
  489. _vector3.setFromMatrixPosition( object.matrixWorld ).applyMatrix4( _projScreenMatrix );
  490. }
  491. const geometry = object.geometry;
  492. const material = object.material;
  493. if ( material.visible ) {
  494. renderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  495. }
  496. }
  497. } else if ( object.isLineLoop ) {
  498. console.error( 'THREE.WebGPURenderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.' );
  499. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  500. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  501. const geometry = object.geometry;
  502. const material = object.material;
  503. if ( this.sortObjects === true ) {
  504. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  505. _vector3
  506. .copy( geometry.boundingSphere.center )
  507. .applyMatrix4( object.matrixWorld )
  508. .applyMatrix4( _projScreenMatrix );
  509. }
  510. if ( Array.isArray( material ) ) {
  511. const groups = geometry.groups;
  512. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  513. const group = groups[ i ];
  514. const groupMaterial = material[ group.materialIndex ];
  515. if ( groupMaterial && groupMaterial.visible ) {
  516. renderList.push( object, geometry, groupMaterial, groupOrder, _vector3.z, group );
  517. }
  518. }
  519. } else if ( material.visible ) {
  520. renderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  521. }
  522. }
  523. }
  524. }
  525. const children = object.children;
  526. for ( let i = 0, l = children.length; i < l; i ++ ) {
  527. this._projectObject( children[ i ], camera, groupOrder, renderList );
  528. }
  529. }
  530. _renderObjects( renderList, camera, scene, lightsNode ) {
  531. // process renderable objects
  532. for ( let i = 0, il = renderList.length; i < il; i ++ ) {
  533. const renderItem = renderList[ i ];
  534. // @TODO: Add support for multiple materials per object. This will require to extract
  535. // the material from the renderItem object and pass it with its group data to _renderObject().
  536. const { object, geometry, material, group } = renderItem;
  537. if ( camera.isArrayCamera ) {
  538. const cameras = camera.cameras;
  539. for ( let j = 0, jl = cameras.length; j < jl; j ++ ) {
  540. const camera2 = cameras[ j ];
  541. if ( object.layers.test( camera2.layers ) ) {
  542. const vp = camera2.viewport;
  543. const minDepth = ( vp.minDepth === undefined ) ? 0 : vp.minDepth;
  544. const maxDepth = ( vp.maxDepth === undefined ) ? 1 : vp.maxDepth;
  545. this._currentRenderState.currentPassGPU.setViewport( vp.x, vp.y, vp.width, vp.height, minDepth, maxDepth );
  546. this._renderObject( object, scene, camera2, geometry, material, group, lightsNode );
  547. }
  548. }
  549. } else {
  550. this._renderObject( object, scene, camera, geometry, material, group, lightsNode );
  551. }
  552. }
  553. }
  554. _renderObject( object, scene, camera, geometry, material, group, lightsNode ) {
  555. material = scene.overrideMaterial !== null ? scene.overrideMaterial : material;
  556. //
  557. object.onBeforeRender( this, scene, camera, geometry, material, group );
  558. //
  559. const renderObject = this._getRenderObject( object, material, scene, camera, lightsNode );
  560. //
  561. this._nodes.updateBefore( renderObject );
  562. //
  563. const passEncoder = this._currentRenderState.currentPassGPU;
  564. const info = this._info;
  565. //
  566. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  567. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  568. // updates
  569. this._nodes.update( renderObject );
  570. this._geometries.update( renderObject );
  571. this._bindings.update( renderObject );
  572. // pipeline
  573. const renderPipeline = this._renderPipelines.get( renderObject );
  574. passEncoder.setPipeline( renderPipeline.pipeline );
  575. // bind group
  576. const bindGroup = this._bindings.get( renderObject ).group;
  577. passEncoder.setBindGroup( 0, bindGroup );
  578. // index
  579. const index = this._geometries.getIndex( renderObject );
  580. const hasIndex = ( index !== null );
  581. if ( hasIndex === true ) {
  582. this._setupIndexBuffer( index, passEncoder );
  583. }
  584. // vertex buffers
  585. this._setupVertexBuffers( geometry.attributes, passEncoder, renderPipeline );
  586. // draw
  587. const drawRange = geometry.drawRange;
  588. const firstVertex = drawRange.start;
  589. const instanceCount = geometry.isInstancedBufferGeometry ? geometry.instanceCount : ( object.isInstancedMesh ? object.count : 1 );
  590. if ( hasIndex === true ) {
  591. const indexCount = ( drawRange.count !== Infinity ) ? drawRange.count : index.count;
  592. passEncoder.drawIndexed( indexCount, instanceCount, firstVertex, 0, 0 );
  593. info.update( object, indexCount, instanceCount );
  594. } else {
  595. const positionAttribute = geometry.attributes.position;
  596. const vertexCount = ( drawRange.count !== Infinity ) ? drawRange.count : positionAttribute.count;
  597. passEncoder.draw( vertexCount, instanceCount, firstVertex, 0 );
  598. info.update( object, vertexCount, instanceCount );
  599. }
  600. }
  601. _getRenderObject( object, material, scene, camera, lightsNode ) {
  602. const renderObject = this._objects.get( object, material, scene, camera, lightsNode );
  603. const renderObjectProperties = this._properties.get( renderObject );
  604. if ( renderObjectProperties.initialized !== true ) {
  605. renderObjectProperties.initialized = true;
  606. const dispose = () => {
  607. this._renderPipelines.remove( renderObject );
  608. this._nodes.remove( renderObject );
  609. this._properties.remove( renderObject );
  610. this._objects.remove( object, material, scene, camera, lightsNode );
  611. renderObject.material.removeEventListener( 'dispose', dispose );
  612. };
  613. renderObject.material.addEventListener( 'dispose', dispose );
  614. }
  615. const cacheKey = renderObject.getCacheKey();
  616. if ( renderObjectProperties.cacheKey !== cacheKey ) {
  617. renderObjectProperties.cacheKey = cacheKey;
  618. this._renderPipelines.remove( renderObject );
  619. this._nodes.remove( renderObject );
  620. }
  621. return renderObject;
  622. }
  623. _setupIndexBuffer( index, encoder ) {
  624. const buffer = this._attributes.get( index ).buffer;
  625. const indexFormat = ( index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  626. encoder.setIndexBuffer( buffer, indexFormat );
  627. }
  628. _setupVertexBuffers( geometryAttributes, encoder, renderPipeline ) {
  629. const shaderAttributes = renderPipeline.shaderAttributes;
  630. for ( const shaderAttribute of shaderAttributes ) {
  631. const name = shaderAttribute.name;
  632. const slot = shaderAttribute.slot;
  633. const attribute = geometryAttributes[ name ];
  634. if ( attribute !== undefined ) {
  635. const buffer = this._attributes.get( attribute ).buffer;
  636. encoder.setVertexBuffer( slot, buffer );
  637. }
  638. }
  639. }
  640. _setupColorBuffer() {
  641. const device = this._device;
  642. if ( device ) {
  643. if ( this._colorBuffer ) this._colorBuffer.destroy();
  644. this._colorBuffer = this._device.createTexture( {
  645. label: 'colorBuffer',
  646. size: {
  647. width: Math.floor( this._width * this._pixelRatio ),
  648. height: Math.floor( this._height * this._pixelRatio ),
  649. depthOrArrayLayers: 1
  650. },
  651. sampleCount: this._parameters.sampleCount,
  652. format: GPUTextureFormat.BGRA8Unorm,
  653. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC
  654. } );
  655. }
  656. }
  657. _setupDepthBuffer() {
  658. const device = this._device;
  659. if ( device ) {
  660. if ( this._depthBuffer ) this._depthBuffer.destroy();
  661. this._depthBuffer = this._device.createTexture( {
  662. label: 'depthBuffer',
  663. size: {
  664. width: Math.floor( this._width * this._pixelRatio ),
  665. height: Math.floor( this._height * this._pixelRatio ),
  666. depthOrArrayLayers: 1
  667. },
  668. sampleCount: this._parameters.sampleCount,
  669. format: GPUTextureFormat.Depth24PlusStencil8,
  670. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC
  671. } );
  672. }
  673. }
  674. _configureContext() {
  675. const device = this._device;
  676. if ( device ) {
  677. this._context.configure( {
  678. device: device,
  679. format: GPUTextureFormat.BGRA8Unorm,
  680. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
  681. alphaMode: 'premultiplied'
  682. } );
  683. }
  684. }
  685. _createCanvasElement() {
  686. const canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  687. canvas.style.display = 'block';
  688. return canvas;
  689. }
  690. }
  691. export default WebGPURenderer;