Skip to content

Instantly share code, notes, and snippets.

@zicklag
Created November 7, 2022 15:16
Show Gist options
  • Save zicklag/21c169c991f06733227db5a471886500 to your computer and use it in GitHub Desktop.
Save zicklag/21c169c991f06733227db5a471886500 to your computer and use it in GitHub Desktop.
Example of creating a dense representation of player inputs for sending over the network.
use numquant::{Quantized, IntRange};
bitfield::bitfield! {
/// A player's controller inputs densely packed into a single u16
pub struct DensePlayerControl(u16);
impl Debug;
jump_pressed, set_jump_pressed: 0;
shoot_pressed, set_shoot_pressed: 1;
grab_pressed, set_grab_pressed: 2;
slide_pressed, set_slide_pressed: 3;
from into DenseMoveDirection, move_direction, set_move_direction: 16, 4;
}
#[derive(Debug)]
struct DenseMoveDirection {
pub x: f32,
pub y: f32,
}
type MoveDirQuant = Quantized<IntRange<u16, 0b111111, -1, 1>>;
impl From<u16> for DenseMoveDirection {
fn from(bits: u16) -> Self {
// maximum movement value representable, we use 6 bits to represent each movement direction.
let max = 0b111111;
// The first six bits represent the x movement
let x_move_bits = bits & max;
println!("from x_bits: {:#08b}", x_move_bits);
// The second six bits represents the y movement
let y_move_bits = (bits >> 6) & max;
println!("from y_bits: {:#08b}", y_move_bits);
DenseMoveDirection {
x: MoveDirQuant::from_raw(x_move_bits).to_f32(),
y: MoveDirQuant::from_raw(y_move_bits).to_f32(),
}
}
}
impl From<DenseMoveDirection> for u16 {
fn from(dir: DenseMoveDirection) -> Self {
let x_bits = MoveDirQuant::from_f32(dir.x).raw();
let y_bits = MoveDirQuant::from_f32(dir.y).raw();
println!("to x_bits : {:#08b}", x_bits);
println!("to y_bits : {:#08b}", y_bits);
x_bits | (y_bits << 6)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment