rust/lib-hedgewars-engine/src/lib.rs
author unC0Rr
Thu, 22 Nov 2018 10:58:55 +0100
changeset 14271 1aac8a62be6f
parent 14255 a239e4243cf9
child 14272 3152d9fdb499
permissions -rw-r--r--
Implement send_ipc and read_ipc in engine lib, send_ipc in frontend

mod ipc;
mod world;

use std::io::{Read, Write};

use self::ipc::IPC;

#[repr(C)]
pub struct EngineInstance {
    world: world::World,
    ipc: IPC,
}

impl EngineInstance {
    pub fn new() -> Self {
        let world = world::World::new();
        Self {
            world,
            ipc: IPC::new(),
        }
    }

    pub fn render<R, C>(
        &self,
        context: &mut gfx::Encoder<R, C>,
        target: &gfx::handle::RenderTargetView<R, gfx::format::Rgba8>,
    ) where
        R: gfx::Resources,
        C: gfx::CommandBuffer<R>,
    {
        context.clear(target, [0.0, 0.5, 0.0, 1.0]);
    }
}

#[repr(C)]
#[derive(Copy, Clone)]
pub struct PreviewInfo {
    width: u32,
    height: u32,
    hedgehogs_number: u8,
    land: *const u8,
}

#[no_mangle]
pub extern "C" fn protocol_version() -> u32 {
    56
}

#[no_mangle]
pub extern "C" fn start_engine() -> *mut EngineInstance {
    let engine_state = Box::new(EngineInstance::new());

    Box::leak(engine_state)
}

#[no_mangle]
pub extern "C" fn generate_preview(engine_state: &mut EngineInstance, preview: &mut PreviewInfo) {
    (*engine_state).world.generate_preview();

    let land_preview = (*engine_state).world.preview();

    *preview = PreviewInfo {
        width: land_preview.width() as u32,
        height: land_preview.height() as u32,
        hedgehogs_number: 0,
        land: land_preview.raw_pixels().as_ptr(),
    };
}

#[no_mangle]
pub extern "C" fn send_ipc(engine_state: &mut EngineInstance, buf: *const [u8], size: usize) {
    unsafe {
        (*engine_state).ipc.write(&(*buf)[0..size]);
    }
}

#[no_mangle]
pub extern "C" fn read_ipc(
    engine_state: &mut EngineInstance,
    buf: *mut [u8],
    size: usize,
) -> usize {
    unsafe { (*engine_state).ipc.read(&mut (*buf)[0..size]).unwrap_or(0) }
}

#[no_mangle]
pub extern "C" fn cleanup(engine_state: *mut EngineInstance) {
    unsafe {
        Box::from_raw(engine_state);
    }
}