GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — three-rs/examples/webgpu_mrt.rs at main · oneilltomhq/three-rs

Expand file tree

/

webgpu_mrt.rs

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
274 lines (245 loc) · 12.1 KB
/

webgpu_mrt.rs

Copy path

File metadata and controls

274 lines (245 loc) · 12.1 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
//! Port of `three.js/examples/webgpu_mrt.html`, calling the three-rs API in
//! the same order the page's `init()` and its nested loader callbacks 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.
//!
//! # What the page shows
//!
//! `webgpu_loader_gltf`'s scene — one UltraHDR map as both `scene.background`
//! and `scene.environment`, with DamagedHelmet in front of it — drawn **once**
//! into four colour attachments, and then all four composited side by side in
//! fifths of the screen:
//!
//! | x | attachment | through |
//! |---|---|---|
//! | 0.0 – 0.2 | `output` | `renderOutput()`: ACES, then sRGB |
//! | 0.2 – 0.4 | `output` | raw, linear, untransformed |
//! | 0.4 – 0.6 | `normal` | `packNormalToRGB( normalView )` |
//! | 0.6 – 0.8 | `emissive` | `EmissiveColor` |
//! | 0.8 – 1.0 | `diffuse` | `DiffuseColor` |
//!
//! Five bands from four attachments: the first two are the *same* texture, and
//! the whole point of the leftmost is that it is the only one of the five the
//! output colour transform is applied to. `renderPipeline.outputColorTransform
//! = false` is what makes the other four land in the canvas untouched.
//!
//! # Three things this rung is the gate on
//!
//! * **`pass( scene, camera, { minFilter: NearestFilter, magFilter:
//! NearestFilter } )` changes the generated code.** A texture that is
//! `NearestFilter` on both sides is *unfilterable*
//! (`WGSLNodeBuilder.isUnfilterable`): three binds it with a `non-filtering`
//! sample type and no sampler at all, and every tap on it becomes a
//! `textureLoad` against `textureDimensions` instead of a `textureSample`.
//! Three's `dump-mrt/m12` has four bare `texture_2d<f32>` bindings and not
//! one `_sampler`. See `docs/nodes.md` §23.
//! * **A `vec3` MRT output is written as `vec4( value, 1.0 )`.** `normal` and
//! `emissive` are `vec3`s; `OutputStructNode` converts each member to the
//! attachment's `vec4`, appending 1.0 rather than the fragment's alpha —
//! unlike `webgpu_postprocessing_bloom_emissive`, whose page writes the
//! `vec4( emissive, output.a )` out by hand.
//! * **`normal` / `diffuse` / `emissive` are `UnsignedByteType`.** "optimize
//! textures": attachment 0 stays `rgba16float` and the other three are
//! `rgba8unorm`, so the pipeline needs a colour target per attachment. With
//! `antialias: true` all four are also 4x multisampled and resolved.
//!
//! `requiredLimits: { maxColorAttachments: 5 }` is a WebGPU device request for
//! a limit this port already gets from wgpu's default adapter limits (8).
use std::cell::RefCell;
use std::rc::Rc;
use three_rs::addons::controls::OrbitControls;
use three_rs::loaders::{GltfLoader, UltraHdrLoader};
use three_rs::materials::{render_output, ToneMapping};
use three_rs::nodes::mrt;
use three_rs::nodes::pmrem_node::PmremEnvironment;
use three_rs::nodes::tsl::{
diffuse_color, emissive_color, mix, normal_view, pack_normal_to_rgb, screen_uv, step,
};
use three_rs::objects::Background;
use three_rs::renderer::{cube_render_target, PassOptions};
use three_rs::textures::{TextureFilter, TextureType};
use three_rs::{PassNode, PerspectiveCamera, 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;
fn examples_dir() -> std::path::PathBuf {
three_rs::testing::three_js_dir().join("examples")
}
pub struct App {
pub renderer: Renderer,
/// Shared with `scene_pass`, which renders it from `updateBefore()`.
pub scene: Rc<RefCell<Scene>>,
/// Shared with `scene_pass`.
pub camera: Rc<RefCell<PerspectiveCamera>>,
/// The page's `controls`.
pub controls: OrbitControls,
pub environment: PmremEnvironment,
pub scene_pass: PassNode,
pub render_pipeline: RenderPipeline,
}
pub fn init() -> App {
// `new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight,
// 0.25, 20 )`, then `camera.position.set( - 1.8, 0.6, 2.7 )`. Unlike
// `webgpu_loader_gltf`, nothing moves it afterwards.
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 scene = Scene::new();
// `new THREE.WebGPURenderer( { antialias: true, requiredLimits: {
// maxColorAttachments: 5 } } )`. The page builds it after the loader call;
// here it is first, because the two environment conversions below take it.
let mut parameters = RendererParameters::default();
parameters.antialias = true;
let mut renderer = Renderer::new(parameters).unwrap();
renderer.set_pixel_ratio(DPR);
renderer.set_size(INNER_WIDTH, INNER_HEIGHT);
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.
let texture = UltraHdrLoader::new()
.load(examples_dir().join("textures/equirectangular/royal_esplanade_2k.hdr.jpg"))
.unwrap();
// `texture.mapping = EquirectangularReflectionMapping; scene.background =
// texture` — the 512² cube the skybox samples.
let background = cube_render_target::from_equirectangular_texture(&mut renderer, &texture)
.expect("the equirectangular background converts to a cube");
let scene = Rc::new(RefCell::new(scene));
let camera = Rc::new(RefCell::new(camera));
scene.borrow_mut().background = Some(Background::CubeTexture(background));
// `scene.environment = texture`: the same map, PMREM-filtered, and the
// only light in the scene.
let mut environment = PmremEnvironment::from_equirectangular(&texture);
environment.update(&mut renderer).unwrap();
scene.borrow_mut().environment = Some(environment.handle());
// `new GLTFLoader().setPath( 'models/gltf/DamagedHelmet/glTF/' ).load(
// 'DamagedHelmet.gltf', … )`.
let gltf =
GltfLoader::load(examples_dir().join("models/gltf/DamagedHelmet/glTF/DamagedHelmet.gltf"))
.expect("DamagedHelmet.gltf");
scene.borrow_mut().add(&gltf.scene);
// `const controls = new OrbitControls( camera, renderer.domElement );`
let mut controls = OrbitControls::new(&mut camera.borrow_mut());
// The renderer's canvas stands in for the element's `clientWidth` /
// `clientHeight`.
controls.set_element_size(INNER_WIDTH, INNER_HEIGHT);
// `controls.minDistance = 2; controls.maxDistance = 10;`
controls.min_distance = 2.0;
controls.max_distance = 10.0;
// `controls.target.set( 0, 0, - 0.2 ); controls.update();` — the camera's
// pose for the whole page.
controls.target.set(0.0, 0.0, -0.2);
controls.update(&mut camera.borrow_mut(), None);
// post processing
// `pass( scene, camera, { minFilter: NearestFilter, magFilter:
// NearestFilter } )` — the filters are what make all four attachments
// unfilterable, so the composite below reads them with `textureLoad`. The
// pass holds the scene and camera, and the renderer renders it the first
// time a draw samples one of its textures (`docs/nodes.md` §57).
let mut options = PassOptions::default();
options.min_filter = TextureFilter::Nearest;
options.mag_filter = TextureFilter::Nearest;
let scene_pass = PassNode::new_with_options(options);
scene_pass.set_scene(scene.clone(), camera.clone());
// `scenePass.setMRT( mrt( { output, normal: packNormalToRGB( normalView ),
// diffuse: diffuseColor, emissive } ) )`. `normal` and `emissive` are
// `vec3`s and land as `vec4( v, 1.0 )`.
let mut scene_mrt = mrt(vec![("output", three_rs::nodes::tsl::output_property())]);
// `normal: packNormalToRGB( normalView )`. `normalView` is a node object
// upstream, so its `setup()` runs per material: the helmet's is its normal
// map's, and the skybox's is `normalViewGeometry * - 1` because
// `Background.material` is `BackSide`. This port's TSL is eager, so the
// expression is handed over as a closure instead. See `docs/nodes.md` §23.
scene_mrt.set_deferred("normal", || pack_normal_to_rgb(normal_view()));
scene_mrt.set("diffuse", diffuse_color());
scene_mrt.set("emissive", emissive_color());
scene_pass.set_mrt(scene_mrt);
// `normalTexture.type = diffuseTexture.type = emissiveTexture.type =
// THREE.UnsignedByteType` — "optimize textures". Attachment 0 stays
// `rgba16float`.
for name in ["normal", "diffuse", "emissive"] {
scene_pass
.texture_named(name)
.set_texture_type(TextureType::UnsignedByte);
}
let output = scene_pass.texture_node("output");
let normal = scene_pass.texture_node("normal");
let diffuse = scene_pass.texture_node("diffuse");
let emissive = scene_pass.texture_node("emissive");
// `renderPipeline.outputColorTransform = false` and the `Fn` that
// composites the four. The leftmost fifth is the only band that goes
// through `renderOutput()`, which is what the transform being off buys.
let mut render_pipeline = RenderPipeline::new();
render_pipeline.output_color_transform = false;
let out = mix(
render_output(output.clone(), ToneMapping::AcesFilmic),
output,
step(0.2, screen_uv().x()),
);
let nor = mix(out, normal, step(0.4, screen_uv().x()));
let emi = mix(nor, emissive, step(0.6, screen_uv().x()));
let dif = mix(emi, diffuse, step(0.8, screen_uv().x()));
render_pipeline.output_node = Some(dif);
App {
renderer,
scene,
camera,
controls,
environment,
scene_pass,
render_pipeline,
}
}
/// The page's `render()` — `renderPipeline.render()`, whose composite reads
/// the scene pass's four textures and so runs its `updateBefore()` first
/// (`docs/nodes.md` §57).
pub fn animate(app: &mut App) {
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_mrt.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.