summaryrefslogtreecommitdiff
path: root/src/main.rs
blob: 0cbe7541ed91c01bdfb6bb1adc9b6f12d06f9cbd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
use std::error::Error;
use std::path::Path;

use engine::camera::Camera;
use engine::delta_time::DeltaTime;
use engine::ecs::sole::Single;
use engine::ecs::Query;
use engine::event::Update as UpdateEvent;
use engine::input::{Extension as InputExtension, Keys};
use engine::lighting::{LightSource, LightSourceBuilder};
use engine::material::Builder as MaterialBuilder;
use engine::renderer::Extension as RendererExtension;
use engine::shader::{Kind as ShaderKind, Program as ShaderProgram, Shader};
use engine::texture::{Id as TextureId, Map as TextureMap, Texture};
use engine::transform::Transform;
use engine::vector::{Vec2, Vec3};
use engine::vertex::Builder as VertexBuilder;
use engine::window::{Extension as WindowExtension, Key, KeyState};
use engine::Engine;
use tracing::Level;
use tracing_subscriber::FmtSubscriber;

use crate::cube::{create_cube_mesh, Corner as CubeCorner, Side as CubeSide};

mod cube;

const VERTEX_SHADER_FILE: &str = "vertex.glsl";
const FRAGMENT_SHADER_FILE: &str = "fragment.glsl";

const SHADER_DIR: &str = "engine";

const CAM_SPEED: f32 = 3.0;

const LIGHT_SOURCE_SPEED: f32 = 1.2;

fn lmao(
    camera_query: Query<(Camera,)>,
    light_source_query: Query<(LightSource,)>,
    keys: Single<Keys>,
    delta_time: Single<DeltaTime>,
)
{
    let (mut camera,) = camera_query.iter().next().expect("No camera");

    let (mut light_source,) = light_source_query.iter().next().expect("No light source");

    let delta_time = delta_time.duration;

    if matches!(keys.get_key_state(Key::W), KeyState::Pressed) {
        let cam_target_direction = camera.target_direction().clone();

        camera.position += cam_target_direction * CAM_SPEED * delta_time.as_secs_f32();
    }

    if matches!(keys.get_key_state(Key::S), KeyState::Pressed) {
        let rev_cam_target_direction = -camera.target_direction().clone();

        camera.position +=
            rev_cam_target_direction * CAM_SPEED * delta_time.as_secs_f32();
    }

    if matches!(keys.get_key_state(Key::A), KeyState::Pressed) {
        let cam_left = camera.left().clone();

        // Camera speed adjusted to be same no matter how far the distance is to the
        // camera target
        let cam_speed_dist_adj =
            CAM_SPEED * (camera.position.clone() - camera.target.clone()).length();

        camera.position += cam_left * cam_speed_dist_adj * delta_time.as_secs_f32();
    }

    if matches!(keys.get_key_state(Key::D), KeyState::Pressed) {
        let cam_right = camera.right().clone();

        // Camera speed adjusted to be same no matter how far the distance is to the
        // camera target
        let cam_speed_dist_adj =
            CAM_SPEED * (camera.position.clone() - camera.target.clone()).length();

        camera.position += cam_right * cam_speed_dist_adj * delta_time.as_secs_f32();
    }

    if matches!(keys.get_key_state(Key::K), KeyState::Pressed) {
        let cam_up = camera.up().clone();

        // Camera speed adjusted to be same no matter how far the distance is to the
        // camera target
        let cam_speed_dist_adj =
            CAM_SPEED * (camera.position.clone() - camera.target.clone()).length();

        camera.position += cam_up * cam_speed_dist_adj * delta_time.as_secs_f32();
    }

    if matches!(keys.get_key_state(Key::J), KeyState::Pressed) {
        let cam_up = camera.down().clone();

        // Camera speed adjusted to be same no matter how far the distance is to the
        // camera target
        let cam_speed_dist_adj =
            CAM_SPEED * (camera.position.clone() - camera.target.clone()).length();

        camera.position += cam_up * cam_speed_dist_adj * delta_time.as_secs_f32();
    }

    if matches!(keys.get_key_state(Key::O), KeyState::Pressed) {
        let front_right = Vec3 { x: 1.0, y: 0.0, z: 1.0 };

        light_source
            .translate(front_right * LIGHT_SOURCE_SPEED * delta_time.as_secs_f32());
    }

    if matches!(keys.get_key_state(Key::L), KeyState::Pressed) {
        let back_left = Vec3 { x: -1.0, y: 0.0, z: -1.0 };

        light_source.translate(back_left * LIGHT_SOURCE_SPEED * delta_time.as_secs_f32());
    }
}

fn main() -> Result<(), Box<dyn Error>>
{
    let subscriber = FmtSubscriber::builder()
        .with_max_level(Level::TRACE)
        .finish();

    tracing::subscriber::set_global_default(subscriber)?;

    let mut engine = Engine::new();

    let texture = Texture::open(Path::new("vent.png"))?;

    let material = MaterialBuilder::new()
        .ambient_map(TextureId::new(0))
        .diffuse_map(TextureId::new(0))
        .specular_map(TextureId::new(0))
        .build();

    /*
    let mut textured_cube = create_cube(cube_vertex_builder_cb)
        .texture(TextureId::new(0), texture.clone())
        .material(material.clone())
        .build(ObjectId::new(4))?;

    textured_cube.translate(Vec3 { x: 1.6, y: 0.0, z: 0.0 });

    engine.add_object(textured_cube);
    */

    let mut transform = Transform::new();

    transform.set_position(Vec3 { x: 1.6, y: 0.0, z: 0.0 });

    let mut shader_program = ShaderProgram::new();

    shader_program.push_shader(
        Shader::read_shader_file(
            ShaderKind::Vertex,
            &Path::new(SHADER_DIR).join(VERTEX_SHADER_FILE),
        )?
        .preprocess()?,
    );

    shader_program.push_shader(
        Shader::read_shader_file(
            ShaderKind::Fragment,
            &Path::new(SHADER_DIR).join(FRAGMENT_SHADER_FILE),
        )?
        .preprocess()?,
    );

    engine.spawn((
        create_cube_mesh(cube_vertex_builder_cb),
        TextureMap::from_iter([(TextureId::new(0), texture)]),
        material,
        transform,
        shader_program,
    ));

    let light_source = LightSourceBuilder::new()
        .position(Vec3 { x: 1.2, y: 1.0, z: 1.5 })
        .build();

    engine.spawn((light_source,));

    engine.spawn((Camera { current: true, ..Default::default() },));

    engine.register_system(UpdateEvent, lmao);

    engine.add_extension(RendererExtension::default());
    engine.add_extension(WindowExtension::default().window_title("Game"));
    engine.add_extension(InputExtension::default());

    engine.start();

    Ok(())
}

fn cube_vertex_builder_cb(
    vertex_builder: VertexBuilder,
    _side: CubeSide,
    corner: CubeCorner,
) -> VertexBuilder
{
    vertex_builder.texture_coords(match corner {
        CubeCorner::TopRight => Vec2 { x: 1.0, y: 1.0 },
        CubeCorner::TopLeft => Vec2 { x: 0.0, y: 1.0 },
        CubeCorner::BottomRight => Vec2 { x: 1.0, y: 0.0 },
        CubeCorner::BottomLeft => Vec2 { x: 0.0, y: 0.0 },
    })
}

trait CameraExt
{
    fn target_direction(&self) -> Vec3<f32>;

    fn right(&self) -> Vec3<f32>;

    fn left(&self) -> Vec3<f32>;

    fn up(&self) -> Vec3<f32>;

    fn down(&self) -> Vec3<f32>;
}

impl CameraExt for Camera
{
    fn target_direction(&self) -> Vec3<f32>
    {
        -(&self.position - &self.target).normalize()
    }

    fn right(&self) -> Vec3<f32>
    {
        let rev_target_direction = (&self.position - &self.target).normalize();

        Vec3::UP.cross(&rev_target_direction).normalize()
    }

    fn left(&self) -> Vec3<f32>
    {
        -self.right()
    }

    fn up(&self) -> Vec3<f32>
    {
        let rev_target_direction = (&self.position - &self.target).normalize();

        rev_target_direction.cross(&self.right())
    }

    fn down(&self) -> Vec3<f32>
    {
        -self.up()
    }
}