[oden] lol sprite API

This commit is contained in:
John Doty 2023-06-23 06:25:45 -07:00
parent c7903382a0
commit aa90cea4a3
3 changed files with 168 additions and 75 deletions

View file

@ -1,4 +1,4 @@
use oden_js::{module, ContextRef, Error, Value, ValueRef, ValueResult};
use oden_js::{module, ContextRef, Value, ValueRef, ValueResult};
use std::sync::mpsc::Sender;
use std::sync::Arc;
@ -10,9 +10,21 @@ pub struct ClearCommand {
pub color: [f64; 4],
}
pub struct SpriteCommand {
pub x: f32,
pub y: f32,
pub w: f32,
pub h: f32,
pub u: f32,
pub v: f32,
pub sw: f32,
pub sh: f32,
}
pub enum GraphicsCommand {
Clear(ClearCommand),
Print(PrintCommand),
Sprite(SpriteCommand),
EndFrame,
}
@ -39,22 +51,37 @@ impl GraphicsImpl {
Ok(Value::undefined(ctx))
}
fn cls_fn(&self, ctx: &ContextRef, args: &[&ValueRef]) -> ValueResult {
if args.len() != 3 {
return Err(Error::ArgumentCountMismatch {
expected: 3,
received: args.len(),
});
}
let r = args[0].to_float64(&ctx)?;
let g = args[1].to_float64(&ctx)?;
let b = args[1].to_float64(&ctx)?;
fn cls_fn(&self, ctx: &ContextRef, r: f64, g: f64, b: f64) -> ValueResult {
let _ = self.sender.send(GraphicsCommand::Clear(ClearCommand {
color: [r, g, b, 1.0],
}));
Ok(Value::undefined(ctx))
}
fn spr_fn(
&self,
ctx: &ContextRef,
x: f32,
y: f32,
w: f32,
h: f32,
u: f32,
v: f32,
sw: Option<f32>,
sh: Option<f32>,
) -> ValueResult {
let _ = self.sender.send(GraphicsCommand::Sprite(SpriteCommand {
x,
y,
w,
h,
u,
v,
sw: sw.unwrap_or(w),
sh: sh.unwrap_or(h),
}));
Ok(Value::undefined(ctx))
}
}
pub struct GraphicsAPI {
@ -64,18 +91,43 @@ pub struct GraphicsAPI {
impl GraphicsAPI {
pub fn define(ctx: &ContextRef, sender: Sender<GraphicsCommand>) -> oden_js::Result<Self> {
let gfx = Arc::new(GraphicsImpl::new(sender));
let gfx_a = gfx.clone();
let gfx_b = gfx.clone();
module::NativeModuleBuilder::new(ctx)
.export(
let mut builder = module::NativeModuleBuilder::new(ctx);
{
let gfx = gfx.clone();
builder.export(
"print",
ctx.new_dynamic_fn(move |ctx, _, args| gfx_a.print_fn(ctx, args))?,
)?
.export(
ctx.new_dynamic_fn(move |ctx, _, args| gfx.print_fn(ctx, args))?,
)?;
}
{
let gfx = gfx.clone();
builder.export(
"cls",
ctx.new_dynamic_fn(move |ctx, _, args| gfx_b.cls_fn(ctx, args))?,
)?
.build("graphics")?;
ctx.new_fn(move |ctx: &ContextRef, r: f64, g: f64, b: f64| {
gfx.cls_fn(ctx, r, g, b)
})?,
)?;
}
{
let gfx = gfx.clone();
builder.export(
"spr",
ctx.new_fn(
move |ctx: &ContextRef,
x: f32,
y: f32,
w: f32,
h: f32,
u: f32,
v: f32,
sw: Option<f32>,
sh: Option<f32>| {
gfx.spr_fn(ctx, x, y, w, h, u, v, sw, sh)
},
)?,
)?;
}
builder.build("graphics")?;
Ok(GraphicsAPI { gfx })
}