Compare commits

...

11 Commits

Author SHA1 Message Date
Mark fd94cd6701
Improved system parser 2023-12-25 10:30:27 -08:00
Mark 4f0d77eeea
Minor cleanup 2023-12-25 10:29:52 -08:00
Mark 10823b9714
Adjust scale for z-distance 2023-12-25 10:23:25 -08:00
Mark 73c2820af2
Added luna 2023-12-25 10:21:52 -08:00
Mark 5b65d8adc3
Added system name 2023-12-25 09:01:59 -08:00
Mark 619b8ae797
Added system loading from file 2023-12-25 09:01:12 -08:00
Mark 50bd3bdb8c
Minor rename 2023-12-25 08:46:10 -08:00
Mark b2e9f64c91
Minor cleanup 2023-12-25 08:35:34 -08:00
Mark 7e2673f852
Minor cleanup 2023-12-25 08:33:31 -08:00
Mark 3b41739b0f
Minor cleanup 2023-12-25 08:31:20 -08:00
Mark b7d12ac875
Edited include format 2023-12-25 08:17:05 -08:00
19 changed files with 234 additions and 139 deletions

2
assets

@ -1 +1 @@
Subproject commit 66b7aab8af273cac9b805d813f2e5cb70a920000
Subproject commit 45f65b6a639f3e59d9d1db2a4cf452fe406bd4b2

View File

@ -3,11 +3,26 @@
name = "12 Autumn above"
[object.star]
sprite = "star::a0"
center = [0.0, 0.0]
sprite = "star::star"
position = [0.0, 0.0]
size = 1000
parallax = 20.0
[object.earth]
sprite = "planet::earth"
center = "star"
radius = 200
angle = 14
position.center = "star"
position.radius = 4000
position.angle = 0
size = 1000
parallax = 10.0
[object.luna]
sprite = "planet::luna"
position.center = "earth"
position.radius = 1600
position.angle = 135
size = 500
angle = -45
parallax = 7.8

View File

@ -1,24 +1,25 @@
use anyhow::Result;
use anyhow::{Context, Result};
use std::path::PathBuf;
use super::{syntax, ContentType};
#[derive(Debug)]
pub struct Content {
systems: Vec<syntax::System>,
pub systems: Vec<syntax::system::System>,
}
impl Content {
pub fn new(cv: Vec<ContentType>) -> Result<Self> {
pub fn new(cv: Vec<(PathBuf, ContentType)>) -> Result<Self> {
let mut content = Self {
systems: Vec::new(),
};
// TODO: locate bad files
// These methods check intra-file consistency
for c in cv {
for (p, c) in cv {
match c {
ContentType::System(v) => content.add_system(v)?,
ContentType::System(v) => content
.add_system(v)
.with_context(|| format!("Could not parse {}", p.display()))?,
};
}
@ -26,7 +27,7 @@ impl Content {
}
fn add_system(&mut self, toml: syntax::system::toml::SystemRoot) -> Result<()> {
self.systems.push(syntax::System::parse(toml)?);
self.systems.push(syntax::system::System::parse(toml)?);
return Ok(());
}
}

View File

@ -1,4 +1,4 @@
use anyhow::Result;
use anyhow::{bail, Result};
use std::{fs::File, io::Read, path::Path};
use super::syntax;
@ -12,12 +12,21 @@ pub enum ContentType {
impl ContentType {
pub fn try_parse(file_string: &str) -> Result<Option<Self>> {
// TODO: More advanced parsing, read the whole top comment
let (first, _) = file_string.split_once("\n").unwrap();
let first = match file_string.split_once("\n") {
None => bail!("This file is empty."),
Some((first, _)) => first,
};
let type_spec = first[1..].trim(); // Remove hash
return Ok(match type_spec {
"content type: system" => Some(Self::System(toml::from_str(&file_string)?)),
_ => None,
let type_spec = if type_spec.starts_with("content type: ") {
type_spec[14..].to_owned()
} else {
bail!("No content type specified")
};
return Ok(match &type_spec[..] {
"system" => Some(Self::System(toml::from_str(&file_string)?)),
_ => bail!("Invalid content type `{}`", type_spec),
});
}

View File

@ -4,3 +4,38 @@ mod syntax;
pub use content::Content;
pub use contenttype::ContentType;
pub use syntax::system;
use anyhow::{Context, Result};
use walkdir::WalkDir;
pub fn load_content_dir(path: &str) -> Result<Content> {
let mut raw_content = Vec::new();
for e in WalkDir::new(path).into_iter().filter_map(|e| e.ok()) {
if e.metadata().unwrap().is_file() {
// TODO: better warnings
match e.path().extension() {
Some(t) => {
if t.to_str() != Some("toml") {
println!("[WARNING] {e:#?} is not a toml file, skipping.");
continue;
}
}
None => {
println!("[WARNING] {e:#?} is not a toml file, skipping.");
continue;
}
}
let c = crate::content::ContentType::from_path(e.path())
.with_context(|| format!("Could not load {:#?}", e.path()))?;
match c {
Some(c) => raw_content.push((e.path().to_path_buf(), c)),
None => continue,
}
}
}
return crate::content::Content::new(raw_content);
}

View File

@ -1,3 +1,2 @@
#![allow(dead_code)]
pub mod system;
pub use system::System;

View File

@ -1,8 +1,8 @@
use anyhow::{bail, Result};
use cgmath::Point2;
use std::collections::HashMap;
use anyhow::{bail, Context, Result};
use cgmath::{Deg, Point2};
use std::collections::{HashMap, HashSet};
use crate::physics::Pfloat;
use crate::physics::{Pfloat, Polar};
/// Toml file syntax
pub(in crate::content) mod toml {
@ -24,43 +24,106 @@ pub(in crate::content) mod toml {
#[derive(Debug, Deserialize)]
pub struct Object {
pub sprite: String,
pub center: Center,
pub position: Position,
#[serde(default)]
pub size: Pfloat,
pub parallax: Pfloat,
pub radius: Option<Pfloat>,
pub angle: Option<Pfloat>,
}
#[derive(Debug, Deserialize)]
#[serde(untagged)]
pub enum Position {
Polar(PolarCoords),
Cartesian(Coordinates),
}
#[derive(Debug, Deserialize)]
pub struct PolarCoords {
pub center: Coordinates,
pub radius: Pfloat,
#[serde(default)]
pub angle: Pfloat,
}
#[derive(Debug, Deserialize)]
#[serde(untagged)]
pub enum Center {
pub enum Coordinates {
Label(String),
Coords([Pfloat; 2]),
}
impl ToString for Coordinates {
fn to_string(&self) -> String {
match self {
Self::Label(s) => s.to_owned(),
Self::Coords(v) => format!("{:?}", v),
}
}
}
}
#[derive(Debug)]
pub struct System {
name: String,
objects: Vec<Object>,
pub name: String,
pub objects: Vec<Object>,
}
#[derive(Debug)]
struct Object {
sprite: String,
center: Point2<Pfloat>,
radius: Pfloat,
angle: Pfloat,
pub struct Object {
pub sprite: String,
pub position: Point2<f32>,
pub size: Pfloat,
pub parallax: Pfloat,
pub angle: Deg<Pfloat>,
}
fn resolve_center(
fn resolve_coordinates(
objects: &HashMap<String, toml::Object>,
cor: &toml::Coordinates,
mut cycle_detector: HashSet<String>,
) -> Result<Point2<f32>> {
match cor {
toml::Coordinates::Coords(c) => Ok((*c).into()),
toml::Coordinates::Label(l) => {
if cycle_detector.contains(l) {
bail!(
"Found coordinate cycle: `{}`",
cycle_detector.iter().fold(String::new(), |sum, a| {
if sum.is_empty() {
a.to_string()
} else {
sum + " -> " + a
}
})
);
}
cycle_detector.insert(l.to_owned());
let p = match objects.get(l) {
Some(p) => p,
None => bail!("Could not resolve coordinate label `{l}`"),
};
Ok(resolve_position(&objects, &p, cycle_detector)
.with_context(|| format!("In object {:#?}", l))?)
}
}
}
fn resolve_position(
objects: &HashMap<String, toml::Object>,
obj: &toml::Object,
) -> Option<Point2<f32>> {
match &obj.center {
toml::Center::Label(s) => resolve_center(&objects, objects.get(s)?),
toml::Center::Coords(v) => Some(Point2::from(*v)),
cycle_detector: HashSet<String>,
) -> Result<Point2<f32>> {
match &obj.position {
toml::Position::Cartesian(c) => Ok(resolve_coordinates(objects, c, cycle_detector)?),
toml::Position::Polar(p) => Ok(Polar {
center: resolve_coordinates(&objects, &p.center, cycle_detector)?,
radius: p.radius,
angle: Deg(p.angle),
}
.to_cartesian()),
}
}
@ -68,22 +131,17 @@ impl System {
pub fn parse(value: toml::SystemRoot) -> Result<Self> {
let mut objects = Vec::new();
for (_, obj) in &value.object {
let center = match resolve_center(&value.object, obj) {
Some(v) => v,
None => {
bail!(
"Failed to parse content file: could not resolve center label `{:?}`",
obj.center
);
}
};
for (label, obj) in &value.object {
let mut cycle_detector = HashSet::new();
cycle_detector.insert(label.to_owned());
objects.push(Object {
sprite: obj.sprite.clone(),
center,
radius: obj.radius,
angle: obj.angle,
position: resolve_position(&value.object, &obj, cycle_detector)
.with_context(|| format!("In object {:#?}", label))?,
size: obj.size,
parallax: obj.parallax,
angle: Deg(obj.angle.unwrap_or(0.0)),
});
}

View File

@ -6,17 +6,18 @@ pub struct Doodad {
pub sprite: SpriteTexture,
pub pos: Point2<Pfloat>,
pub parallax: Pfloat,
pub height: Pfloat,
pub size: Pfloat,
pub angle: Deg<Pfloat>,
}
impl Spriteable for Doodad {
fn get_sprite(&self) -> Sprite {
return Sprite {
texture: self.sprite.clone(),
pos: self.pos,
angle: Deg { 0: 0.0 },
scale: 1.0,
height: self.height,
pos: self.pos,
angle: self.angle,
size: self.size,
parallax: self.parallax,
};
}

View File

@ -8,8 +8,8 @@ mod system;
use anyhow::Result;
use cgmath::{Deg, Point2};
use content::Content;
use std::time::Instant;
use walkdir::WalkDir;
use winit::{
event::{
ElementState, Event, KeyboardInput, MouseButton, MouseScrollDelta, TouchPhase,
@ -69,10 +69,10 @@ struct Sprite {
/// The size of this sprite,
/// given as height in world units.
height: Pfloat,
size: Pfloat,
/// Scale factor.
/// if this is 1, sprite height is exactly self.height.
/// if this is 1, sprite height is exactly self.size.
scale: Pfloat,
/// This sprite's rotation
@ -95,7 +95,7 @@ struct Game {
}
impl Game {
fn new() -> Self {
fn new(ct: Content) -> Self {
Game {
last_update: Instant::now(),
input: InputStatus::new(),
@ -104,7 +104,7 @@ impl Game {
pos: (0.0, 0.0).into(),
zoom: 500.0,
},
system: System::new(),
system: System::new(&ct.systems[0]),
}
}
@ -128,11 +128,11 @@ impl Game {
}
if self.input.key_right {
self.player.body.rot(Deg { 0: 35.0 } * t);
self.player.body.rot(Deg(35.0) * t);
}
if self.input.key_left {
self.player.body.rot(Deg { 0: -35.0 } * t);
self.player.body.rot(Deg(-35.0) * t);
}
if self.input.v_scroll != 0.0 {
@ -140,6 +140,7 @@ impl Game {
self.input.v_scroll = 0.0;
}
println!("{:?}", self.player.body.pos);
self.player.body.tick(t);
self.camera.pos = self.player.body.pos;
@ -163,12 +164,11 @@ impl Game {
}
}
pub async fn run() -> Result<()> {
async fn run(mut game: Game) -> Result<()> {
let event_loop = EventLoop::new();
let window = WindowBuilder::new().build(&event_loop).unwrap();
let mut gpu = GPUState::new(window).await?;
let mut game = Game::new();
gpu.update_starfield_buffer(&game);
@ -231,20 +231,10 @@ pub async fn run() -> Result<()> {
}
fn main() -> Result<()> {
let mut raw_content = Vec::new();
for e in WalkDir::new("content").into_iter().filter_map(|e| e.ok()) {
if e.metadata().unwrap().is_file() {
let c = crate::content::ContentType::from_path(e.path())?;
match c {
Some(c) => raw_content.push(c),
None => continue,
}
}
}
let content = content::load_content_dir("./content")?;
println!("{:?}", content);
let game = Game::new(content);
let a = crate::content::Content::new(raw_content)?;
println!("{:?}", a);
//pollster::block_on(run())?;
pollster::block_on(run(game))?;
return Ok(());
}

View File

@ -14,7 +14,7 @@ impl PhysBody {
pos,
vel: (0.0, 0.0).into(),
mass: 0.3,
angle: Deg { 0: 0.0 },
angle: Deg(0.0),
};
}
@ -43,9 +43,7 @@ impl PhysBody {
// Wrap angles
if self.angle.0.abs() > 180.0 {
self.angle -= Deg {
0: self.angle.0.signum() * 360.0,
};
self.angle -= Deg(self.angle.0.signum() * 360.0);
}
}
}

View File

@ -1,5 +1,5 @@
use super::Pfloat;
use cgmath::{Angle, Deg, EuclideanSpace, Point2};
use cgmath::{Angle, Deg, Point2, Vector2};
#[derive(Debug, Clone, Copy)]
pub struct Polar {
@ -10,9 +10,11 @@ pub struct Polar {
impl Polar {
pub fn to_cartesian(self) -> Point2<Pfloat> {
return Point2 {
let v = Vector2 {
x: self.radius * self.angle.sin(),
y: self.radius * self.angle.cos(),
} + self.center.to_vec();
};
return self.center + v;
}
}

View File

@ -223,7 +223,7 @@ impl GPUState {
// Game dimensions of this sprite post-scale.
// Don't divide by 2, we use this later.
let height = s.height * s.scale;
let height = s.size * s.scale / s.parallax;
let width = height * texture.aspect;
// Don't draw (or compute matrices for)
@ -311,7 +311,7 @@ impl GPUState {
instances.push(StarfieldInstance {
position: (s.pos + offset).into(),
parallax: s.parallax,
height: s.height,
size: s.size,
tint: s.tint.into(),
})
}

View File

@ -7,10 +7,8 @@ mod vertexbuffer;
pub use gpustate::GPUState;
/// A handle to a sprite texture
#[derive(Debug, Clone, Copy)]
pub struct SpriteTexture {
pub name: &'static str,
}
#[derive(Debug, Clone)]
pub struct SpriteTexture(pub String);
// API correction matrix.
// cgmath uses OpenGL's matrix format, which

View File

@ -2,7 +2,7 @@
struct InstanceInput {
@location(2) position: vec2<f32>,
@location(3) parallax: f32,
@location(4) height: f32,
@location(4) size: f32,
@location(5) tint: vec2<f32>,
};
@ -57,7 +57,7 @@ fn vertex_shader_main(
// Apply sprite aspect ratio & scale factor
// also applies screen aspect ratio
var scale: f32 = instance.height / global.camera_zoom.x;
var scale: f32 = instance.size / global.camera_zoom.x;
// Minimum scale to prevent flicker at large zoom levels
var real_size = scale * global.window_size.xy;

View File

@ -21,7 +21,7 @@ impl TextureArray {
}
pub fn get_sprite_texture(&self, sprite: SpriteTexture) -> Texture {
return self.get_texture(sprite.name);
return self.get_texture(&sprite.0);
}
fn get_texture(&self, name: &str) -> Texture {

View File

@ -1,10 +1,11 @@
use anyhow::Result;
use std::{collections::HashMap, fs::File, io::Read, path::Path};
use std::{collections::HashMap, fs::File, io::Read, path::Path, path::PathBuf};
use super::{rawtexture::RawTexture, Texture, TextureArrayConfig};
mod fields {
use super::{File, Path, RawTexture, Read, Result, TextureArrayConfig};
use super::{File, HashMap, Path, PathBuf, RawTexture, Read, Result, TextureArrayConfig};
use serde::Deserialize;
// Config is used outside of this file,
@ -13,7 +14,7 @@ mod fields {
#[derive(Deserialize)]
pub struct Index {
pub config: TextureArrayConfig,
pub include: Option<Vec<String>>,
pub include: Option<HashMap<PathBuf, String>>,
pub texture: Vec<Texture>,
}
@ -31,7 +32,7 @@ mod fields {
#[derive(Deserialize)]
pub struct SubIndex {
pub include: Option<Vec<String>>,
pub include: Option<HashMap<PathBuf, String>>,
pub texture: Vec<Texture>,
}
@ -152,8 +153,8 @@ impl TextureLoader {
// Load included files
if let Some(include) = index.include {
for i in include {
let sub_root = texture_root.join(&i);
for (path, sub_prefix) in include {
let sub_root = texture_root.join(&path);
let index: fields::SubIndex = {
let mut texture_index_string = String::new();
let _ = File::open(sub_root.join(Self::INDEX_NAME))?
@ -167,9 +168,9 @@ impl TextureLoader {
index,
&sub_root,
if prefix.is_empty() {
i
sub_prefix
} else {
format!("{prefix}::{i}")
format!("{prefix}::{sub_prefix}")
},
)?;
for (s, data) in sub_textures {

View File

@ -44,9 +44,7 @@ pub struct StarfieldInstance {
/// Parallax factor (same unit as usual)
pub parallax: f32,
/// Height of (unrotated) sprite in world units
pub height: f32,
pub size: f32,
pub tint: [f32; 2],
}
@ -68,7 +66,7 @@ impl BufferObject for StarfieldInstance {
shader_location: 3,
format: wgpu::VertexFormat::Float32,
},
// Height
// Size
wgpu::VertexAttribute {
offset: mem::size_of::<[f32; 3]>() as wgpu::BufferAddress,
shader_location: 4,

View File

@ -12,10 +12,10 @@ impl ShipKind {
Self::Gypsum => "ship::gypsum",
};
return SpriteTexture { name };
return SpriteTexture(name.to_owned());
}
fn height(&self) -> Pfloat {
fn size(&self) -> Pfloat {
match self {
Self::Gypsum => 100.0,
}
@ -44,7 +44,7 @@ impl Spriteable for Ship {
angle: self.body.angle,
scale: 1.0,
parallax: 1.0,
height: self.kind.height(),
size: self.kind.size(),
};
}
}

View File

@ -1,10 +1,8 @@
use crate::{
physics::{Pfloat, Polar},
render::SpriteTexture,
Doodad, Sprite, Spriteable, STARFIELD_COUNT, STARFIELD_PARALLAX_MAX, STARFIELD_PARALLAX_MIN,
STARFIELD_SIZE,
content, physics::Pfloat, render::SpriteTexture, Doodad, Sprite, Spriteable, STARFIELD_COUNT,
STARFIELD_PARALLAX_MAX, STARFIELD_PARALLAX_MIN, STARFIELD_SIZE,
};
use cgmath::{Deg, Point2, Vector2};
use cgmath::{Point2, Vector2};
use rand::{self, Rng};
pub struct StarfieldStar {
@ -12,8 +10,9 @@ pub struct StarfieldStar {
/// These are relative to the center of a starfield tile.
pub pos: Point2<Pfloat>,
// TODO: z-coordinate?
pub parallax: Pfloat,
pub height: Pfloat,
pub size: Pfloat,
/// Color/brightness variation.
/// See shader.
@ -21,15 +20,17 @@ pub struct StarfieldStar {
}
pub struct System {
pub name: String,
bodies: Vec<Doodad>,
pub starfield: Vec<StarfieldStar>,
}
impl System {
pub fn new() -> Self {
pub fn new(ct: &content::system::System) -> Self {
let mut rng = rand::thread_rng();
let sz = STARFIELD_SIZE as f32 / 2.0;
let mut s = System {
name: ct.name.clone(),
bodies: Vec::new(),
starfield: (0..STARFIELD_COUNT)
.map(|_| StarfieldStar {
@ -38,7 +39,7 @@ impl System {
y: rng.gen_range(-sz..=sz),
},
parallax: rng.gen_range(STARFIELD_PARALLAX_MIN..STARFIELD_PARALLAX_MAX),
height: rng.gen_range(0.2..0.8), // TODO: configurable
size: rng.gen_range(0.2..0.8), // TODO: configurable
tint: Vector2 {
x: rng.gen_range(0.0..=1.0),
y: rng.gen_range(0.0..=1.0),
@ -47,26 +48,15 @@ impl System {
.collect(),
};
s.bodies.push(Doodad {
pos: (0.0, 0.0).into(),
sprite: SpriteTexture { name: "star::star" },
parallax: 10.0,
height: 80.0,
});
s.bodies.push(Doodad {
pos: Polar {
center: (0.0, 0.0).into(),
radius: 5000.0,
angle: Deg { 0: 31.0 },
}
.to_cartesian(),
sprite: SpriteTexture {
name: "planet::earth",
},
parallax: 5.0,
height: 120.0,
});
for o in &ct.objects {
s.bodies.push(Doodad {
pos: o.position,
sprite: SpriteTexture(o.sprite.to_owned()),
size: o.size,
parallax: o.parallax,
angle: o.angle,
});
}
return s;
}