[oden] Graphics module can create textures directly

This commit is contained in:
John Doty 2023-06-30 06:28:57 -07:00
parent 4959adc7e6
commit d2dfa7c401
5 changed files with 69 additions and 6 deletions

View file

@ -30,7 +30,7 @@ impl AssetsImpl {
.send(GraphicsCommand::CreateTexture(CreateTextureCommand {
id,
image,
label: path.into(),
label: Some(path.into()),
}));
Ok(id)

View file

@ -1,4 +1,5 @@
use oden_js::{module, ContextRef};
use oden_js::{module, ContextRef, Error, Result, Value};
use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::mpsc::Sender;
use std::sync::Arc;
@ -28,7 +29,7 @@ pub struct SpriteCommand {
pub struct CreateTextureCommand {
pub id: u32,
pub image: image::DynamicImage,
pub label: String,
pub label: Option<String>,
}
#[derive(Debug)]
@ -42,12 +43,16 @@ pub enum GraphicsCommand {
}
struct GraphicsImpl {
next_texture_id: AtomicU32,
sender: Sender<GraphicsCommand>,
}
impl GraphicsImpl {
pub fn new(sender: Sender<GraphicsCommand>) -> Self {
GraphicsImpl { sender }
GraphicsImpl {
sender,
next_texture_id: AtomicU32::new(0),
}
}
fn print(&self, text: String) -> () {
@ -75,6 +80,30 @@ impl GraphicsImpl {
}));
}
fn create_texture(
&self,
context: &ContextRef,
buffer: Value,
label: Option<String>,
) -> Result<u32> {
let bytes = buffer.get_array_buffer(context)?;
let image = match image::load_from_memory(&bytes) {
Ok(i) => i,
Err(e) => return Err(Error::RustFunctionError(format!("{e}"))),
};
let id = self.next_texture_id.fetch_add(1, Ordering::SeqCst);
let _ = self
.sender
.send(GraphicsCommand::CreateTexture(CreateTextureCommand {
id,
image,
label,
}));
Ok(id)
}
fn use_texture(&self, id: u32) {
let _ = self.sender.send(GraphicsCommand::UseTexture(id));
}
@ -126,6 +155,17 @@ impl GraphicsAPI {
ctx.new_fn(move |_: &ContextRef, id: u32| gfx.use_texture(id))?,
)?;
}
{
let gfx = gfx.clone();
builder.export(
"create_texture",
ctx.new_fn(
move |c: &ContextRef, buffer: Value, label: Option<String>| {
gfx.create_texture(c, buffer, label)
},
)?,
)?;
}
builder.build("graphics-core")?;
Ok(GraphicsAPI { gfx })
}