Skip to main content

D3Camera

Trait D3Camera 

Source
pub trait D3Camera: Send + Sync {
Show 18 methods // Required methods fn new() -> Self where Self: Sized; fn basis_vectors(&self) -> (Vec3<f32>, Vec3<f32>, Vec3<f32>); fn projection_matrix(&self, width: f32, height: f32) -> Mat4<f32>; fn as_scenevm_camera(&self) -> Camera3D; // Provided methods fn id(&self) -> String { ... } fn view_matrix(&self) -> Mat4<f32> { ... } fn position(&self) -> Vec3<f32> { ... } fn scale(&self) -> f32 { ... } fn fov(&self) -> f32 { ... } fn distance(&self) -> f32 { ... } fn get_parameter_f32(&mut self, key: &str) -> f32 { ... } fn set_parameter_f32(&mut self, key: &str, value: f32) { ... } fn set_parameter_vec2(&mut self, key: &str, value: Vec2<f32>) { ... } fn set_parameter_vec3(&mut self, key: &str, value: Vec3<f32>) { ... } fn set_parameter_vec4(&mut self, key: &str, value: Vec4<f32>) { ... } fn create_ray( &self, uv: Vec2<f32>, screen: Vec2<f32>, offset: Vec2<f32>, ) -> Ray { ... } fn rotate(&mut self, delta: Vec2<f32>) { ... } fn zoom(&mut self, delta: f32) { ... }
}

Required Methods§

Source

fn new() -> Self
where Self: Sized,

Source

fn basis_vectors(&self) -> (Vec3<f32>, Vec3<f32>, Vec3<f32>)

Source

fn projection_matrix(&self, width: f32, height: f32) -> Mat4<f32>

Source

fn as_scenevm_camera(&self) -> Camera3D

Generate a SceneVM Camera

Provided Methods§

Source

fn id(&self) -> String

Examples found in repository?
examples/map.rs (line 56)
37    fn new() -> Self
38    where
39        Self: Sized,
40    {
41        let camera = Box::new(D3FirstPCamera::new());
42        let mut scene = Scene::default();
43
44        // Collect the assets and compile the world map.
45        let mut assets = Assets::default();
46        assets.collect_from_directory("minigame".into());
47        // let _ = assets.compile_source_map("world".into());
48
49        if let Some(map) = assets.get_map("world") {
50            // Build 3D scene from the world map.
51            let mut builder = D3Builder::new();
52            scene = builder.build(
53                map,
54                &assets,
55                Vec2::zero(), // Only needed for 2D builders
56                &camera.id(),
57                &ValueContainer::default(),
58            );
59        }
60
61        // Create an entity with a default position / orientation which serves as the camera.
62        let entity = rusterix::Entity {
63            position: Vec3::new(6.0600824, 1.0, 4.5524735),
64            orientation: Vec2::new(0.03489969, 0.99939084),
65            ..Default::default()
66        };
67
68        // Add logo on top of the scene
69        scene.d2_static = vec![
70            Batch2D::from_rectangle(0.0, 0.0, 200.0, 200.0)
71                .receives_light(false)
72                .source(PixelSource::StaticTileIndex(0)),
73        ];
74        // scene
75        //     .textures
76        //     .push(Tile::from_texture(Texture::from_image(Path::new(
77        //         "images/logo.png",
78        //     ))));
79
80        Self {
81            camera,
82            scene,
83            entity,
84            movement: Off,
85            assets,
86        }
87    }
88
89    /// Draw a cube and a rectangle
90    fn draw(&mut self, pixels: &mut [u8], ctx: &mut TheContext) {
91        let _start = get_time();
92
93        match &self.movement {
94            MoveForward => {
95                self.entity.move_forward(0.05);
96            }
97            MoveBackward => {
98                self.entity.move_backward(0.05);
99            }
100            TurnLeft => {
101                self.entity.turn_left(1.0);
102            }
103            TurnRight => {
104                self.entity.turn_right(1.0);
105            }
106            Off => {}
107        }
108        // self.entity.apply_to_camera(&mut self.camera);
109
110        // Set it up
111        Rasterizer::setup(
112            None,
113            self.camera.view_matrix(),
114            self.camera
115                .projection_matrix(ctx.width as f32, ctx.height as f32),
116        )
117        .ambient(Vec4::one())
118        .rasterize(
119            &mut self.scene,
120            pixels,     // Destination buffer
121            ctx.width,  // Destination buffer width
122            ctx.height, // Destination buffer height
123            40,         // Tile size
124            &self.assets,
125        );
126
127        let _stop = get_time();
128        // println!("Execution time: {:?} ms.", _stop - _start);
129    }
130
131    // Query if the widget needs a redraw, we redraw at max speed (which is not necessary)
132    fn update(&mut self, _ctx: &mut TheContext) -> bool {
133        true
134    }
135
136    fn window_title(&self) -> String {
137        "Rusterix Map Demo".to_string()
138    }
139
140    fn hover(&mut self, x: f32, y: f32, ctx: &mut TheContext) -> bool {
141        if self.camera.id() == "orbit" {
142            self.camera.set_parameter_vec2(
143                "from_normalized",
144                Vec2::new(x / ctx.width as f32, y / ctx.height as f32),
145            );
146        } else if self.camera.id() == "firstp" {
147            self.entity
148                .set_tilt_from_screen_coordinate(1.0 - y / ctx.height as f32);
149        }
150        true
151    }
Source

fn view_matrix(&self) -> Mat4<f32>

Examples found in repository?
examples/cube.rs (line 78)
68    fn draw(&mut self, pixels: &mut [u8], ctx: &mut TheContext) {
69        let _start = get_time();
70
71        // Animate light in circle around Y-axis
72        let elapsed = self.start_time.elapsed().as_secs_f32() * 1.5;
73        self.scene.lights[0].position = Vec3::new(2.0 * elapsed.cos(), 0.8, 2.0 * elapsed.sin());
74
75        // Set it up
76        Rasterizer::setup(
77            None,
78            self.camera.view_matrix(),
79            self.camera
80                .projection_matrix(ctx.width as f32, ctx.height as f32),
81        )
82        .ambient(Vec4::broadcast(0.1))
83        .rasterize(
84            &mut self.scene,
85            pixels,     // Destination buffer
86            ctx.width,  // Destination buffer width
87            ctx.height, // Destination buffer height
88            60,         // Tile size
89            &self.assets,
90        );
91
92        let _stop = get_time();
93        // println!("Execution time: {:?} ms.", _stop - _start);
94    }
More examples
Hide additional examples
examples/obj.rs (line 71)
61    fn draw(&mut self, pixels: &mut [u8], ctx: &mut TheContext) {
62        let _start = get_time();
63
64        // Animate light in circle around Y-axis
65        let elapsed = self.start_time.elapsed().as_secs_f32() * 1.5;
66        self.scene.lights[0].position = Vec3::new(2.0 * elapsed.cos(), 0.8, 2.0 * elapsed.sin());
67
68        // Set it up
69        Rasterizer::setup(
70            None,
71            self.camera.view_matrix(),
72            self.camera
73                .projection_matrix(ctx.width as f32, ctx.height as f32),
74        )
75        .ambient(Vec4::broadcast(0.8))
76        .rasterize(
77            &mut self.scene,
78            pixels,     // Destination buffer
79            ctx.width,  // Destination buffer width
80            ctx.height, // Destination buffer height
81            60,         // Tile size
82            &self.assets,
83        );
84
85        let _stop = get_time();
86        // println!("Execution time: {:?} ms.", _stop - _start);
87    }
examples/cube_shaded.rs (line 130)
120    fn draw(&mut self, pixels: &mut [u8], ctx: &mut TheContext) {
121        let _start = get_time();
122
123        // Animate light in circle around Y-axis
124        let elapsed = self.start_time.elapsed().as_secs_f32() * 1.5;
125        self.scene.lights[0].position = Vec3::new(2.0 * elapsed.cos(), 0.8, 2.0 * elapsed.sin());
126
127        // Set it up
128        Rasterizer::setup(
129            None,
130            self.camera.view_matrix(),
131            self.camera
132                .projection_matrix(ctx.width as f32, ctx.height as f32),
133        )
134        .ambient(Vec4::broadcast(0.1))
135        .time(elapsed)
136        .rasterize(
137            &mut self.scene,
138            pixels,     // Destination buffer
139            ctx.width,  // Destination buffer width
140            ctx.height, // Destination buffer height
141            80,         // Tile size
142            &self.assets,
143        );
144
145        let _stop = get_time();
146        println!("Execution time: {:?} ms.", _stop - _start);
147    }
examples/map.rs (line 113)
90    fn draw(&mut self, pixels: &mut [u8], ctx: &mut TheContext) {
91        let _start = get_time();
92
93        match &self.movement {
94            MoveForward => {
95                self.entity.move_forward(0.05);
96            }
97            MoveBackward => {
98                self.entity.move_backward(0.05);
99            }
100            TurnLeft => {
101                self.entity.turn_left(1.0);
102            }
103            TurnRight => {
104                self.entity.turn_right(1.0);
105            }
106            Off => {}
107        }
108        // self.entity.apply_to_camera(&mut self.camera);
109
110        // Set it up
111        Rasterizer::setup(
112            None,
113            self.camera.view_matrix(),
114            self.camera
115                .projection_matrix(ctx.width as f32, ctx.height as f32),
116        )
117        .ambient(Vec4::one())
118        .rasterize(
119            &mut self.scene,
120            pixels,     // Destination buffer
121            ctx.width,  // Destination buffer width
122            ctx.height, // Destination buffer height
123            40,         // Tile size
124            &self.assets,
125        );
126
127        let _stop = get_time();
128        // println!("Execution time: {:?} ms.", _stop - _start);
129    }
Source

fn position(&self) -> Vec3<f32>

Source

fn scale(&self) -> f32

Source

fn fov(&self) -> f32

Source

fn distance(&self) -> f32

Source

fn get_parameter_f32(&mut self, key: &str) -> f32

Get an f32 parameter.

Source

fn set_parameter_f32(&mut self, key: &str, value: f32)

Set an f32 parameter.

Examples found in repository?
examples/obj.rs (line 51)
24    fn new() -> Self
25    where
26        Self: Sized,
27    {
28        let scene = Scene::from_static(
29            vec![Batch2D::from_rectangle(0.0, 0.0, 200.0, 200.0)],
30            vec![
31                Batch3D::from_obj(Path::new("examples/teapot.obj"))
32                    .source(PixelSource::StaticTileIndex(0))
33                    .repeat_mode(RepeatMode::RepeatXY)
34                    .transform(Mat4::scaling_3d(Vec3::new(0.35, -0.35, 0.35)))
35                    .with_computed_normals(),
36            ],
37        )
38        .lights(vec![
39            Light::new(LightType::Point)
40                .with_intensity(1.0)
41                .with_color([1.0, 1.0, 0.95])
42                .compile(),
43        ])
44        .background(Box::new(VGrayGradientShader::new()));
45
46        let assets = Assets::default().textures(vec![Tile::from_texture(Texture::from_image(
47            Path::new("images/logo.png"),
48        ))]);
49
50        let mut camera = D3OrbitCamera::new();
51        camera.set_parameter_f32("distance", 1.5);
52
53        Self {
54            camera,
55            scene,
56            start_time: Instant::now(),
57            assets,
58        }
59    }
More examples
Hide additional examples
examples/cube.rs (line 57)
23    fn new() -> Self
24    where
25        Self: Sized,
26    {
27        let scene = Scene::from_static(
28            vec![Batch2D::from_rectangle(0.0, 0.0, 200.0, 200.0)],
29            vec![
30                Batch3D::from_box(-0.5, -0.5, -0.5, 1.0, 1.0, 1.0)
31                    .source(PixelSource::StaticTileIndex(0))
32                    .cull_mode(CullMode::Off)
33                    // Metallic material which is based on half of the
34                    // saturation of the pixel color
35                    .material(Material::new(
36                        MaterialRole::Metallic,
37                        MaterialModifier::Saturation,
38                        0.6,
39                        0.0,
40                    ))
41                    .with_computed_normals(),
42            ],
43        )
44        .lights(vec![
45            Light::new(LightType::Point)
46                .with_intensity(1.0)
47                .with_color([1.0, 1.0, 0.95])
48                .compile(),
49        ])
50        .background(Box::new(VGrayGradientShader::new()));
51
52        let assets = Assets::default().textures(vec![Tile::from_texture(Texture::from_image(
53            Path::new("images/logo.png"),
54        ))]);
55
56        let mut camera = D3OrbitCamera::new();
57        camera.set_parameter_f32("distance", 1.5);
58
59        Self {
60            camera,
61            scene,
62            start_time: Instant::now(),
63            assets,
64        }
65    }
examples/cube_shaded.rs (line 109)
23    fn new() -> Self
24    where
25        Self: Sized,
26    {
27        let mut scene = Scene::from_static(
28            vec![Batch2D::from_rectangle(0.0, 0.0, 200.0, 200.0)],
29            vec![
30                Batch3D::from_box(-0.5, -0.5, -0.5, 1.0, 1.0, 1.0)
31                    .source(PixelSource::StaticTileIndex(0))
32                    .cull_mode(CullMode::Off)
33                    .ambient_color(Vec3::broadcast(0.3))
34                    .shader(0)
35                    .with_computed_normals(),
36            ],
37        )
38        .lights(vec![
39            Light::new(LightType::Point)
40                .with_intensity(1.0)
41                .with_color([1.0, 1.0, 0.95])
42                .compile(),
43        ])
44        .background(Box::new(VGrayGradientShader::new()));
45
46        scene.add_shader(
47            r#"
48            fn shade() {
49                // Procedural wood: concentric growth rings warped by turbulence + fine grain.
50                // Only the .x channel of textures is used (value channel).
51                let t = time * 0.0;
52
53                // Move and scale domain; center the rings roughly in the middle of each face.
54                let uv2 = uv / 3.0 - vec2(1.5);
55
56                // fBm turbulence (zero-mean) to warp the rings
57                let n1 = sample(uv2 + vec2(t, 0.0), "fbm_perlin");   // [0,1]
58                let n2 = sample(uv2 * 2.0 + vec2(0.0, t*0.7), "fbm_perlin");
59                let turb = 0.65 * n1 + 0.35 * n2;                       // [0,1]
60                let turb_zm = (turb - 0.5) * 2.0;                       // [-1,1]
61
62                // Radial distance from center (log cross-section look)
63                let r = length(uv2);
64
65                // Warp rings by turbulence (phase modulation)
66                let ring_freq = 10.0;            // number of rings
67                let ring_warp = 0.22;            // strength of warp
68                let rings = r + ring_warp * turb_zm;
69                let waves = sin(rings * ring_freq);
70
71                // Map sine to ring mask; sharpen valleys to make rings thinner
72                let rings_mask = pow(1.0 - abs(waves), 3.0);
73
74                // Fine longitudinal grain: high-frequency value noise stretched along X
75                let grain_uv = vec2(uv2.x * 8.0, uv2.y * 40.0);
76                let g = sample(grain_uv + vec2(0.0, t*0.5), "value");
77                let grain = (g - 0.5) * 2.0;     // zero-mean
78
79                // Base wood hues
80                let base_light = vec3(0.72, 0.52, 0.32);
81                let base_dark  = vec3(0.45, 0.30, 0.16);
82
83                // Mix light/dark by ring mask
84                color = mix(base_light, base_dark, rings_mask);
85
86                // Apply subtle anisotropic grain as a multiplicative zero-mean factor
87                color *= (1.0 + 0.06 * grain);
88
89                // Optional pore streaks (cathedrals): directional bands along Y with slight turbulence
90                let band = uv2.y + 0.15 * turb_zm;
91                let cathedral = pow(1.0 - abs(sin(band * 6.0)), 4.0);
92                color = mix(color, color * 0.9, cathedral * 0.2);
93
94                // Roughness varies: pores are rougher, rings smoother
95                roughness = 0.6 + cathedral * 0.3;
96
97                // 16 Colors
98                //let color_steps = 16.0;
99                //color = floor(color * color_steps) / color_steps;
100            }
101        "#,
102        );
103
104        let assets = Assets::default().textures(vec![Tile::from_texture(Texture::from_image(
105            Path::new("images/logo.png"),
106        ))]);
107
108        let mut camera = D3OrbitCamera::new();
109        camera.set_parameter_f32("distance", 1.5);
110
111        Self {
112            camera,
113            scene,
114            start_time: Instant::now(),
115            assets,
116        }
117    }
Source

fn set_parameter_vec2(&mut self, key: &str, value: Vec2<f32>)

Set a Vec2 parameter.

Examples found in repository?
examples/cube.rs (lines 98-101)
97    fn hover(&mut self, x: f32, y: f32, ctx: &mut TheContext) -> bool {
98        self.camera.set_parameter_vec2(
99            "from_normalized",
100            Vec2::new(x / ctx.width as f32, y / ctx.height as f32),
101        );
102        true
103    }
More examples
Hide additional examples
examples/cube_shaded.rs (lines 151-154)
150    fn hover(&mut self, x: f32, y: f32, ctx: &mut TheContext) -> bool {
151        self.camera.set_parameter_vec2(
152            "from_normalized",
153            Vec2::new(x / ctx.width as f32, y / ctx.height as f32),
154        );
155        true
156    }
examples/obj.rs (lines 91-94)
90    fn hover(&mut self, x: f32, y: f32, ctx: &mut TheContext) -> bool {
91        self.camera.set_parameter_vec2(
92            "from_normalized",
93            Vec2::new(x / ctx.width as f32, y / ctx.height as f32),
94        );
95        true
96    }
examples/map.rs (lines 142-145)
140    fn hover(&mut self, x: f32, y: f32, ctx: &mut TheContext) -> bool {
141        if self.camera.id() == "orbit" {
142            self.camera.set_parameter_vec2(
143                "from_normalized",
144                Vec2::new(x / ctx.width as f32, y / ctx.height as f32),
145            );
146        } else if self.camera.id() == "firstp" {
147            self.entity
148                .set_tilt_from_screen_coordinate(1.0 - y / ctx.height as f32);
149        }
150        true
151    }
Source

fn set_parameter_vec3(&mut self, key: &str, value: Vec3<f32>)

Set a Vec3 parameter.

Source

fn set_parameter_vec4(&mut self, key: &str, value: Vec4<f32>)

Set a Vec4 parameter.

Source

fn create_ray(&self, uv: Vec2<f32>, screen: Vec2<f32>, offset: Vec2<f32>) -> Ray

Creates a ray

Source

fn rotate(&mut self, delta: Vec2<f32>)

Rotate (only used by orbit camera)

Source

fn zoom(&mut self, delta: f32)

Zoom (only used by orbit camera)

Implementors§