WebGPURenderer.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766
  1. import { GPUIndexFormat, GPUTextureFormat, GPUStoreOp } from './constants.js';
  2. import WebGPUObjects from './WebGPUObjects.js';
  3. import WebGPUAttributes from './WebGPUAttributes.js';
  4. import WebGPUGeometries from './WebGPUGeometries.js';
  5. import WebGPUInfo from './WebGPUInfo.js';
  6. import WebGPUProperties from './WebGPUProperties.js';
  7. import WebGPURenderPipelines from './WebGPURenderPipelines.js';
  8. import WebGPUBindings from './WebGPUBindings.js';
  9. import WebGPURenderLists from './WebGPURenderLists.js';
  10. import WebGPUTextures from './WebGPUTextures.js';
  11. import WebGPUBackground from './WebGPUBackground.js';
  12. import { Frustum, Matrix4, Vector3, Color } from '../../../../build/three.module.js';
  13. const _frustum = new Frustum();
  14. const _projScreenMatrix = new Matrix4();
  15. const _vector3 = new Vector3();
  16. class WebGPURenderer {
  17. constructor( parameters = {} ) {
  18. // public
  19. this.domElement = ( parameters.canvas !== undefined ) ? parameters.canvas : document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  20. this.parameters = Object.assign( {}, parameters );
  21. this.autoClear = true;
  22. this.autoClearColor = true;
  23. this.autoClearDepth = true;
  24. this.autoClearStencil = true;
  25. this.sortObjects = true;
  26. // internals
  27. this._pixelRatio = 1;
  28. this._width = this.domElement.width;
  29. this._height = this.domElement.height;
  30. this._viewport = null;
  31. this._scissor = null;
  32. this._adapter = null;
  33. this._device = null;
  34. this._context = null;
  35. this._swapChain = null;
  36. this._colorBuffer = null;
  37. this._depthBuffer = null;
  38. this._info = null;
  39. this._properties = null;
  40. this._attributes = null;
  41. this._geometries = null;
  42. this._bindings = null;
  43. this._objects = null;
  44. this._renderPipelines = null;
  45. this._renderLists = null;
  46. this._textures = null;
  47. this._background = null;
  48. this._renderPassDescriptor = null;
  49. this._currentRenderList = null;
  50. this._opaqueSort = null;
  51. this._transparentSort = null;
  52. this._clearAlpha = 1;
  53. this._clearColor = new Color( 0x000000 );
  54. this._clearDepth = 1;
  55. this._clearStencil = 0;
  56. this._renderTarget = null;
  57. // ensure some parameters
  58. this.parameters.antialias = ( this.parameters.antialias === true );
  59. if ( this.parameters.antialias === true ) {
  60. this.parameters.sampleCount = this.parameters.sampleCount || 4;
  61. } else {
  62. this.parameters.sampleCount = 1;
  63. }
  64. }
  65. init() {
  66. return initWebGPU( this );
  67. }
  68. render( scene, camera ) {
  69. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  70. if ( camera.parent === null ) camera.updateMatrixWorld();
  71. if ( this._info.autoReset === true ) this._info.reset();
  72. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  73. _frustum.setFromProjectionMatrix( _projScreenMatrix );
  74. this._currentRenderList = this._renderLists.get( scene, camera );
  75. this._currentRenderList.init();
  76. this._projectObject( scene, camera, 0 );
  77. this._currentRenderList.finish();
  78. if ( this.sortObjects === true ) {
  79. this._currentRenderList.sort( this._opaqueSort, this._transparentSort );
  80. }
  81. // prepare render pass descriptor
  82. const colorAttachment = this._renderPassDescriptor.colorAttachments[ 0 ];
  83. const depthStencilAttachment = this._renderPassDescriptor.depthStencilAttachment;
  84. const renderTarget = this._renderTarget;
  85. if ( renderTarget !== null ) {
  86. // @TODO: Support RenderTarget with antialiasing.
  87. const renderTargetProperties = this._properties.get( renderTarget );
  88. colorAttachment.attachment = renderTargetProperties.colorTextureGPU.createView();
  89. depthStencilAttachment.attachment = renderTargetProperties.depthTextureGPU.createView();
  90. } else {
  91. if ( this.parameters.antialias ) {
  92. colorAttachment.attachment = this._colorBuffer.createView();
  93. colorAttachment.resolveTarget = this._swapChain.getCurrentTexture().createView();
  94. colorAttachment.storeOp = GPUStoreOp.Clear;
  95. } else {
  96. colorAttachment.attachment = this._swapChain.getCurrentTexture().createView();
  97. colorAttachment.resolveTarget = undefined;
  98. colorAttachment.storeOp = undefined;
  99. }
  100. depthStencilAttachment.attachment = this._depthBuffer.createView();
  101. }
  102. //
  103. this._background.update( scene );
  104. // start render pass
  105. const device = this._device;
  106. const cmdEncoder = device.createCommandEncoder( {} );
  107. const passEncoder = cmdEncoder.beginRenderPass( this._renderPassDescriptor );
  108. // global rasterization settings for all renderable objects
  109. const vp = this._viewport;
  110. if ( vp !== null ) {
  111. const width = Math.floor( vp.width * this._pixelRatio );
  112. const height = Math.floor( vp.height * this._pixelRatio );
  113. passEncoder.setViewport( vp.x, vp.y, width, height, vp.minDepth, vp.maxDepth );
  114. }
  115. const sc = this._scissor;
  116. if ( sc !== null ) {
  117. const width = Math.floor( sc.width * this._pixelRatio );
  118. const height = Math.floor( sc.height * this._pixelRatio );
  119. passEncoder.setScissorRect( sc.x, sc.y, width, height );
  120. }
  121. // process render lists
  122. const opaqueObjects = this._currentRenderList.opaque;
  123. const transparentObjects = this._currentRenderList.transparent;
  124. if ( opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, passEncoder );
  125. if ( transparentObjects.length > 0 ) this._renderObjects( transparentObjects, camera, passEncoder );
  126. // finish render pass
  127. passEncoder.endPass();
  128. device.defaultQueue.submit( [ cmdEncoder.finish() ] );
  129. }
  130. getContext() {
  131. return this._context;
  132. }
  133. getPixelRatio() {
  134. return this._pixelRatio;
  135. }
  136. getDrawingBufferSize( target ) {
  137. return target.set( this._width * this._pixelRatio, this._height * this._pixelRatio ).floor();
  138. }
  139. getSize( target ) {
  140. return target.set( this._width, this._height );
  141. }
  142. setPixelRatio( value = 1 ) {
  143. this._pixelRatio = value;
  144. this.setSize( this._width, this._height, false );
  145. }
  146. setDrawingBufferSize( width, height, pixelRatio ) {
  147. this._width = width;
  148. this._height = height;
  149. this._pixelRatio = pixelRatio;
  150. this.domElement.width = Math.floor( width * pixelRatio );
  151. this.domElement.height = Math.floor( height * pixelRatio );
  152. this._setupColorBuffer();
  153. this._setupDepthBuffer();
  154. }
  155. setSize( width, height, updateStyle = true ) {
  156. this._width = width;
  157. this._height = height;
  158. this.domElement.width = Math.floor( width * this._pixelRatio );
  159. this.domElement.height = Math.floor( height * this._pixelRatio );
  160. if ( updateStyle === true ) {
  161. this.domElement.style.width = width + 'px';
  162. this.domElement.style.height = height + 'px';
  163. }
  164. this._setupColorBuffer();
  165. this._setupDepthBuffer();
  166. }
  167. setOpaqueSort( method ) {
  168. this._opaqueSort = method;
  169. }
  170. setTransparentSort( method ) {
  171. this._transparentSort = method;
  172. }
  173. getScissor( target ) {
  174. const scissor = this._scissor;
  175. target.x = scissor.x;
  176. target.y = scissor.y;
  177. target.width = scissor.width;
  178. target.height = scissor.height;
  179. return target;
  180. }
  181. setScissor( x, y, width, height ) {
  182. if ( x === null ) {
  183. this._scissor = null;
  184. } else {
  185. this._scissor = {
  186. x: x,
  187. y: y,
  188. width: width,
  189. height: height
  190. };
  191. }
  192. }
  193. getViewport( target ) {
  194. const viewport = this._viewport;
  195. target.x = viewport.x;
  196. target.y = viewport.y;
  197. target.width = viewport.width;
  198. target.height = viewport.height;
  199. target.minDepth = viewport.minDepth;
  200. target.maxDepth = viewport.maxDepth;
  201. return target;
  202. }
  203. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  204. if ( x === null ) {
  205. this._viewport = null;
  206. } else {
  207. this._viewport = {
  208. x: x,
  209. y: y,
  210. width: width,
  211. height: height,
  212. minDepth: minDepth,
  213. maxDepth: maxDepth
  214. };
  215. }
  216. }
  217. getClearColor() {
  218. return this._clearColor;
  219. }
  220. setClearColor( color, alpha = 1 ) {
  221. this._clearColor.set( color );
  222. this._clearAlpha = alpha;
  223. }
  224. getClearAlpha() {
  225. return this._clearAlpha;
  226. }
  227. setClearAlpha( alpha ) {
  228. this._clearAlpha = alpha;
  229. }
  230. getClearDepth() {
  231. return this._clearDepth;
  232. }
  233. setClearDepth( depth ) {
  234. this._clearDepth = depth;
  235. }
  236. getClearStencil() {
  237. return this._clearStencil;
  238. }
  239. setClearStencil( stencil ) {
  240. this._clearStencil = stencil;
  241. }
  242. clear() {
  243. this._background.clear();
  244. }
  245. dispose() {
  246. this._objects.dispose();
  247. this._properties.dispose();
  248. this._renderPipelines.dispose();
  249. this._bindings.dispose();
  250. this._info.dispose();
  251. this._renderLists.dispose();
  252. this._textures.dispose();
  253. }
  254. setRenderTarget( renderTarget ) {
  255. this._renderTarget = renderTarget;
  256. if ( renderTarget !== null ) {
  257. this._textures.initRenderTarget( renderTarget );
  258. }
  259. }
  260. _projectObject( object, camera, groupOrder ) {
  261. const info = this._info;
  262. const currentRenderList = this._currentRenderList;
  263. if ( object.visible === false ) return;
  264. const visible = object.layers.test( camera.layers );
  265. if ( visible ) {
  266. if ( object.isGroup ) {
  267. groupOrder = object.renderOrder;
  268. } else if ( object.isLOD ) {
  269. if ( object.autoUpdate === true ) object.update( camera );
  270. } else if ( object.isLight ) {
  271. //currentRenderState.pushLight( object );
  272. if ( object.castShadow ) {
  273. //currentRenderState.pushShadow( object );
  274. }
  275. } else if ( object.isSprite ) {
  276. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  277. if ( this.sortObjects === true ) {
  278. _vector3.setFromMatrixPosition( object.matrixWorld ).applyMatrix4( _projScreenMatrix );
  279. }
  280. const geometry = object.geometry;
  281. const material = object.material;
  282. if ( material.visible ) {
  283. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  284. }
  285. }
  286. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  287. if ( object.isSkinnedMesh ) {
  288. // update skeleton only once in a frame
  289. if ( object.skeleton.frame !== info.render.frame ) {
  290. object.skeleton.update();
  291. object.skeleton.frame = info.render.frame;
  292. }
  293. }
  294. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  295. if ( this.sortObjects === true ) {
  296. _vector3.setFromMatrixPosition( object.matrixWorld ).applyMatrix4( _projScreenMatrix );
  297. }
  298. const geometry = object.geometry;
  299. const material = object.material;
  300. if ( Array.isArray( material ) ) {
  301. const groups = geometry.groups;
  302. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  303. const group = groups[ i ];
  304. const groupMaterial = material[ group.materialIndex ];
  305. if ( groupMaterial && groupMaterial.visible ) {
  306. currentRenderList.push( object, geometry, groupMaterial, groupOrder, _vector3.z, group );
  307. }
  308. }
  309. } else if ( material.visible ) {
  310. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  311. }
  312. }
  313. }
  314. }
  315. const children = object.children;
  316. for ( let i = 0, l = children.length; i < l; i ++ ) {
  317. this._projectObject( children[ i ], camera, groupOrder );
  318. }
  319. }
  320. _renderObjects( renderList, camera, passEncoder ) {
  321. // process renderable objects
  322. for ( let i = 0, l = renderList.length; i < l; i ++ ) {
  323. const renderItem = renderList[ i ];
  324. const object = renderItem.object;
  325. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  326. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  327. this._objects.update( object );
  328. this._bindings.update( object, camera );
  329. this._renderObject( object, passEncoder );
  330. }
  331. }
  332. _renderObject( object, passEncoder ) {
  333. const info = this._info;
  334. // pipeline
  335. const pipeline = this._renderPipelines.get( object );
  336. passEncoder.setPipeline( pipeline );
  337. // bind group
  338. const bindGroup = this._bindings.get( object ).group;
  339. passEncoder.setBindGroup( 0, bindGroup );
  340. // index
  341. const geometry = object.geometry;
  342. const index = geometry.index;
  343. const hasIndex = ( index !== null );
  344. if ( hasIndex === true ) {
  345. this._setupIndexBuffer( index, passEncoder );
  346. }
  347. // vertex buffers
  348. this._setupVertexBuffers( geometry.attributes, passEncoder, pipeline );
  349. // draw
  350. const drawRange = geometry.drawRange;
  351. const firstVertex = drawRange.start;
  352. if ( hasIndex === true ) {
  353. const indexCount = ( drawRange.count !== Infinity ) ? drawRange.count : index.count;
  354. passEncoder.drawIndexed( indexCount, 1, firstVertex, 0, 0 );
  355. info.update( object, indexCount );
  356. } else {
  357. const positionAttribute = geometry.attributes.position;
  358. const vertexCount = ( drawRange.count !== Infinity ) ? drawRange.count : positionAttribute.count;
  359. passEncoder.draw( vertexCount, 1, firstVertex, 0 );
  360. info.update( object, vertexCount );
  361. }
  362. }
  363. _setupIndexBuffer( index, encoder ) {
  364. const buffer = this._attributes.get( index ).buffer;
  365. const indexFormat = ( index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  366. encoder.setIndexBuffer( buffer, indexFormat );
  367. }
  368. _setupVertexBuffers( geometryAttributes, encoder, pipeline ) {
  369. const shaderAttributes = this._renderPipelines.getShaderAttributes( pipeline );
  370. for ( const shaderAttribute of shaderAttributes ) {
  371. const name = shaderAttribute.name;
  372. const slot = shaderAttribute.slot;
  373. const attribute = geometryAttributes[ name ];
  374. if ( attribute !== undefined ) {
  375. const buffer = this._attributes.get( attribute ).buffer;
  376. encoder.setVertexBuffer( slot, buffer );
  377. }
  378. }
  379. }
  380. _setupColorBuffer() {
  381. const device = this._device;
  382. if ( device ) {
  383. if ( this._colorBuffer ) this._colorBuffer.destroy();
  384. this._colorBuffer = this._device.createTexture( {
  385. size: {
  386. width: this._width * this._pixelRatio,
  387. height: this._height * this._pixelRatio,
  388. depth: 1
  389. },
  390. sampleCount: this.parameters.sampleCount,
  391. format: GPUTextureFormat.BRGA8Unorm,
  392. usage: GPUTextureUsage.OUTPUT_ATTACHMENT
  393. } );
  394. }
  395. }
  396. _setupDepthBuffer() {
  397. const device = this._device;
  398. if ( device ) {
  399. if ( this._depthBuffer ) this._depthBuffer.destroy();
  400. this._depthBuffer = this._device.createTexture( {
  401. size: {
  402. width: this._width * this._pixelRatio,
  403. height: this._height * this._pixelRatio,
  404. depth: 1
  405. },
  406. sampleCount: this.parameters.sampleCount,
  407. format: GPUTextureFormat.Depth24PlusStencil8,
  408. usage: GPUTextureUsage.OUTPUT_ATTACHMENT
  409. } );
  410. }
  411. }
  412. }
  413. async function initWebGPU( scope ) {
  414. const parameters = scope.parameters;
  415. const adapterOptions = {
  416. powerPreference: ( parameters.powerPreference !== undefined ) ? parameters.powerPreference : undefined
  417. };
  418. const adapter = await navigator.gpu.requestAdapter( adapterOptions );
  419. const deviceDescriptor = {
  420. enabledExtensions: ( parameters.enabledExtensions !== undefined ) ? parameters.enabledExtensions : [],
  421. limits: ( parameters.limits !== undefined ) ? parameters.limits : {}
  422. };
  423. const device = await adapter.requestDevice( deviceDescriptor );
  424. const glslang = await import( 'https://cdn.jsdelivr.net/npm/@webgpu/[email protected]/dist/web-devel/glslang.js' );
  425. const compiler = await glslang.default();
  426. const context = ( parameters.context !== undefined ) ? parameters.context : scope.domElement.getContext( 'gpupresent' );
  427. const swapChain = context.configureSwapChain( {
  428. device: device,
  429. format: GPUTextureFormat.BRGA8Unorm
  430. } );
  431. scope._adapter = adapter;
  432. scope._device = device;
  433. scope._context = context;
  434. scope._swapChain = swapChain;
  435. scope._info = new WebGPUInfo();
  436. scope._properties = new WebGPUProperties();
  437. scope._attributes = new WebGPUAttributes( device );
  438. scope._geometries = new WebGPUGeometries( scope._attributes, scope._info );
  439. scope._textures = new WebGPUTextures( device, scope._properties, scope._info, compiler );
  440. scope._bindings = new WebGPUBindings( device, scope._info, scope._properties, scope._textures );
  441. scope._objects = new WebGPUObjects( scope._geometries, scope._info );
  442. scope._renderPipelines = new WebGPURenderPipelines( device, compiler, scope._bindings, scope.parameters.sampleCount );
  443. scope._renderLists = new WebGPURenderLists();
  444. scope._background = new WebGPUBackground( scope );
  445. //
  446. scope._renderPassDescriptor = {
  447. colorAttachments: [ {
  448. attachment: null
  449. } ],
  450. depthStencilAttachment: {
  451. attachment: null,
  452. depthStoreOp: GPUStoreOp.Store,
  453. stencilStoreOp: GPUStoreOp.Store
  454. }
  455. };
  456. scope._setupColorBuffer();
  457. scope._setupDepthBuffer();
  458. }
  459. export default WebGPURenderer;