2021-32-bit-holiday-jam/src/main.rs

622 lines
14 KiB
Rust
Raw Normal View History

use nom::{
IResult,
2020-01-09 00:27:46 +00:00
bytes::complete::{tag},
number::complete::{le_u32},
};
2020-01-06 01:25:17 +00:00
use sdl2::event::Event;
use sdl2::keyboard::Keycode;
use std::collections::HashMap;
2020-01-06 01:57:34 +00:00
use std::convert::TryInto;
use std::ffi::{c_void, CStr, CString};
2020-01-09 00:18:12 +00:00
use std::fs::File;
use std::io::Read;
use std::path::Path;
2020-01-06 01:25:17 +00:00
use std::time::Duration;
2020-01-09 03:15:41 +00:00
mod iqm_consts {
pub const VERSION: usize = 0;
pub const FILESIZE: usize = 1;
pub const FLAGS: usize = 2;
pub const NUM_TEXT: usize = 3;
pub const OFS_TEXT: usize = 4;
pub const NUM_MESHES: usize = 5;
pub const OFS_MESHES: usize = 6;
pub const NUM_VERTEXARRAYS: usize = 7;
pub const NUM_VERTEXES: usize = 8;
pub const OFS_VERTEXARRAYS: usize = 9;
pub const NUM_TRIANGLES: usize = 10;
pub const OFS_TRIANGLES: usize = 11;
pub const OFS_ADJACENCY: usize = 12;
pub const NUM_JOINTS: usize = 13;
pub const OFS_JOINTS: usize = 14;
pub const NUM_POSES: usize = 15;
pub const OFS_POSES: usize = 16;
pub const NUM_ANIMS: usize = 17;
pub const OFS_ANIMS: usize = 18;
pub const NUM_FRAMES: usize = 19;
pub const NUM_FRAMECHANNELS: usize = 20;
pub const OFS_FRAMES: usize = 21;
pub const OFS_BOUNDS: usize = 22;
pub const NUM_COMMENT: usize = 23;
pub const OFS_COMMENT: usize = 24;
pub const NUM_EXTENSIONS: usize = 25;
pub const OFS_EXTENSIONS: usize = 26;
2020-01-09 00:18:12 +00:00
}
2020-01-09 03:55:44 +00:00
mod iqm_types {
pub const POSITION: u32 = 0;
pub const TEXCOORD: u32 = 1;
pub const NORMAL: u32 = 2;
pub const TANGENT: u32 = 3;
pub const BLENDINDEXES: u32 = 4;
pub const BLENDWEIGHTS: u32 = 5;
pub const COLOR: u32 = 6;
pub const CUSTOM: u32 = 0x10;
}
mod iqm_formats {
pub const BYTE: u32 = 0;
pub const UBYTE: u32 = 1;
pub const SHORT: u32 = 2;
pub const USHORT: u32 = 3;
pub const INT: u32 = 4;
pub const UINT: u32 = 5;
pub const HALF: u32 = 6;
pub const FLOAT: u32 = 7;
pub const DOUBLE: u32 = 8;
}
2020-01-09 03:15:41 +00:00
#[derive (Debug)]
pub struct IqmMesh {
name: u32,
material: u32,
first_vertex: u32,
num_vertexes: u32,
first_triangle: u32,
num_triangles: u32,
}
#[derive (Debug)]
pub struct IqmHeader {
fields: [u32; 27],
}
#[derive (Debug)]
2020-01-09 03:55:44 +00:00
pub struct IqmVertexArray {
va_type: u32,
va_flags: u32,
va_format: u32,
va_size: u32,
va_offset: u32,
}
#[derive (Debug)]
pub struct IqmModel <'a> {
data: &'a [u8],
2020-01-09 03:15:41 +00:00
header: IqmHeader,
text: Vec <u8>,
meshes: Vec <IqmMesh>,
2020-01-09 03:55:44 +00:00
vertexarrays: Vec <IqmVertexArray>,
2020-01-09 03:15:41 +00:00
}
impl IqmHeader {
pub fn from_slice (input: &[u8]) -> IResult <&[u8], IqmHeader> {
let (input, _) = tag (b"INTERQUAKEMODEL\0")(input)?;
let (input, version) = le_u32 (input)?;
// I only know how to parse version 2
assert_eq! (version, 2);
let mut input = input;
let mut fields = [0; 27];
fields [0] = version;
for index in 1..fields.len () {
let (i, h) = le_u32 (input)?;
input = i;
fields [usize::from (index)] = h;
}
Ok ((input, IqmHeader {
fields,
}))
}
}
impl IqmMesh {
pub fn from_slice (input: &[u8]) -> IResult <&[u8], IqmMesh> {
let mut result = IqmMesh {
name: 0,
material: 0,
first_vertex: 0,
num_vertexes: 0,
first_triangle: 0,
num_triangles: 0,
};
let mut input = input;
for field in [
&mut result.name,
&mut result.material,
&mut result.first_vertex,
&mut result.num_vertexes,
&mut result.first_triangle,
&mut result.num_triangles,
].iter_mut () {
let (i, f) = le_u32 (input)?;
input = i;
**field = f;
}
Ok ((input, result))
}
}
2020-01-09 03:55:44 +00:00
impl IqmVertexArray {
pub fn from_slice (input: &[u8]) -> IResult <&[u8], IqmVertexArray> {
let mut result = IqmVertexArray {
va_type: 0,
va_flags: 0,
va_format: 0,
va_size: 0,
va_offset: 0,
};
let mut input = input;
for field in [
&mut result.va_type,
&mut result.va_flags,
&mut result.va_format,
&mut result.va_size,
&mut result.va_offset,
].iter_mut () {
let (i, f) = le_u32 (input)?;
input = i;
**field = f;
}
Ok ((input, result))
}
}
impl <'a> IqmModel <'a> {
pub fn from_slice (data: &'a [u8]) -> IqmModel <'a> {
let header = IqmHeader::from_slice (data).unwrap ().1;
2020-01-09 03:15:41 +00:00
let text = {
let offset: usize = header.fields [iqm_consts::OFS_TEXT].try_into ().unwrap ();
let num: usize = header.fields [iqm_consts::NUM_TEXT].try_into ().unwrap ();
2020-01-09 03:55:44 +00:00
Vec::from (&data [offset..offset + num])
2020-01-09 03:15:41 +00:00
};
let meshes = {
2020-01-09 03:55:44 +00:00
let num: usize = header.fields [iqm_consts::NUM_MESHES].try_into ().unwrap ();
let mut meshes = Vec::with_capacity (num);
2020-01-09 03:15:41 +00:00
let mesh_size = 6 * 4;
let meshes_offset: usize = header.fields [iqm_consts::OFS_MESHES].try_into ().unwrap ();
2020-01-09 03:55:44 +00:00
for i in 0..num {
2020-01-09 03:15:41 +00:00
let offset = meshes_offset + i * mesh_size;
2020-01-09 03:55:44 +00:00
let mesh_slice = &data [offset..offset + mesh_size];
2020-01-09 03:15:41 +00:00
meshes.push (IqmMesh::from_slice (mesh_slice).unwrap ().1);
}
meshes
};
2020-01-09 03:55:44 +00:00
let vertexarrays = {
let num: usize = header.fields [iqm_consts::NUM_VERTEXARRAYS].try_into ().unwrap ();
let mut vertexarrays = Vec::with_capacity (num);
let vertexarray_size = 5 * 4;
let vertexarrays_offset: usize = header.fields [iqm_consts::OFS_VERTEXARRAYS].try_into ().unwrap ();
for i in 0..num {
let offset = vertexarrays_offset + i * vertexarray_size;
let vertexarray_slice = &data [offset..offset + vertexarray_size];
vertexarrays.push (IqmVertexArray::from_slice (vertexarray_slice).unwrap ().1);
}
vertexarrays
};
2020-01-09 03:15:41 +00:00
IqmModel {
2020-01-09 03:55:44 +00:00
data,
2020-01-09 03:15:41 +00:00
header,
text,
meshes,
2020-01-09 03:55:44 +00:00
vertexarrays,
2020-01-09 03:15:41 +00:00
}
}
2020-01-09 03:55:44 +00:00
pub fn get_vertex_slice (&self,
mesh_index: usize, vertexarray_index: usize
) -> &[u8]
{
let vertexarray = &self.vertexarrays [vertexarray_index];
let bytes_per_float = 4;
let stride = bytes_per_float * vertexarray.va_size;
let mesh = &self.meshes [mesh_index];
let offset: usize = (vertexarray.va_offset + stride * mesh.first_vertex).try_into ().unwrap ();
let num_bytes: usize = (stride * mesh.num_vertexes).try_into ().unwrap ();
&self.data [offset..offset + num_bytes]
}
pub fn get_index_slice (&self, mesh_index: usize) -> &[u8] {
let mesh = &self.meshes [mesh_index];
let bytes_per_u32 = 4;
let indexes_per_tri = 3;
let stride = bytes_per_u32 * indexes_per_tri;
let offset: usize = (self.header.fields [iqm_consts::OFS_TRIANGLES] + stride * mesh.first_triangle).try_into ().unwrap ();
let num_bytes: usize = (stride * mesh.num_triangles).try_into ().unwrap ();
&self.data [offset..offset + num_bytes]
}
2020-01-09 00:18:12 +00:00
}
pub fn load_small_file <P> (name: P) -> Vec <u8>
where P: AsRef <Path>
{
let mut f = File::open (name).unwrap ();
let len = f.metadata ().unwrap ().len ();
if len > 1024 * 1024 {
panic! ("File is too big");
}
let mut data = vec! [0u8; len.try_into ().unwrap ()];
f.read (&mut data [..]).unwrap ();
data
}
2020-01-06 01:57:34 +00:00
const VERT_SHADER_SRC: &str =
"
#define lowp
#define mediump
#define highp
#line 0
uniform highp mat4 uni_model;
uniform highp mat4 uni_viewproj;
attribute highp vec4 attr_pos;
attribute mediump vec2 attr_uv;
attribute lowp vec3 attr_normal;
varying lowp vec4 vary_color;
varying mediump vec2 vary_uv;
void main (void) {
vary_uv = attr_uv;
lowp vec4 light_color = vec4 (1.0);
vary_color = light_color;
vec4 world_pos = uni_model * attr_pos;
gl_Position = uni_viewproj * world_pos;
}";
const FRAG_SHADER_SRC: &str =
"
#define lowp
#define mediump
#define highp
#line 0
uniform lowp sampler2D uni_texture;
varying lowp vec4 vary_color;
varying mediump vec2 vary_uv;
void main (void) {
gl_FragColor = texture2D (uni_texture, vary_uv) * vary_color;
//gl_FragColor = vec4 (1.0, 0.0, 1.0, 1.0);
}
";
pub struct ShaderObject {
id: u32,
}
impl ShaderObject {
pub fn id (&self) -> u32 {
self.id
}
pub fn new (shader_type: u32, source: &str) -> Result <ShaderObject, String>
{
let id = unsafe {
gl::CreateShader (shader_type)
};
let sources = [
source.as_ptr () as *const i8,
];
let lengths = [
source.len ().try_into ().unwrap (),
];
let success = unsafe {
gl::ShaderSource (id, sources.len ().try_into ().unwrap (), sources.as_ptr (), lengths.as_ptr ());
gl::CompileShader (id);
let mut success = 0;
gl::GetShaderiv (id, gl::COMPILE_STATUS, &mut success);
success == 1
};
if success {
Ok (ShaderObject {
id,
})
}
else {
let mut info_log = vec! [0u8; 4096];
let mut log_length = 0;
unsafe {
gl::GetShaderInfoLog (id, (info_log.len () - 1).try_into ().unwrap (), &mut log_length, info_log.as_mut_ptr () as *mut i8);
}
info_log.truncate (log_length.try_into ().unwrap ());
let info = String::from_utf8 (info_log).unwrap ();
Err (info)
}
}
}
impl Drop for ShaderObject {
fn drop (&mut self) {
unsafe {
gl::DeleteShader (self.id);
}
}
}
pub struct ShaderProgram {
id: u32,
}
impl ShaderProgram {
pub fn new (vert: &ShaderObject, frag: &ShaderObject)
-> Result <ShaderProgram, String>
{
let id = unsafe {
gl::CreateProgram ()
};
unsafe {
gl::AttachShader (id, vert.id ());
gl::AttachShader (id, frag.id ());
gl::LinkProgram (id);
}
let success = unsafe {
let mut success = 0;
gl::GetProgramiv (id, gl::LINK_STATUS, &mut success);
success == 1
};
if success {
Ok (ShaderProgram {
id,
})
}
else {
let mut info_log = vec! [0u8; 4096];
let mut log_length = 0;
unsafe {
gl::GetProgramInfoLog (id, (info_log.len () - 1).try_into ().unwrap (), &mut log_length, info_log.as_mut_ptr () as *mut i8);
}
info_log.truncate (log_length.try_into ().unwrap ());
let info = String::from_utf8 (info_log).unwrap ();
Err (info)
}
}
pub fn get_uniform_location (&self, name: &CStr) -> i32 {
unsafe {
gl::UseProgram (self.id);
gl::GetUniformLocation (self.id, name.as_ptr ())
}
}
pub fn get_attribute_location (&self, name: &CStr) -> i32 {
unsafe {
gl::UseProgram (self.id);
gl::GetAttribLocation (self.id, name.as_ptr ())
}
}
}
impl Drop for ShaderProgram {
fn drop (&mut self) {
unsafe {
gl::DeleteProgram (self.id);
}
}
}
2020-01-06 01:25:17 +00:00
fn main () {
let sdl_context = sdl2::init ().unwrap ();
let video_subsystem = sdl_context.video ().unwrap ();
let window = video_subsystem.window ("OpenGL? In my Rust?", 1280, 720)
.position_centered ()
.opengl ()
.build ()
.unwrap ();
gl::load_with (|s| {
let result = video_subsystem.gl_get_proc_address (s) as *const _;
//println! ("{:?}", result);
result
});
assert! (gl::ClearColor::is_loaded ());
let gl_ctx = window.gl_create_context ().unwrap ();
2020-01-06 01:57:34 +00:00
window.gl_make_current (&gl_ctx).unwrap ();
// I love how with Rust I can throw unwrap ()s everywhere
// It's safer than C / C++'s default behavior of unchecked errors
// It's more programmer-friendly and explicit than C#'s unchecked
// exceptions that can appear almost anywhere at runtime with no
// compile-time warning
// And I'm still not actually checking errors - Just checkmarking
// that I know where they are.
2020-01-06 01:57:34 +00:00
let vert_shader = ShaderObject::new (gl::VERTEX_SHADER, VERT_SHADER_SRC).unwrap ();
let frag_shader = ShaderObject::new (gl::FRAGMENT_SHADER, FRAG_SHADER_SRC).unwrap ();
let shader_program = ShaderProgram::new (&vert_shader, &frag_shader).unwrap ();
let unis: HashMap <_, _> = vec! [
"model",
"viewproj",
].iter ()
.map (|name| {
let mut s = String::from ("uni_");
s.push_str (name);
let c_str = CString::new (s.as_bytes ()).unwrap ();
(String::from (*name), shader_program.get_uniform_location (&c_str))
})
.collect ();
println! ("uni_model: {}", unis ["model"]);
println! ("uni_viewproj: {}", unis ["viewproj"]);
let attrs: HashMap <_, u32> = vec! [
"pos",
"uv",
//"normal",
].iter ()
.map (|name| {
let mut s = String::from ("attr_");
s.push_str (name);
let c_str = CString::new (s.as_bytes ()).unwrap ();
let loc = shader_program.get_attribute_location (&c_str);
(String::from (*name), loc.try_into ().unwrap ())
})
.collect ();
println! ("attr_pos: {}", attrs ["pos"]);
let tri_mesh: Vec <f32> = vec! [
0.0, 0.0,
1.0, 0.0,
1.0, 1.0,
];
2020-01-09 03:55:44 +00:00
let model_data = load_small_file ("pumpking.iqm");
let model = IqmModel::from_slice (&model_data [..]);
let vertex_slice = model.get_vertex_slice (0, 0);
let index_slice = model.get_index_slice (0);
let id_mat: Vec <f32> = vec! [
1.0, 0.0, 0.0, 0.0,
0.0, 1.0, 0.0, 0.0,
0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 1.0,
];
2020-01-09 03:55:44 +00:00
let view_mat: Vec <f32> = vec! [
0.3125, 0.0, 0.0, 0.0,
0.0, 0.5, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 1.0,
];
let indexes: Vec <u16> = vec! [0, 1, 2];
const FALSE_U8: u8 = 0;
unsafe {
gl::EnableVertexAttribArray (attrs ["pos"]);
2020-01-09 03:55:44 +00:00
let num_coords = 3;
let stride = 4 * num_coords;
gl::VertexAttribPointer (attrs ["pos"], num_coords, gl::FLOAT, FALSE_U8, stride, &vertex_slice [0] as *const u8 as *const c_void);
2020-01-09 03:55:44 +00:00
gl::UniformMatrix4fv (unis ["viewproj"], 1, FALSE_U8, &view_mat [0]);
gl::UniformMatrix4fv (unis ["model"], 1, FALSE_U8, &id_mat [0]);
}
2020-01-06 01:25:17 +00:00
let mut event_pump = sdl_context.event_pump ().unwrap ();
'running: loop {
2020-01-06 01:57:34 +00:00
let _mouse = event_pump.mouse_state ();
2020-01-06 01:25:17 +00:00
for event in event_pump.poll_iter() {
match event {
Event::Quit {..} |
Event::KeyDown { keycode: Some (Keycode::Escape), .. } => {
break 'running
},
_ => (),
}
}
window.gl_make_current (&gl_ctx).unwrap ();
unsafe {
gl::ClearColor (1.0f32, 0.0f32, 1.0f32, 1.0f32);
gl::Clear (gl::COLOR_BUFFER_BIT | gl::DEPTH_BUFFER_BIT);
2020-01-09 03:55:44 +00:00
gl::Disable (gl::CULL_FACE);
2020-01-09 03:55:44 +00:00
gl::DrawElements (gl::TRIANGLES, (model.meshes [0].num_triangles * 3) as i32, gl::UNSIGNED_INT, &index_slice [0] as *const u8 as *const c_void);
2020-01-06 01:25:17 +00:00
}
window.gl_swap_window ();
::std::thread::sleep (Duration::from_millis (15));
}
}
#[cfg (test)]
mod tests {
use super::*;
#[test]
pub fn iqm () {
2020-01-09 00:27:46 +00:00
let data = load_small_file ("pumpking.iqm");
2020-01-09 00:18:12 +00:00
2020-01-09 03:15:41 +00:00
{
let model = IqmHeader::from_slice (&data [..]).unwrap ().1;
assert_eq! (model.fields [1], 90368);
assert_eq! (model.fields [2], 0);
assert_eq! (model.fields [iqm_consts::VERSION], 2);
}
{
let model = IqmModel::from_slice (&data [..]);
println! ("{:?}", model.meshes);
2020-01-09 03:55:44 +00:00
println! ("{:?}", model.vertexarrays);
2020-01-09 03:15:41 +00:00
}
}
}