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

Bytes module #80

Open
wants to merge 10 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,5 @@ target
.vscode
dist
node_modules
examples/resources
tools/wasm-template
4 changes: 2 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,14 @@ appveyor = { repository = "shawnscode/crayon", branch = "master", service = "git
codecov = { repository = "shawnscode/crayon", branch = "master", service = "github" }

[workspace]
members = [ "modules/world", "modules/audio" ]
members = [ "modules/world", "modules/audio","modules/audio" ]

[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
gl = "0.10.0"
glutin = "0.18.0"

[target.'cfg(target_arch = "wasm32")'.dependencies]
wasm-bindgen = "0.2.29"
wasm-bindgen = "0.2.38"
js-sys = "0.3.6"
console_error_panic_hook = "0.1.5"

Expand Down
4 changes: 2 additions & 2 deletions examples/resources/427EB273E77446B8B7010ACE1B7652EE
Git LFS file not shown
4 changes: 2 additions & 2 deletions examples/resources/4572A4B5C9F146BD84517F6FA535FAE6
Git LFS file not shown
4 changes: 2 additions & 2 deletions examples/resources/E32F80DF6B5946D9B49E4651AAF8A64E
Git LFS file not shown
13 changes: 13 additions & 0 deletions modules/bytes/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
[package]
name = "crayon_bytes"
version = "0.7.1"
authors = ["Jingkai Mao <[email protected]>"]
description = "The bytes module of crayon game framework."
repository = "https://github.com/shawnscode/crayon"
license = "Apache-2.0"
keywords = ["crayon", "game-dev", "bytes"]
categories = ["multimedia", "game-engines"]

[dependencies]
crayon = { path = "../../", version = "0.7.1" }
failure = "0.1.2"
5 changes: 5 additions & 0 deletions modules/bytes/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
## Byte

The Byte module of [crayon](https://github.com/shawnscode/crayon) game framework. The module can be used to load bytes from font files.

### Platform-Specific
79 changes: 79 additions & 0 deletions modules/bytes/examples/bytes.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
extern crate crayon;
extern crate crayon_bytes;

use crayon::prelude::*;
use crayon_bytes::prelude::*;


#[derive(Debug, Clone, Copy)]
struct WindowResources {
b: BytesHandle,
}

impl WindowResources {
pub fn new() -> CrResult<Self> {
crayon_bytes::setup()?;
Ok(WindowResources {
b: crayon_bytes::create_bytes_from("res:crate.bmp")?,
})
}
}
impl LatchProbe for WindowResources {
fn is_set(&self) -> bool {
crayon_bytes::state(self.b) != ResourceState::NotReady
}
}

struct Window {
resources: WindowResources,
}

impl Drop for Window {
fn drop(&mut self) {
crayon_bytes::discard();
}
}

impl Window {
fn new(resources: &WindowResources) -> CrResult<Self> {

Ok(Window {
resources: *resources,
})
}
}

impl LifecycleListener for Window {
fn on_update(&mut self) -> CrResult<()> {

Ok(())
}
}

main!({
#[cfg(not(target_arch = "wasm32"))]
let res = format!(
"file://{}/../../examples/resources/",
env!("CARGO_MANIFEST_DIR")
);
#[cfg(not(target_arch = "wasm32"))]
let size = (640, 128);

#[cfg(target_arch = "wasm32")]
let res = format!("http://localhost:8080/examples/resources/");
#[cfg(target_arch = "wasm32")]
let size = (256, 256);

let mut params = Params::default();
params.window.size = size.into();
params.window.title =
"CR: Audio (Key[K]: Play Sound Effect; Key[1]: Increase Volume; Key[2] Decrease Volume)"
.into();

params.res.shortcuts.add("res:", res).unwrap();
params.res.dirs.push("res:".into());
crayon::application::setup(params, || {
let resources = WindowResources::new()?;
Ok(Launcher::new(resources, |r| Window::new(r)))
}).unwrap();
});
37 changes: 37 additions & 0 deletions modules/bytes/src/assets/bytes_loader.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
use std::sync::Arc;

use crayon::errors::Result;
use crayon::res::utils::prelude::ResourceLoader;

impl_handle!(BytesHandle);

#[derive(Clone)]
pub struct BytesLoader {}

impl BytesLoader {
pub(crate) fn new() -> Self {
BytesLoader {}
}
}

impl ResourceLoader for BytesLoader {
type Handle = BytesHandle;
type Intermediate = Vec<u8>;
type Resource = Vec<u8>;

fn load(&self, _handle: Self::Handle, bytes: &[u8]) -> Result<Self::Intermediate> {
let data = bytes.to_vec();
info!(
"[BytesLoader] data: {:?}).",
data.clone()
);

Ok(data)
}

fn create(&self, _: Self::Handle, item: Self::Intermediate) -> Result<Self::Resource> {
Ok(item.clone())
}

fn delete(&self, _: Self::Handle, _: Self::Resource) {}
}
5 changes: 5 additions & 0 deletions modules/bytes/src/assets/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
pub mod bytes_loader;

pub mod prelude {
pub use super::bytes_loader::{BytesLoader,BytesHandle};
}
82 changes: 82 additions & 0 deletions modules/bytes/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
#[macro_use]
extern crate crayon;
extern crate failure;

pub mod assets;

mod system;

pub mod prelude {
pub use assets::prelude::BytesHandle;
}

pub use self::inside::{discard, setup};

use crayon::errors::Result;
use crayon::res::prelude::ResourceState;
use crayon::uuid::Uuid;

use self::assets::prelude::BytesHandle;
use self::inside::ctx;

/// Creates a byte object from file asynchronously.
#[inline]
pub fn create_bytes_from<T: AsRef<str>>(url: T) -> Result<BytesHandle> {
ctx().create_bytes_from(url)
}

/// Creates a byte object from file asynchronously.
#[inline]
pub fn create_bytes_from_uuid(uuid: Uuid) -> Result<BytesHandle> {
ctx().create_bytes_from_uuid(uuid)
}

#[inline]
pub fn state(handle: BytesHandle) -> ResourceState {
ctx().state(handle)
}
#[inline]
pub fn create_bytes(handle: BytesHandle) -> Option<Vec<u8>>{
ctx().create_bytes(handle)
}

mod inside {
use super::system::BytesSystem;

static mut CTX: *const BytesSystem = std::ptr::null();

#[inline]
pub fn ctx() -> &'static BytesSystem {
unsafe {
debug_assert!(
!CTX.is_null(),
"bytes system has not been initialized properly."
);

&*CTX
}
}

/// Setup the world system.
pub fn setup() -> Result<(), failure::Error> {
unsafe {
debug_assert!(CTX.is_null(), "duplicated setup of bytes system.");

let ctx = BytesSystem::new()?;
CTX = Box::into_raw(Box::new(ctx));
Ok(())
}
}

/// Discard the world system.
pub fn discard() {
unsafe {
if CTX.is_null() {
return;
}

drop(Box::from_raw(CTX as *mut BytesSystem));
CTX = std::ptr::null();
}
}
}
68 changes: 68 additions & 0 deletions modules/bytes/src/system.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
use std::sync::{Arc, RwLock};

use crayon::application::prelude::{LifecycleListener, LifecycleListenerHandle};
use crayon::errors::Result;
use crayon::res::utils::prelude::{ResourcePool, ResourceState};
use crayon::uuid::Uuid;

use super::assets::prelude::{BytesHandle, BytesLoader};

/// The centralized management of bytes sub-system.
pub struct BytesSystem {
lis: LifecycleListenerHandle,
bytes: Arc<RwLock<ResourcePool<BytesHandle, BytesLoader>>>,
}

struct BytesState {
bytes: Arc<RwLock<ResourcePool<BytesHandle, BytesLoader>>>,
}

impl LifecycleListener for BytesState {
fn on_pre_update(&mut self) -> Result<()> {
self.bytes.write().unwrap().advance()?;
Ok(())
}
}

impl Drop for BytesSystem {
fn drop(&mut self) {
crayon::application::detach(self.lis);
}
}

impl BytesSystem {
pub fn new() -> Result<Self> {
let bytes = Arc::new(RwLock::new(ResourcePool::new(BytesLoader::new())));

let state = BytesState {
bytes: bytes.clone(),
};

Ok(BytesSystem {
lis: crayon::application::attach(state),
bytes: bytes,
})
}


/// Creates a byte object from file asynchronously.
#[inline]
pub fn create_bytes_from<T: AsRef<str>>(&self, url: T) -> Result<BytesHandle> {
self.bytes.write().unwrap().create_from(url)
}

/// Creates a byte object from file asynchronously.
#[inline]
pub fn create_bytes_from_uuid(&self, uuid: Uuid) -> Result<BytesHandle> {
self.bytes.write().unwrap().create_from_uuid(uuid)
}

#[inline]
pub fn state(&self, handle: BytesHandle) -> ResourceState {
self.bytes.read().unwrap().state(handle)
}
#[inline]
pub fn create_bytes(&self, handle: BytesHandle) -> Option<Vec<u8>>{
self.bytes.read().unwrap().resource(handle).cloned()
}
}
9 changes: 9 additions & 0 deletions src/input/keyboard.rs
Original file line number Diff line number Diff line change
Expand Up @@ -275,12 +275,21 @@ impl Keyboard {
pub fn is_key_press(&self, key: Key) -> bool {
self.presses.contains(&key)
}
#[inline]
pub fn key_presses(&self) -> FastHashSet<Key> {
self.presses.clone()
}

#[inline]
pub fn is_key_release(&self, key: Key) -> bool {
self.releases.contains(&key)
}

#[inline]
pub fn key_releases(&self) -> FastHashSet<Key> {
self.releases.clone()
}

pub fn is_key_repeat(&self, key: Key) -> bool {
if let Some(v) = self.downs.get(&key) {
match *v {
Expand Down
Loading