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
#![warn(missing_docs)]
#![allow(unused_imports)]
#![allow(clippy::cast_lossless)]

//! Lokathor makes stuff.
//!
//! Currently we're working on some [Handmade Hero](https://handmadehero.org/)
//! inspired stuff using
//! [winapi](https://docs.rs/winapi/*/x86_64-pc-windows-msvc/winapi/).

pub mod interchange;
use interchange::*;

/// Updates the game, renders the frame, and also does sound.
pub fn game_update_and_render(
  memory: &mut GameMemory, _time: Duration, input: &GameInput, bitmap: &mut Bitmap,
  sound: &mut SoundBuffer,
) {
  input.xbox_controllers[0].map(|x| {
    if x.dpad_left.pressed {
      memory.x_offset += 1;
    }
    if x.dpad_right.pressed {
      memory.x_offset -= 1;
    }
    if x.dpad_up.pressed {
      memory.y_offset += 1;
    }
    if x.dpad_down.pressed {
      memory.y_offset -= 1;
    }
  });
  game_output_sound(sound, memory.tone_hz);
  render_weird_gradient(bitmap, memory.x_offset, memory.y_offset)
}

/// Renders the weird gradient into the bitmap.
pub fn render_weird_gradient(bitmap: &mut Bitmap, blue_offset: i32, green_offset: i32) {
  let bitmap_memory = bitmap.memory;
  let width = bitmap.width;
  let height = bitmap.height;
  let pitch = bitmap.pitch;
  let mut row_start = bitmap_memory;
  for y in 0..height {
    #[allow(clippy::cast_ptr_alignment)]
    let mut pixel = row_start as *mut u32;
    for x in 0..width {
      // Note(Lokathor): Windows uses "BGRA" bitmaps, when written as a
      // little-endian `u32` the bytes end up being ordered as `0xAA_RR_GG_BB`.
      let blue = (x + blue_offset) as u8 as u32;
      let green = (y + green_offset) as u8 as u32;
      unsafe {
        pixel.write_unaligned(blue | (green << 8));
        pixel = pixel.offset(1);
      }
    }
    row_start = unsafe { row_start.offset(pitch) };
  }
}

/// Causes the game to output sound.
///
/// Right now it's just a debug tone.
pub fn game_output_sound(sound_buffer: &mut SoundBuffer, tone_hz: i32) {
  static mut T_SINE: f32 = 0.0;
  const VOLUME: i16 = 1000;
  const TWO_PI: f32 = 2.0 * std::f32::consts::PI;
  let wave_period = sound_buffer.samples_per_second / tone_hz;

  let mut sample_out: *mut i16 = sound_buffer.samples;
  for _sample_index in 0..sound_buffer.sample_count {
    unsafe {
      let sine_value = T_SINE.sin();
      let sample_value = (sine_value * f32::from(VOLUME)) as i16;
      *sample_out = sample_value;
      sample_out = sample_out.offset(1);
      *sample_out = sample_value;
      sample_out = sample_out.offset(1);
      T_SINE += 2.0 * std::f32::consts::PI * 1.0 / wave_period as f32;
      if T_SINE > TWO_PI {
        T_SINE -= TWO_PI;
      }
    }
  }
}