GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — three-rs/examples/webgpu_deferred.rs at main · oneilltomhq/three-rs Expand file tree/ Copy pathwebgpu_deferred.rsMore file actions 451 lines (395 loc) · 19.1 KB / Copy pathwebgpu_deferred.rsFile metadata and controls451 lines (395 loc) · 19.1 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 //! Port of `three.js/examples/webgpu_deferred.html`, calling the three-rs API //! in the same order the page's `init()` and its UltraHDR callback do. //! //! Under the e2e harness the viewport is `400 * 2` x `250 * 2` with no //! `deviceScaleFactor`, so `window.innerWidth` / `innerHeight` / //! `devicePixelRatio` are 800, 500 and 1. `timer.getDelta()` is zero on the //! graded frame — the harness freezes `performance.now` — so the light group //! and the plane group are at the poses `init()` left them in. //! //! # The frame //! //! Four `pass( scene, camera )` nodes over one scene, told apart by the camera //! layer mask each renders with and by the renderer switches each sets. Three //! of them run (the page's `forwardPass` is only reachable through the GUI's //! `mode: 'forward'`, and `renderPipeline.outputNode` never references it, so //! three.js never fires its `updateBefore` either): //! //! 1. **the opaque pass** — layer 0, `transparent = false`, `lighting.enabled //! = false`, with an MRT that writes a three-attachment G-buffer: //! `output = diffuseColor`, `position = vec4( positionView, metalness )`, //! `normal = vec4( normalView, roughness )`. Unlit, so `Output` is just the //! emissive; nothing reads it. This is the pass that owns the depth //! attachment. //! 2. **the resolve pass** — layer 2 only, which is where the full-screen //! quad lives and where the eight point lights are also enabled. The quad's //! `MeshStandardNodeMaterial` reads the G-buffer back and runs the standard //! lighting flow over it: `colorNode` is the `output` attachment behind a //! `discard` on depth 1, `metalnessNode` / `roughnessNode` are the `.w` //! channels of the other two, and `contextNode = overrideNodes( … )` swaps //! `positionView`, `positionViewDirection` and `normalView` for the //! G-buffer values. `depthNode` writes the opaque depth back out through //! `@builtin( frag_depth )`. //! 3. **the transparent pass** — layer 0, `opaque = false`, sharing the opaque //! pass's `depthTexture` with `autoClearDepth: false`, so the six planes //! depth-test against geometry this pass never drew. `opaque = false` also //! drops the skybox, because `Background.update()` unshifts it into //! `renderList.opaque`. //! //! The composite is `vec4( opaque.rgb * ( 1 - transparent.a ) + transparent.rgb, //! 1 )` — the planes are premultiplied by their own pass's blend. //! //! # What is new here //! //! `docs/nodes.md` §27 covers all of it: `frag_depth`, `overrideNodes()`, the //! `metalnessNode` / `roughnessNode` seam, the pass-scoped `opaque` / //! `transparent` / `lighting` / layer switches, a pass that borrows another //! pass's depth attachment, and `_renderObjectDirect()`'s two-draw split of a //! transparent `DoubleSide` material (the planes: a `BackSide` draw and then a //! `FrontSide` one, per object). use std::cell::RefCell; use std::rc::Rc; use three_rs::addons::controls::OrbitControls; use three_rs::core::Layers; use three_rs::geometries::{plane_geometry, quad_geometry, sphere_geometry, teapot_geometry}; use three_rs::loaders::UltraHdrLoader; use three_rs::materials::{MeshStandardNodeMaterial, Side, ToneMapping}; use three_rs::math::ColorSpace; use three_rs::nodes::mrt; use three_rs::nodes::pmrem_node::PmremEnvironment; use three_rs::nodes::tsl::{ diffuse_color, discard, float, if_then, metalness, normal_view, position_geometry, position_view, roughness, vec4_join, OverrideNodes, }; use three_rs::objects::Background; use three_rs::renderer::{cube_render_target, PassOptions}; use three_rs::Timer; use three_rs::{ pass, Color, Group, Mesh, PassNode, PerspectiveCamera, PointLight, RenderPipeline, Renderer, RendererParameters, Scene, }; pub const INNER_WIDTH: f64 = 800.0; pub const INNER_HEIGHT: f64 = 500.0; /// `renderer.setPixelRatio( window.devicePixelRatio )`. pub const DPR: f64 = 1.0; /// `const RESOLVE_LAYER = 2`. const RESOLVE_LAYER: u32 = 2; fn examples_dir() -> std::path::PathBuf { three_rs::testing::three_js_dir().join("examples") } pub struct App { pub renderer: Renderer, /// Shared with the three passes, which render it from `updateBefore()`. pub scene: Rc<RefCell<Scene>>, /// Shared with the three passes. pub camera: Rc<RefCell<PerspectiveCamera>>, pub environment: PmremEnvironment, /// The page's `lightGroup`, turned by `render()`. pub light_group: three_rs::ObjectRef, /// The page's `planesGroup`, turned the other way. pub planes_group: three_rs::ObjectRef, /// The page's module-level `timer`. pub timer: Timer, pub opaque_pass: PassNode, pub resolved_pass: PassNode, pub transparent_pass: PassNode, pub render_pipeline: RenderPipeline, /// The page's `controls`. pub controls: OrbitControls, } pub fn init() -> App { // `new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, // 0.25, 20 ); camera.position.set( - 1.8, 0.6, 2.7 )`. let camera = PerspectiveCamera::new(45.0, INNER_WIDTH / INNER_HEIGHT, 0.25, 20.0); camera.node.borrow_mut().position.set(-1.8, 0.6, 2.7); let mut scene = Scene::new(); // `new THREE.WebGPURenderer()` — no `antialias`, so every pass target is // single-sampled and the shared depth attachment is a plain // `texture_depth_2d`. let mut renderer = Renderer::new(RendererParameters::default()).unwrap(); renderer.set_pixel_ratio(DPR); renderer.set_size(INNER_WIDTH, INNER_HEIGHT); // `renderer.toneMapping = THREE.ACESFilmicToneMapping`. renderer.tone_mapping = ToneMapping::AcesFilmic; // `new UltraHDRLoader().setPath( 'textures/equirectangular/' ).load( // 'royal_esplanade_2k.hdr.jpg', … )`. The loader resolves synchronously // here, so the callback's body is written inline — and it is the callback // that adds the teapot, so nothing else in `init()` depends on it. let texture = UltraHdrLoader::new() .load(examples_dir().join("textures/equirectangular/royal_esplanade_2k.hdr.jpg")) .unwrap(); // `texture.mapping = THREE.EquirectangularReflectionMapping; scene.background // = texture`: at `backgroundBlurriness` 0 an equirectangular background is // not a PMREM (`NodeManager.updateBackground()` takes `pmremTexture` only // for blurriness or `isPMREMTexture`), so `CubeMapNode` converts it into a // cube once and the skybox samples that. let background = cube_render_target::from_equirectangular_texture(&mut renderer, &texture) .expect("the equirectangular background converts to a cube"); scene.background = Some(Background::CubeTexture(background)); // `scene.environment = texture`: the same map, PMREM-filtered. let mut environment = PmremEnvironment::from_equirectangular(&texture); environment.update(&mut renderer).unwrap(); scene.environment = Some(environment.handle()); // `const teapotGeometry = new TeapotGeometry( 0.4, 18 ); … teapot.position.y // = - 0.15`. let teapot_material = MeshStandardNodeMaterial::standard(Color::from_hex(0x333333), 0.2, 0.8); let teapot = Mesh::new(Rc::new(teapot_geometry(0.4, 18)), teapot_material); teapot.borrow_mut().position.y = -0.15; scene.add(&teapot); // light group let light_group = Group::new(); light_group.borrow_mut().position.y = -0.15; scene.add(&light_group); let num_lights = 8; let radius = 1.2; let sphere = Rc::new(sphere_geometry(0.03, 16, 8)); for i in 0..num_lights { let angle = (i as f64 / num_lights as f64) * std::f64::consts::PI * 2.0; let x = angle.cos() * radius; let z = angle.sin() * radius; // `new THREE.Color().setHSL( i / numLights, 1.0, 0.5 )` — `setHSL`'s // default `colorSpace` is `ColorManagement.workingColorSpace`, i.e. // linear-sRGB: the HSL triple is taken as working-space values and is // *not* converted. let mut color_hex = Color::default(); color_hex.set_hsl( i as f64 / num_lights as f64, 1.0, 0.5, ColorSpace::LinearSrgb, ); let light_mat = MeshStandardNodeMaterial::standard(color_hex, 1.0, 0.0); let light_mesh = Mesh::new(sphere.clone(), light_mat); // `new THREE.PointLight( colorHex, 5, 5 ); light.layers.enable( // RESOLVE_LAYER )` — the lights are the only objects on *both* layers, // which is what lets the resolve pass see them and nothing else. let light = PointLight::new(color_hex, 5.0, 5.0); light.borrow_mut().layers.enable(RESOLVE_LAYER); light.borrow_mut().position.set(x, 0.0, z); light.add(&light_mesh); light_group.add(&light); } // planes group let planes_group = Group::new(); planes_group.borrow_mut().position.y = -0.15; scene.add(&planes_group); let plane = Rc::new(plane_geometry(0.4, 0.4, 1, 1)); let mut plane_material = MeshStandardNodeMaterial::standard(Color::from_hex(0x999999), 0.5, 0.5); plane_material.side = Side::Double; plane_material.transparent = true; plane_material.opacity = 0.5; let num_planes = 6; let planes_radius = 1.5; for i in 0..num_planes { let angle = (i as f64 / num_planes as f64) * std::f64::consts::PI * 2.0; let pivot = Group::new(); // `pivot.rotation.y = angle` — three's `Euler.onChange` updates the // quaternion, which is what `set_rotation` is here. pivot.borrow_mut().set_rotation(0.0, angle, 0.0); planes_group.add(&pivot); let mesh = Mesh::new(plane.clone(), plane_material.clone()); mesh.borrow_mut().position.z = planes_radius; pivot.add(&mesh); } // `pass( scene, camera )`: the passes below hold both and the renderer // renders each the first time a draw samples its texture, in whatever // order that pulls them (`docs/nodes.md` §57). let scene = Rc::new(RefCell::new(scene)); let camera = Rc::new(RefCell::new(camera)); // opaque pass // `const opaquePass = pass( scene, camera ); opaquePass.transparent = // false; opaquePass.setLayers( new THREE.Layers() )`. let mut opaque_pass = pass(scene.clone(), camera.clone()); opaque_pass.set_transparent(false); opaque_pass.set_layers(Layers::new()); // `opaquePass.setMRT( mrt( { output: diffuseColor, position: vec4( // positionView, metalness ), normal: vec4( normalView, roughness ) } ) )`. // // `positionView` and `normalView` are node objects upstream, so their // `setup()` runs once per material and reads that material's side and // normal map; the port's TSL is eager, so both go in as closures // (`docs/nodes.md` §23.2). let mut g_buffer = mrt(vec![("output", diffuse_color())]); g_buffer.set_deferred("position", || vec4_join(vec![position_view(), metalness()])); g_buffer.set_deferred("normal", || vec4_join(vec![normal_view(), roughness()])); opaque_pass.set_mrt(g_buffer); // `opaquePass.lighting = new THREE.Lighting(); opaquePass.lighting.enabled // = false` — the G-buffer holds unlit `diffuseColor`. opaque_pass.set_lighting_enabled(false); // opaque nodes let opaque_output_node = opaque_pass.texture_node("output"); let opaque_position_view = opaque_pass.texture_node("position").xyz(); let opaque_normal_view = opaque_pass.texture_node("normal").xyz(); let opaque_depth_node = opaque_pass.texture_node("depth"); let opaque_metalness = opaque_pass.texture_node("position").w(); let opaque_roughness = opaque_pass.texture_node("normal").w(); // resolve opaque pass - deferred lighting let mut resolve_layers = Layers::new(); resolve_layers.disable_all(); resolve_layers.enable(RESOLVE_LAYER); // the resolve material must be compatible with the other materials in the // scene; in common deferred rendering scenarios, a standardized material // is used. let mut resolve_material = MeshStandardNodeMaterial::standard(Color::new(1.0, 1.0, 1.0), 1.0, 0.0); // `Fn( () => { opaqueDepthNode.greaterThanEqual( 1.0 ).discard(); return // opaqueOutputNode; } )()` — a cleared depth means nothing opaque was // drawn there, so the quad leaves the pass's own clear alone. resolve_material.color_node = Some(three_rs::nodes::tsl::block( vec![if_then( opaque_depth_node.greater_than_equal(float(1.0)), vec![discard()], )], opaque_output_node, )); resolve_material.metalness_node = Some(opaque_metalness); resolve_material.roughness_node = Some(opaque_roughness); // `resolveMaterial.vertexNode = vec4( positionGeometry.xy, 0.0, 1.0 )`. resolve_material.vertex_node = Some(vec4_join(vec![ position_geometry().xy(), float(0.0), float(1.0), ])); resolve_material.depth_node = Some(opaque_depth_node.clone()); let mut overrides = OverrideNodes::default(); overrides.position_view = Some(opaque_position_view.clone()); overrides.position_view_direction = Some(opaque_position_view.negate().normalize()); overrides.normal_view = Some(opaque_normal_view); resolve_material.context_overrides = Some(overrides); // `const resolveMesh = new THREE.QuadMesh( resolveMaterial ); // resolveMesh.layers.set( RESOLVE_LAYER ); scene.add( resolveMesh )` — // a `QuadMesh` is a `Mesh` over `QuadGeometry`, and here it goes into the // scene graph rather than being rendered on its own. let resolve_mesh = Mesh::new(Rc::new(quad_geometry()), resolve_material); resolve_mesh.borrow_mut().layers.set(RESOLVE_LAYER); scene.borrow().add(&resolve_mesh); // `const resolvedPass = pass( scene, camera ); resolvedPass.setLayers( // resolveLayers ); resolvedPass.lighting = new THREE.Lighting()`. let resolved_pass = pass(scene.clone(), camera.clone()); resolved_pass.set_layers(resolve_layers); // transparent pass // `pass( scene, camera, { depthTexture: opaquePass.getTexture( 'depth' ), // autoClearDepth: false } )` — the opaque pass is the one registered as // the depth texture's producer; this pass only reuses it. let mut options = PassOptions::default(); options.depth_texture = Some(opaque_pass.depth_texture()); options.auto_clear_depth = false; let mut transparent_pass = PassNode::new_with_options(options); transparent_pass.set_scene(scene.clone(), camera.clone()); transparent_pass.set_layers(Layers::new()); transparent_pass.set_opaque(false); // resolved - render pipeline // `vec4( opaqueNode.rgb.mul( transparentNode.a.oneMinus() ).add( // transparentNode.rgb ), 1.0 )`. let opaque_node = resolved_pass.node(); let transparent_node = transparent_pass.node(); let deferred_node = vec4_join(vec![ opaque_node .rgb() .mul(transparent_node.a().one_minus()) .add(transparent_node.rgb()), float(1.0), ]); let mut render_pipeline = RenderPipeline::new(); render_pipeline.output_node = Some(deferred_node); // controls // `const controls = new OrbitControls( camera, renderer.domElement );` // The `update()` below has nothing to clamp — the distance is already // inside `[ minDistance, maxDistance ]` — so it only aims the camera at // the target. let mut controls = OrbitControls::new(&mut camera.borrow_mut()); // The canvas the example renders at, standing in for the element's // `clientWidth` / `clientHeight`. controls.set_element_size(INNER_WIDTH, INNER_HEIGHT); controls.min_distance = 2.0; controls.max_distance = 10.0; controls.target.set(0.0, 0.0, -0.2); // `controls.update();` controls.update(&mut camera.borrow_mut(), None); App { renderer, scene, camera, environment, light_group, planes_group, // `const timer = new THREE.Timer();` timer: Timer::new(), opaque_pass, resolved_pass, transparent_pass, render_pipeline, controls, } } /// The page's `render()`. `params.animated` defaults to true, so the two /// groups turn by the timer's delta — which is zero on the graded frame, /// because `Timer`'s first `update()` after a pinned clock has nowhere to /// move from. `renderPipeline.render()`: the composite's draw runs the three /// passes' `updateBefore()` on its way (`docs/nodes.md` §57) — the resolve /// pass and the transparent pass both read what the opaque pass just wrote, /// which is why the renderer renders it first regardless of pull order. pub fn animate(app: &mut App) { app.timer.update(); // `if ( params.animated )` — true, and the GUI that could turn it off is // not ported. let delta = app.timer.get_delta(); { let mut group = app.light_group.borrow_mut(); let rotation = group.rotation; group.set_rotation(rotation.x, rotation.y + delta, rotation.z); } { let mut group = app.planes_group.borrow_mut(); let rotation = group.rotation; group.set_rotation(rotation.x, rotation.y - delta * 0.5, rotation.z); } app.environment.update(&mut app.renderer).unwrap(); app.render_pipeline.render(&mut app.renderer); } /// The page's `onWindowResize()`. /// /// The rung harness never calls this — the graded frame is always /// 800 x 500 — but the viewer and the browser shell do, so the example /// owns its own reaction to a resized canvas instead of the host /// guessing at one. pub fn resize(app: &mut App, width: f64, height: f64) { let mut camera = app.camera.borrow_mut(); camera.aspect = width / height; camera.update_projection_matrix(); app.renderer.set_size(width, height); } /// The example's controls, for a host that has a pointer. `None` when the /// page creates none — the signature is the same for every example so the /// viewer and the browser shell can drive any of them through one call. pub fn controls(app: &mut App) -> Option<&mut OrbitControls> { Some(&mut app.controls) } /// The controls and the camera at once, which every one of the controls' /// event handlers needs: the JS holds the camera as `this.object` and Rust /// cannot, so `pointer_move` and the rest take it as an argument. /// /// They are two fields of the same `App`, so borrowing both is sound — but /// only this module can say so; a host holding `&mut App` and calling /// [`controls`] and then reaching for the camera cannot. Hence the pair. pub fn controls_and_camera( app: &mut App, ) -> Option<(&mut OrbitControls, std::cell::RefMut<'_, PerspectiveCamera>)> { Some((&mut app.controls, app.camera.borrow_mut())) } fn main() { // Pin both clocks to zero, as three.js' `test/e2e/deterministic-injection.js` // does to the page, so that the frame this writes is the frame the rung // grades no matter how long `init()` took. three_rs::testing::pin_time(Some(0.0)); let mut app = init(); println!("adapter: {:?}", app.renderer.adapter_info()); animate(&mut app); let (width, height, pixels) = app.renderer.read_canvas_pixels().unwrap(); let path = std::env::args() .nth(1) .unwrap_or_else(|| "target/webgpu_deferred.png".to_string()); three_rs::testing::write_png(&path, width, height, &pixels); println!("wrote {path} ({width}x{height})"); } |
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |