use std::sync::Arc; use std::sync::Mutex; use std::cmp::{min, max}; use std::time::Instant; use cgmath::Vector3; use std::thread; use std::sync::{mpsc, mpsc::Receiver, mpsc::Sender}; use byteorder::{LittleEndian, ByteOrder}; pub const NODE_TEX_SIZE: usize = 128; // 32x32x32 nodes in texture pub const NODE_TEX_SIZE_SQ: usize = NODE_TEX_SIZE*NODE_TEX_SIZE; pub const NODE_TEX_SIZE_QB: usize = NODE_TEX_SIZE*NODE_TEX_SIZE*NODE_TEX_SIZE; type NodeBuffer = (Vector3, Box<[u32]>); pub struct Nodes { buffer: Box<[u32]>, offset: Vector3, dirty: bool, shift: Option>, working: bool, channel: (Sender, Receiver) } impl Nodes { pub fn new() -> Self { Self { // Present buffer: vec![0_u32; NODE_TEX_SIZE_QB].into_boxed_slice(), offset: Vector3{x:0,y:0,z:0}, dirty: false, shift: None, working: false, channel: mpsc::channel() } } pub fn get_world_offset(&self) -> Vector3 { self.offset } pub fn get_node(&self, index: usize) -> u32 { self.buffer[index] } pub fn is_busy(&self) -> bool { self.shift != None } pub fn set_node(&mut self, index: usize, value: u32) { self.buffer[index] = value; self.dirty = true; } pub fn shift(&mut self, offset: &Vector3) { if self.shift == None { self.shift = Some(*offset); } else { println!("Tried to shift while another shifin was in progress"); } } pub fn update(&mut self, queue: &wgpu::Queue, texture: &wgpu::Texture) { // Check if there is some more work if !self.working { if let Some(offset) = self.shift { let source = self.buffer.clone(); let tx = self.channel.0.clone(); self.working = true; // Spawn worker thread::spawn(move || { let size = NODE_TEX_SIZE as i32; let mut target = vec![0_u32; NODE_TEX_SIZE_QB].into_boxed_slice(); let (ox, oy, oz) = (offset.x, offset.y, offset.z); // Copy slice of source buffer into target buffer for x in max(0, -ox)..min(size-ox, size) { for y in max(0, -oy)..min(size-oy, size) { for z in max(0, -oz)..min(size-oz, size) { let idx0 = x + size * (y + size * z); let idx1 = (x+ox) + size * ((y+oy) + size * (z+oz)); target[idx1 as usize] = source[idx0 as usize]; } } } // Send result tx.send((offset, target)).unwrap(); }); } } // Receive work while let Ok(result) = self.channel.1.try_recv() { self.offset += result.0; self.buffer = result.1; self.shift = None; self.dirty = true; self.working = false; } if self.dirty { self.dirty = false; // Write all nodes to gpu for z in 0..NODE_TEX_SIZE { // Convert u32 node buffer to u8 let node_origin = wgpu::Origin3d{ x:0, y: 0, z: z as u32 }; let node_size = wgpu::Extent3d { width: NODE_TEX_SIZE as u32, height: NODE_TEX_SIZE as u32, depth: 1 }; let mut node_bytes = [0_u8; NODE_TEX_SIZE_SQ*4]; let offset = NODE_TEX_SIZE_SQ*z; LittleEndian::write_u32_into(&self.buffer[offset..offset+NODE_TEX_SIZE_SQ], &mut node_bytes); // Write nodes queue.write_texture( wgpu::TextureCopyView { texture: texture, mip_level: 0, origin: node_origin }, &node_bytes, wgpu::TextureDataLayout { offset: 0, bytes_per_row: 4*node_size.width, rows_per_image: node_size.height }, node_size ); } } } }