Compare commits
No commits in common. "fdf1c4d33850857d67ad72e1c549a624ad8accc9" and "792596078d3800c3d2867a609fa89b3977f5a8a1" have entirely different histories.
fdf1c4d338
...
792596078d
|
@ -2,7 +2,7 @@ use std::sync::Arc;
|
|||
|
||||
use base64::Engine;
|
||||
|
||||
use crate::{ResourceLoader, LoaderError, Mesh, Model, MeshVertexAttribute, VertexAttributeData, Resource, Material, ResHandle};
|
||||
use crate::{ResourceLoader, LoaderError, Mesh, Model, MeshVertexAttribute, VertexAttributeData, Resource, Material, PbrRoughness};
|
||||
|
||||
impl From<gltf::Error> for LoaderError {
|
||||
fn from(value: gltf::Error) -> Self {
|
||||
|
@ -73,9 +73,7 @@ impl ModelLoader {
|
|||
new_mesh.indices = Some(indices);
|
||||
}
|
||||
|
||||
let mat = materials.get(prim.material().index().unwrap()).unwrap();
|
||||
new_mesh.set_material(mat.clone());
|
||||
//prim.material().
|
||||
prim.material().
|
||||
|
||||
meshes.push(new_mesh);
|
||||
}
|
||||
|
@ -115,7 +113,13 @@ impl ResourceLoader for ModelLoader {
|
|||
|
||||
// Load the materials
|
||||
let materials: Vec<Material> = gltf.materials()
|
||||
.map(|mat| Material::from(mat)).collect();
|
||||
.map(|mat| Material {
|
||||
double_sided: mat.double_sided(),
|
||||
name: mat.name().map(|s| s.to_string()),
|
||||
shader_uuid: None,
|
||||
pbr: Some(PbrRoughness::from(mat.pbr_metallic_roughness())),
|
||||
texture: None
|
||||
}).collect();
|
||||
|
||||
let meshes: Vec<Mesh> = scene.nodes()
|
||||
.map(|node| self.process_node(&buffers, &materials, node))
|
||||
|
@ -142,14 +146,12 @@ mod tests {
|
|||
|
||||
let loader = ModelLoader::default();
|
||||
let model = loader.load(&path).unwrap();
|
||||
let model = Arc::downcast::<Resource<Model>>(model.as_arc_any()).unwrap();
|
||||
let model = model.data.as_ref().unwrap();
|
||||
let model = Arc::downcast::<Model>(model.as_arc_any()).unwrap();
|
||||
assert_eq!(model.meshes.len(), 1); // There should only be 1 mesh
|
||||
let mesh = &model.meshes[0];
|
||||
assert!(mesh.position().unwrap().len() > 0);
|
||||
assert!(mesh.normals().unwrap().len() > 0);
|
||||
assert!(mesh.tex_coords().unwrap().len() > 0);
|
||||
assert!(mesh.indices.clone().unwrap().len() > 0);
|
||||
let _mesh_mat = mesh.material(); // inner panic if material was not loaded
|
||||
}
|
||||
}
|
|
@ -37,16 +37,6 @@ pub struct PbrGlossiness {
|
|||
// pub glossiness_texture // TODO
|
||||
}
|
||||
|
||||
impl From<gltf::material::PbrSpecularGlossiness<'_>> for PbrGlossiness {
|
||||
fn from(value: gltf::material::PbrSpecularGlossiness) -> Self {
|
||||
PbrGlossiness {
|
||||
diffuse_color: value.diffuse_factor(),
|
||||
specular: value.specular_factor(),
|
||||
glossiness: value.glossiness_factor()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
pub struct Material {
|
||||
pub shader_uuid: Option<u64>,
|
||||
|
@ -59,20 +49,3 @@ pub struct Material {
|
|||
|
||||
pub texture: Option<ResHandle<Texture>>,
|
||||
}
|
||||
|
||||
impl From<gltf::Material<'_>> for Material {
|
||||
fn from(value: gltf::Material) -> Self {
|
||||
Material {
|
||||
name: value.name()
|
||||
.map(|s| s.to_string()),
|
||||
double_sided: value.double_sided(),
|
||||
pbr_roughness: value.pbr_metallic_roughness().into(),
|
||||
pbr_glossiness: value.pbr_specular_glossiness()
|
||||
.map(|o| o.into()),
|
||||
alpha_cutoff: value.alpha_cutoff(),
|
||||
alpha_mode: value.alpha_mode(),
|
||||
shader_uuid: None,
|
||||
texture: None,
|
||||
}
|
||||
}
|
||||
}
|
|
@ -46,7 +46,7 @@ pub enum MeshVertexAttribute {
|
|||
pub struct Mesh {
|
||||
pub attributes: HashMap<MeshVertexAttribute, VertexAttributeData>,
|
||||
pub indices: Option<Vec<u32>>,
|
||||
material: Option<Material>,
|
||||
material: Option<ResHandle<Material>>,
|
||||
}
|
||||
|
||||
impl Mesh {
|
||||
|
@ -76,13 +76,9 @@ impl Mesh {
|
|||
.map(|p| p.as_vec2())
|
||||
}
|
||||
|
||||
pub fn material(&self) -> Material {
|
||||
pub fn material(&self) -> ResHandle<Material> {
|
||||
self.material.clone().expect("This mesh is missing a material!")
|
||||
}
|
||||
|
||||
pub fn set_material(&mut self, val: Material) {
|
||||
self.material = Some(val);
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
|
|
|
@ -1,16 +1,18 @@
|
|||
use edict::Component;
|
||||
|
||||
use lyra_resource::Mesh;
|
||||
use crate::render::{vertex::Vertex, mesh::Mesh, material::Material};
|
||||
|
||||
#[derive(Clone, Component)]
|
||||
pub struct MeshComponent {
|
||||
pub mesh: Mesh,
|
||||
pub material: Material,
|
||||
}
|
||||
|
||||
impl MeshComponent {
|
||||
pub fn new(mesh: Mesh) -> Self {
|
||||
pub fn new(mesh: Mesh, material: Material) -> Self {
|
||||
Self {
|
||||
mesh,
|
||||
material
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,22 +1,22 @@
|
|||
use lyra_resource::ResHandle;
|
||||
use crate::assets::{Model, Resource};
|
||||
|
||||
use crate::assets::Model;
|
||||
use std::sync::Arc;
|
||||
|
||||
#[derive(Clone, edict::Component)]
|
||||
pub struct ModelComponent(pub ResHandle<Model>);
|
||||
pub struct ModelComponent(pub Arc<Resource<Model>>);
|
||||
|
||||
impl From<ResHandle<Model>> for ModelComponent {
|
||||
fn from(value: ResHandle<Model>) -> Self {
|
||||
impl From<Arc<Resource<Model>>> for ModelComponent {
|
||||
fn from(value: Arc<Resource<Model>>) -> Self {
|
||||
ModelComponent(value)
|
||||
}
|
||||
}
|
||||
|
||||
/* impl From<ResHandle<Model> for ModelComponent {
|
||||
/* impl From<Arc<Resource<Model>> for ModelComponent {
|
||||
|
||||
} */
|
||||
|
||||
impl std::ops::Deref for ModelComponent {
|
||||
type Target = ResHandle<Model>;
|
||||
type Target = Arc<Resource<Model>>;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.0
|
||||
|
|
|
@ -2,11 +2,11 @@ use edict::EntityId;
|
|||
|
||||
use crate::math::Transform;
|
||||
|
||||
//use super::mesh::Mesh;
|
||||
use lyra_resource::Mesh;
|
||||
use super::{mesh::Mesh, material::Material};
|
||||
|
||||
pub struct RenderJob {
|
||||
mesh: Mesh,
|
||||
material: Material,
|
||||
entity: EntityId,
|
||||
|
||||
transform: Transform,
|
||||
|
@ -14,9 +14,10 @@ pub struct RenderJob {
|
|||
}
|
||||
|
||||
impl RenderJob {
|
||||
pub fn new(mesh: Mesh, entity: EntityId, transform: Transform, last_transform: Option<Transform>) -> Self {
|
||||
pub fn new(mesh: Mesh, material: Material, entity: EntityId, transform: Transform, last_transform: Option<Transform>) -> Self {
|
||||
Self {
|
||||
mesh,
|
||||
material,
|
||||
entity,
|
||||
transform,
|
||||
last_transform,
|
||||
|
@ -27,6 +28,10 @@ impl RenderJob {
|
|||
&self.mesh
|
||||
}
|
||||
|
||||
pub fn material(&self)-> &Material {
|
||||
&self.material
|
||||
}
|
||||
|
||||
pub fn entity(&self)-> EntityId {
|
||||
self.entity
|
||||
}
|
||||
|
|
|
@ -5,25 +5,30 @@ use std::num::NonZeroU64;
|
|||
use std::sync::Arc;
|
||||
use std::borrow::Cow;
|
||||
|
||||
use aligned_vec::AVec;
|
||||
use async_std::sync::Mutex;
|
||||
use async_trait::async_trait;
|
||||
|
||||
use atomicell::{AtomicCell, RefMut};
|
||||
use edict::query::EpochOf;
|
||||
use edict::{EntityId, Entities};
|
||||
use glam::Vec3;
|
||||
use glam::Mat4;
|
||||
use tracing::{debug, warn};
|
||||
use wgpu::{BindGroup, BindGroupLayout, Limits};
|
||||
use wgpu::{BindGroup, BindGroupLayout, Limits, BufferBinding};
|
||||
use wgpu::util::DeviceExt;
|
||||
use winit::window::Window;
|
||||
|
||||
use crate::ecs::components::camera::CameraComponent;
|
||||
use crate::ecs::components::mesh::MeshComponent;
|
||||
use crate::ecs::components::model::ModelComponent;
|
||||
use crate::ecs::components::transform::TransformComponent;
|
||||
use crate::math::{Transform, Angle};
|
||||
use crate::resources;
|
||||
|
||||
use super::camera::RenderCamera;
|
||||
use super::desc_buf_lay::DescVertexBufferLayout;
|
||||
use super::texture::RenderTexture;
|
||||
use super::{render_pipeline::FullRenderPipeline, render_buffer::BufferStorage, render_job::RenderJob};
|
||||
|
||||
use lyra_resource::Mesh;
|
||||
use super::vertex::Vertex;
|
||||
use super::{render_pipeline::FullRenderPipeline, render_buffer::BufferStorage, render_job::RenderJob, mesh::Mesh};
|
||||
|
||||
pub trait Renderer {
|
||||
fn prepare(&mut self, main_world: &mut edict::World);
|
||||
|
@ -31,7 +36,7 @@ pub trait Renderer {
|
|||
fn on_resize(&mut self, new_size: winit::dpi::PhysicalSize<u32>);
|
||||
|
||||
fn surface_size(&self) -> winit::dpi::PhysicalSize<u32>;
|
||||
fn add_render_pipeline(&mut self, shader_id: u64, pipeline: Arc<FullRenderPipeline>);
|
||||
fn add_render_pipeline(&mut self, shader_id: u32, pipeline: Arc<FullRenderPipeline>);
|
||||
}
|
||||
|
||||
struct RenderBufferStorage {
|
||||
|
@ -140,7 +145,7 @@ pub struct BasicRenderer {
|
|||
|
||||
pub clear_color: wgpu::Color,
|
||||
|
||||
pub render_pipelines: HashMap<u64, Arc<FullRenderPipeline>>,
|
||||
pub render_pipelines: HashMap<u32, Arc<FullRenderPipeline>>,
|
||||
pub render_jobs: VecDeque<RenderJob>,
|
||||
|
||||
buffer_storage: HashMap<EntityId, RenderBufferStorage>, // TODO: clean up left over buffers from deleted entities/components
|
||||
|
@ -386,13 +391,13 @@ impl BasicRenderer {
|
|||
}
|
||||
|
||||
// TODO: minimize how often model buffers are updated by checking if they changed
|
||||
fn update_mesh_buffers(&mut self, entity: EntityId, mesh: &Mesh) {
|
||||
fn update_model_buffers(&mut self, entity: EntityId, model: &MeshComponent) {
|
||||
if let Some(buffers) = self.buffer_storage.get_mut(&entity) {
|
||||
// check if the buffer sizes dont match. If they dont, completely remake the buffers
|
||||
let vertices = mesh.position().unwrap();
|
||||
let vertices = &model.mesh.vertices;
|
||||
if buffers.buffer_vertex.count() != vertices.len() {
|
||||
drop(buffers);
|
||||
let (vert, idx) = self.create_vertex_index_buffers(mesh);
|
||||
let (vert, idx) = self.create_vertex_index_buffers(&model.mesh);
|
||||
|
||||
// have to re-get buffers because of borrow checker
|
||||
let buffers = self.buffer_storage.get_mut(&entity).unwrap();
|
||||
|
@ -406,14 +411,14 @@ impl BasicRenderer {
|
|||
let vertex_buffer = buffers.buffer_vertex.buffer();
|
||||
let vertices = vertices.as_slice();
|
||||
// align the vertices to 4 bytes (u32 is 4 bytes, which is wgpu::COPY_BUFFER_ALIGNMENT)
|
||||
let (_, vertices, _) = bytemuck::pod_align_to::<Vec3, u32>(vertices);
|
||||
let (_, vertices, _) = bytemuck::pod_align_to::<Vertex, u32>(vertices);
|
||||
self.queue.write_buffer(&vertex_buffer, 0, bytemuck::cast_slice(&vertices));
|
||||
|
||||
// update the indices if they're given
|
||||
if let Some(index_buffer) = buffers.buffer_indices.as_ref() {
|
||||
let index_buffer = index_buffer.buffer();
|
||||
let indices = mesh.indices.as_ref().unwrap().as_slice();
|
||||
let (_, indices, _) = bytemuck::pod_align_to::<u32, u32>(indices); // TODO: Don't force indicies into u32
|
||||
let indices = model.mesh.indices.as_ref().unwrap().as_slice();
|
||||
let (_, indices, _) = bytemuck::pod_align_to::<u16, u32>(indices);
|
||||
|
||||
self.queue.write_buffer(index_buffer, 0, bytemuck::cast_slice(&indices));
|
||||
}
|
||||
|
@ -421,15 +426,14 @@ impl BasicRenderer {
|
|||
}
|
||||
|
||||
fn create_vertex_index_buffers(&mut self, mesh: &Mesh) -> (BufferStorage, Option<BufferStorage>) {
|
||||
let vertices = mesh.position().unwrap();
|
||||
let vertex_buffer = self.device.create_buffer_init(
|
||||
&wgpu::util::BufferInitDescriptor {
|
||||
label: Some("Vertex Buffer"),
|
||||
contents: bytemuck::cast_slice(vertices.as_slice()),
|
||||
contents: bytemuck::cast_slice(mesh.vertices.as_slice()),
|
||||
usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages:: COPY_DST,
|
||||
}
|
||||
);
|
||||
let vertex_buffer = BufferStorage::new(vertex_buffer, 0, vertices.len());
|
||||
let vertex_buffer = BufferStorage::new(vertex_buffer, 0, mesh.vertices.len());
|
||||
|
||||
let buffer_indices = match mesh.indices.as_ref() {
|
||||
Some(indices) => {
|
||||
|
@ -453,10 +457,12 @@ impl BasicRenderer {
|
|||
( vertex_buffer, buffer_indices )
|
||||
}
|
||||
|
||||
fn create_mesh_buffers(&mut self, mesh: &Mesh, transform_indices: TransformBufferIndices) -> RenderBufferStorage {
|
||||
fn create_model_buffers(&mut self, model: &MeshComponent, transform_indices: TransformBufferIndices) -> RenderBufferStorage {
|
||||
let mesh = &model.mesh;
|
||||
|
||||
let (vertex_buffer, buffer_indices) = self.create_vertex_index_buffers(mesh);
|
||||
|
||||
let (diffuse_layout, diffuse_bindgroup) = if let Some(model_texture) = &mesh.material().texture {
|
||||
let model_texture = &model.material.texture;
|
||||
let image = &model_texture.data.as_ref().unwrap().image;
|
||||
let diffuse_texture = RenderTexture::from_image(&self.device, &self.queue, image, None).unwrap();
|
||||
|
||||
|
@ -502,17 +508,12 @@ impl BasicRenderer {
|
|||
}
|
||||
);
|
||||
|
||||
(Some(texture_bind_group_layout), Some(diffuse_bind_group))
|
||||
} else {
|
||||
(None, None)
|
||||
};
|
||||
|
||||
RenderBufferStorage {
|
||||
buffer_vertex: vertex_buffer,
|
||||
buffer_indices,
|
||||
render_texture: None,
|
||||
texture_layout: diffuse_layout,
|
||||
texture_bindgroup: diffuse_bindgroup,
|
||||
texture_layout: None,
|
||||
texture_bindgroup: Some(diffuse_bind_group),
|
||||
transform_index: transform_indices
|
||||
}
|
||||
}
|
||||
|
@ -560,13 +561,9 @@ impl Renderer for BasicRenderer {
|
|||
|
||||
let mut alive_entities = HashSet::new();
|
||||
|
||||
for (entity, model, model_epoch, transform) in main_world.query::<(Entities, &ModelComponent, EpochOf<ModelComponent>, &TransformComponent)>().iter() {
|
||||
debug!("Collecting model things");
|
||||
let model = model.data.as_ref().unwrap().as_ref();
|
||||
let model_mesh = model.meshes.first().unwrap();
|
||||
|
||||
for (entity, model, model_epoch, transform) in main_world.query::<(Entities, &MeshComponent, EpochOf<MeshComponent>, &TransformComponent)>().iter() {
|
||||
// Create the render job and push it to the queue
|
||||
let job = RenderJob::new(model_mesh.clone(), entity, transform.transform, None);
|
||||
let job = RenderJob::new(model.mesh.clone(), model.material.clone(), entity, transform.transform, None);
|
||||
self.render_jobs.push_back(job);
|
||||
|
||||
alive_entities.insert(entity);
|
||||
|
@ -582,7 +579,7 @@ impl Renderer for BasicRenderer {
|
|||
entity, transform.transform.calculate_mat4());
|
||||
|
||||
// create the mesh's buffers
|
||||
let buffers = self.create_mesh_buffers(model_mesh, indices);
|
||||
let buffers = self.create_model_buffers(model, indices);
|
||||
self.buffer_storage.insert(entity, buffers);
|
||||
} else {
|
||||
// update entity transforms
|
||||
|
@ -591,15 +588,11 @@ impl Renderer for BasicRenderer {
|
|||
|
||||
// if the model was updated, update its buffers
|
||||
if model_epoch == last_epoch {
|
||||
self.update_mesh_buffers(entity, model_mesh);
|
||||
self.update_model_buffers(entity, model);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (entity, mesh, mesh_epoch, transform) in main_world.query::<(Entities, &MeshComponent, EpochOf<MeshComponent>, &TransformComponent)>().iter() {
|
||||
debug!("TODO: Process MeshComponents"); // TODO: Process MeshComponents
|
||||
}
|
||||
|
||||
// collect dead entities
|
||||
self.transform_buffers.tick();
|
||||
|
||||
|
@ -649,11 +642,9 @@ impl Renderer for BasicRenderer {
|
|||
}),
|
||||
});
|
||||
|
||||
debug!("Executing {} render jobs", self.render_jobs.len());
|
||||
|
||||
// Pop off jobs from the queue as they're being processed
|
||||
while let Some(job) = self.render_jobs.pop_front() {
|
||||
if let Some(pipeline) = self.render_pipelines.get(&job.mesh().material().shader_uuid.unwrap_or(0)) {
|
||||
if let Some(pipeline) = self.render_pipelines.get(&job.material().shader_id) {
|
||||
// specify to use this pipeline
|
||||
render_pass.set_pipeline(pipeline.get_wgpu_pipeline());
|
||||
|
||||
|
@ -683,13 +674,11 @@ impl Renderer for BasicRenderer {
|
|||
render_pass.set_index_buffer(indices.buffer().slice(..), wgpu::IndexFormat::Uint16);
|
||||
render_pass.draw_indexed(0..indices_len, 0, 0..1);
|
||||
} else {
|
||||
let vertices = mesh.position().unwrap();
|
||||
|
||||
render_pass.set_vertex_buffer(buffers.buffer_vertex.slot(), buffers.buffer_vertex.buffer().slice(..));
|
||||
render_pass.draw(0..vertices.len() as u32, 0..1);
|
||||
render_pass.draw(0..mesh.vertices.len() as u32, 0..1);
|
||||
}
|
||||
} else {
|
||||
warn!("Failure to find RenderPipeline with shader id of '{}'!", job.mesh().material().shader_uuid.unwrap_or(0));
|
||||
warn!("Failure to find RenderPipeline with shader id of '{}'!", job.material().shader_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -717,7 +706,7 @@ impl Renderer for BasicRenderer {
|
|||
self.size
|
||||
}
|
||||
|
||||
fn add_render_pipeline(&mut self, shader_id: u64, pipeline: Arc<FullRenderPipeline>) {
|
||||
fn add_render_pipeline(&mut self, shader_id: u32, pipeline: Arc<FullRenderPipeline>) {
|
||||
self.render_pipelines.insert(shader_id, pipeline);
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue