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 9 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" }
159 changes: 159 additions & 0 deletions src/aimodule.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@

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

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

pub trait AIHandler {
fn on_start(&self);
fn on_end(&mut self, isWinner: bool);
fn on_frame(&mut self);
fn on_send_text(&mut self, text: &str);
fn on_receive_text(&mut self, player: &mut Player, text: &str);
fn on_player_left(&mut self, player: &mut Player);
// TODO fn on_nuke_detect(&mut self, target: Position);
fn on_unit_discover(&mut self, unit: &mut Unit);
fn on_unit_evade(&mut self, unit: &mut Unit);
fn on_unit_show(&mut self, unit: &mut Unit);
fn on_unit_hide(&mut self, unit: &mut Unit);
fn on_unit_create(&mut self, unit: &mut Unit);
fn on_unit_destroy(&mut self, unit: &mut Unit);
fn on_unit_morph(&mut self, unit: &mut Unit);
fn on_unit_renegade(&mut self, unit: &mut Unit);
fn on_save_game(&mut self, game_name: &str);
fn on_unit_complete(&mut self, unit: &mut Unit);
}

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

impl AIModule {
pub fn new(handler: Box<AIHandler>) -> 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 AIHandler {
let module = sys_module as *mut AIModule;
&mut * (*module).handler
}

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

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

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

unsafe extern 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 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 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 fn on_nuke_detect(sys_module: *mut sys::AIModule, target: sys::Position) {
// TODO
}

unsafe extern 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 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 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 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 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 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 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 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 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 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<AIHandler>) -> *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)
}
62 changes: 62 additions & 0 deletions src/game.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@

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

use unit::Unit;
use player::*;

use std::os::raw::c_void as void;

pub struct Game(*mut sys::Game);

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

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

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

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

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.0, ctype, coords.0, coords.1, data.as_ptr());
}
}

pub fn get_self(&self) -> Player {
unsafe {
Player::from_raw(sys::Game_self(self.0) as *mut void)
}
}

pub fn get_minerals(&self) -> Box<Iterator<Item=Unit>> {
unsafe {
let iter = sys::Game_getMinerals(self.0) 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);
}
}
}
11 changes: 11 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,14 @@
extern crate bwapi_sys;

pub mod string;
pub mod iterator;

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

pub mod aimodule;

#[cfg(test)]
mod tests {
#[test]
Expand Down
31 changes: 31 additions & 0 deletions src/player.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@

use bwapi_sys::bridge as sys;
use string::BwString;
use iterator::{BwIterator, FromRaw};
use std::os::raw::c_void as void;
use unit::Unit;

pub struct Player(*mut sys::Player);

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

impl Player {
pub fn get_name(&self) -> BwString {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Зачем BwString?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Пока не могу внятно ответить, разбираюсь с интерфейсами и пытаюсь осознать, какие контракты нам будут нужны.

Если сходу конвертировать в String будет еще одна аллокация. Вообще можно использовать OsString который является промежуточным звеном между сырыми строками и строками Rust, и может быть дешево преобразован в обе стороны при условии, что внутри лежит UTF-8.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Дим, наверно пофиг на доп аллокацию? get_name не должны спрашивать чаще 16 раз за такт

Copy link
Member Author

@0x7CFE 0x7CFE May 10, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Не то что бы это было критично. Просто зачем?

Я реализовал Deref<Target=str> и AsRef<str> для этого типа, то есть его можно спокойно подставлять в те функции, где ожидается &str. Если же потребуется владение, то или x.to_owned() или String::from(x).

unsafe {
let name = sys::Player_getName(self.0);
BwString::from_raw(name as *mut void)
}
}

pub fn get_units(&self) -> Box<Iterator<Item=Unit>> {
unsafe {
let iter = sys::Player_getUnits(self.0) as *mut sys::Iterator;
Box::new(BwIterator::from(iter))
}
}
}
Loading