Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Initial concepts of type safe API #2

Open
wants to merge 31 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 14 commits
Commits
Show all changes
31 commits
Select commit Hold shift + click to select a range
34167a7
Adds draft implementation of the BwString wrapper
0x7CFE May 8, 2017
6fbf0f0
Initial concept of lifetime-safe iterator wrappers
0x7CFE May 9, 2017
ac6887c
Fixes lifetimes of BwIterator
0x7CFE May 11, 2017
b3cc14c
Fixes identifiers to reflect changes in bwapi-c
0x7CFE May 13, 2017
a70ad92
Minor fixes
0x7CFE May 22, 2017
67858c6
Adds prototype implementation of AIModule
0x7CFE May 22, 2017
4e046a5
Adds handler wrappers, fixes link issues
0x7CFE May 23, 2017
e65c6fa
Adds more handler wrappers
0x7CFE May 24, 2017
b134f03
Adds UnitType, basic unit methods, HasPosition
0x7CFE May 25, 2017
b872ca2
Adds more methods, polymorphism to Unit::right_click()
0x7CFE May 26, 2017
ebd89c4
Renames methods according to Rust convention
0x7CFE May 27, 2017
5f4b7f1
Adds Region, more Game methods
0x7CFE May 28, 2017
867fa16
Refactors AIHandler to game::EventHandler, fixes imports
0x7CFE May 29, 2017
52cf040
Adds prototype of session lifetimes
0x7CFE Jun 13, 2017
b9e0a79
Adds .cargo/config
kpp Jun 14, 2017
36c17e0
Ports to bwapi-sys
kpp Jun 14, 2017
06a052a
Adds examples
kpp Jun 14, 2017
8337400
Adds implementation for position
kpp Jun 16, 2017
a964f63
Fixes tests
kpp Jun 16, 2017
45ba8e5
Implements on_nuke_detect
kpp Jun 16, 2017
c677da8
Fixes Region::center
kpp Jun 16, 2017
9ff5fce
Fixes unused import + variable
kpp Jun 16, 2017
e3b4c2c
Reintroduces lifetime 'g as global invariant
0x7CFE Jul 1, 2017
6d5c26c
Adds handler factory stuff
0x7CFE Jul 1, 2017
48a7065
Fixes game singleton and events
0x7CFE Jul 1, 2017
bbfbdb6
Refactors code to reflect new API
0x7CFE Jul 1, 2017
4a0596f
Adds handler startup and shutdown
0x7CFE Jul 2, 2017
ec8c266
Add Game::average_fps
kpp Feb 26, 2018
6dcb93a
Uses bwapi-sys from crates.io
kpp Jul 11, 2018
85d099b
Updates TravisCI config to use g++-7
kpp Jul 11, 2018
0ff36e6
Fixes tests for Position
kpp Jul 11, 2018
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,4 @@ description = "Rust bindings to the Starcraft Broodwar game API"
license = "Unlicense/MIT"

[dependencies]
bwapi-sys = { path = "../bwapi-sys" }
161 changes: 161 additions & 0 deletions src/aimodule.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@

use bwapi_sys::bridge as sys;
use unit::Unit;
use player::Player;
use iterator::FromRaw;
use game;

use std::ptr;
use std::mem;
use std::ffi::CStr;
use std::os::raw::c_void as void;
use std::borrow::Borrow;

static mut GAME: *mut void = 0 as *mut void;

#[repr(C)]
pub struct AIModule<'g> {
vtable: Box<sys::AIModule_vtable>,
handler: Box<game::EventHandler<'g>>,
}

impl<'g> AIModule<'g> {
pub fn new(handler: Box<game::EventHandler<'g>>) -> AIModule {
AIModule {
vtable: Box::new(sys::AIModule_vtable {
onStart: Some(AIModule::on_start),
onEnd: Some(AIModule::on_end),
onFrame: Some(AIModule::on_frame),
onSendText: Some(AIModule::on_send_text),
onReceiveText: Some(AIModule::on_receive_text),
onPlayerLeft: Some(AIModule::on_player_left),
onNukeDetect: Some(AIModule::on_nuke_detect),
onUnitDiscover: Some(AIModule::on_unit_discover),
onUnitEvade: Some(AIModule::on_unit_evade),
onUnitShow: Some(AIModule::on_unit_show),
onUnitHide: Some(AIModule::on_unit_hide),
onUnitCreate: Some(AIModule::on_unit_create),
onUnitDestroy: Some(AIModule::on_unit_destroy),
onUnitMorph: Some(AIModule::on_unit_morph),
onUnitRenegade: Some(AIModule::on_unit_renegade),
onSaveGame: Some(AIModule::on_save_game),
onUnitComplete: Some(AIModule::on_unit_complete),
}),

handler,
}
}

unsafe fn get_handler<'a>(sys_module: *mut sys::AIModule) -> &'a mut game::EventHandler<'a> {
let module = sys_module as *mut AIModule;
&mut *(*module).handler
}

unsafe extern "C" fn on_start(sys_module: *mut sys::AIModule) {
let game = game::Game::from_raw(GAME);
Self::get_handler(sys_module).on_start(game);
}

unsafe extern "C" fn on_end(sys_module: *mut sys::AIModule, is_winner: bool) {
Self::get_handler(sys_module).on_end(is_winner);
}

unsafe extern "C" fn on_frame(sys_module: *mut sys::AIModule) {
Self::get_handler(sys_module).on_frame();
}

unsafe extern "C" fn on_send_text(sys_module: *mut sys::AIModule,
text: *const ::std::os::raw::c_char) {
let text = CStr::from_ptr(text)
.to_str()
.unwrap();
Self::get_handler(sys_module).on_send_text(&text);
}

unsafe extern "C" fn on_receive_text(sys_module: *mut sys::AIModule,
player: *mut sys::Player,
text: *const ::std::os::raw::c_char) {
let mut player = Player::from_raw(player as *mut void);
let text = CStr::from_ptr(text)
.to_str()
.unwrap();
Self::get_handler(sys_module).on_receive_text(&mut player, &text);
}

unsafe extern "C" fn on_player_left(sys_module: *mut sys::AIModule, player: *mut sys::Player) {
let mut player = Player::from_raw(player as *mut void);
Self::get_handler(sys_module).on_player_left(&mut player);
}

unsafe extern "C" fn on_nuke_detect(sys_module: *mut sys::AIModule, target: sys::Position) {
// TODO
}

unsafe extern "C" fn on_unit_discover(sys_module: *mut sys::AIModule, unit: *mut sys::Unit) {
let mut unit = Unit::from_raw(unit as *mut void);
Self::get_handler(sys_module).on_unit_discover(&mut unit);
}

unsafe extern "C" fn on_unit_evade(sys_module: *mut sys::AIModule, unit: *mut sys::Unit) {
let mut unit = Unit::from_raw(unit as *mut void);
Self::get_handler(sys_module).on_unit_evade(&mut unit);
}

unsafe extern "C" fn on_unit_show(sys_module: *mut sys::AIModule, unit: *mut sys::Unit) {
let mut unit = Unit::from_raw(unit as *mut void);
Self::get_handler(sys_module).on_unit_show(&mut unit);
}

unsafe extern "C" fn on_unit_hide(sys_module: *mut sys::AIModule, unit: *mut sys::Unit) {
let mut unit = Unit::from_raw(unit as *mut void);
Self::get_handler(sys_module).on_unit_hide(&mut unit);
}

unsafe extern "C" fn on_unit_create(sys_module: *mut sys::AIModule, unit: *mut sys::Unit) {
let mut unit = Unit::from_raw(unit as *mut void);
Self::get_handler(sys_module).on_unit_create(&mut unit);
}

unsafe extern "C" fn on_unit_destroy(sys_module: *mut sys::AIModule, unit: *mut sys::Unit) {
let mut unit = Unit::from_raw(unit as *mut void);
Self::get_handler(sys_module).on_unit_destroy(&mut unit);
}

unsafe extern "C" fn on_unit_morph(sys_module: *mut sys::AIModule, unit: *mut sys::Unit) {
let mut unit = Unit::from_raw(unit as *mut void);
Self::get_handler(sys_module).on_unit_morph(&mut unit);
}

unsafe extern "C" fn on_unit_renegade(sys_module: *mut sys::AIModule, unit: *mut sys::Unit) {
let mut unit = Unit::from_raw(unit as *mut void);
Self::get_handler(sys_module).on_unit_renegade(&mut unit);
}

unsafe extern "C" fn on_save_game(sys_module: *mut sys::AIModule,
game_name: *const ::std::os::raw::c_char) {
let game_name = CStr::from_ptr(game_name)
.to_str()
.unwrap();
Self::get_handler(sys_module).on_save_game(game_name);
}

unsafe extern "C" fn on_unit_complete(sys_module: *mut sys::AIModule, unit: *mut sys::Unit) {
let mut unit = Unit::from_raw(unit as *mut void);
Self::get_handler(sys_module).on_unit_complete(&mut unit);
}
}

pub unsafe fn wrap_handler(handler: Box<game::EventHandler>) -> *mut ::std::os::raw::c_void {
let module = Box::new(AIModule::new(handler));
let module_ptr = Box::into_raw(module) as *mut sys::AIModule;

sys::createAIModuleWrapper(module_ptr)
}

#[no_mangle]
#[allow(non_snake_case)]
pub unsafe extern "C" fn gameInit(game: *mut void) {
println!("gameInit called!");
GAME = game;
}

150 changes: 150 additions & 0 deletions src/game.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@

use bwapi_sys::bridge as sys;
use std::ffi::{CString, CStr};
use iterator::{BwIterator, FromRaw};

use unit::Unit;
use player::Player;
use region::Region;

use std::os::raw::c_void as void;
use std::ops::{Deref, DerefMut};

pub trait EventHandler<'g> {
fn on_start(&'g mut self, game: Game);
fn on_end(&'g mut self, is_winner: bool) -> Game;
fn on_frame(&'g mut self);
fn on_send_text(&'g mut self, text: &str);
fn on_receive_text(&'g mut self, player: &mut Player, text: &str);
fn on_player_left(&'g mut self, player: &mut Player);
// TODO fn on_nuke_detect(&mut self, target: Position);
fn on_unit_discover(&'g mut self, unit: &mut Unit);
fn on_unit_evade(&'g mut self, unit: &mut Unit);
fn on_unit_show(&'g mut self, unit: &mut Unit);
fn on_unit_hide(&'g mut self, unit: &mut Unit);
fn on_unit_create(&'g mut self, unit: &mut Unit);
fn on_unit_destroy(&'g mut self, unit: &mut Unit);
fn on_unit_morph(&'g mut self, unit: &mut Unit);
fn on_unit_renegade(&'g mut self, unit: &mut Unit);
fn on_save_game(&'g mut self, game_name: &str);
fn on_unit_complete(&'g mut self, unit: &mut Unit);
}

pub struct Session<T> {
game: Game,
context: T,
}

impl<T> Session<T> {
pub fn new(game: Game, context: T) -> Self { Session { game, context } }
pub fn release(self) -> Game { self.game }
pub fn game(&self) -> &Game { &self.game }
pub fn game_mut(&mut self) -> &mut Game { &mut self.game }
pub fn data(&self) -> &T { &self.context }
pub fn data_mut(&mut self) -> &mut T { &mut self.context }
}

/*
impl<T> Deref for Session<T> {
type Target = T;

fn deref(&self) -> &T { &self.context }
}

impl<T> DerefMut for Session<T> {
fn deref_mut(&mut self) -> &mut T { &mut self.context }
}*/

pub struct Game {
raw: *mut sys::Game,
}

impl FromRaw for Game {
unsafe fn from_raw(raw: *mut void) -> Game {
assert!(!raw.is_null());
Game { raw: raw as *mut sys::Game }
}
}

pub enum CoordinateType {
None = 0,
Screen = 1,
Map = 2,
Mouse = 3,
}

pub enum CheatFlag {
CompleteMapInfo = 0,
UserInput = 1,
}

pub enum CommandOptLevel {
None = 0,
Some = 1,
More = 2,
Extensive = 3,
Aggressive = 4,
}

impl Game {
pub fn enable_flag(&self, flag: CheatFlag) {
unsafe {
sys::Game_enableFlag(self.raw, flag as i32);
}
}

pub fn send_text(&self, text: &str) {
unsafe {
let data = CString::new(text).unwrap();
sys::Game_sendText(self.raw, data.as_ptr());
}
}

pub fn frame_count(&self) -> i32 { unsafe { sys::Game_getFrameCount(self.raw) } }

pub fn get_apm(&self, include_selects: bool) -> i32 {
unsafe { sys::Game_getAPM(self.raw, include_selects) }
}

pub fn set_command_optimization_level(&self, level: CommandOptLevel) {
unsafe { sys::Game_setCommandOptimizationLevel(self.raw, level as i32) }
}

pub fn draw_text(&self, ctype: CoordinateType, coords: (i32, i32), text: &str) {
unsafe {
let data = CString::new(text).unwrap();
let ctype = sys::CoordinateType { id: ctype as i32 };
sys::Game_drawText(self.raw, ctype, coords.0, coords.1, data.as_ptr());
}
}

pub fn draw_line(&self,
ctype: CoordinateType,
first: (i32, i32),
second: (i32, i32),
color: sys::Color) {
unsafe {
let ctype = sys::CoordinateType { id: ctype as i32 };
sys::Game_drawLine(self.raw, ctype, first.0, first.1, second.0, second.1, color);
}
}

pub fn self_player<'s, 'p: 's>(&'s self) -> Player<'p> {
unsafe { Player::from_raw(sys::Game_self(self.raw) as *mut void) }
}

pub fn minerals<'s, 'g: 's>(&'s self) -> Box<Iterator<Item = Unit<'g>>> {
unsafe {
let iter = sys::Game_getMinerals(self.raw) as *mut sys::Iterator;
Box::new(BwIterator::from(iter))
}
}

pub fn regions(&self) -> Box<Iterator<Item = Region>> {
unsafe {
let iter = sys::Game_getAllRegions(self.raw) as *mut sys::Iterator;
Box::new(BwIterator::from(iter))
}
}
}

53 changes: 53 additions & 0 deletions src/iterator.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@

use bwapi_sys::bridge as sys;
use std::marker::PhantomData;
use std::os::raw::c_void as void;

/// `FromRaw` is a trait for entities that
/// are typically created outside of Rust code.
/// TODO Move to a proper place
pub trait FromRaw {
/// Construct entity from raw data. Unsafe.
/// Please be 100% sure that you pass correct pointer.
unsafe fn from_raw(raw: *mut void) -> Self;
}

/// Iterator is a wrapper over API iterator.
/// To ensure safety it's lifetime is bound
/// to the lifetime of the referenced data.
pub struct BwIterator<'i, 'g: 'i, T: FromRaw + 'g> {
raw: &'i mut sys::Iterator,
phantom: PhantomData<&'g T>,
}

impl<'i, 'g: 'i, T: FromRaw + 'g> BwIterator<'i, 'g, T> {
pub unsafe fn from(raw: *mut sys::Iterator) -> BwIterator<'i, 'g, T> {
assert!(!raw.is_null());
BwIterator { raw: &mut *raw, phantom: PhantomData }
}
}

impl<'i,'g: 'i, T: FromRaw + 'g> Iterator for BwIterator<'i, 'g, T> {
type Item = T;

fn next(&mut self) -> Option<Self::Item> {
unsafe {
if sys::Iterator_valid(self.raw) {
let item = sys::Iterator_get(self.raw);
sys::Iterator_next(self.raw);

Some(T::from_raw(item))
} else {
None
}
}
}
}

impl<'i, 'g: 'i, T: FromRaw + 'g> Drop for BwIterator<'i, 'g, T> {
fn drop(&mut self) {
unsafe {
sys::Iterator_release(self.raw);
}
}
}
12 changes: 12 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,15 @@
extern crate bwapi_sys;

pub mod string;
pub mod iterator;

pub mod player;
pub mod game;
pub mod unit;
pub mod region;

pub mod aimodule;

#[cfg(test)]
mod tests {
#[test]
Expand Down
Loading