ira 0.3.0

A general-purpose, code-first game engine.
Documentation
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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
use crate::{
	client::ClientId,
	packet::{CreateInstance, Packet, TrustedPacket},
	physics::{InstanceHandle, PhysicsState},
	server::{self, InstanceId},
	DrumExt, GpuDrum, Instance, InstanceBuilder,
};

#[cfg(feature = "client")]
use crate::render::RenderState;

use std::{
	collections::BTreeMap,
	fmt,
	sync::{atomic::AtomicU32, mpsc, Arc},
	time::{self, Duration},
};

use glam::Vec2;
use ira_drum::Drum;
use rapier3d::data::Arena;
use tracing::info;
#[cfg(feature = "client")]
use winit::{
	application::ApplicationHandler,
	error::EventLoopError,
	event::{DeviceEvent, KeyEvent, WindowEvent},
	event_loop::{ActiveEventLoop, ControlFlow, EventLoop},
	keyboard::{KeyCode, PhysicalKey},
	window::{CursorGrabMode, Fullscreen, Window, WindowAttributes, WindowId},
};

/// Implemented by the application to handle user input,
/// physics, and rendering.
///
/// For networked games, implement the [`Network`] trait as well.
#[allow(unused_variables)]
pub trait App<M = ()> {
	/// Connects to the server. This is only called on clients.
	#[must_use]
	fn connect() -> std::net::TcpStream {
		std::net::TcpStream::connect("127.0.0.1:12345").unwrap()
	}

	/// Creates a new listener for the server to receive connections.
	#[must_use]
	fn listen() -> std::net::TcpListener {
		std::net::TcpListener::bind("127.0.0.1:12345").unwrap()
	}

	/// Called when a remote player joins the game. This should return
	/// the model id, and a builder for the instance.
	fn create_player(ctx: &mut Context<M>) -> (u32, InstanceBuilder);

	/// Called when a packet is received from the server.
	fn on_packet(ctx: &mut Context<M>, packet: TrustedPacket<M>) {}
	/// Called once at the start of the program, right after the window
	/// is created but before anything else is done.
	fn on_init() -> Drum;
	/// Called once when everything has been created on the GPU.
	fn on_ready(ctx: &mut Context<M>) -> Self;
	/// Called once per frame, right before rendering. Note that this
	/// will not be called if the `render` feature is not enabled.
	fn on_update(&mut self, ctx: &mut Context<M>, delta: Duration) {}
	/// Called every 1/60th of a second. If queued at the same time as an update,
	/// this will always be called first.
	fn on_fixed_update(&mut self, ctx: &mut Context<M>) {}
}

/// A game instance.
///
/// [`A`] is the application type (that implements [`App`]).
/// [`M`] is the custom message that can be sent between the client and server.
pub struct Game<A, M = ()> {
	state: Option<(Context<M>, A)>,
}

#[derive(Debug)]
pub enum Error {
	/// An error occurred while running the event loop.
	#[cfg(feature = "client")]
	EventLoop(EventLoopError),
}

#[cfg(feature = "client")]
impl From<EventLoopError> for Error {
	fn from(e: EventLoopError) -> Self {
		Self::EventLoop(e)
	}
}

impl<A, M> Default for Game<A, M> {
	fn default() -> Self {
		Self { state: None }
	}
}

impl<A: App<M>, M> Game<A, M> {
	/// Runs the application.
	///
	/// This function will block the current thread until the application is closed.
	///
	/// # Errors
	///
	/// See [`winit::error::EventLoopError`] for errors.
	#[cfg(feature = "client")]
	pub fn run(mut self) -> Result<(), Error>
	where
		M: bitcode::Encode + bitcode::DecodeOwned + fmt::Debug + Send + 'static,
	{
		let event_loop = EventLoop::new()?;

		event_loop.set_control_flow(ControlFlow::Poll);
		event_loop.run_app(&mut self)?;

		Ok(())
	}

	/// Runs the application.
	///
	/// This function will block the current thread until the application is closed.
	///
	/// # Errors
	///
	/// See [`Error`] for errors.
	#[cfg(not(feature = "client"))]
	pub fn run(self) -> Result<(), Error>
	where
		M: bitcode::Encode + bitcode::DecodeOwned + fmt::Debug + Send + 'static,
	{
		use tracing::info;

		let drum = A::on_init();
		let mut ctx = pollster::block_on(Context::<M>::new::<A>(drum));
		let mut app = A::on_ready(&mut ctx);

		info!("starting render loop");

		loop {
			ctx.render(&mut app);
		}
	}
}

/// The game context, containing all game-related data.
pub struct Context<M = ()> {
	last_frame: time::Instant,
	last_physics: time::Instant,

	pub physics: PhysicsState,

	pub(crate) desired_fps: f32,

	#[cfg(feature = "client")]
	pub(crate) pressed_keys: Vec<KeyCode>,
	#[cfg(feature = "client")]
	pub(crate) just_pressed: Vec<KeyCode>,
	#[cfg(feature = "client")]
	pub(crate) mouse_delta: Vec2,

	pub(crate) handles: BTreeMap<InstanceId, InstanceHandle>,
	pub(crate) instance_ids: BTreeMap<InstanceHandle, InstanceId>,
	pub(crate) clients: BTreeMap<ClientId, InstanceId>,

	pub instances: Arena<Instance>,

	/// Used to send messages to the thread that communicates with the server.
	/// If the "server" feature is enabled, this will be directly to the server.
	pub(crate) packet_tx: mpsc::Sender<Packet<M>>,
	/// Used to receive messages from the thread that communicates with the server.
	/// If the "server" feature is enabled, this will be directly from the server.
	pub(crate) packet_rx: mpsc::Receiver<TrustedPacket<M>>,

	pub(crate) next_instance_id: Arc<AtomicU32>,
	pub client_id: Option<ClientId>,
	pub instance_id: Option<InstanceId>,

	pub drum: GpuDrum,
	#[cfg(feature = "client")]
	pub render: RenderState,
}

impl<M> Context<M> {
	async fn new<A: App<M>>(#[cfg(feature = "client")] window: Window, drum: Drum) -> Self
	where
		M: bitcode::Encode + bitcode::DecodeOwned + fmt::Debug + Send + 'static,
	{
		#[cfg(feature = "client")]
		let render = RenderState::new(window, &drum).await;
		let physics = PhysicsState::default();

		let (server_packet_tx, packet_rx) = mpsc::channel();
		let (packet_tx, server_packet_rx) = mpsc::channel();

		let next_instance_id = Arc::new(AtomicU32::new(0));

		let drum = drum.into_gpu(
			#[cfg(feature = "client")]
			&render.device,
			#[cfg(feature = "client")]
			&render.queue,
		);

		let mut ctx = Self {
			#[cfg(feature = "client")]
			render,
			drum,
			last_frame: time::Instant::now(),
			last_physics: time::Instant::now(),
			physics,

			desired_fps: 120.0,

			#[cfg(feature = "client")]
			pressed_keys: Vec::new(),
			#[cfg(feature = "client")]
			just_pressed: Vec::new(),
			#[cfg(feature = "client")]
			mouse_delta: Vec2::ZERO,

			handles: BTreeMap::new(),
			instance_ids: BTreeMap::new(),
			instances: Arena::new(),
			clients: BTreeMap::new(),

			packet_tx,
			packet_rx,

			next_instance_id: Arc::clone(&next_instance_id),
			client_id: None,
			instance_id: None,
		};

		std::thread::spawn({
			let (model_id, builder) = A::create_player(&mut ctx);

			move || {
				server::run::<A, _>(
					server_packet_tx,
					server_packet_rx,
					next_instance_id,
					CreateInstance::from_builder(&builder, model_id),
				);
			}
		});

		ctx
	}

	#[cfg(feature = "client")]
	pub fn pressed(&self, key: KeyCode) -> bool {
		self.pressed_keys.contains(&key)
	}

	#[cfg(feature = "client")]
	pub fn just_pressed(&self, key: KeyCode) -> bool {
		self.just_pressed.contains(&key)
	}

	#[cfg(feature = "client")]
	pub fn mouse_delta(&self) -> Vec2 {
		self.mouse_delta
	}
}

impl<M> Context<M> {
	fn on_packet<A: App<M>>(ctx: &mut Context<M>, packet: TrustedPacket<M>) {
		let client_id = packet.client_id;

		match packet.inner {
			Packet::Custom(..) => {}
			Packet::CreateClient { instance_id } => {
				let (model_id, instance) = A::create_player(ctx);
				let instance = ctx.add_instance_local(model_id, instance);

				ctx.handles.insert(instance_id, instance);
				ctx.instance_ids.insert(instance, instance_id);
				ctx.clients.insert(client_id, instance_id);
			}
			Packet::DeleteClient => {
				let Some(instance_id) = ctx.clients.remove(&client_id) else {
					return;
				};

				ctx.remove_instance_local(instance_id);
			}
			Packet::CreateInstance { ref options, id } => {
				info!("creating instance {id:?} with options {options:?}");

				if Some(id) == ctx.instance_id {
					return;
				}

				let instance = ctx.add_instance_local(options.model_id, options.to_builder());

				ctx.handles.insert(id, instance);
				ctx.instance_ids.insert(instance, id);
			}
			Packet::DeleteInstance { id } => {
				ctx.remove_instance_local(id);
			}
			Packet::UpdateInstance { id, ref delta } => {
				let Some(&mut instance) = ctx.handles.get_mut(&id) else {
					return;
				};

				instance.update(ctx, |i, p| {
					delta.apply(p, i);
				});
			}
			Packet::Connected { instance_id } => {
				ctx.client_id = Some(client_id);
				ctx.instance_id = Some(instance_id);
			}
		}

		A::on_packet(ctx, packet);
	}

	fn render<A: App<M>>(
		&mut self,
		app: &mut A,
		#[cfg(feature = "client")] event_loop: &ActiveEventLoop,
	) {
		std::hint::spin_loop();

		while let Ok(packet) = self.packet_rx.try_recv() {
			Self::on_packet::<A>(self, packet);
		}

		let delta = self.last_physics.elapsed();

		// physics 60fps
		if delta.as_secs_f32() >= 1.0 / 60.0 {
			self.last_physics = time::Instant::now();
			self.physics_update();
			app.on_fixed_update(self);
		}

		#[cfg(feature = "client")]
		{
			let delta = self.last_frame.elapsed();

			if delta.as_secs_f32() < 1.0 / self.desired_fps {
				return;
			}

			self.last_frame = time::Instant::now();

			app.on_update(self, delta);
			#[cfg(feature = "client")]
			self.render.camera.update_view_proj(&self.render.queue);

			self.just_pressed.clear();
			self.mouse_delta = Vec2::ZERO;

			for model in &mut self.drum.models {
				model.update_instance_buffer(&self.render.device, &self.render.queue);
			}

			match self.render.render_frame(&self.drum) {
				Ok(..) => {}
				Err(wgpu::SurfaceError::Lost | wgpu::SurfaceError::Outdated) => {
					self.render.resize(self.render.window.inner_size());
				}
				Err(wgpu::SurfaceError::OutOfMemory) => event_loop.exit(),
				Err(wgpu::SurfaceError::Timeout) => log::warn!("surface timeout"),
			}
		}
	}
}

#[cfg(feature = "client")]
impl<A: App<M>, M> ApplicationHandler for Game<A, M>
where
	M: bitcode::Encode + bitcode::DecodeOwned + fmt::Debug + Send + 'static,
{
	fn resumed(&mut self, event_loop: &ActiveEventLoop) {
		let window = event_loop
			.create_window(WindowAttributes::default().with_title(
				#[cfg(feature = "server")]
				"Server",
				#[cfg(not(feature = "server"))]
				"Client",
			))
			.unwrap();

		let _ = window.set_cursor_grab(CursorGrabMode::Locked);
		window.set_cursor_visible(false);

		let drum = A::on_init();
		let mut ctx = pollster::block_on(Context::<M>::new::<A>(window, drum));
		let app = A::on_ready(&mut ctx);

		self.state = Some((ctx, app));
	}

	fn device_event(
		&mut self,
		_event_loop: &ActiveEventLoop,
		_device_id: winit::event::DeviceId,
		event: DeviceEvent,
	) {
		let Some((ctx, _)) = self.state.as_mut() else {
			return;
		};

		if let DeviceEvent::MouseMotion { delta } = event {
			ctx.mouse_delta += Vec2::from((delta.0 as f32, delta.1 as f32));
		}
	}

	fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) {
		let Some((ctx, app)) = self.state.as_mut() else {
			return;
		};

		ctx.render(app, event_loop);
	}

	fn window_event(
		&mut self,
		event_loop: &ActiveEventLoop,
		window_id: WindowId,
		event: WindowEvent,
	) {
		let Some((ctx, app)) = self.state.as_mut() else {
			return;
		};

		if window_id != ctx.render.window.id() {
			return;
		}

		match event {
			WindowEvent::Resized(size) => {
				ctx.render.resize(size);
			}
			WindowEvent::RedrawRequested => {
				ctx.render(app, event_loop);
			}
			WindowEvent::CloseRequested => {
				event_loop.exit();
			}
			WindowEvent::KeyboardInput {
				event:
					KeyEvent {
						state,
						physical_key: PhysicalKey::Code(key),
						..
					},
				..
			} => {
				if state.is_pressed() {
					if !ctx.pressed_keys.contains(&key) {
						ctx.pressed_keys.push(key);
					}

					match key {
						KeyCode::F11 if ctx.render.window.fullscreen().is_none() => {
							ctx.render
								.window
								.set_fullscreen(Some(Fullscreen::Borderless(None)));
						}
						KeyCode::F11 => {
							ctx.render.window.set_fullscreen(None);
						}
						_ => {}
					}
				} else if let Some(index) = ctx.pressed_keys.iter().position(|&k| k == key) {
					ctx.pressed_keys.swap_remove(index);
				}
			}
			_ => {}
		}
	}
}