WebGPURenderer.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601
  1. import { GPUIndexFormat } 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 { Frustum, Matrix4, Vector3 } from '../../../../build/three.module.js';
  12. const _frustum = new Frustum();
  13. const _projScreenMatrix = new Matrix4();
  14. const _vector3 = new Vector3();
  15. class WebGPURenderer {
  16. constructor( parameters = {} ) {
  17. // public
  18. this.domElement = ( parameters.canvas !== undefined ) ? parameters.canvas : document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  19. this.parameters = parameters;
  20. this.sortObjects = true;
  21. // internals
  22. this._pixelRatio = 1;
  23. this._width = this.domElement.width;
  24. this._height = this.domElement.height;
  25. this._viewport = null;
  26. this._scissor = null;
  27. this._adapter = null;
  28. this._device = null;
  29. this._context = null;
  30. this._swapChain = null;
  31. this._depthBuffer = null;
  32. this._info = null;
  33. this._properties = null;
  34. this._attributes = null;
  35. this._geometries = null;
  36. this._bindings = null;
  37. this._objects = null;
  38. this._renderPipelines = null;
  39. this._renderLists = null;
  40. this._textures = null;
  41. this._renderPassDescriptor = null;
  42. this._currentRenderList = null;
  43. this._opaqueSort = null;
  44. this._transparentSort = null;
  45. }
  46. init() {
  47. return initWebGPU( this );
  48. }
  49. render( scene, camera ) {
  50. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  51. if ( camera.parent === null ) camera.updateMatrixWorld();
  52. if ( this._info.autoReset === true ) this._info.reset();
  53. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  54. _frustum.setFromProjectionMatrix( _projScreenMatrix );
  55. this._currentRenderList = this._renderLists.get( scene, camera );
  56. this._currentRenderList.init();
  57. this._projectObject( scene, camera, 0 );
  58. this._currentRenderList.finish();
  59. if ( this.sortObjects === true ) {
  60. this._currentRenderList.sort( this._opaqueSort, this._transparentSort );
  61. }
  62. const colorAttachment = this._renderPassDescriptor.colorAttachments[ 0 ];
  63. colorAttachment.attachment = this._swapChain.getCurrentTexture().createView();
  64. colorAttachment.loadValue = 'load';
  65. const depthStencilAttachment = this._renderPassDescriptor.depthStencilAttachment;
  66. depthStencilAttachment.attachment = this._depthBuffer.createView();
  67. const opaqueObjects = this._currentRenderList.opaque;
  68. const transparentObjects = this._currentRenderList.transparent;
  69. if ( opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera );
  70. if ( transparentObjects.length > 0 ) this._renderObjects( transparentObjects, camera );
  71. }
  72. getContext() {
  73. return this._context;
  74. }
  75. getPixelRatio() {
  76. return this._pixelRatio;
  77. }
  78. getDrawingBufferSize( target ) {
  79. return target.set( this._width * this._pixelRatio, this._height * this._pixelRatio ).floor();
  80. }
  81. getSize( target ) {
  82. return target.set( this._width, this._height );
  83. }
  84. setPixelRatio( value = 1 ) {
  85. this._pixelRatio = value;
  86. this.setSize( this._width, this._height, false );
  87. }
  88. setDrawingBufferSize( width, height, pixelRatio ) {
  89. this._width = width;
  90. this._height = height;
  91. this._pixelRatio = pixelRatio;
  92. this.domElement.width = Math.floor( width * pixelRatio );
  93. this.domElement.height = Math.floor( height * pixelRatio );
  94. this._setupDepthBuffer();
  95. }
  96. setSize( width, height, updateStyle = true ) {
  97. this._width = width;
  98. this._height = height;
  99. this.domElement.width = Math.floor( width * this._pixelRatio );
  100. this.domElement.height = Math.floor( height * this._pixelRatio );
  101. if ( updateStyle === true ) {
  102. this.domElement.style.width = width + 'px';
  103. this.domElement.style.height = height + 'px';
  104. }
  105. this._setupDepthBuffer();
  106. }
  107. setOpaqueSort( method ) {
  108. this._opaqueSort = method;
  109. }
  110. setTransparentSort( method ) {
  111. this._transparentSort = method;
  112. }
  113. getScissor( target ) {
  114. const scissor = this._scissor;
  115. target.x = scissor.x;
  116. target.y = scissor.y;
  117. target.width = scissor.width;
  118. target.height = scissor.height;
  119. return target;
  120. }
  121. setScissor( x, y, width, height ) {
  122. if ( x === null ) {
  123. this._scissor = null;
  124. } else {
  125. this._scissor = {
  126. x: x,
  127. y: y,
  128. width: width,
  129. height: height
  130. };
  131. }
  132. }
  133. getViewport( target ) {
  134. const viewport = this._viewport;
  135. target.x = viewport.x;
  136. target.y = viewport.y;
  137. target.width = viewport.width;
  138. target.height = viewport.height;
  139. target.minDepth = viewport.minDepth;
  140. target.maxDepth = viewport.maxDepth;
  141. return target;
  142. }
  143. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  144. if ( x === null ) {
  145. this._viewport = null;
  146. } else {
  147. this._viewport = {
  148. x: x,
  149. y: y,
  150. width: width,
  151. height: height,
  152. minDepth: minDepth,
  153. maxDepth: maxDepth
  154. };
  155. }
  156. }
  157. dispose() {
  158. this._objects.dispose();
  159. this._properties.dispose();
  160. this._renderPipelines.dispose();
  161. this._bindings.dispose();
  162. this._info.dispose();
  163. this._renderLists.dispose();
  164. }
  165. _projectObject( object, camera, groupOrder ) {
  166. const info = this._info;
  167. const currentRenderList = this._currentRenderList;
  168. if ( object.visible === false ) return;
  169. const visible = object.layers.test( camera.layers );
  170. if ( visible ) {
  171. if ( object.isGroup ) {
  172. groupOrder = object.renderOrder;
  173. } else if ( object.isLOD ) {
  174. if ( object.autoUpdate === true ) object.update( camera );
  175. } else if ( object.isLight ) {
  176. //currentRenderState.pushLight( object );
  177. if ( object.castShadow ) {
  178. //currentRenderState.pushShadow( object );
  179. }
  180. } else if ( object.isSprite ) {
  181. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  182. if ( this.sortObjects === true ) {
  183. _vector3.setFromMatrixPosition( object.matrixWorld ).applyMatrix4( _projScreenMatrix );
  184. }
  185. const geometry = object.geometry;
  186. const material = object.material;
  187. if ( material.visible ) {
  188. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  189. }
  190. }
  191. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  192. if ( object.isSkinnedMesh ) {
  193. // update skeleton only once in a frame
  194. if ( object.skeleton.frame !== info.render.frame ) {
  195. object.skeleton.update();
  196. object.skeleton.frame = info.render.frame;
  197. }
  198. }
  199. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  200. if ( this.sortObjects === true ) {
  201. _vector3.setFromMatrixPosition( object.matrixWorld ).applyMatrix4( _projScreenMatrix );
  202. }
  203. const geometry = object.geometry;
  204. const material = object.material;
  205. if ( Array.isArray( material ) ) {
  206. const groups = geometry.groups;
  207. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  208. const group = groups[ i ];
  209. const groupMaterial = material[ group.materialIndex ];
  210. if ( groupMaterial && groupMaterial.visible ) {
  211. currentRenderList.push( object, geometry, groupMaterial, groupOrder, _vector3.z, group );
  212. }
  213. }
  214. } else if ( material.visible ) {
  215. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  216. }
  217. }
  218. }
  219. }
  220. const children = object.children;
  221. for ( let i = 0, l = children.length; i < l; i ++ ) {
  222. this._projectObject( children[ i ], camera, groupOrder );
  223. }
  224. }
  225. _renderObjects( renderList, camera ) {
  226. for ( let i = 0, l = renderList.length; i < l; i ++ ) {
  227. const renderItem = renderList[ i ];
  228. const object = renderItem.object;
  229. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  230. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  231. this._objects.update( object );
  232. this._bindings.update( object, camera );
  233. this._renderObject( object );
  234. }
  235. }
  236. _renderObject( object ) {
  237. const device = this._device;
  238. const info = this._info;
  239. // begin
  240. const cmdEncoder = device.createCommandEncoder( {} );
  241. const passEncoder = cmdEncoder.beginRenderPass( this._renderPassDescriptor );
  242. // pipeline
  243. const pipeline = this._renderPipelines.get( object );
  244. passEncoder.setPipeline( pipeline );
  245. // rasterization
  246. const vp = this._viewport;
  247. if ( vp !== null ) {
  248. const width = Math.floor( vp.width * this._pixelRatio );
  249. const height = Math.floor( vp.height * this._pixelRatio );
  250. passEncoder.setViewport( vp.x, vp.y, width, height, vp.minDepth, vp.maxDepth );
  251. }
  252. const sc = this._scissor;
  253. if ( sc !== null ) {
  254. const width = Math.floor( sc.width * this._pixelRatio );
  255. const height = Math.floor( sc.height * this._pixelRatio );
  256. passEncoder.setScissorRect( sc.x, sc.y, width, height );
  257. }
  258. // bind group
  259. const bindGroup = this._bindings.get( object ).group;
  260. passEncoder.setBindGroup( 0, bindGroup );
  261. // index
  262. const geometry = object.geometry;
  263. const index = geometry.index;
  264. const hasIndex = ( index !== null );
  265. if ( hasIndex === true ) {
  266. this._setupIndexBuffer( passEncoder, index );
  267. }
  268. // vertex buffers
  269. this._setupVertexBuffers( passEncoder, geometry.attributes );
  270. // draw
  271. const drawRange = geometry.drawRange;
  272. const firstVertex = drawRange.start;
  273. if ( hasIndex === true ) {
  274. const indexCount = ( drawRange.count !== Infinity ) ? drawRange.count : index.count;
  275. passEncoder.drawIndexed( indexCount, 1, firstVertex, 0, 0 );
  276. info.update( object, indexCount );
  277. } else {
  278. const positionAttribute = geometry.attributes.position;
  279. const vertexCount = ( drawRange.count !== Infinity ) ? drawRange.count : positionAttribute.count;
  280. passEncoder.draw( vertexCount, 1, firstVertex, 0 );
  281. info.update( object, vertexCount );
  282. }
  283. // end
  284. passEncoder.endPass();
  285. device.defaultQueue.submit( [ cmdEncoder.finish() ] );
  286. }
  287. _setupIndexBuffer( encoder, index ) {
  288. const buffer = this._attributes.get( index ).buffer;
  289. const indexFormat = ( index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  290. encoder.setIndexBuffer( buffer, indexFormat );
  291. }
  292. _setupVertexBuffers( encoder, geometryAttributes ) {
  293. let slot = 0;
  294. for ( const name in geometryAttributes ) {
  295. const attribute = geometryAttributes[ name ];
  296. const buffer = this._attributes.get( attribute ).buffer;
  297. encoder.setVertexBuffer( slot, buffer );
  298. slot ++;
  299. }
  300. }
  301. _setupDepthBuffer() {
  302. const device = this._device;
  303. if ( device ) {
  304. if ( this._depthBuffer ) this._depthBuffer.destroy();
  305. this._depthBuffer = this._device.createTexture( {
  306. size: {
  307. width: this._width * this._pixelRatio,
  308. height: this._height * this._pixelRatio,
  309. depth: 1
  310. },
  311. format: 'depth24plus-stencil8',
  312. usage: GPUTextureUsage.OUTPUT_ATTACHMENT
  313. } );
  314. }
  315. }
  316. }
  317. async function initWebGPU( scope ) {
  318. const parameters = scope.parameters;
  319. const adapterOptions = {
  320. powerPreference: ( parameters.powerPreference !== undefined ) ? parameters.powerPreference : undefined
  321. };
  322. const adapter = await navigator.gpu.requestAdapter( adapterOptions );
  323. const deviceDescriptor = {
  324. enabledExtensions: ( parameters.enabledExtensions !== undefined ) ? parameters.enabledExtensions : [],
  325. limits: ( parameters.limits !== undefined ) ? parameters.limits : {}
  326. };
  327. const device = await adapter.requestDevice( deviceDescriptor );
  328. const glslang = await import( 'https://cdn.jsdelivr.net/npm/@webgpu/[email protected]/dist/web-devel/glslang.js' );
  329. const compiler = await glslang.default();
  330. const context = ( parameters.context !== undefined ) ? parameters.context : scope.domElement.getContext( 'gpupresent' );
  331. const swapChain = context.configureSwapChain( {
  332. device: device,
  333. format: 'bgra8unorm'
  334. } );
  335. scope._adapter = adapter;
  336. scope._device = device;
  337. scope._context = context;
  338. scope._swapChain = swapChain;
  339. scope._info = new WebGPUInfo();
  340. scope._properties = new WebGPUProperties();
  341. scope._attributes = new WebGPUAttributes( device );
  342. scope._geometries = new WebGPUGeometries( scope._attributes, scope._info );
  343. scope._textures = new WebGPUTextures( device, scope._properties );
  344. scope._bindings = new WebGPUBindings( device, scope._info, scope._properties, scope._textures );
  345. scope._objects = new WebGPUObjects( scope._geometries, scope._info );
  346. scope._renderPipelines = new WebGPURenderPipelines( device, compiler, scope._bindings );
  347. scope._renderLists = new WebGPURenderLists();
  348. //
  349. scope._renderPassDescriptor = {
  350. colorAttachments: [ {
  351. attachment: null
  352. } ],
  353. depthStencilAttachment: {
  354. attachment: null,
  355. depthLoadValue: 1,
  356. depthStoreOp: 'store',
  357. stencilLoadValue: 0,
  358. stencilStoreOp: 'store'
  359. }
  360. };
  361. scope._setupDepthBuffer();
  362. }
  363. export default WebGPURenderer;