Skip to content

Commit

Permalink
Fix sprite example
Browse files Browse the repository at this point in the history
  • Loading branch information
mattkleiny committed Apr 23, 2024
1 parent 84e0429 commit f516df2
Show file tree
Hide file tree
Showing 21 changed files with 110 additions and 74 deletions.
10 changes: 10 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 5 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -41,4 +41,8 @@ scripting = { package = "surreal-scripting", path = "./modules/scripting", optio

[[example]]
name = "hello-world"
required-features = ["sdl", "graphics", "input"]
required-features = ["sdl", "graphics"]

[[example]]
name = "sprites"
required-features = ["sdl", "graphics"]
14 changes: 13 additions & 1 deletion backends/sdl/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,16 @@
//! SDL bindings for Surreal.
use std::ffi::CString;
use std::ffi::{c_int, CString};

use common::FastHashSet;
pub use sdl2_sys as sys;
use sdl2_sys::{
SDL_GLattr::{
SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_MAJOR_VERSION, SDL_GL_CONTEXT_MINOR_VERSION, SDL_GL_CONTEXT_PROFILE_MASK,
},
SDL_GLcontextFlag::SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG,
SDL_GLprofile::SDL_GL_CONTEXT_PROFILE_CORE,
};
use sys::{SDL_KeyCode, SDL_Keycode};

/// Represents an error that can occur when creating a window.
Expand Down Expand Up @@ -72,6 +79,11 @@ impl Window {
return Err(WindowError::FailedToCreateWindow);
}

SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG as c_int);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE as c_int);

// create the OpenGL context
let gl_context = SDL_GL_CreateContext(window);
if gl_context.is_null() {
Expand Down
19 changes: 1 addition & 18 deletions common/src/maths/linear/frustum.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ impl Frustum {
}

/// Determines whether the given AABB is contained within this frustum.
pub fn contains_aabb(&self, aabb: AABB) -> bool {
pub fn contains_aabb(&self, aabb: &AABB) -> bool {
self.contains_point(aabb.min)
&& self.contains_point(aabb.max)
&& self.contains_point(vec3(aabb.min.x, aabb.min.y, aabb.max.z))
Expand Down Expand Up @@ -128,21 +128,4 @@ impl Frustum {
pub fn as_slice(&self) -> &[Plane; 6] {
unsafe { reinterpret_cast(self) }
}

/// Determines whether the given values is contained within this frustum.
pub fn contains(&self, value: &impl FrustumCullable) -> bool {
value.is_inside_frustum(self)
}
}

/// A trait for objects that can be frustum culled.
pub trait FrustumCullable {
/// Determines whether this object is inside the given frustum.
fn is_inside(&self, frustum: &Frustum) -> bool;
}

impl FrustumCullable for AABB {
fn is_inside(&self, _frustum: &Frustum) -> bool {
todo!()
}
}
2 changes: 1 addition & 1 deletion common/src/maths/paths.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ pub trait PathFindingGrid<T: Copy + Hash + Eq = IVec2> {
let mut neighbours = NeighbourList::new();

while let Some(current) = frontier.pop() {
// dont search too far afield
// don't search too far afield
if cost_so_far.len() >= MAXIMUM_STEPS {
return None;
}
Expand Down
6 changes: 1 addition & 5 deletions examples/hello-world.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use surreal::{backends::sdl::*, common::*, graphics::*, input::*};
use surreal::{backends::sdl::*, common::*, graphics::*};

fn main() {
let mut window = Window::new(WindowSettings {
Expand All @@ -21,9 +21,5 @@ fn main() {

graphics.clear_color_buffer(Color::lerp(color1, color2, total_time.ping_pong()));
window.present();

if window.is_key_down(VirtualKey::Escape) {
break;
}
}
}
41 changes: 41 additions & 0 deletions examples/sprites.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
use surreal::{backends::sdl::*, common::*, graphics::*};

fn main() {
let mut window = Window::new(WindowSettings {
title: "Sprite Example".to_string(),
..Default::default()
})
.expect("Failed to create window");

let graphics = GraphicsEngine::opengl(&window);
let mut batch = SpriteBatch::new(&graphics).unwrap();
let mut material = Material::from_template(&graphics, &SHADER_SPRITE_STANDARD).unwrap();
let texture = Texture::from_path(&graphics, "assets/sprites/bunny.png")
.unwrap()
.to_region();

material.set_blend_state(BlendState::Enabled {
source: BlendFactor::SrcAlpha,
destination: BlendFactor::OneMinusSrcAlpha,
});

material.set_uniform(
PROJECTION_VIEW,
&Mat4::orthographic_lh(0.0, 800.0, 600.0, 0.0, -1.0, 1.0),
);

while window.update() {
graphics.clear_color_buffer(Color::BLACK);

batch.begin(&material);

batch.draw_sprite(&texture, &SpriteOptions {
position: vec2(400.0, 300.0),
..Default::default()
});

batch.flush();

window.present();
}
}
1 change: 1 addition & 0 deletions modules/audio/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,4 @@ edition.workspace = true

[dependencies]
common = { package = "surreal-common", path = "../../common" }
openal-sys = "1.16.0"
2 changes: 1 addition & 1 deletion modules/graphics/src/opengl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -497,7 +497,7 @@ impl GraphicsBackend for OpenGLGraphicsBackend {

#[profiling]
fn shader_metadata(&self, _shader: ShaderId) -> Result<ShaderFlags, ShaderError> {
todo!()
Ok(ShaderFlags::empty()) // TODO: implement me
}

#[profiling]
Expand Down
2 changes: 0 additions & 2 deletions modules/graphics/src/shaders/embedded/canvas-standard.glsl
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
// Implements a simple shader for screen-space canvas rendering.

#version 330 core

#shader_type vertex

uniform vec2 u_viewport_size;
Expand Down
8 changes: 3 additions & 5 deletions modules/graphics/src/shaders/embedded/mesh-skinned.glsl
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
// This is a simple shader that enables skeletal animation.

#version 330

#shader_type vertex

uniform mat4 u_model_view_projection;
Expand All @@ -19,9 +17,9 @@ varying vec3 v_normal;
void main() {
// blend the bone matrices
mat4 boneMatrix = u_bone_matrices[a_bone_indices.x] * a_bone_weights.x +
u_bone_matrices[a_bone_indices.y] * a_bone_weights.y +
u_bone_matrices[a_bone_indices.z] * a_bone_weights.z +
u_bone_matrices[a_bone_indices.w] * a_bone_weights.w;
u_bone_matrices[a_bone_indices.y] * a_bone_weights.y +
u_bone_matrices[a_bone_indices.z] * a_bone_weights.z +
u_bone_matrices[a_bone_indices.w] * a_bone_weights.w;

vec4 position = boneMatrix * vec4(a_position, 1.0);
vec4 normal = boneMatrix * vec4(a_normal, 0.0);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
// Implements a sprite shader that supports multiple texture per batch.

#version 330 core

#shader_type vertex

uniform mat4 u_projection_view;
Expand Down
2 changes: 0 additions & 2 deletions modules/graphics/src/shaders/embedded/sprite-multitex.glsl
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
// Implements a sprite shader that supports multiple texture per batch.

#version 330 core

#shader_type vertex

uniform mat4 u_projection_view;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
// Implements a sprite shader with per-vertex tint.

#version 330 core

#shader_type vertex

uniform mat4 u_projection_view;
Expand Down
13 changes: 8 additions & 5 deletions modules/graphics/src/shaders/embedded/sprite-standard.glsl
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
// Implements a sprite shader with per-vertex tint.

#version 330 core

#shader_type vertex

uniform mat4 u_projection_view;
Expand All @@ -10,8 +8,8 @@ layout(location = 0) in vec2 a_position;
layout(location = 1) in vec2 a_texcoord_0;
layout(location = 2) in vec4 a_color;

varying vec2 v_texcoord_0;
varying vec4 v_color;
out vec2 v_texcoord_0;
out vec4 v_color;

void main() {
v_texcoord_0 = a_texcoord_0;
Expand All @@ -24,6 +22,11 @@ void main() {

uniform sampler2D u_texture;

in vec2 v_texcoord_0;
in vec4 v_color;

out vec4 frag_color;

void main() {
gl_FragColor = texture(u_texture, v_texcoord_0) * v_color;
frag_color = texture(u_texture, v_texcoord_0) * v_color;
}
22 changes: 2 additions & 20 deletions modules/graphics/src/shaders/lang/glsl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,9 @@ use super::*;
/// Possible versions of OpenGL that can be targeted by a shader program.
#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
pub enum OpenGLVersion {
Glsl300,
Glsl330,
Glsl400,
Glsl410,
Glsl420,
Glsl430,
Glsl440,
Glsl450,
Glsl460,
Glsl470,
Glsl480,
Glsl500,
}

/// The OpenGL environment for a shader program.
Expand All @@ -28,7 +19,7 @@ pub struct OpenGLEnvironment {
impl Default for OpenGLEnvironment {
fn default() -> Self {
Self {
version: OpenGLVersion::Glsl330,
version: OpenGLVersion::Glsl410,
constants: vec![ShaderConstant {
name: "MAX_TEXTURES".to_string(),
value: ShaderUniform::U32(MAX_TEXTURE_UNITS as u32),
Expand Down Expand Up @@ -78,22 +69,13 @@ impl ShaderLanguage for GLSL {

// add the GLSL version directive
let version = match environment.version {
OpenGLVersion::Glsl300 => "300 core",
OpenGLVersion::Glsl330 => "330 core",
OpenGLVersion::Glsl400 => "400 core",
OpenGLVersion::Glsl410 => "410 core",
OpenGLVersion::Glsl420 => "420 core",
OpenGLVersion::Glsl430 => "430 core",
OpenGLVersion::Glsl440 => "440 core",
OpenGLVersion::Glsl450 => "450 core",
OpenGLVersion::Glsl460 => "460 core",
OpenGLVersion::Glsl470 => "470 core",
OpenGLVersion::Glsl480 => "480 core",
OpenGLVersion::Glsl500 => "500 core",
};

shared_code
.write_str(&format!("#version {}\n\n", version))
.write_str(&format!("#version {}\n", version))
.map_err(|_| ShaderError::CompileError("Failed to write version".to_string()))?;

for line in source_code.lines() {
Expand Down
13 changes: 13 additions & 0 deletions modules/graphics/src/shaders/templates.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,17 @@ impl<S: ShaderLanguage> ShaderTemplate<S> {
}
}

impl Material {
/// Creates a new material from the given shader template.
pub fn from_template<S: ShaderLanguage>(
graphics: &GraphicsEngine,
template: &ShaderTemplate<S>,
) -> Result<Self, ShaderError> {
let program = template.to_program(graphics)?;
Ok(Material::new(&graphics, &program))
}
}

/// Loads a shader template from the given path.
#[macro_export]
macro_rules! include_shader {
Expand All @@ -43,6 +54,8 @@ macro_rules! include_shader {
mod embedded {
use super::*;

pub const PROJECTION_VIEW: ShaderUniformKey<&Mat4> = ShaderUniformKey::new("u_projection_view");

pub const SHADER_CANVAS_STANDARD: ShaderTemplate<GLSL> = include_shader!("./embedded/canvas-standard.glsl");
pub const SHADER_MESH_SKINNED: ShaderTemplate<GLSL> = include_shader!("./embedded/mesh-skinned.glsl");
pub const SHADER_SPRITE_STANDARD: ShaderTemplate<GLSL> = include_shader!("./embedded/sprite-standard.glsl");
Expand Down
8 changes: 4 additions & 4 deletions modules/graphics/src/skinning.rs
Original file line number Diff line number Diff line change
Expand Up @@ -105,20 +105,20 @@ impl Skeleton {
self.bones.get_mut(index)
}

/// Borrows all of the bones in this skeleton.
/// Borrows all the bones in this skeleton.
pub fn bones(&self) -> &[Bone] {
&self.bones
}

/// Mutably borrows all of the bones in this skeleton.
/// Mutably borrows all the bones in this skeleton.
pub fn bones_mut(&mut self) -> &mut [Bone] {
&mut self.bones
}

/// Updates all the inverse bind matrices for this skeleton.
///
/// Use this to after a change to the skeleton's bone transforms, to ensure
/// that the inverse bind matrices are up to date.
/// that the inverse bind matrices are up-to-date.
pub fn update_bind_matrices(&mut self) {
let bones = self.bones.clone(); // TODO: remove this clone; might need some unsafe code

Expand Down Expand Up @@ -214,7 +214,7 @@ impl Animation {
pub struct Skin {
/// The skeleton of this skin.
pub skeleton: Skeleton,
/// All of the animations for this skin.
/// All the animations for this skin.
pub animations: Vec<Animation>,
}

Expand Down
3 changes: 0 additions & 3 deletions modules/graphics/src/sprites.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
//! Sprite management and rendering.
//!
//! Sprites are very common in projects, so this is a dedicated batch to
//! support.
use common::{vec2, Angle, Mat2, Vec2};

Expand Down
Loading

0 comments on commit f516df2

Please sign in to comment.