summaryrefslogtreecommitdiff
path: root/engine/src/renderer
diff options
context:
space:
mode:
Diffstat (limited to 'engine/src/renderer')
-rw-r--r--engine/src/renderer/object.rs123
-rw-r--r--engine/src/renderer/opengl.rs1661
-rw-r--r--engine/src/renderer/opengl/glsl/fragment.glsl73
-rw-r--r--engine/src/renderer/opengl/glsl/light.glsl133
-rw-r--r--engine/src/renderer/opengl/glsl/vertex.glsl24
-rw-r--r--engine/src/renderer/opengl/glsl/vertex_data.glsl11
-rw-r--r--engine/src/renderer/opengl/glutin_compat.rs268
-rw-r--r--engine/src/renderer/opengl/graphics_mesh.rs136
-rw-r--r--engine/src/renderer/opengl/vertex.rs65
9 files changed, 1694 insertions, 800 deletions
diff --git a/engine/src/renderer/object.rs b/engine/src/renderer/object.rs
new file mode 100644
index 0000000..357bd6a
--- /dev/null
+++ b/engine/src/renderer/object.rs
@@ -0,0 +1,123 @@
+use std::collections::HashMap;
+use std::collections::hash_map::Entry as HashMapEntry;
+
+use ecs::Component;
+
+use crate::asset::Id as AssetId;
+
+/// Renderer object ID.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
+pub enum Id
+{
+ Asset(AssetId),
+ Other(u64),
+}
+
+/// Renderer object store.
+#[derive(Debug, Default, Component)]
+pub struct Store
+{
+ objects: HashMap<Id, Object>,
+}
+
+impl Store
+{
+ pub fn get_obj(&self, id: &Id) -> Option<&Object>
+ {
+ self.objects.get(id)
+ }
+
+ pub fn get_texture_obj(&self, id: &Id) -> Option<&Object>
+ {
+ let obj = self.get_obj(id)?;
+
+ if !matches!(obj.kind(), Kind::Texture) {
+ return None;
+ }
+
+ Some(obj)
+ }
+
+ pub fn get_shader_program_obj(&self, id: &Id) -> Option<&Object>
+ {
+ let obj = self.get_obj(id)?;
+
+ if !matches!(obj.kind(), Kind::ShaderProgram) {
+ return None;
+ }
+
+ Some(obj)
+ }
+
+ pub fn contains_with_id(&self, id: &Id) -> bool
+ {
+ self.objects.contains_key(id)
+ }
+
+ pub fn insert(&mut self, id: Id, object: Object)
+ {
+ self.objects.insert(id, object);
+ }
+
+ pub fn entry(&mut self, id: Id) -> StoreEntry<'_>
+ {
+ StoreEntry { inner: self.objects.entry(id) }
+ }
+}
+
+#[derive(Debug)]
+pub struct StoreEntry<'store>
+{
+ inner: HashMapEntry<'store, Id, Object>,
+}
+
+impl<'store> StoreEntry<'store>
+{
+ pub fn or_insert(self, default_obj: Object) -> &'store mut Object
+ {
+ self.inner.or_insert(default_obj)
+ }
+
+ pub fn or_insert_with(
+ self,
+ default_func: impl FnOnce() -> Object,
+ ) -> &'store mut Object
+ {
+ self.inner.or_insert_with(default_func)
+ }
+}
+
+/// Renderer object.
+#[derive(Debug, Clone)]
+pub struct Object
+{
+ raw: u32,
+ kind: Kind,
+}
+
+impl Object
+{
+ pub fn from_raw(raw: u32, kind: Kind) -> Self
+ {
+ Self { raw, kind }
+ }
+
+ pub fn as_raw(&self) -> u32
+ {
+ self.raw
+ }
+
+ pub fn kind(&self) -> Kind
+ {
+ self.kind
+ }
+}
+
+/// Renderer object kind.
+#[derive(Debug, Clone, Copy)]
+#[non_exhaustive]
+pub enum Kind
+{
+ Texture,
+ ShaderProgram,
+}
diff --git a/engine/src/renderer/opengl.rs b/engine/src/renderer/opengl.rs
index deb26a8..c72a344 100644
--- a/engine/src/renderer/opengl.rs
+++ b/engine/src/renderer/opengl.rs
@@ -1,70 +1,143 @@
//! OpenGL renderer.
+use std::any::type_name;
+use std::borrow::Cow;
use std::collections::HashMap;
-use std::ffi::{c_void, CString};
-use std::io::{Error as IoError, ErrorKind as IoErrorKind};
-use std::ops::Deref;
-use std::path::Path;
-use std::process::abort;
use ecs::actions::Actions;
-use ecs::component::local::Local;
-use ecs::query::options::{Not, With};
+use ecs::entity::obtainer::Obtainer as EntityObtainer;
+use ecs::event::component::{Changed, Removed};
+use ecs::pair::{ChildOf, Pair, Wildcard};
+use ecs::phase::{Phase, START as START_PHASE};
+use ecs::query::term::Without;
use ecs::sole::Single;
-use ecs::system::{Into as _, System};
-use ecs::{Component, Query};
-
-use crate::camera::{Active as ActiveCamera, Camera};
-use crate::color::Color;
-use crate::data_types::dimens::Dimens;
-use crate::draw_flags::{DrawFlags, NoDraw, PolygonModeConfig};
-use crate::event::{Present as PresentEvent, Start as StartEvent};
-use crate::lighting::{DirectionalLight, GlobalLight, PointLight};
-use crate::material::{Flags as MaterialFlags, Material};
-use crate::matrix::Matrix;
-use crate::mesh::Mesh;
-use crate::opengl::buffer::{Buffer, Usage as BufferUsage};
-#[cfg(feature = "debug")]
-use crate::opengl::debug::{MessageSeverity, MessageSource, MessageType};
-use crate::opengl::glsl::{
- preprocess as glsl_preprocess,
- PreprocessingError as GlslPreprocessingError,
+use ecs::system::observer::Observe;
+use ecs::{Component, Query, declare_entity};
+use glutin::display::GetGlDisplay;
+use glutin::prelude::GlDisplay;
+use glutin::surface::{
+ GlSurface,
+ Surface as GlutinSurface,
+ WindowSurface as GlutinWindowSurface,
+};
+use opengl_bindings::debug::{
+ MessageIdsAction,
+ MessageSeverity,
+ MessageSource,
+ MessageType,
+ SetDebugMessageControlError as GlSetDebugMessageControlError,
+ set_debug_message_callback,
+ set_debug_message_control,
+};
+use opengl_bindings::misc::{
+ BufferClearMask as GlBufferClearMask,
+ Capability,
+ SetViewportError as GlSetViewportError,
+ clear_buffers,
+ enable,
+ set_enabled,
};
-use crate::opengl::shader::{
+use opengl_bindings::shader::{
Error as GlShaderError,
Kind as ShaderKind,
Program as GlShaderProgram,
Shader as GlShader,
+ // UniformLocation as GlUniformLocation,
};
-use crate::opengl::texture::{
- set_active_texture_unit,
+use opengl_bindings::texture::{
+ Filtering as GlTextureFiltering,
+ GenerateError as GlTextureGenerateError,
+ PixelDataFormat as GlTexturePixelDataFormat,
Texture as GlTexture,
- TextureUnit,
+ Wrapping as GlTextureWrapping,
};
-use crate::opengl::vertex_array::{
- DataType as VertexArrayDataType,
+use opengl_bindings::vertex_array::{
+ DrawError as GlDrawError,
PrimitiveKind,
VertexArray,
};
-use crate::opengl::{clear_buffers, enable, BufferClearMask, Capability};
-use crate::projection::{new_perspective_matrix, Projection};
-use crate::texture::{Id as TextureId, Texture};
-use crate::transform::{Position, Scale};
-use crate::util::NeverDrop;
+use opengl_bindings::{ContextWithFns, CurrentContextWithFns};
+use safer_ffi::layout::ReprC;
+use zerocopy::{Immutable, IntoBytes};
+
+use crate::asset::{Assets, Id as AssetId};
+use crate::data_types::dimens::Dimens;
+use crate::image::{ColorType as ImageColorType, Image};
+use crate::matrix::Matrix;
+use crate::model::Model;
+use crate::renderer::object::{
+ Id as RendererObjectId,
+ Kind as RendererObjectKind,
+ Object as RendererObject,
+ Store as RendererObjectStore,
+};
+use crate::renderer::opengl::glutin_compat::{
+ DisplayBuilder,
+ Error as GlutinCompatError,
+};
+use crate::renderer::opengl::graphics_mesh::GraphicsMesh;
+use crate::renderer::{
+ BufferClearMask,
+ Command as RendererCommand,
+ CommandQueue as RendererCommandQueue,
+ CtxUsedByWindow as RendererCtxUsedByWindow,
+ GraphicsProperties,
+ PRE_RENDER_PHASE,
+ RENDER_PHASE,
+ SurfaceId,
+ SurfaceSpec,
+ WindowUsingRendererCtx,
+};
+use crate::shader::cursor::BindingValue as ShaderBindingValue;
+use crate::shader::{
+ Error as ShaderError,
+ Program as ShaderProgram,
+ Stage as ShaderStage,
+};
+use crate::texture::{
+ Filtering as TextureFiltering,
+ Properties as TextureProperties,
+ Wrapping as TextureWrapping,
+};
use crate::vector::{Vec2, Vec3};
-use crate::vertex::{AttributeComponentType, Vertex};
-use crate::window::Window;
-
-type RenderableEntity = (
- Mesh,
- Material,
- Option<MaterialFlags>,
- Option<Position>,
- Option<Scale>,
- Option<DrawFlags>,
- Option<GlObjects>,
+use crate::windowing::Context as WindowingContext;
+use crate::windowing::window::{
+ Closed as WindowClosed,
+ CreationAttributes as WindowCreationAttributes,
+ CreationReady,
+ Window,
+};
+
+mod glutin_compat;
+mod graphics_mesh;
+mod vertex;
+
+declare_entity!(
+ pub POST_RENDER_PHASE,
+ (Phase, Pair::builder().relation::<ChildOf>().target_id(*RENDER_PHASE).build())
);
+#[derive(Debug, Component)]
+struct WindowGlConfig
+{
+ gl_config: glutin::config::Config,
+}
+
+#[derive(Component)]
+struct GraphicsContext
+{
+ gl_context: ContextWithFns,
+ graphics_mesh_store: GraphicsMeshStore,
+ surfaces: HashMap<SurfaceId, GlutinSurface<GlutinWindowSurface>>,
+ uniform_buffer_objs: HashMap<u32, opengl_bindings::buffer::Buffer<u8>>,
+}
+
+#[derive(Debug, Default)]
+struct GraphicsMeshStore
+{
+ graphics_meshes: HashMap<AssetId, GraphicsMesh>,
+}
+
#[derive(Debug, Default)]
#[non_exhaustive]
pub struct Extension {}
@@ -73,622 +146,1010 @@ impl ecs::extension::Extension for Extension
{
fn collect(self, mut collector: ecs::extension::Collector<'_>)
{
- collector.add_system(StartEvent, initialize);
-
- collector.add_system(
- PresentEvent,
- render
- .into_system()
- .initialize((GlobalGlObjects::default(),)),
- );
- }
-}
-
-fn initialize(window: Single<Window>)
-{
- window
- .make_context_current()
- .expect("Failed to make window context current");
-
- gl::load_with(|symbol| match window.get_proc_address(symbol) {
- Ok(addr) => addr as *const c_void,
- Err(err) => {
- println!(
- "FATAL ERROR: Failed to get adress of OpenGL function {symbol}: {err}",
- );
-
- abort();
- }
- });
+ collector.add_declared_entity(&PRE_RENDER_PHASE);
+ collector.add_declared_entity(&RENDER_PHASE);
+ collector.add_declared_entity(&POST_RENDER_PHASE);
- #[cfg(feature = "debug")]
- initialize_debug();
+ collector.add_system(*START_PHASE, super::init);
- let window_size = window.size().expect("Failed to get window size");
+ collector.add_system(*RENDER_PHASE, super::enqueue_commands);
+ collector.add_system(*RENDER_PHASE, handle_commands);
- set_viewport(Vec2 { x: 0, y: 0 }, window_size);
+ collector.add_system(*POST_RENDER_PHASE, prepare_windows);
+ collector.add_system(*POST_RENDER_PHASE, init_window_graphics);
- window.set_framebuffer_size_callback(|new_window_size| {
- set_viewport(Vec2::ZERO, new_window_size);
- });
+ collector.add_observer(handle_model_removed);
- enable(Capability::DepthTest);
- enable(Capability::MultiSample);
+ collector.add_observer(handle_window_changed);
+ collector.add_observer(handle_window_removed);
+ }
}
-#[allow(clippy::too_many_arguments)]
-fn render(
- query: Query<RenderableEntity, Not<With<NoDraw>>>,
- point_light_query: Query<(PointLight,)>,
- directional_lights: Query<(DirectionalLight,)>,
- camera_query: Query<(Camera, Position, ActiveCamera)>,
- window: Single<Window>,
- global_light: Single<GlobalLight>,
- mut gl_objects: Local<GlobalGlObjects>,
- mut actions: Actions,
+#[tracing::instrument(skip_all)]
+fn handle_model_removed(
+ observe: Observe<Pair<Removed, Model>>,
+ renderer_ctx_query: Query<(
+ &mut GraphicsContext,
+ Pair<RendererCtxUsedByWindow, Wildcard>,
+ )>,
+ assets: Single<Assets>,
)
{
- let Some((camera, camera_pos, _)) = camera_query.iter().next() else {
- #[cfg(feature = "debug")]
- tracing::warn!("No current camera. Nothing will be rendered");
- return;
- };
-
- let point_lights = point_light_query
- .iter()
- .map(|(point_light,)| point_light)
- .collect::<Vec<_>>();
-
- let directional_lights = directional_lights.iter().collect::<Vec<_>>();
-
- let GlobalGlObjects {
- shader_program,
- textures: gl_textures,
- } = &mut *gl_objects;
+ for evt_match in &observe {
+ let model_ent_id = evt_match.id();
+
+ for (renderer_ctx_ent_id, (mut graphics_ctx, renderer_ctx_used_by_window)) in
+ renderer_ctx_query.iter_with_euids()
+ {
+ let GraphicsContext {
+ ref gl_context,
+ ref mut graphics_mesh_store,
+ ref surfaces,
+ ..
+ } = *graphics_ctx;
+
+ let model = evt_match.get_removed_comp();
+
+ let Some(model_spec) = assets.get(&model.spec_asset) else {
+ continue;
+ };
- let shader_program =
- shader_program.get_or_insert_with(|| create_default_shader_program().unwrap());
+ let Some(mesh_asset) = &model_spec.mesh_asset else {
+ continue;
+ };
- clear_buffers(BufferClearMask::COLOR | BufferClearMask::DEPTH);
+ if !graphics_mesh_store
+ .graphics_meshes
+ .contains_key(&mesh_asset.id())
+ {
+ continue;
+ }
- for (
- entity_index,
- (mesh, material, material_flags, position, scale, draw_flags, gl_objects),
- ) in query.iter().enumerate()
- {
- let material_flags = material_flags
- .map(|material_flags| material_flags.clone())
- .unwrap_or_default();
+ let Some(window_ent) = renderer_ctx_used_by_window.get_target_ent() else {
+ tracing::error!(
+ window_entity_id = %renderer_ctx_used_by_window.id().target_entity(),
+ "Window entity does not exist"
+ );
+ continue;
+ };
- let new_gl_objects;
+ let Some(surface_spec) = window_ent.get::<SurfaceSpec>() else {
+ tracing::error!(
+ window_entity_id = %window_ent.uid(),
+ "Window entity does not have a {} component",
+ type_name::<SurfaceSpec>()
+ );
+ continue;
+ };
- let gl_objects = if let Some(gl_objects) = gl_objects.as_deref() {
- gl_objects
- } else {
- // TODO: Account for when meshes are changed
- let gl_objects = GlObjects::new(&mesh);
+ let Some(surface) = surfaces.get(&surface_spec.id) else {
+ tracing::error!(
+ window_entity_id = %window_ent.uid(),
+ "Surface specified by window entity's {} component does not exist",
+ type_name::<SurfaceSpec>()
+ );
+ continue;
+ };
- new_gl_objects = Some(gl_objects.clone());
+ let curr_gl_ctx = match gl_context.make_current(surface) {
+ Ok(curr_gl_ctx) => curr_gl_ctx,
+ Err(err) => {
+ tracing::error!("{err}");
+ continue;
+ }
+ };
- actions.add_components(
- query.get_entity_uid(entity_index).unwrap(),
- (gl_objects,),
+ tracing::debug!(
+ model_entity_id=%model_ent_id,
+ renderer_ctx_entity_id=%renderer_ctx_ent_id,
+ "Cleaning up after model in renderer context"
);
- &*new_gl_objects.unwrap()
- };
-
- apply_transformation_matrices(
- Transformation {
- position: position.map(|pos| *pos).unwrap_or_default().position,
- scale: scale.map(|scale| *scale).unwrap_or_default().scale,
- },
- shader_program,
- &camera,
- &camera_pos,
- window.size().expect("Failed to get window size"),
- );
+ let Some(mut graphics_mesh) =
+ graphics_mesh_store.graphics_meshes.remove(&mesh_asset.id())
+ else {
+ tracing::warn!(
+ model_entity_id=%model_ent_id,
+ "No mesh exists for model"
+ );
+ continue;
+ };
- apply_light(
- &material,
- &material_flags,
- &global_light,
- shader_program,
- point_lights.as_slice(),
- directional_lights
- .iter()
- .map(|(dir_light,)| &**dir_light)
- .collect::<Vec<_>>()
- .as_slice(),
- &camera_pos,
- );
+ graphics_mesh.destroy(&curr_gl_ctx);
+ }
+ }
+}
- for texture in &material.textures {
- let gl_texture = gl_textures
- .entry(texture.id())
- .or_insert_with(|| create_gl_texture(texture));
+#[tracing::instrument(skip_all)]
+fn handle_window_changed(
+ observe: Observe<Pair<Changed, Window>>,
+ entity_obtainer: EntityObtainer,
+)
+{
+ for evt_match in &observe {
+ let window_ent = evt_match.get_ent_infallible();
- let texture_unit =
- TextureUnit::from_texture_id(texture.id()).unwrap_or_else(|| {
- panic!("Texture id {} is a invalid texture unit", texture.id());
- });
+ tracing::trace!(
+ new_state = ?evt_match.get_changed_comp(),
+ "Handling window change"
+ );
- set_active_texture_unit(texture_unit);
+ let Some(surface_spec) = window_ent.get::<SurfaceSpec>() else {
+ continue;
+ };
- gl_texture.bind();
- }
+ let Some(renderer_ctx_ent_id) = window_ent
+ .get_matching_components(
+ Pair::builder()
+ .relation::<WindowUsingRendererCtx>()
+ .target_id(Wildcard::uid())
+ .build()
+ .id(),
+ )
+ .next()
+ .map(|comp_ref| comp_ref.id().target_entity())
+ else {
+ continue;
+ };
- shader_program.activate();
+ let Some(renderer_ctx_ent) = entity_obtainer.get_entity(renderer_ctx_ent_id)
+ else {
+ tracing::error!("Renderer context entity does not exist");
+ continue;
+ };
- if let Some(draw_flags) = &draw_flags {
- crate::opengl::set_polygon_mode(
- draw_flags.polygon_mode_config.face,
- draw_flags.polygon_mode_config.mode,
+ let Some(graphics_context) = renderer_ctx_ent.get::<GraphicsContext>() else {
+ tracing::error!(
+ "Renderer context entity does not have a GraphicsContext component"
);
- }
+ continue;
+ };
- draw_mesh(gl_objects);
+ let Some(surface) = graphics_context.surfaces.get(&surface_spec.id) else {
+ tracing::error!(
+ window_entity_id = %window_ent.uid(),
+ "Surface specified by window entity's {} component does not exist",
+ type_name::<SurfaceSpec>()
+ );
+ continue;
+ };
- if draw_flags.is_some() {
- let default_polygon_mode_config = PolygonModeConfig::default();
+ let Ok(current_graphics_context) =
+ graphics_context.gl_context.make_current(surface)
+ else {
+ tracing::error!("Failed to make graphics context current");
+ continue;
+ };
- crate::opengl::set_polygon_mode(
- default_polygon_mode_config.face,
- default_polygon_mode_config.mode,
- );
+ if let Err(err) = set_viewport(
+ &current_graphics_context,
+ Vec2::default(),
+ evt_match.get_changed_comp().inner_size(),
+ ) {
+ tracing::error!("Failed to set viewport: {err}");
}
}
}
-#[derive(Debug, Default, Component)]
-struct GlobalGlObjects
-{
- shader_program: Option<GlShaderProgram>,
- textures: HashMap<TextureId, GlTexture>,
-}
-
-fn set_viewport(position: Vec2<u32>, size: Dimens<u32>)
-{
- crate::opengl::set_viewport(position, size);
-}
-
-#[cfg(feature = "debug")]
-fn initialize_debug()
+#[tracing::instrument(skip_all)]
+fn handle_window_removed(observe: Observe<Pair<Removed, Window>>, mut actions: Actions)
{
- use crate::opengl::debug::{
- enable_debug_output,
- set_debug_message_callback,
- set_debug_message_control,
- MessageIdsAction,
- };
-
- enable_debug_output();
+ for evt_match in &observe {
+ let window_ent_id = evt_match.id();
- set_debug_message_callback(opengl_debug_message_cb);
+ let window_ent = evt_match.get_ent_infallible();
- set_debug_message_control(None, None, None, &[], MessageIdsAction::Disable);
-}
+ tracing::debug!(
+ entity_id = %window_ent_id,
+ title = %evt_match.get_removed_comp().title,
+ "Handling removal of window"
+ );
-fn draw_mesh(gl_objects: &GlObjects)
-{
- gl_objects.vertex_arr.bind();
+ actions.remove_comps::<(SurfaceSpec, WindowGlConfig)>(window_ent_id);
- if gl_objects.index_buffer.is_some() {
- VertexArray::draw_elements(PrimitiveKind::Triangles, 0, gl_objects.index_cnt);
- } else {
- VertexArray::draw_arrays(PrimitiveKind::Triangles, 0, 3);
- }
-}
+ let Some(with_renderer_ctx_pair) = window_ent
+ .get_first_wildcard_pair_match::<WindowUsingRendererCtx, Wildcard>()
+ else {
+ tracing::warn!(
+ "Window entity is missing a ({}, *) pair",
+ type_name::<WindowUsingRendererCtx>()
+ );
+ continue;
+ };
-fn create_gl_texture(texture: &Texture) -> GlTexture
-{
- let mut gl_texture = GlTexture::new();
+ let renderer_context_ent_id = with_renderer_ctx_pair.id().target_entity();
- gl_texture.generate(
- *texture.dimensions(),
- texture.image().as_bytes(),
- texture.pixel_data_format(),
- );
+ actions.remove_comps::<(GraphicsContext, RendererObjectStore)>(
+ renderer_context_ent_id,
+ );
- gl_texture.apply_properties(texture.properties());
+ actions.remove_components(
+ renderer_context_ent_id,
+ [Pair::builder()
+ .relation::<RendererCtxUsedByWindow>()
+ .target_id(window_ent_id)
+ .build()
+ .id()],
+ );
- gl_texture
+ actions.remove_components(window_ent_id, [with_renderer_ctx_pair.id()]);
+ }
}
-const VERTEX_GLSL_SHADER_SRC: &str = include_str!("opengl/glsl/vertex.glsl");
-const FRAGMENT_GLSL_SHADER_SRC: &str = include_str!("opengl/glsl/fragment.glsl");
-
-const VERTEX_DATA_GLSL_SHADER_SRC: &str = include_str!("opengl/glsl/vertex_data.glsl");
-const LIGHT_GLSL_SHADER_SRC: &str = include_str!("opengl/glsl/light.glsl");
-
-fn create_default_shader_program() -> Result<GlShaderProgram, CreateShaderError>
+#[derive(Debug, Component)]
+struct SetupFailed;
+
+fn prepare_windows(
+ window_query: Query<
+ (
+ Option<&Window>,
+ &mut WindowCreationAttributes,
+ Option<&GraphicsProperties>,
+ ),
+ (
+ Without<CreationReady>,
+ Without<WindowGlConfig>,
+ Without<WindowClosed>,
+ Without<SetupFailed>,
+ ),
+ >,
+ windowing_context: Single<WindowingContext>,
+ mut actions: Actions,
+)
{
- let mut vertex_shader = GlShader::new(ShaderKind::Vertex);
-
- vertex_shader.set_source(&*glsl_preprocess(
- VERTEX_GLSL_SHADER_SRC,
- &get_glsl_shader_content,
- )?)?;
-
- vertex_shader.compile()?;
-
- let mut fragment_shader = GlShader::new(ShaderKind::Fragment);
+ let Some(display_handle) = windowing_context.display_handle() else {
+ return;
+ };
- fragment_shader.set_source(&*glsl_preprocess(
- FRAGMENT_GLSL_SHADER_SRC,
- &get_glsl_shader_content,
- )?)?;
+ for (window_ent_id, (window, mut window_creation_attrs, graphics_props)) in
+ window_query.iter_with_euids()
+ {
+ tracing::debug!("Preparing window entity {window_ent_id} for use in rendering");
- fragment_shader.compile()?;
+ let mut glutin_config_template_builder =
+ glutin::config::ConfigTemplateBuilder::new();
- let mut gl_shader_program = GlShaderProgram::new();
+ let graphics_props = match graphics_props.as_ref() {
+ Some(graphics_props) => &*graphics_props,
+ None => {
+ actions.add_components(window_ent_id, (GraphicsProperties::default(),));
- gl_shader_program.attach(&vertex_shader);
- gl_shader_program.attach(&fragment_shader);
+ &GraphicsProperties::default()
+ }
+ };
- gl_shader_program.link()?;
+ if let Some(multisampling_sample_cnt) = graphics_props.multisampling_sample_cnt {
+ glutin_config_template_builder = glutin_config_template_builder
+ .with_multisampling(multisampling_sample_cnt);
+ }
- Ok(gl_shader_program)
-}
+ let window_handle = match window
+ .as_ref()
+ .map(|window| unsafe {
+ windowing_context.get_window_as_handle(&window.wid())
+ })
+ .flatten()
+ .transpose()
+ {
+ Ok(window_handle) => window_handle,
+ Err(err) => {
+ tracing::error!("Failed to get window handle: {err}");
+ actions.add_components(window_ent_id, (SetupFailed,));
+ continue;
+ }
+ };
-#[derive(Debug, thiserror::Error)]
-enum CreateShaderError
-{
- #[error(transparent)]
- ShaderError(#[from] GlShaderError),
+ let (new_window_creation_attrs, gl_config) = match DisplayBuilder::new()
+ .with_window_attributes(window_creation_attrs.clone())
+ .build(
+ window_handle,
+ &display_handle,
+ glutin_config_template_builder,
+ |mut cfgs| cfgs.next(),
+ ) {
+ Ok((new_window_creation_attrs, gl_config)) => {
+ (new_window_creation_attrs, gl_config)
+ }
+ Err(GlutinCompatError::WindowRequired) => {
+ actions.add_components(window_ent_id, (CreationReady,));
+ continue;
+ }
+ Err(err) => {
+ tracing::error!("Failed to create platform graphics display: {err}");
+ actions.add_components(window_ent_id, (SetupFailed,));
+ continue;
+ }
+ };
- #[error(transparent)]
- PreprocessingError(#[from] GlslPreprocessingError),
-}
+ *window_creation_attrs = new_window_creation_attrs;
-fn get_glsl_shader_content(path: &Path) -> Result<Vec<u8>, std::io::Error>
-{
- if path == Path::new("vertex_data.glsl") {
- return Ok(VERTEX_DATA_GLSL_SHADER_SRC.as_bytes().to_vec());
- }
+ actions.add_components(window_ent_id, (WindowGlConfig { gl_config },));
- if path == Path::new("light.glsl") {
- return Ok(LIGHT_GLSL_SHADER_SRC.as_bytes().to_vec());
+ if window.is_none() {
+ actions.add_components(window_ent_id, (CreationReady,));
+ }
}
-
- Err(IoError::new(
- IoErrorKind::NotFound,
- format!("Content for shader file {} not found", path.display()),
- ))
}
-#[derive(Debug, Component)]
-struct GlObjects
-{
- /// Vertex and index buffer has to live as long as the vertex array
- vertex_buffer: Buffer<Vertex>,
- index_buffer: Option<Buffer<u32>>,
- index_cnt: u32,
-
- vertex_arr: VertexArray,
-}
-
-impl GlObjects
+#[tracing::instrument(skip_all)]
+fn init_window_graphics(
+ window_query: Query<
+ (&Window, &WindowGlConfig, &GraphicsProperties),
+ (Without<SurfaceSpec>, Without<SetupFailed>),
+ >,
+ mut actions: Actions,
+ windowing_context: Single<WindowingContext>,
+)
{
- #[cfg_attr(feature = "debug", tracing::instrument(skip_all))]
- fn new(mesh: &Mesh) -> Self
+ for (window_ent_id, (window, window_gl_config, graphics_props)) in
+ window_query.iter_with_euids()
{
- #[cfg(feature = "debug")]
- tracing::trace!(
- "Creating vertex array, vertex buffer{}",
- if mesh.indices().is_some() {
- " and index buffer"
- } else {
- ""
- }
- );
-
- let mut vertex_arr = VertexArray::new();
- let mut vertex_buffer = Buffer::new();
-
- vertex_buffer.store(mesh.vertices(), BufferUsage::Static);
+ tracing::info!("Initializing graphics for window {window_ent_id}");
+
+ let display = window_gl_config.gl_config.display();
+
+ let window_handle =
+ match unsafe { windowing_context.get_window_as_handle(&window.wid()) }
+ .transpose()
+ {
+ Ok(Some(window_handle)) => window_handle,
+ Ok(None) => {
+ tracing::error!(
+ wid = ?window.wid(),
+ entity_id = %window_ent_id,
+ "Windowing context does not contain window"
+ );
+ actions.add_components(window_ent_id, (SetupFailed,));
+ continue;
+ }
+ Err(err) => {
+ tracing::error!("Failed to get window handle: {err}");
+ actions.add_components(window_ent_id, (SetupFailed,));
+ continue;
+ }
+ };
- vertex_arr.bind_vertex_buffer(0, &vertex_buffer, 0);
+ let Some(window_inner_size) = window.inner_size().try_into_nonzero() else {
+ tracing::error!(
+ "Cannot create a surface for a window with a width/height of 0",
+ );
+ continue;
+ };
- let mut offset = 0u32;
+ let surface = match unsafe {
+ display.create_window_surface(
+ &window_gl_config.gl_config,
+ &glutin::surface::SurfaceAttributesBuilder::<
+ glutin::surface::WindowSurface,
+ >::new()
+ .build(
+ window_handle.as_raw(),
+ window_inner_size.width,
+ window_inner_size.height,
+ ),
+ )
+ } {
+ Ok(surface) => surface,
+ Err(err) => {
+ tracing::error!("Failed to create window surface: {err}");
+ continue;
+ }
+ };
- for attrib in Vertex::attrs() {
- vertex_arr.enable_attrib(attrib.index);
+ let context = match unsafe {
+ display.create_context(
+ &window_gl_config.gl_config,
+ &glutin::context::ContextAttributesBuilder::new()
+ .with_debug(graphics_props.debug)
+ .build(Some(window_handle.as_raw())),
+ )
+ } {
+ Ok(context) => context,
+ Err(err) => {
+ tracing::error!("Failed to create graphics context: {err}");
+ continue;
+ }
+ };
- vertex_arr.set_attrib_format(
- attrib.index,
- match attrib.component_type {
- AttributeComponentType::Float => VertexArrayDataType::Float,
- },
- false,
- offset,
- );
+ let gl_context = match ContextWithFns::new(context, &surface) {
+ Ok(context) => context,
+ Err(err) => {
+ tracing::error!("Failed to create graphics context: {err}");
+ continue;
+ }
+ };
- vertex_arr.set_attrib_vertex_buf_binding(attrib.index, 0);
+ let Ok(curr_gl_context) = gl_context.make_current(&surface) else {
+ tracing::error!("Failed to make graphics context current");
+ continue;
+ };
- offset += attrib.component_size * attrib.component_cnt as u32;
+ if let Err(err) =
+ set_viewport(&curr_gl_context, Vec2 { x: 0, y: 0 }, window.inner_size())
+ {
+ tracing::error!("Failed to set viewport: {err}");
}
- if let Some(indices) = mesh.indices() {
- let mut index_buffer = Buffer::new();
-
- index_buffer.store(indices, BufferUsage::Static);
+ set_enabled(
+ &curr_gl_context,
+ Capability::DepthTest,
+ graphics_props.depth_test,
+ );
- vertex_arr.bind_element_buffer(&index_buffer);
+ set_enabled(
+ &curr_gl_context,
+ Capability::MultiSample,
+ graphics_props.multisampling_sample_cnt.is_some(),
+ );
- return Self {
- vertex_buffer,
- index_buffer: Some(index_buffer),
- index_cnt: indices.len().try_into().unwrap(),
- vertex_arr,
- };
+ if graphics_props.debug {
+ enable(&curr_gl_context, Capability::DebugOutput);
+ enable(&curr_gl_context, Capability::DebugOutputSynchronous);
+
+ set_debug_message_callback(&curr_gl_context, opengl_debug_message_cb);
+
+ match set_debug_message_control(
+ &curr_gl_context,
+ None,
+ None,
+ None,
+ &[],
+ MessageIdsAction::Disable,
+ ) {
+ Ok(()) => {}
+ Err(GlSetDebugMessageControlError::TooManyIds {
+ id_cnt: _,
+ max_id_cnt: _,
+ }) => {
+ unreachable!() // No ids are given
+ }
+ }
}
- Self {
- vertex_buffer,
- index_buffer: None,
- index_cnt: 0,
- vertex_arr,
- }
- }
+ let surface_id = SurfaceId::new_unique();
- pub fn clone(&self) -> NeverDrop<Self>
- {
- NeverDrop::new(Self {
- // SAFETY: The vertex buffer will never become dropped (NeverDrop ensures it)
- vertex_buffer: unsafe { self.vertex_buffer.clone_weak() },
- index_buffer: self
- .index_buffer
- .as_ref()
- // SAFETY: The index buffer will never become dropped (NeverDrop ensures
- // it)
- .map(|index_buffer| unsafe { index_buffer.clone_weak() }),
- index_cnt: self.index_cnt,
- // SAFETY: The vertex array will never become dropped (NeverDrop ensures it)
- vertex_arr: unsafe { self.vertex_arr.clone_unsafe() },
- })
+ let renderer_ctx_ent_id = actions.spawn((
+ GraphicsContext {
+ gl_context,
+ graphics_mesh_store: GraphicsMeshStore::default(),
+ surfaces: HashMap::from([(surface_id, surface)]),
+ uniform_buffer_objs: HashMap::new(),
+ },
+ RendererObjectStore::default(),
+ RendererCommandQueue::default(),
+ Pair::builder()
+ .relation::<RendererCtxUsedByWindow>()
+ .target_id(window_ent_id)
+ .build(),
+ ));
+
+ actions.add_components(
+ window_ent_id,
+ (
+ SurfaceSpec { id: surface_id },
+ Pair::builder()
+ .relation::<WindowUsingRendererCtx>()
+ .target_id(renderer_ctx_ent_id)
+ .build(),
+ ),
+ );
}
}
-fn apply_transformation_matrices(
- transformation: Transformation,
- gl_shader_program: &mut GlShaderProgram,
- camera: &Camera,
- camera_pos: &Position,
- window_size: Dimens<u32>,
+#[tracing::instrument(skip_all)]
+fn handle_commands(
+ renderer_ctx_query: Query<(
+ &mut GraphicsContext,
+ &mut RendererObjectStore,
+ &mut RendererCommandQueue,
+ )>,
+ assets: Single<Assets>,
)
{
- gl_shader_program
- .set_uniform_matrix_4fv(c"model", &create_transformation_matrix(transformation));
-
- let view = create_view(camera, camera_pos);
-
- gl_shader_program.set_uniform_matrix_4fv(c"view", &view);
-
- #[allow(clippy::cast_precision_loss)]
- let projection = match &camera.projection {
- Projection::Perspective(perspective) => new_perspective_matrix(
- perspective,
- window_size.width as f32 / window_size.height as f32,
- ),
- };
-
- gl_shader_program.set_uniform_matrix_4fv(c"projection", &projection);
+ for (mut graphics_ctx, mut renderer_object_store, mut command_queue) in
+ &renderer_ctx_query
+ {
+ let GraphicsContext {
+ ref gl_context,
+ ref mut graphics_mesh_store,
+ ref surfaces,
+ ref mut uniform_buffer_objs,
+ } = *graphics_ctx;
+
+ let mut opt_curr_gl_ctx: Option<CurrentContextWithFns> = None;
+
+ let mut activated_gl_shader_program: Option<GlShaderProgram> = None;
+
+ for command in command_queue.drain() {
+ let tracing_span = tracing::info_span!("handle_cmd");
+ let _tracing_span_enter = tracing_span.enter();
+
+ match command {
+ RendererCommand::MakeCurrent(surface_id) => {
+ let Some(surface) = surfaces.get(&surface_id) else {
+ tracing::error!(surface_id=?surface_id, "Surface does not exist");
+ continue;
+ };
+
+ let curr_gl_ctx = match gl_context.make_current(surface) {
+ Ok(current_graphics_context) => current_graphics_context,
+ Err(err) => {
+ tracing::error!(
+ "Failed to make graphics context current: {err}"
+ );
+ continue;
+ }
+ };
+
+ opt_curr_gl_ctx = Some(curr_gl_ctx);
+ }
+ RendererCommand::ClearBuffers(buffer_clear_mask) => {
+ let Some(curr_gl_ctx) = &opt_curr_gl_ctx else {
+ tracing::error!("No GL context is current");
+ continue;
+ };
+
+ let mut clear_mask = GlBufferClearMask::empty();
+
+ clear_mask.set(
+ GlBufferClearMask::COLOR,
+ buffer_clear_mask.contains(BufferClearMask::COLOR),
+ );
+
+ clear_mask.set(
+ GlBufferClearMask::DEPTH,
+ buffer_clear_mask.contains(BufferClearMask::DEPTH),
+ );
+
+ clear_mask.set(
+ GlBufferClearMask::STENCIL,
+ buffer_clear_mask.contains(BufferClearMask::STENCIL),
+ );
+
+ clear_buffers(&curr_gl_ctx, clear_mask);
+ }
+ RendererCommand::SwapBuffers(surface_id) => {
+ let Some(surface) = surfaces.get(&surface_id) else {
+ tracing::error!(surface_id=?surface_id, "Surface does not exist");
+ continue;
+ };
+
+ if let Err(err) = surface.swap_buffers(gl_context.context()) {
+ tracing::error!("Failed to swap buffers: {err}");
+ }
+ }
+ RendererCommand::CreateShaderProgram(
+ shader_program_obj_id,
+ shader_program,
+ ) => {
+ let Some(curr_gl_ctx) = &opt_curr_gl_ctx else {
+ tracing::error!("No GL context is current");
+ continue;
+ };
+
+ if renderer_object_store.contains_with_id(&shader_program_obj_id) {
+ tracing::error!(
+ object_id=?shader_program_obj_id,
+ "Object store already contains a object with this ID"
+ );
+ continue;
+ }
+
+ let gl_shader_program =
+ match create_shader_program(&curr_gl_ctx, &shader_program) {
+ Ok(gl_shader_program) => gl_shader_program,
+ Err(err) => {
+ tracing::error!("Failed to create shader program: {err}");
+ continue;
+ }
+ };
+
+ renderer_object_store.insert(
+ shader_program_obj_id,
+ RendererObject::from_raw(
+ gl_shader_program.into_raw(),
+ RendererObjectKind::ShaderProgram,
+ ),
+ );
+ }
+ RendererCommand::ActivateShader(shader_program_obj_id) => {
+ let Some(curr_gl_ctx) = &opt_curr_gl_ctx else {
+ tracing::error!("No GL context is current");
+ continue;
+ };
+
+ let Some(shader_program_obj) = renderer_object_store
+ .get_shader_program_obj(&shader_program_obj_id)
+ else {
+ tracing::error!(
+ "Shader object does not exist or has a wrong kind"
+ );
+ continue;
+ };
+
+ let gl_shader_program =
+ GlShaderProgram::from_raw(shader_program_obj.as_raw());
+
+ gl_shader_program.activate(&curr_gl_ctx);
+
+ activated_gl_shader_program = Some(gl_shader_program);
+ }
+ RendererCommand::SetShaderBinding(binding_location, binding_value) => {
+ let Some(curr_gl_ctx) = &opt_curr_gl_ctx else {
+ tracing::error!("No GL context is current");
+ continue;
+ };
+
+ if activated_gl_shader_program.is_none() {
+ tracing::error!("No shader program is activated");
+ continue;
+ }
+
+ if let ShaderBindingValue::Texture(texture_asset) = &binding_value {
+ let Some(texture_obj) = renderer_object_store.get_texture_obj(
+ &RendererObjectId::Asset(texture_asset.id()),
+ ) else {
+ tracing::error!(
+ "Texture {:?} does not exist in renderer object store",
+ assets.get_label(texture_asset)
+ );
+ continue;
+ };
+
+ let gl_texture = GlTexture::from_raw(texture_obj.as_raw());
+
+ gl_texture.bind_to_texture_unit(
+ curr_gl_ctx,
+ binding_location.binding_index,
+ );
+
+ // gl_shader_program.set_uniform_at_location(
+ // curr_gl_ctx,
+ // GlUniformLocation::from_number(
+ // binding_location.binding_index as i32,
+ // ),
+ // &binding_location.binding_index,
+ // );
+
+ continue;
+ }
+
+ let binding_index = binding_location.binding_index;
+
+ let uniform_buffer =
+ uniform_buffer_objs.entry(binding_index).or_insert_with(|| {
+ let uniform_buf =
+ opengl_bindings::buffer::Buffer::<u8>::new(curr_gl_ctx);
+
+ uniform_buf
+ .init(
+ curr_gl_ctx,
+ binding_location.binding_size,
+ opengl_bindings::buffer::Usage::Dynamic,
+ )
+ .unwrap();
+
+ uniform_buf.bind_to_indexed_target(
+ curr_gl_ctx,
+ opengl_bindings::buffer::BindingTarget::UniformBuffer,
+ binding_index as u32,
+ );
+
+ uniform_buf
+ });
+
+ let fvec3_value;
+
+ uniform_buffer
+ .store_at_byte_offset(
+ curr_gl_ctx,
+ binding_location.byte_offset,
+ match binding_value {
+ ShaderBindingValue::Uint(ref value) => value.as_bytes(),
+ ShaderBindingValue::Int(ref value) => value.as_bytes(),
+ ShaderBindingValue::Float(ref value) => value.as_bytes(),
+ ShaderBindingValue::FVec3(value) => {
+ fvec3_value = CF32Vec3::from(value);
+
+ fvec3_value.as_bytes()
+ }
+ ShaderBindingValue::FMat4x4(ref value) => {
+ value.items().as_bytes()
+ }
+ ShaderBindingValue::Texture(_) => unreachable!(),
+ },
+ )
+ .unwrap();
+ }
+ RendererCommand::CreateTexture(texture) => {
+ let Some(curr_gl_ctx) = &opt_curr_gl_ctx else {
+ tracing::error!("No GL context is current");
+ continue;
+ };
+
+ let Some(texture_image) = assets.get(&texture.asset_handle) else {
+ tracing::error!("Texture asset is not loaded",);
+ continue;
+ };
+
+ if let Err(err) = create_texture_object(
+ curr_gl_ctx,
+ &mut renderer_object_store,
+ texture.asset_handle.id(),
+ texture_image,
+ &texture.properties,
+ ) {
+ tracing::error!("Failed to create texture object: {err}");
+ }
+ }
+ RendererCommand::DrawMesh { mesh_asset } => {
+ let Some(curr_gl_ctx) = &opt_curr_gl_ctx else {
+ tracing::error!("No GL context is current");
+ continue;
+ };
+
+ // tracing::warn!("ARGH! Drawing mesh");
+
+ let graphics_mesh =
+ match graphics_mesh_store.graphics_meshes.get(&mesh_asset.id()) {
+ Some(graphics_mesh) => graphics_mesh,
+ None => {
+ let Some(mesh) = assets.get(&mesh_asset) else {
+ tracing::trace!("Missing model asset");
+ continue;
+ };
+
+ let graphics_mesh =
+ match GraphicsMesh::new(&curr_gl_ctx, mesh) {
+ Ok(graphics_mesh) => graphics_mesh,
+ Err(err) => {
+ tracing::error!(
+ "Failed to create {}: {err}",
+ type_name::<GraphicsMesh>()
+ );
+
+ continue;
+ }
+ };
+
+ graphics_mesh_store
+ .graphics_meshes
+ .entry(mesh_asset.id())
+ .or_insert(graphics_mesh)
+ }
+ };
+
+ if let Err(err) = draw_mesh(&curr_gl_ctx, graphics_mesh) {
+ tracing::error!("Failed to draw mesh: {err}");
+ };
+ }
+ RendererCommand::SetPolygonModeConfig(polygon_mode_config) => {
+ let Some(curr_gl_ctx) = &opt_curr_gl_ctx else {
+ tracing::error!("No GL context is current");
+ continue;
+ };
+
+ opengl_bindings::misc::set_polygon_mode(
+ &curr_gl_ctx,
+ polygon_mode_config.face,
+ polygon_mode_config.mode,
+ );
+ }
+ }
+ }
+ }
}
-fn apply_light<PointLightHolder>(
- material: &Material,
- material_flags: &MaterialFlags,
- global_light: &GlobalLight,
- gl_shader_program: &mut GlShaderProgram,
- point_lights: &[PointLightHolder],
- directional_lights: &[&DirectionalLight],
- camera_pos: &Position,
-) where
- PointLightHolder: Deref<Target = PointLight>,
+#[tracing::instrument(skip_all)]
+fn create_texture_object(
+ curr_gl_ctx: &CurrentContextWithFns<'_>,
+ renderer_object_store: &mut RendererObjectStore,
+ texture_image_asset_id: AssetId,
+ image: &Image,
+ texture_properties: &TextureProperties,
+) -> Result<(), GlTextureGenerateError>
{
- debug_assert!(
- point_lights.len() < 64,
- "Shader cannot handle more than 64 point lights"
- );
-
- debug_assert!(
- directional_lights.len() < 64,
- "Shader cannot handle more than 64 directional lights"
- );
-
- for (dir_light_index, dir_light) in directional_lights.iter().enumerate() {
- gl_shader_program.set_uniform_vec_3fv(
- &create_light_uniform_name(
- "directional_lights",
- dir_light_index,
- "direction",
- ),
- &dir_light.direction,
- );
-
- set_light_phong_uniforms(
- gl_shader_program,
- "directional_lights",
- dir_light_index,
- *dir_light,
- );
- }
-
- // There probably won't be more than 2147483648 directional lights
- #[allow(clippy::cast_possible_wrap, clippy::cast_possible_truncation)]
- gl_shader_program
- .set_uniform_1i(c"directional_light_cnt", directional_lights.len() as i32);
-
- for (point_light_index, point_light) in point_lights.iter().enumerate() {
- gl_shader_program.set_uniform_vec_3fv(
- &create_light_uniform_name("point_lights", point_light_index, "position"),
- &point_light.position,
- );
-
- set_light_phong_uniforms(
- gl_shader_program,
- "point_lights",
- point_light_index,
- &**point_light,
- );
+ let object_id = RendererObjectId::Asset(texture_image_asset_id);
- set_light_attenuation_uniforms(
- gl_shader_program,
- "point_lights",
- point_light_index,
- point_light,
+ if renderer_object_store.contains_with_id(&object_id) {
+ tracing::error!(
+ texture_object_id=?object_id,
+ "Renderer object store already contains object with this ID"
);
+ return Ok(());
}
- // There probably won't be more than 2147483648 point lights
- #[allow(clippy::cast_possible_wrap, clippy::cast_possible_truncation)]
- gl_shader_program.set_uniform_1i(c"point_light_cnt", point_lights.len() as i32);
-
- gl_shader_program.set_uniform_vec_3fv(
- c"material.ambient",
- &if material_flags.use_ambient_color {
- material.ambient.clone()
- } else {
- global_light.ambient.clone()
- }
- .into(),
+ renderer_object_store.insert(
+ object_id,
+ RendererObject::from_raw(
+ create_gl_texture(curr_gl_ctx, image, texture_properties)?.into_raw(),
+ RendererObjectKind::Texture,
+ ),
);
- gl_shader_program
- .set_uniform_vec_3fv(c"material.diffuse", &material.diffuse.clone().into());
-
- #[allow(clippy::cast_possible_wrap)]
- gl_shader_program
- .set_uniform_vec_3fv(c"material.specular", &material.specular.clone().into());
+ Ok(())
+}
- #[allow(clippy::cast_possible_wrap)]
- gl_shader_program.set_uniform_1i(
- c"material.ambient_map",
- material.ambient_map.into_inner() as i32,
- );
+fn set_viewport(
+ current_context: &CurrentContextWithFns<'_>,
+ position: Vec2<u32>,
+ size: &Dimens<u32>,
+) -> Result<(), GlSetViewportError>
+{
+ let position =
+ opengl_bindings::data_types::Vec2::<u32> { x: position.x, y: position.y };
- #[allow(clippy::cast_possible_wrap)]
- gl_shader_program.set_uniform_1i(
- c"material.diffuse_map",
- material.diffuse_map.into_inner() as i32,
- );
+ let size = opengl_bindings::data_types::Dimens::<u32> {
+ width: size.width,
+ height: size.height,
+ };
- #[allow(clippy::cast_possible_wrap)]
- gl_shader_program.set_uniform_1i(
- c"material.specular_map",
- material.specular_map.into_inner() as i32,
- );
+ opengl_bindings::misc::set_viewport(current_context, &position, &size)
+}
- gl_shader_program.set_uniform_1fv(c"material.shininess", material.shininess);
+fn draw_mesh(
+ current_context: &CurrentContextWithFns<'_>,
+ graphics_mesh: &GraphicsMesh,
+) -> Result<(), GlDrawError>
+{
+ graphics_mesh.vertex_arr.bind(current_context);
+
+ if graphics_mesh.index_buffer.is_some() {
+ VertexArray::draw_elements(
+ current_context,
+ PrimitiveKind::Triangles,
+ 0,
+ graphics_mesh.element_cnt,
+ )?;
+ } else {
+ VertexArray::draw_arrays(
+ current_context,
+ PrimitiveKind::Triangles,
+ 0,
+ graphics_mesh.element_cnt,
+ )?;
+ }
- gl_shader_program.set_uniform_vec_3fv(c"view_pos", &camera_pos.position);
+ Ok(())
}
-fn set_light_attenuation_uniforms(
- gl_shader_program: &mut GlShaderProgram,
- light_array: &str,
- light_index: usize,
- light: &PointLight,
-)
+fn create_gl_texture(
+ current_context: &CurrentContextWithFns<'_>,
+ image: &Image,
+ texture_properties: &TextureProperties,
+) -> Result<GlTexture, GlTextureGenerateError>
{
- gl_shader_program.set_uniform_1fv(
- &create_light_uniform_name(
- light_array,
- light_index,
- "attenuation_props.constant",
- ),
- light.attenuation_params.constant,
- );
+ let gl_texture = GlTexture::new(current_context);
- gl_shader_program.set_uniform_1fv(
- &create_light_uniform_name(light_array, light_index, "attenuation_props.linear"),
- light.attenuation_params.linear,
- );
+ gl_texture.generate(
+ current_context,
+ &image.dimensions().into(),
+ image.as_bytes(),
+ match image.color_type() {
+ ImageColorType::Rgb8 => GlTexturePixelDataFormat::Rgb8,
+ ImageColorType::Rgba8 => GlTexturePixelDataFormat::Rgba8,
+ _ => {
+ unimplemented!();
+ }
+ },
+ )?;
- gl_shader_program.set_uniform_1fv(
- &create_light_uniform_name(
- light_array,
- light_index,
- "attenuation_props.quadratic",
- ),
- light.attenuation_params.quadratic,
+ gl_texture.set_wrap(
+ current_context,
+ texture_wrapping_to_gl(texture_properties.wrap),
);
-}
-fn set_light_phong_uniforms(
- gl_shader_program: &mut GlShaderProgram,
- light_array: &str,
- light_index: usize,
- light: &impl Light,
-)
-{
- gl_shader_program.set_uniform_vec_3fv(
- &create_light_uniform_name(light_array, light_index, "phong.diffuse"),
- &light.diffuse().clone().into(),
+ gl_texture.set_magnifying_filter(
+ current_context,
+ texture_filtering_to_gl(texture_properties.magnifying_filter),
);
- gl_shader_program.set_uniform_vec_3fv(
- &create_light_uniform_name(light_array, light_index, "phong.specular"),
- &light.specular().clone().into(),
+ gl_texture.set_minifying_filter(
+ current_context,
+ texture_filtering_to_gl(texture_properties.minifying_filter),
);
-}
-trait Light
-{
- fn diffuse(&self) -> &Color<f32>;
- fn specular(&self) -> &Color<f32>;
+ Ok(gl_texture)
}
-impl Light for PointLight
+fn create_shader_program(
+ current_context: &CurrentContextWithFns<'_>,
+ shader_program: &ShaderProgram,
+) -> Result<GlShaderProgram, CreateShaderError>
{
- fn diffuse(&self) -> &Color<f32>
- {
- &self.diffuse
- }
+ let shader_program_reflection = shader_program.reflection(0).expect("Not possible");
+
+ let (vs_entry_point_index, vs_entry_point_reflection) = shader_program_reflection
+ .entry_points()
+ .enumerate()
+ .find(|(_, entry_point)| entry_point.stage() == ShaderStage::Vertex)
+ .ok_or_else(|| {
+ CreateShaderError::NoShaderStageEntrypointFound(ShaderStage::Vertex)
+ })?;
+
+ let vertex_shader_entry_point_code = shader_program
+ .get_entry_point_code(vs_entry_point_index.try_into().expect(
+ "Vertex shader entry point index does not fit in 32-bit unsigned int",
+ ))
+ .map_err(|err| CreateShaderError::GetShaderEntryPointCodeFailed {
+ err,
+ stage: ShaderStage::Vertex,
+ entrypoint: vs_entry_point_reflection
+ .name()
+ .map(|name| name.to_string().into())
+ .unwrap_or("(none)".into()),
+ })?;
+
+ let (fs_entry_point_index, fs_entry_point_reflection) = shader_program_reflection
+ .entry_points()
+ .enumerate()
+ .find(|(_, entry_point)| entry_point.stage() == ShaderStage::Fragment)
+ .ok_or_else(|| {
+ CreateShaderError::NoShaderStageEntrypointFound(ShaderStage::Fragment)
+ })?;
+
+ let fragment_shader_entry_point_code = shader_program
+ .get_entry_point_code(fs_entry_point_index.try_into().expect(
+ "Fragment shader entry point index does not fit in 32-bit unsigned int",
+ ))
+ .map_err(|err| CreateShaderError::GetShaderEntryPointCodeFailed {
+ err,
+ stage: ShaderStage::Fragment,
+ entrypoint: fs_entry_point_reflection
+ .name()
+ .map(|name| name.to_string().into())
+ .unwrap_or("(none)".into()),
+ })?;
+
+ let vertex_shader = GlShader::new(current_context, ShaderKind::Vertex);
+
+ vertex_shader.set_source(
+ current_context,
+ &vertex_shader_entry_point_code.as_str().unwrap(),
+ )?;
+
+ vertex_shader.compile(current_context)?;
+
+ let fragment_shader = GlShader::new(current_context, ShaderKind::Fragment);
+
+ fragment_shader.set_source(
+ current_context,
+ &fragment_shader_entry_point_code.as_str().unwrap(),
+ )?;
+
+ fragment_shader.compile(current_context)?;
+
+ let gl_shader_program = GlShaderProgram::new(current_context);
+
+ gl_shader_program.attach(current_context, &vertex_shader);
+ gl_shader_program.attach(current_context, &fragment_shader);
+
+ gl_shader_program.link(current_context)?;
- fn specular(&self) -> &Color<f32>
- {
- &self.specular
- }
+ Ok(gl_shader_program)
}
-impl Light for DirectionalLight
+#[derive(Debug, thiserror::Error)]
+enum CreateShaderError
{
- fn diffuse(&self) -> &Color<f32>
- {
- &self.diffuse
- }
-
- fn specular(&self) -> &Color<f32>
+ #[error(
+ "Failed to get code of shader program entry point {entrypoint} of stage {stage:?}"
+ )]
+ GetShaderEntryPointCodeFailed
{
- &self.specular
- }
-}
-
-fn create_light_uniform_name(
- light_array: &str,
- light_index: usize,
- light_field: &str,
-) -> CString
-{
- unsafe {
- CString::from_vec_with_nul_unchecked(
- format!("{light_array}[{light_index}].{light_field}\0").into(),
- )
- }
-}
-
-fn create_view(camera: &Camera, camera_pos: &Position) -> Matrix<f32, 4, 4>
-{
- let mut view = Matrix::new();
+ #[source]
+ err: ShaderError,
+ stage: ShaderStage,
+ entrypoint: Cow<'static, str>,
+ },
- view.look_at(&camera_pos.position, &camera.target, &camera.global_up);
+ #[error("No entrypoint was found for shader stage {0:?}")]
+ NoShaderStageEntrypointFound(ShaderStage),
- view
+ #[error(transparent)]
+ ShaderError(#[from] GlShaderError),
}
-#[cfg(feature = "debug")]
#[tracing::instrument(skip_all)]
fn opengl_debug_message_cb(
source: MessageSource,
@@ -700,7 +1161,7 @@ fn opengl_debug_message_cb(
{
use std::backtrace::{Backtrace, BacktraceStatus};
- use tracing::{event, Level};
+ use tracing::{Level, event};
macro_rules! create_event {
($level: expr) => {
@@ -719,7 +1180,8 @@ fn opengl_debug_message_cb(
let backtrace = Backtrace::capture();
if matches!(backtrace.status(), BacktraceStatus::Captured) {
- event!(Level::TRACE, "{backtrace}");
+ tracing::error!("{backtrace}");
+ // event!(Level::TRACE, "{backtrace}");
}
}
MessageType::Other => {
@@ -731,19 +1193,100 @@ fn opengl_debug_message_cb(
};
}
-#[derive(Debug)]
-struct Transformation
+#[inline]
+fn texture_wrapping_to_gl(texture_wrapping: TextureWrapping) -> GlTextureWrapping
{
- position: Vec3<f32>,
- scale: Vec3<f32>,
+ match texture_wrapping {
+ TextureWrapping::Repeat => GlTextureWrapping::Repeat,
+ TextureWrapping::MirroredRepeat => GlTextureWrapping::MirroredRepeat,
+ TextureWrapping::ClampToEdge => GlTextureWrapping::ClampToEdge,
+ TextureWrapping::ClampToBorder => GlTextureWrapping::ClampToBorder,
+ }
}
-fn create_transformation_matrix(transformation: Transformation) -> Matrix<f32, 4, 4>
+#[inline]
+fn texture_filtering_to_gl(texture_filtering: TextureFiltering) -> GlTextureFiltering
{
- let mut matrix = Matrix::new_identity();
+ match texture_filtering {
+ TextureFiltering::Linear => GlTextureFiltering::Linear,
+ TextureFiltering::Nearest => GlTextureFiltering::Nearest,
+ }
+}
- matrix.translate(&transformation.position);
- matrix.scale(&transformation.scale);
+impl<Value: ReprC + Copy> From<Vec2<Value>> for opengl_bindings::data_types::Vec2<Value>
+{
+ fn from(vec2: Vec2<Value>) -> Self
+ {
+ Self { x: vec2.x, y: vec2.y }
+ }
+}
- matrix
+impl<Value: ReprC + IntoBytes + Copy> From<Vec3<Value>>
+ for opengl_bindings::data_types::Vec3<Value>
+{
+ fn from(vec3: Vec3<Value>) -> Self
+ {
+ Self { x: vec3.x, y: vec3.y, z: vec3.z }
+ }
+}
+
+impl<Value: ReprC + Copy> From<Matrix<Value, 4, 4>>
+ for opengl_bindings::data_types::Matrix<Value, 4, 4>
+{
+ fn from(matrix: Matrix<Value, 4, 4>) -> Self
+ {
+ Self { items: matrix.items }
+ }
+}
+
+impl<Value: Copy> From<Dimens<Value>> for opengl_bindings::data_types::Dimens<Value>
+{
+ fn from(dimens: Dimens<Value>) -> Self
+ {
+ Self {
+ width: dimens.width,
+ height: dimens.height,
+ }
+ }
+}
+
+impl From<crate::draw_flags::PolygonMode> for opengl_bindings::misc::PolygonMode
+{
+ fn from(mode: crate::draw_flags::PolygonMode) -> Self
+ {
+ match mode {
+ crate::draw_flags::PolygonMode::Point => Self::Point,
+ crate::draw_flags::PolygonMode::Fill => Self::Fill,
+ crate::draw_flags::PolygonMode::Line => Self::Line,
+ }
+ }
+}
+
+impl From<crate::draw_flags::PolygonModeFace> for opengl_bindings::misc::PolygonModeFace
+{
+ fn from(face: crate::draw_flags::PolygonModeFace) -> Self
+ {
+ match face {
+ crate::draw_flags::PolygonModeFace::Front => Self::Front,
+ crate::draw_flags::PolygonModeFace::Back => Self::Back,
+ crate::draw_flags::PolygonModeFace::FrontAndBack => Self::FrontAndBack,
+ }
+ }
+}
+
+#[derive(Debug, IntoBytes, Immutable)]
+#[repr(C)]
+pub struct CF32Vec3
+{
+ x: f32,
+ y: f32,
+ z: f32,
+}
+
+impl From<Vec3<f32>> for CF32Vec3
+{
+ fn from(src: Vec3<f32>) -> Self
+ {
+ Self { x: src.x, y: src.y, z: src.z }
+ }
}
diff --git a/engine/src/renderer/opengl/glsl/fragment.glsl b/engine/src/renderer/opengl/glsl/fragment.glsl
deleted file mode 100644
index 5bf5ff2..0000000
--- a/engine/src/renderer/opengl/glsl/fragment.glsl
+++ /dev/null
@@ -1,73 +0,0 @@
-#version 330 core
-
-#preinclude "light.glsl"
-#preinclude "vertex_data.glsl"
-
-#define MAX_LIGHT_CNT 64
-
-out vec4 FragColor;
-
-in VertexData vertex_data;
-
-uniform vec3 view_pos;
-uniform sampler2D input_texture;
-uniform Material material;
-
-uniform PointLight point_lights[MAX_LIGHT_CNT];
-uniform int point_light_cnt;
-
-uniform DirectionalLight directional_lights[MAX_LIGHT_CNT];
-uniform int directional_light_cnt;
-
-void main()
-{
- vec3 ambient_light = calc_ambient_light(material, vertex_data.texture_coords);
-
- vec3 directional_light_sum = vec3(0.0, 0.0, 0.0);
-
- for (int dl_index = 0; dl_index < directional_light_cnt; dl_index++) {
- CalculatedLight calculated_dir_light;
-
- calc_light(
- // Negated since we want the light to point from the light direction
- normalize(-directional_lights[dl_index].direction),
- directional_lights[dl_index].phong,
- vertex_data,
- view_pos,
- material,
- calculated_dir_light
- );
-
- directional_light_sum +=
- calculated_dir_light.diffuse + calculated_dir_light.specular;
- }
-
- vec3 point_light_sum = vec3(0.0, 0.0, 0.0);
-
- for (int pl_index = 0; pl_index < point_light_cnt; pl_index++) {
- vec3 light_direction =
- normalize(point_lights[pl_index].position - vertex_data.world_space_pos);
-
- CalculatedLight calculated_point_light;
-
- calc_light(
- light_direction,
- point_lights[pl_index].phong,
- vertex_data,
- view_pos,
- material,
- calculated_point_light
- );
-
- float attenuation =
- calc_attenuation(point_lights[pl_index], vertex_data.world_space_pos);
-
- calculated_point_light.diffuse *= attenuation;
- calculated_point_light.specular *= attenuation;
-
- point_light_sum +=
- calculated_point_light.diffuse + calculated_point_light.specular;
- }
-
- FragColor = vec4((ambient_light + directional_light_sum + point_light_sum), 1.0);
-}
diff --git a/engine/src/renderer/opengl/glsl/light.glsl b/engine/src/renderer/opengl/glsl/light.glsl
deleted file mode 100644
index 1bc23a4..0000000
--- a/engine/src/renderer/opengl/glsl/light.glsl
+++ /dev/null
@@ -1,133 +0,0 @@
-#version 330 core
-
-#ifndef LIGHT_GLSL
-#define LIGHT_GLSL
-
-#preinclude "vertex_data.glsl"
-
-struct Material
-{
- vec3 ambient;
- vec3 diffuse;
- vec3 specular;
- sampler2D ambient_map;
- sampler2D diffuse_map;
- sampler2D specular_map;
- float shininess;
-};
-
-struct LightPhong
-{
- vec3 diffuse;
- vec3 specular;
-};
-
-struct AttenuationProperties
-{
- float constant;
- float linear;
- float quadratic;
-};
-
-struct PointLight
-{
- LightPhong phong;
- vec3 position;
- AttenuationProperties attenuation_props;
-};
-
-struct DirectionalLight
-{
- LightPhong phong;
- vec3 direction;
-};
-
-struct CalculatedLight
-{
- vec3 diffuse;
- vec3 specular;
-};
-
-vec3 calc_ambient_light(in Material material, in vec2 texture_coords)
-{
- return vec3(texture(material.ambient_map, texture_coords)) * material.ambient;
-}
-
-vec3 calc_diffuse_light(
- in Material material,
- in LightPhong light_phong,
- in vec3 light_dir,
- in vec3 norm,
- in vec2 texture_coords
-)
-{
- float diff = max(dot(norm, light_dir), 0.0);
-
- return light_phong.diffuse * (
- diff * (vec3(texture(material.diffuse_map, texture_coords)) * material.diffuse)
- );
-}
-
-vec3 calc_specular_light(
- in Material material,
- in LightPhong light_phong,
- in vec3 light_dir,
- in vec3 norm,
- in vec3 view_pos,
- in vec3 frag_pos,
- in vec2 texture_coords
-)
-{
- vec3 view_direction = normalize(view_pos - frag_pos);
-
- vec3 reflect_direction = reflect(-light_dir, norm);
-
- float spec =
- pow(max(dot(view_direction, reflect_direction), 0.0), material.shininess);
-
- return light_phong.specular * (
- spec * (vec3(texture(material.specular_map, texture_coords)) * material.specular)
- );
-}
-
-float calc_attenuation(in PointLight point_light, in vec3 position)
-{
- float light_distance = length(point_light.position - position);
-
- return 1.0 / (point_light.attenuation_props.constant
- + point_light.attenuation_props.linear
- * light_distance + point_light.attenuation_props.quadratic
- * pow(light_distance, 2));
-}
-
-void calc_light(
- in vec3 light_direction,
- in LightPhong light_phong,
- in VertexData vertex_data,
- in vec3 view_pos,
- in Material material,
- out CalculatedLight calculated_light
-)
-{
- vec3 norm = normalize(vertex_data.world_space_normal);
-
- calculated_light.diffuse = calc_diffuse_light(
- material,
- light_phong,
- light_direction,
- norm,
- vertex_data.texture_coords
- );
-
- calculated_light.specular = calc_specular_light(
- material,
- light_phong,
- light_direction,
- norm,
- view_pos,
- vertex_data.world_space_pos,
- vertex_data.texture_coords
- );
-}
-
-#endif
diff --git a/engine/src/renderer/opengl/glsl/vertex.glsl b/engine/src/renderer/opengl/glsl/vertex.glsl
deleted file mode 100644
index b57caa6..0000000
--- a/engine/src/renderer/opengl/glsl/vertex.glsl
+++ /dev/null
@@ -1,24 +0,0 @@
-#version 330 core
-
-#preinclude "vertex_data.glsl"
-
-layout (location = 0) in vec3 pos;
-layout (location = 1) in vec2 texture_coords;
-layout (location = 2) in vec3 normal;
-
-out VertexData vertex_data;
-
-uniform mat4 model;
-uniform mat4 view;
-uniform mat4 projection;
-
-void main()
-{
- gl_Position = projection * view * model * vec4(pos, 1.0);
-
- vertex_data.world_space_pos = vec3(model * vec4(pos, 1.0));
- vertex_data.texture_coords = texture_coords;
-
- // TODO: Do this using CPU for performance increase
- vertex_data.world_space_normal = mat3(transpose(inverse(model))) * normal;
-}
diff --git a/engine/src/renderer/opengl/glsl/vertex_data.glsl b/engine/src/renderer/opengl/glsl/vertex_data.glsl
deleted file mode 100644
index 486d445..0000000
--- a/engine/src/renderer/opengl/glsl/vertex_data.glsl
+++ /dev/null
@@ -1,11 +0,0 @@
-#ifndef VERTEX_DATA_GLSL
-#define VERTEX_DATA_GLSL
-
-struct VertexData
-{
- vec2 texture_coords;
- vec3 world_space_pos;
- vec3 world_space_normal;
-};
-
-#endif
diff --git a/engine/src/renderer/opengl/glutin_compat.rs b/engine/src/renderer/opengl/glutin_compat.rs
new file mode 100644
index 0000000..cfd6ea7
--- /dev/null
+++ b/engine/src/renderer/opengl/glutin_compat.rs
@@ -0,0 +1,268 @@
+// Original file:
+// https://github.com/rust-windowing/glutin/blob/
+// 0433af9018febe0696c485ed9d66c40dad41f2d4/glutin-winit/src/lib.rs
+//
+// Copyright © 2022 Kirill Chibisov
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the “Software”), to deal
+// in the Software without restriction, including without limitation the rights to
+// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
+// of the Software, and to permit persons to whom the Software is furnished to do
+// so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in all
+// copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+// SOFTWARE.
+
+//! This library provides helpers for cross-platform [`glutin`] bootstrapping
+//! with [`winit`].
+
+#![deny(rust_2018_idioms)]
+#![deny(rustdoc::broken_intra_doc_links)]
+#![deny(clippy::all)]
+#![deny(missing_debug_implementations)]
+#![deny(missing_docs)]
+#![cfg_attr(clippy, deny(warnings))]
+
+use glutin::config::{Config, ConfigTemplateBuilder};
+use glutin::display::{Display, DisplayApiPreference};
+use glutin::error::Error as GlutinError;
+#[cfg(x11_platform)]
+use glutin::platform::x11::X11GlConfigExt;
+use glutin::prelude::*;
+use raw_window_handle::{DisplayHandle, RawWindowHandle, WindowHandle};
+
+use crate::windowing::window::CreationAttributes as WindowCreationAttributes;
+
+#[cfg(all(not(egl_backend), not(glx_backend), not(wgl_backend), not(cgl_backend)))]
+compile_error!("Please select at least one api backend");
+
+/// The helper to perform [`Display`] creation and OpenGL platform
+/// bootstrapping with the help of [`winit`] with little to no platform specific
+/// code.
+///
+/// This is only required for the initial setup. If you want to create
+/// additional windows just use the [`finalize_window`] function and the
+/// configuration you've used either for the original window or picked with the
+/// existing [`Display`].
+///
+/// [`winit`]: winit
+/// [`Display`]: glutin::display::Display
+#[derive(Default, Debug, Clone)]
+pub struct DisplayBuilder
+{
+ preference: ApiPreference,
+ window_attributes: WindowCreationAttributes,
+}
+
+impl DisplayBuilder
+{
+ /// Create new display builder.
+ pub fn new() -> Self
+ {
+ Default::default()
+ }
+
+ /// The preference in picking the configuration.
+ #[allow(dead_code)]
+ pub fn with_preference(mut self, preference: ApiPreference) -> Self
+ {
+ self.preference = preference;
+ self
+ }
+
+ /// The window attributes to use when building a window.
+ ///
+ /// By default no window is created.
+ pub fn with_window_attributes(
+ mut self,
+ window_creation_attrs: WindowCreationAttributes,
+ ) -> Self
+ {
+ self.window_attributes = window_creation_attrs;
+ self
+ }
+
+ /// Initialize the OpenGL platform and create a compatible window to use
+ /// with it when the [`WindowAttributes`] was passed with
+ /// [`Self::with_window_attributes()`]. It's optional, since on some
+ /// platforms like `Android` it is not available early on, so you want to
+ /// find configuration and later use it with the [`finalize_window`].
+ /// But if you don't care about such platform you can always pass
+ /// [`WindowAttributes`].
+ ///
+ /// # Api-specific
+ ///
+ /// **WGL:** - [`WindowAttributes`] **must** be passed in
+ /// [`Self::with_window_attributes()`] if modern OpenGL(ES) is desired,
+ /// otherwise only builtin functions like `glClear` will be available.
+ pub fn build<ConfigPickerFn>(
+ self,
+ window_handle: Option<WindowHandle<'_>>,
+ display_handle: &DisplayHandle<'_>,
+ template_builder: ConfigTemplateBuilder,
+ config_picker_fn: ConfigPickerFn,
+ ) -> Result<(WindowCreationAttributes, Config), Error>
+ where
+ ConfigPickerFn: FnOnce(Box<dyn Iterator<Item = Config> + '_>) -> Option<Config>,
+ {
+ // XXX with WGL backend window should be created first.
+ let raw_window_handle = if cfg!(wgl_backend) {
+ let Some(window_handle) = window_handle else {
+ return Err(Error::WindowRequired);
+ };
+
+ Some(window_handle.as_raw())
+ } else {
+ None
+ };
+
+ let gl_display =
+ create_display(display_handle, self.preference, raw_window_handle)
+ .map_err(Error::CreateDisplayFailed)?;
+
+ // XXX the native window must be passed to config picker when WGL is used
+ // otherwise very limited OpenGL features will be supported.
+ #[cfg(wgl_backend)]
+ let template_builder = if let Some(raw_window_handle) = raw_window_handle {
+ template_builder.compatible_with_native_window(raw_window_handle)
+ } else {
+ template_builder
+ };
+
+ let template = template_builder.build();
+
+ // SAFETY: The RawWindowHandle passed on the config template
+ // (when cfg(wgl_backend)) will always point to a valid object since it is
+ // derived from the window_handle argument which when Some is a WindowHandle and
+ // WindowHandles always point to a valid object
+ let gl_configs = unsafe { gl_display.find_configs(template) }
+ .map_err(Error::FindConfigsFailed)?;
+
+ let picked_gl_config =
+ config_picker_fn(gl_configs).ok_or(Error::NoConfigPicked)?;
+
+ #[cfg(not(wgl_backend))]
+ let window_attrs =
+ { finalize_window_creation_attrs(self.window_attributes, &picked_gl_config) };
+
+ #[cfg(wgl_backend)]
+ let window_attrs = self.window_attributes;
+
+ Ok((window_attrs, picked_gl_config))
+ }
+}
+
+#[derive(Debug, thiserror::Error)]
+pub enum Error
+{
+ #[error("Failed to create display")]
+ CreateDisplayFailed(#[source] GlutinError),
+
+ #[error("Failed to find configs")]
+ FindConfigsFailed(#[source] GlutinError),
+
+ #[error("No config was picked by config picker function")]
+ NoConfigPicked,
+
+ #[error("Window required for building display on current platform")]
+ WindowRequired,
+}
+
+fn create_display(
+ display_handle: &DisplayHandle<'_>,
+ _api_preference: ApiPreference,
+ _raw_window_handle: Option<RawWindowHandle>,
+) -> Result<Display, GlutinError>
+{
+ #[cfg(egl_backend)]
+ let _preference = DisplayApiPreference::Egl;
+
+ #[cfg(glx_backend)]
+ let _preference = DisplayApiPreference::Glx(Box::new(
+ crate::windowing::window::platform::x11::register_xlib_error_hook,
+ ));
+
+ #[cfg(cgl_backend)]
+ let _preference = DisplayApiPreference::Cgl;
+
+ #[cfg(wgl_backend)]
+ let _preference = DisplayApiPreference::Wgl(_raw_window_handle);
+
+ #[cfg(all(egl_backend, glx_backend))]
+ let _preference = match _api_preference {
+ ApiPreference::PreferEgl => DisplayApiPreference::EglThenGlx(Box::new(
+ crate::windowing::window::platform::x11::register_xlib_error_hook,
+ )),
+ ApiPreference::FallbackEgl => DisplayApiPreference::GlxThenEgl(Box::new(
+ crate::windowing::window::platform::x11::register_xlib_error_hook,
+ )),
+ };
+
+ #[cfg(all(wgl_backend, egl_backend))]
+ let _preference = match _api_preference {
+ ApiPreference::PreferEgl => DisplayApiPreference::EglThenWgl(_raw_window_handle),
+ ApiPreference::FallbackEgl => {
+ DisplayApiPreference::WglThenEgl(_raw_window_handle)
+ }
+ };
+
+ let handle = display_handle.as_raw();
+ unsafe { Ok(Display::new(handle, _preference)?) }
+}
+
+/// Finalize [`Window`] creation by applying the options from the [`Config`], be
+/// aware that it could remove incompatible options from the window builder like
+/// `transparency`, when the provided config doesn't support it.
+///
+/// [`Window`]: winit::window::Window
+/// [`Config`]: glutin::config::Config
+#[cfg(not(wgl_backend))]
+fn finalize_window_creation_attrs(
+ mut attributes: WindowCreationAttributes,
+ gl_config: &Config,
+) -> WindowCreationAttributes
+{
+ // Disable transparency if the end config doesn't support it.
+ if gl_config.supports_transparency() == Some(false) {
+ attributes = attributes.with_transparent(false);
+ }
+
+ #[cfg(x11_platform)]
+ let attributes = if let Some(x11_visual) = gl_config.x11_visual() {
+ attributes.with_x11_visual(x11_visual.visual_id() as _)
+ } else {
+ attributes
+ };
+
+ attributes
+}
+
+/// Simplified version of the [`DisplayApiPreference`] which is used to simplify
+/// cross platform window creation.
+///
+/// To learn about platform differences the [`DisplayApiPreference`] variants.
+///
+/// [`DisplayApiPreference`]: glutin::display::DisplayApiPreference
+#[allow(dead_code)]
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
+pub enum ApiPreference
+{
+ /// Prefer `EGL` over system provider like `GLX` and `WGL`.
+ PreferEgl,
+
+ /// Fallback to `EGL` when failed to create the system profile.
+ ///
+ /// This behavior is used by default. However consider using
+ /// [`Self::PreferEgl`] if you don't care about missing EGL features.
+ #[default]
+ FallbackEgl,
+}
diff --git a/engine/src/renderer/opengl/graphics_mesh.rs b/engine/src/renderer/opengl/graphics_mesh.rs
new file mode 100644
index 0000000..62dadb8
--- /dev/null
+++ b/engine/src/renderer/opengl/graphics_mesh.rs
@@ -0,0 +1,136 @@
+use opengl_bindings::CurrentContextWithFns as GlCurrentContextWithFns;
+use opengl_bindings::buffer::{Buffer as GlBuffer, Usage as GlBufferUsage};
+use opengl_bindings::vertex_array::{
+ AttributeFormat as GlVertexArrayAttributeFormat,
+ DataType as GlVertexArrayDataType,
+ VertexArray as GlVertexArray,
+};
+
+use crate::mesh::Mesh;
+use crate::renderer::opengl::vertex::{
+ AttributeComponentType as VertexAttributeComponentType,
+ Vertex as RendererVertex,
+};
+
+#[derive(Debug)]
+pub struct GraphicsMesh
+{
+ /// Vertex and index buffer has to live as long as the vertex array
+ vertex_buffer: GlBuffer<RendererVertex>,
+ pub index_buffer: Option<GlBuffer<u32>>,
+ pub element_cnt: u32,
+ pub vertex_arr: GlVertexArray,
+}
+
+impl GraphicsMesh
+{
+ #[tracing::instrument(skip_all)]
+ pub fn new(
+ current_context: &GlCurrentContextWithFns<'_>,
+ mesh: &Mesh,
+ ) -> Result<Self, Error>
+ {
+ tracing::info!(
+ "Creating vertex array, vertex buffer{}",
+ if mesh.indices().is_some() {
+ " and index buffer"
+ } else {
+ ""
+ }
+ );
+
+ let vertex_arr = GlVertexArray::new(current_context);
+ let vertex_buffer = GlBuffer::new(current_context);
+
+ vertex_buffer
+ .store_mapped(
+ current_context,
+ mesh.vertices(),
+ GlBufferUsage::Static,
+ |vertex| RendererVertex {
+ pos: vertex.pos.into(),
+ texture_coords: vertex.texture_coords.into(),
+ normal: vertex.normal.into(),
+ },
+ )
+ .map_err(Error::StoreVerticesFailed)?;
+
+ vertex_arr.bind_vertex_buffer(current_context, 0, &vertex_buffer, 0);
+
+ let mut offset = 0u32;
+
+ for attrib in RendererVertex::attrs() {
+ vertex_arr.enable_attrib(current_context, attrib.index);
+
+ vertex_arr.set_attrib_format(
+ current_context,
+ attrib.index,
+ GlVertexArrayAttributeFormat {
+ data_type: match attrib.component_type {
+ VertexAttributeComponentType::Float => {
+ GlVertexArrayDataType::Float
+ }
+ },
+ count: attrib.component_cnt as u8,
+ normalized: false,
+ offset,
+ },
+ );
+
+ vertex_arr.set_attrib_vertex_buf_binding(current_context, attrib.index, 0);
+
+ offset += attrib.component_size * attrib.component_cnt as u32;
+ }
+
+ if let Some(indices) = mesh.indices() {
+ let index_buffer = GlBuffer::new(current_context);
+
+ index_buffer
+ .store(current_context, indices, GlBufferUsage::Static)
+ .map_err(Error::StoreIndicesFailed)?;
+
+ vertex_arr.bind_element_buffer(current_context, &index_buffer);
+
+ return Ok(Self {
+ vertex_buffer: vertex_buffer,
+ index_buffer: Some(index_buffer),
+ element_cnt: indices
+ .len()
+ .try_into()
+ .expect("Mesh index count does not fit into a 32-bit unsigned int"),
+ vertex_arr,
+ });
+ }
+
+ Ok(Self {
+ vertex_buffer: vertex_buffer,
+ index_buffer: None,
+ element_cnt: mesh
+ .vertices()
+ .len()
+ .try_into()
+ .expect("Mesh vertex count does not fit into a 32-bit unsigned int"),
+ vertex_arr,
+ })
+ }
+
+ pub fn destroy(&mut self, curr_gl_ctx: &GlCurrentContextWithFns<'_>)
+ {
+ self.vertex_arr.delete(curr_gl_ctx);
+ self.vertex_buffer.delete(curr_gl_ctx);
+
+ if let Some(index_buffer) = &self.index_buffer {
+ index_buffer.delete(curr_gl_ctx);
+ }
+ }
+}
+
+#[derive(Debug, thiserror::Error)]
+pub enum Error
+{
+ #[error("Failed to store vertices in vertex buffer")]
+ StoreVerticesFailed(#[source] opengl_bindings::buffer::Error),
+
+ #[error("Failed to store indices in index buffer")]
+ StoreIndicesFailed(#[source] opengl_bindings::buffer::Error),
+}
diff --git a/engine/src/renderer/opengl/vertex.rs b/engine/src/renderer/opengl/vertex.rs
new file mode 100644
index 0000000..5a1593e
--- /dev/null
+++ b/engine/src/renderer/opengl/vertex.rs
@@ -0,0 +1,65 @@
+use safer_ffi::derive_ReprC;
+
+#[derive(Debug, Clone)]
+#[derive_ReprC]
+#[repr(C)]
+pub struct Vertex
+{
+ pub pos: opengl_bindings::data_types::Vec3<f32>,
+ pub texture_coords: opengl_bindings::data_types::Vec2<f32>,
+ pub normal: opengl_bindings::data_types::Vec3<f32>,
+}
+
+impl Vertex
+{
+ pub fn attrs() -> &'static [Attribute]
+ {
+ #[allow(clippy::cast_possible_truncation)]
+ &[
+ Attribute {
+ index: 0,
+ component_type: AttributeComponentType::Float,
+ component_cnt: AttributeComponentCnt::Three,
+ component_size: size_of::<f32>() as u32,
+ },
+ Attribute {
+ index: 1,
+ component_type: AttributeComponentType::Float,
+ component_cnt: AttributeComponentCnt::Two,
+ component_size: size_of::<f32>() as u32,
+ },
+ Attribute {
+ index: 2,
+ component_type: AttributeComponentType::Float,
+ component_cnt: AttributeComponentCnt::Three,
+ component_size: size_of::<f32>() as u32,
+ },
+ ]
+ }
+}
+
+#[derive(Debug)]
+pub struct Attribute
+{
+ pub index: u32,
+ pub component_type: AttributeComponentType,
+ pub component_cnt: AttributeComponentCnt,
+ pub component_size: u32,
+}
+
+#[derive(Debug)]
+pub enum AttributeComponentType
+{
+ Float,
+}
+
+#[derive(Debug, Clone, Copy)]
+#[repr(u32)]
+#[allow(dead_code)]
+pub enum AttributeComponentCnt
+{
+ One = 1,
+ Two = 2,
+ Three = 3,
+ Four = 4,
+}