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
//! The message queue handles communication between the `main.js` and the logic thread.

use std::sync::atomic::AtomicBool;

use rask_engine::events::{Event, KeyModifier, MouseEvent};
use rask_engine::network::protocol::op_codes;

pub const MESSAGE_QUEUE_ELEMENT_COUNT: usize = 128;

#[repr(C, u32)]
#[derive(Debug, Clone)]
#[non_exhaustive]
/// Messages sent by the `main.js`.
pub enum Message {
    None = op_codes::NONE,

    // User interaction handling
    KeyDown(KeyModifier, u32) = op_codes::KEY_DOWN,
    KeyUp(KeyModifier, u32) = op_codes::KEY_UP,
    KeyPress(u32, u16) = op_codes::KEY_PRESS,
    MouseDown(MouseEvent) = op_codes::MOUSE_DOWN,
    MouseUp(MouseEvent) = op_codes::MOUSE_UP,
    /// Ask javascript to set the TextMode on or off.
    TextMode(bool) = op_codes::SET_TEXT_MODE,
    /// Wrapper for game events to be relayed to the server.
    EngineEvent(Event) = op_codes::PUSH_ENGINE_EVENT,

    // Resorce Handling
    RequestAlloc {
        id: u32,
        size: u32,
    } = op_codes::REQUEST_ALLOCATION,
    DoneWritingResource(u32) = op_codes::DONE_WRITING_RESOURCE,
    PushResource(u32) = op_codes::PUSH_RESOURCE,
    /// Rust finshed allocating the requested buffer.
    AllocatedBuffer {
        id: u32,
        ptr: u32,
    } = op_codes::ALLOCATED_BUFFER,
    /// Ask javascript to fetch the requested resource.
    /// In response to this, javascript will fetch the resource and send a RequestAlloc Event.
    /// The rest follows the standard resource flow.
    FetchResource(u32, &'static str) = op_codes::FETCH_RESOURCE,

    // Audio
    /// Ask javascript to fetch the requested sound track.
    PrepareAudio(u32, &'static str) = op_codes::PREPARE_AUDIO,
    AudioLoaded(u32) = op_codes::AUDIO_LOADED,
    PlaySound(u32) = op_codes::PLAY_SOUND,
    StopSound(u32) = op_codes::STOP_SOUND,

    // Misc Management Commands
    /// Send memory offsets to javascript.
    Memory(u32, u32, u32) = op_codes::MEMORY_OFFSETS,
}

impl Default for Message {
    fn default() -> Self {
        Message::None
    }
}

impl Message {
    pub fn to_slice(&self) -> &[u32] {
        let len = std::mem::size_of::<Message>() as u32;
        unsafe { std::slice::from_raw_parts(self as *const Message as *const u32, len as usize) }
    }

    pub fn send(&self) {
        let msg = self.to_slice();
        log::trace!("sending {:?}", self);
        unsafe { post_to_main(msg.as_ptr() as u32, msg.len() as u32) }
    }
}

extern "C" {
    pub fn post_to_main(ptr: u32, len: u32);
}

#[repr(C, align(32))]
#[derive(Debug)]
/// Wrapper for Message Object.
pub struct MessageQueueElement {
    writing: AtomicBool,
    payload: Message,
}

impl From<Message> for MessageQueueElement {
    fn from(message: Message) -> Self {
        Self {
            writing: AtomicBool::new(false),
            payload: message,
        }
    }
}

impl MessageQueueElement {
    fn read(&mut self) -> Option<Message> {
        let e = std::mem::take(&mut self.payload);
        if !*self.writing.get_mut() {
            Some(e)
        } else {
            None
        }
    }
}

impl MessageQueueElement {
    pub const fn new() -> Self {
        Self {
            writing: AtomicBool::new(false),
            payload: Message::None,
        }
    }
}

#[derive(Debug)]
/// Abstracts the communication with the main thread.
pub struct MessageQueue {
    /// The index of the next element to be read.
    reader_index: u32,
    data: [MessageQueueElement; MESSAGE_QUEUE_ELEMENT_COUNT],
}

impl MessageQueue {
    // add method to create message_queue with a memory location to make testing easier
    pub fn new() -> Self {
        let bytes = [0u8; std::mem::size_of::<MessageQueueElement>() * MESSAGE_QUEUE_ELEMENT_COUNT];

        MessageQueue {
            reader_index: 0,
            data: unsafe { std::mem::transmute(bytes) },
        }
    }

    pub fn pop(&mut self) -> Message {
        loop {
            let e = &mut self.data[self.reader_index as usize];
            let e = e.read();
            if let Some(Message::None) = e {
                return Message::None;
            }
            self.reader_index += 1;
            if self.reader_index as usize >= self.data.len() {
                self.reader_index = 0;
            }
            match e {
                None => continue,
                Some(msg) => return msg,
            }
        }
    }

    /// Push an outbound Message to the main thread.
    pub fn push(&self, msg: Message) {
        msg.send();
    }
}