Load f32 tiff into DEM, started BVH, other changes

This commit is contained in:
Matthew Gordon 2024-11-13 17:14:44 -04:00
parent 5dfdd3e927
commit 71b05c31a2
9 changed files with 528 additions and 243 deletions

519
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -7,10 +7,11 @@ edition = "2021"
crate-type = ["cdylib", "rlib"]
[dependencies]
winit = { version = "0.30.3", features = ["rwh_06"] }
tiff = "0.9.1"
log = "0.4.22"
[target.'cfg(target_arch = "x86_64")'.dependencies]
winit = { version = "0.30.3", features = ["rwh_06"] }
wgpu = "0.20.1"
env_logger = "0.11.3"
futures = { version = "0.3.30", features = ["executor"] }

View File

@ -1,15 +1,22 @@
use std::rc::Rc;
use crate::mvu::{Event, MvuApp, Size2i};
use {
std::borrow::Cow,
log::info,
std::{borrow::Cow, path::PathBuf},
wgpu::{Device, Instance, Queue, RenderPipeline, Surface, SurfaceConfiguration},
};
#[derive(Copy, Clone)]
pub struct Model {}
mod raster;
#[derive(Clone)]
pub struct Model {
dem: Option<raster::Dem>,
}
impl Model {
pub fn new() -> Model {
Model {}
Model { dem: None }
}
}
@ -103,6 +110,8 @@ impl MvuApp<Model> for App {
render_pipeline,
queue,
});
info!("Initialized {}x{}.", size.width, size.height);
}
async fn resize(&mut self, new_size: Size2i) {
@ -114,17 +123,22 @@ impl MvuApp<Model> for App {
queue: _,
}) = &mut self.context
{
config.width = new_size.width.max(1);
config.width = dbg!(new_size).width.max(1);
config.height = new_size.height.max(1);
surface.configure(device, config);
info!("Resized_to {}x{}.", new_size.width, new_size.height);
}
}
async fn update(&self, model: Model, _event: Event) -> Model {
model
async fn update(&self, model: Rc<Model>, event: Event) -> Rc<Model> {
match event {
Event::MouseButtonPressed => model,
Event::OpenTestFile(file_path) => open_test_file(file_path, model.clone()),
}
}
async fn view(&mut self, _model: Model) -> Result<(), Box<dyn std::error::Error>> {
async fn view(&mut self, _model: Rc<Model>) -> Result<(), Box<dyn std::error::Error>> {
if let Some(Context {
config: _,
surface,
@ -166,3 +180,8 @@ impl MvuApp<Model> for App {
Ok(())
}
}
fn open_test_file(file_path: PathBuf, model: Rc<Model>) -> Rc<Model> {
let dem = Some(raster::Dem::load_from_image(&file_path));
Rc::new(Model { dem })
}

162
src/app/raster/dem.rs Normal file
View File

@ -0,0 +1,162 @@
use {
std::{fs::File, path::PathBuf},
tiff,
};
#[derive(Clone)]
pub struct Dem {
pub width: u32,
pub height: u32,
pub min_x: f32,
pub max_x: f32,
pub min_y: f32,
pub max_y: f32,
pub min_z: f32,
pub max_z: f32,
pub grid: Vec<u16>,
}
impl Dem {
fn get(&self, x: u32, y: u32) -> u16 {
self.grid[(y * self.width + x) as usize]
}
}
pub struct DemBvh {
pub dem: Dem,
pub layers: Vec<DemBvhLayer>,
}
pub struct DemBvhLayer {
pub width: u32,
pub height: u32,
pub data: Vec<u16>,
}
impl DemBvh {
fn new(dem: Dem) -> DemBvh {
assert!(dem.width == dem.height);
// width-1 must be power of two
assert!(dem.width - 1 & (dem.width - 2) == 0);
let mut layers = vec![create_first_dembvh_layer(&dem)];
while layers.last().unwrap().width > 1 {
layers.push(create_next_dembvh_layer(&layers.last().unwrap()));
}
DemBvh { dem, layers }
}
}
impl DemBvhLayer {
fn get_value(&self, x: u32, y: u32) -> (u16, u16) {
(
self.data[(y * self.width * 2 + x * 2) as usize],
self.data[(y * self.width * 2 + x * 2 + 1) as usize],
)
}
fn set_value(&mut self, x: u32, y: u32, min: u16, max: u16) {
self.data[(y * self.width * 2 + x * 2) as usize] = min;
self.data[(y * self.width * 2 + x * 2 + 1) as usize] = max;
}
}
fn create_first_dembvh_layer(dem: &Dem) -> DemBvhLayer {
let width = dem.width - 1;
let height = dem.height - 1;
let mut result = DemBvhLayer {
width,
height,
data: vec![0; (width * height * 2) as usize],
};
for y in 0..height {
for x in 0..width {
let min = dem
.get(x, y)
.min(dem.get(x + 1, y))
.min(dem.get(x, y + 1))
.min(dem.get(x + 1, y + 1));
let max = dem
.get(x, y)
.max(dem.get(x + 1, y))
.max(dem.get(x, y + 1))
.max(dem.get(x + 1, y + 1));
result.set_value(x, y, min, max);
}
}
result
}
fn create_next_dembvh_layer(prev: &DemBvhLayer) -> DemBvhLayer {
let width = prev.width / 2;
let height = prev.height / 2;
let mut result = DemBvhLayer {
width,
height,
data: vec![0; (width * height * 2) as usize],
};
for y in 0..height {
for x in 0..width {
let min = prev
.get_value(x, y)
.0
.min(prev.get_value(x + 1, y).0)
.min(prev.get_value(x, y + 1).0)
.min(prev.get_value(x + 1, y + 1).0);
let max = prev
.get_value(x, y)
.1
.max(prev.get_value(x + 1, y).1)
.max(prev.get_value(x, y + 1).1)
.max(prev.get_value(x + 1, y + 1).1);
result.set_value(x, y, min, max);
}
}
result
}
fn normalize_f32(value: f32, min: f32, max: f32) -> f32 {
(value - min) / (max - min)
}
fn normalized_f32_to_u16(value: f32) -> u16 {
(value * ((u16::MAX - 1) as f32)) as u16 + 1
}
impl Dem {
pub fn load_from_image(file_path: &PathBuf) -> Dem {
let file = File::open(file_path).unwrap();
let mut tiff = tiff::decoder::Decoder::new(file).unwrap();
let (width, height) = tiff.dimensions().unwrap();
match tiff.read_image().unwrap() {
tiff::decoder::DecodingResult::F32(f32_values) => {
let min_x = -500.0;
let max_x = 500.0;
let min_y = -500.0;
let max_y = 500.0;
let (min_z, max_z) = f32_values[1..]
.iter()
.fold((f32_values[0], f32_values[0]), |(min, max), elem| {
(min.min(*elem), max.max(*elem))
});
let grid = f32_values
.iter()
.map(|v| normalized_f32_to_u16(normalize_f32(*v, min_z, max_z)))
.collect();
Dem {
width,
height,
min_x,
max_x,
min_y,
max_y,
min_z,
max_z,
grid,
}
}
_ => {
panic!("TIFF data type not implmented.")
}
}
}
}

3
src/app/raster/mod.rs Normal file
View File

@ -0,0 +1,3 @@
mod dem;
pub use dem::Dem;

View File

@ -1,3 +1,5 @@
use std::rc::Rc;
#[cfg(target_arch = "wasm32")]
use wasm_bindgen::prelude::*;
#[cfg(target_arch = "wasm32")]
@ -16,6 +18,6 @@ use app::{App,Model};
#[cfg_attr(target_arch = "wasm32", wasm_bindgen(start))]
pub fn main() {
run(App::new(), Model::new());
run(App::new(), Rc::new(Model::new()));
}

View File

@ -1,6 +1,11 @@
use wgpu::{Instance, Surface};
use {
std::{path::PathBuf, rc::Rc},
wgpu::{Instance, Surface},
};
pub enum Event {
MouseButtonPressed,
OpenTestFile(PathBuf),
}
#[derive(Debug, Clone, Copy)]
@ -12,11 +17,9 @@ pub struct Size2i {
#[allow(async_fn_in_trait)]
// https://blog.rust-lang.org/2023/12/21/async-fn-rpit-in-traits.html#where-the-gaps-lie
pub trait MvuApp<M>
where
M: Copy,
{
async fn init(&mut self, instance: &Instance, surface: Surface<'static>, new_size: Size2i);
async fn resize(&mut self, size: Size2i);
async fn update(&self, model: M, event: Event) -> M;
async fn view(&mut self, model: M) -> Result<(), Box<dyn std::error::Error>>;
async fn update(&self, model: Rc<M>, event: Event) -> Rc<M>;
async fn view(&mut self, model: Rc<M>) -> Result<(), Box<dyn std::error::Error>>;
}

View File

@ -1,6 +1,6 @@
use std::sync::Arc;
use std::{rc::Rc, sync::Arc};
use crate::mvu::{MvuApp, Size2i};
use crate::mvu::{self, MvuApp, Size2i};
use {
futures::executor::block_on,
winit::{
@ -15,11 +15,11 @@ use {
struct AppHost<A, M> {
window: Option<Arc<Window>>,
app: A,
model: M,
model: Rc<M>,
}
impl<A, M> AppHost<A, M> {
fn new(app: A, model: M) -> Self {
fn new(app: A, model: Rc<M>) -> Self {
Self {
window: None,
app,
@ -31,7 +31,6 @@ impl<A, M> AppHost<A, M> {
impl<A, M> ApplicationHandler for AppHost<A, M>
where
A: MvuApp<M>,
M: Copy,
{
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
let window = Arc::new(
@ -56,16 +55,21 @@ where
println!("The close button was pressed; stopping");
event_loop.exit();
}
WindowEvent::RedrawRequested => block_on(self.app.view(self.model)).unwrap(),
WindowEvent::RedrawRequested => block_on(self.app.view(self.model.clone())).unwrap(),
WindowEvent::DroppedFile(file_path) => {
self.model = block_on(
self.app
.update(self.model.clone(), mvu::Event::OpenTestFile(file_path)),
)
}
_ => (),
}
}
}
pub fn run<A, M>(app: A, model: M)
pub fn run<A, M>(app: A, model: Rc<M>)
where
A: MvuApp<M>,
M: Copy,
{
env_logger::init();
let event_loop = EventLoop::new().unwrap();

View File

@ -1,14 +1,14 @@
use {
wasm_bindgen::prelude::*, wasm_bindgen_futures::spawn_local, web_sys::HtmlCanvasElement,
wgpu::SurfaceTarget,
std::rc::Rc, wasm_bindgen::prelude::*, wasm_bindgen_futures::spawn_local,
web_sys::HtmlCanvasElement, wgpu::SurfaceTarget,
};
use crate::mvu::{MvuApp, Size2i};
async fn run_async<A, M>(mut app: A, model: M)
async fn run_async<A, M>(mut app: A, model: Rc<M>)
where
A: MvuApp<M> + 'static,
M: Copy + 'static,
M: 'static,
{
let window = web_sys::window().unwrap();
let document = window.document().unwrap();
@ -26,10 +26,10 @@ where
app.view(model).await.unwrap();
}
pub fn run<A, M>(app: A, model: M)
pub fn run<A, M>(app: A, model: Rc<M>)
where
A: MvuApp<M> + 'static,
M: Copy + 'static,
M: 'static,
{
std::panic::set_hook(Box::new(console_error_panic_hook::hook));
console_log::init_with_level(log::Level::Info).expect("Couldn't initialize logger");