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_compute_points.rs at main · oneilltomhq/three-rs Expand file tree/ Copy pathwebgpu_compute_points.rsMore file actions 262 lines (232 loc) · 10.1 KB / Copy pathwebgpu_compute_points.rsFile metadata and controls262 lines (232 loc) · 10.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 //! Port of `three.js/examples/webgpu_compute_points.html`, calling the three-rs //! API in the same order the page's `init()` / `animate()` 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. The pointer handler never fires, so //! `pointerVector` keeps its `( -10, -10 )` and every particle is at least //! 10 units from it: the "reset to the origin" branch is dead for the graded //! frame, but it is in the kernel because it is in the page. //! //! The `Inspector` UI and its two `scaleVector` sliders are hidden by //! `clean-page.js` and touch nothing but the uniform's default, so they are not //! ported. Unlike `webgpu_tsl_galaxy`, this page's `Inspector` draws no //! `Math.random`, because nothing in the scene is a `range()`. use std::rc::Rc; // `PerspectiveCamera` only names the type in `controls_and_camera`'s signature, // which is uniform across the examples; this page's camera is orthographic and it // creates no controls, so the function returns `None`. use three_rs::addons::controls::OrbitControls; use three_rs::core::BufferGeometry; use three_rs::nodes::tsl::{ abs, instance_index, length, max, to_var, two_pi, uniform_value, vec2, vec2_join, vec3, StorageArray, }; use three_rs::nodes::{ComputeFlow, Type}; use three_rs::PerspectiveCamera; use three_rs::{ OrthographicCamera, Points, PointsNodeMaterial, Renderer, RendererParameters, Scene, Vector3, }; 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 particleCount = 300000;` pub const PARTICLE_COUNT: usize = 300_000; /// The page's two storage buffers and the two kernels over them. Split out so /// `tests/nodes_compute_wgsl.rs` and `tests/renderer_compute_points.rs` build /// exactly what the example runs. pub struct Particles { /// `const particleArray = instancedArray( particleCount, 'vec2' );` pub particle: StorageArray, /// `const velocityArray = instancedArray( particleCount, 'vec2' );` pub velocity: StorageArray, /// `computeNode` — `Update Particles`, run every frame, carrying /// `precomputeShaderNode` as its `onInit`. pub update: ComputeFlow, } pub fn particles() -> Particles { let particle = three_rs::nodes::tsl::instanced_array(PARTICLE_COUNT, Type::Vec2); let velocity = three_rs::nodes::tsl::instanced_array(PARTICLE_COUNT, Type::Vec2); // ```js // const computeInit = Fn( () => { // const particle = particleArray.element( instanceIndex ); // const velocity = velocityArray.element( instanceIndex ); // const randX = instanceIndex.hash(); // not in r186's dump // ... // } ) // ``` // What r186 actually generates for `onInit` is the angle/speed spiral // below, writing the *velocity* buffer only; the particle buffer keeps the // zeros it was created with. let precompute = { let angle = instance_index().to(Type::F32).mul(0.005).mul(two_pi()); let angle = to_var(None, angle); let speed = to_var(None, instance_index().to(Type::F32).mul(1e-8).add(1e-7)); ComputeFlow::new( vec![velocity.element(instance_index()).assign(vec2_join(vec![ angle.sin().mul(speed.clone()), angle.cos().mul(speed), ]))], PARTICLE_COUNT, ) }; // ```js // const computeUpdate = Fn( () => { // const position = particleArray.element( instanceIndex ); // const velocity = velocityArray.element( instanceIndex ); // ... // } )().compute( particleCount ); // computeUpdate.setName( 'Update Particles' ); // ``` let update = { // `uniform( scaleVector )` and `uniform( pointerVector )`. Neither is // ever written for the graded frame — the sliders are hidden and the // pointer handler never fires. let limit = uniform_value(Type::Vec2, vec![1.0, 1.0]); let pointer = uniform_value(Type::Vec2, vec![-10.0, -10.0]); let particle_at = particle.element(instance_index()); let velocity_at = velocity.element(instance_index()); // `const position = particle.add( velocity ).toVar();` let position = to_var(None, particle_at.add(velocity_at.clone())); // The two bounce tests write the *velocity* buffer before the position // is clamped, which is why the clamp is a separate statement below and // not folded into the `select`s. let bounce = |component: &'static str| { let v = velocity_at.swizzle(component); v.assign( abs(position.swizzle(component)) .greater_than_equal(limit.swizzle(component)) .select(v.negate(), v.clone()), ) }; let mut update = ComputeFlow::new( vec![ position.clone(), bounce("x"), bounce("y"), // `position.assign( max( min( position, limit ), limit.negate() ) )` position.assign(max(position.min(limit.clone()), limit.negate())), // `particle.assign( select( pointer.sub( position ).length() // .lessThanEqual( 0.1 ), vec2( 0 ), position ) )` particle_at.assign( length(pointer.sub(position.clone())) .less_than_equal(0.1) .select(vec2(0.0, 0.0), position), ), ], PARTICLE_COUNT, ); update.name = Some("Update Particles".to_string()); update.on_init = Some(Box::new(precompute)); update }; Particles { particle, velocity, update, } } /// `new THREE.PointsNodeMaterial()` with the two nodes the page sets. Split /// out so the WGSL gate builds exactly what the example renders. pub fn material() -> PointsNodeMaterial { let particles = particles(); material_for(&particles) } fn material_for(particles: &Particles) -> PointsNodeMaterial { let mut material = PointsNodeMaterial::points(); material.position_node = Some(particles.particle.element(instance_index())); // `.add( color( 0xFFFFFF ) )` — white in linear-sRGB is ( 1, 1, 1 ), and // the add widens the `vec2` to a `vec3` by filling `z` with 0. material.color_node = Some( particles .particle .element(instance_index()) .add(vec3(1.0, 1.0, 1.0)), ); material } pub struct App { pub renderer: Renderer, pub scene: Scene, pub camera: OrthographicCamera, pub particles: Particles, } pub fn init() -> App { // `new THREE.OrthographicCamera( -1, 1, 1, -1, 0, 1 )`, `camera.position.z = 1`. // `near = 0`, `far = 1` and the particles sit at `z = 0`, i.e. exactly on // the far plane — only `depthCompare: less-equal` draws them. let mut camera = OrthographicCamera::new(-1.0, 1.0, 1.0, -1.0, 0.0, 1.0); camera.object.position.z = 1.0; camera.update_matrix_world(); // `scene.background` is never set, so the pass clears to a transparent // black rather than to a colour. let scene = Scene::new(); let particles = particles(); let material = material_for(&particles); // `new THREE.BufferGeometry()` with `new Float32Array( 3 )` — one vertex at // the origin — and `drawRange.count = 1`. Every particle is an *instance* // of that one vertex; the storage buffer is what moves it. let mut geometry = BufferGeometry::new(); geometry.set_from_points(&[Vector3::new(0.0, 0.0, 0.0)]); geometry.set_draw_range(0, 1); let mesh = Points::new(Rc::new(geometry), material); mesh.borrow_mut().payload.points_mut().unwrap().count = Some(PARTICLE_COUNT); scene.add(&mesh); 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); App { renderer, scene, camera, particles, } } /// The page's `animate()`: `renderer.compute( computeNode )` then /// `renderer.render( scene, camera )`. pub fn animate(app: &mut App) { app.renderer.compute(&app.particles.update).unwrap(); app.renderer.render(&app.scene, &mut app.camera); } /// 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. /// /// The page sets no `camera.aspect`: its camera is the orthographic /// `( -1, 1, 1, -1, 0, 1 )` unit box, which does not have one, so the /// `updateProjectionMatrix()` it still calls changes nothing. pub fn resize(app: &mut App, width: f64, height: f64) { app.camera.update_projection_matrix(); app.renderer.set_size(width, height); } /// The example's controls, for a host that has a pointer. `None` here: /// the page creates none. pub fn controls(_app: &mut App) -> Option<&mut OrbitControls> { None } /// The controls and the camera at once, for a host delivering pointer events. /// `None` here: the page creates no controls. pub fn controls_and_camera(_app: &mut App) -> Option<(&mut OrbitControls, &mut PerspectiveCamera)> { None } 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_compute_points.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. |