Skip to content

Commit

Permalink
Support inverted axis mapping and local icons (#56)
Browse files Browse the repository at this point in the history
* add reverse axis mapping and test

* clean up

* implement loading local icons as data url

* tried to improve monaco editor size, i don't think it helped
  • Loading branch information
Pistonight authored Sep 27, 2023
1 parent 3b25a1b commit 1be178a
Show file tree
Hide file tree
Showing 32 changed files with 334 additions and 175 deletions.
7 changes: 7 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions compiler-core/src/comp/comp_coord.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ macro_rules! map_coord {
Axis::X => $output.0 = n,
Axis::Y => $output.1 = n,
Axis::Z => $output.2 = n,
Axis::NegX => $output.0 = -n,
Axis::NegY => $output.1 = -n,
Axis::NegZ => $output.2 = -n,
}
Ok(())
}
Expand Down
13 changes: 12 additions & 1 deletion compiler-core/src/comp/mod.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
use std::convert::Infallible;

use celerctypes::DocDiagnostic;
use serde_json::Value;

use crate::lang::parse_poor;
use crate::pack::PackerError;
#[cfg(feature = "wasm")]
use crate::util::WasmError;

mod comp_coord;
Expand Down Expand Up @@ -123,6 +126,12 @@ pub enum CompilerError {
Wasm(#[from] WasmError),
}

impl From<Infallible> for CompilerError {
fn from(_: Infallible) -> Self {
unreachable!()
}
}

impl CompilerError {
/// Get the more info url for a compiler error
pub fn get_info_url(&self) -> String {
Expand Down Expand Up @@ -164,6 +173,7 @@ impl CompilerError {
CompilerError::InvalidRouteType => {
"https://celer.pistonite.org/docs/route/route-structure#entry-point".to_string()
}
#[cfg(feature = "wasm")]
CompilerError::Wasm(_) => "".to_string(),
}
}
Expand All @@ -187,10 +197,11 @@ impl CompilerError {
| CompilerError::IsPreface(_)
| CompilerError::InvalidSectionType
| CompilerError::PackerErrors(_)
| CompilerError::Wasm(_)
| CompilerError::InvalidRouteType => "error",

CompilerError::UnusedProperty(_) | CompilerError::TooManyTagsInCounter => "warn",
#[cfg(feature = "wasm")]
CompilerError::Wasm(_) => "error",
};

s.to_string()
Expand Down
3 changes: 1 addition & 2 deletions compiler-core/src/exec/exec_section.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,7 @@ impl CompSection {
mod test {
use celerctypes::{GameCoord, MapIcon, MapLine, MapMarker};

use crate::comp::{CompMarker, CompMovement};
use crate::CompLine;
use crate::comp::{CompLine, CompMarker, CompMovement};

use super::*;

Expand Down
10 changes: 10 additions & 0 deletions compiler-core/src/exec/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
//! The [`CompDoc`] will be transformed into a [`ExecDoc`]
//! for rendering
use std::convert::Infallible;

mod exec_line;
pub use exec_line::*;
mod exec_map;
Expand All @@ -13,10 +15,12 @@ pub use exec_section::*;
mod exec_doc;
pub use exec_doc::*;

#[cfg(feature = "wasm")]
use crate::util::WasmError;

#[derive(Debug, Clone, thiserror::Error)]
pub enum ExecError {
#[cfg(feature = "wasm")]
#[error("wasm error: {0}")]
Wasm(#[from] WasmError),
}
Expand All @@ -31,3 +35,9 @@ impl ExecError {
x
}
}

impl From<Infallible> for ExecError {
fn from(_: Infallible) -> Self {
unreachable!()
}
}
2 changes: 1 addition & 1 deletion compiler-core/src/lang/tempstr/hydrate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ impl TempStr {
S: AsRef<str>,
{
let mut s = String::new();
async_for!(block in &self.0, {
let _ = async_for!(block in &self.0, {
match block {
TempStrBlock::Lit(lit) => s.push_str(lit),
TempStrBlock::Var(idx) => {
Expand Down
41 changes: 41 additions & 0 deletions compiler-core/src/pack/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
//! and a json blob of the route.
use std::collections::BTreeMap;
use std::convert::Infallible;
use serde_json::{Map, Value};

use celerctypes::DocDiagnostic;
Expand All @@ -32,6 +33,7 @@ pub use resource::*;

use crate::json::Cast;
use crate::lang::parse_poor;
#[cfg(feature = "wasm")]
use crate::util::{WasmError, Path};

#[derive(Debug, Clone, PartialEq, thiserror::Error)]
Expand Down Expand Up @@ -133,6 +135,12 @@ impl PackerError {
}
}

impl From<Infallible> for PackerError {
fn from(_: Infallible) -> Self {
unreachable!()
}
}

pub type PackerResult<T> = Result<T, PackerError>;

/// JSON value with an Err variant
Expand Down Expand Up @@ -250,3 +258,36 @@ impl PackerValue {
}
}
}

pub enum ImageFormat {
PNG,
JPEG,
GIF,
WEBP,
}

impl ImageFormat {
pub fn try_from_path(path: &str) -> Option<Self> {
let path = path.to_lowercase();
if path.ends_with(".png") {
Some(Self::PNG)
} else if path.ends_with(".jpg") || path.ends_with(".jpeg") {
Some(Self::JPEG)
} else if path.ends_with(".gif") {
Some(Self::GIF)
} else if path.ends_with(".webp") {
Some(Self::WEBP)
} else {
None
}
}

pub fn media_type(&self) -> &'static str {
match self {
Self::PNG => "image/png",
Self::JPEG => "image/jpeg",
Self::GIF => "image/gif",
Self::WEBP => "image/webp",
}
}
}
13 changes: 13 additions & 0 deletions compiler-core/src/pack/pack_coord_map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -350,5 +350,18 @@ mod test {
mapping_3d: (Axis::X, Axis::Z, Axis::Z),
})
);

let v = json!({
"2d": ["-x", "x"],
"3d": ["x", "-z", "-y"],
});
let result = pack_coord_map(v, 0).await;
assert_eq!(
result,
Ok(MapCoordMap {
mapping_2d: (Axis::NegX, Axis::X),
mapping_3d: (Axis::X, Axis::NegZ, Axis::NegY),
})
);
}
}
2 changes: 1 addition & 1 deletion compiler-core/src/pack/pack_preset.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ async fn pack_presets_internal(
})?;
output.push((full_key, preset));
}
});
})?;

Ok(())
}
2 changes: 1 addition & 1 deletion compiler-core/src/pack/pack_route.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ async fn pack_route_internal(
let route = match route.try_into_array() {
Ok(arr) => {
let mut output = vec![];
async_for!(x in arr.into_iter(), {
let _ = async_for!(x in arr.into_iter(), {
match Use::from(x) {
Use::Invalid(path) => {
output.push(PackerValue::Err(PackerError::InvalidUse(path)));
Expand Down
14 changes: 7 additions & 7 deletions compiler-core/src/pack/resource/loader_cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,15 @@ use serde_json::Value;

use crate::pack::PackerResult;

use super::ResourceLoader;
use super::{ResourceLoader, ArcLoader};

/// A loader that caches loaded resources in memory. The cache is global.
pub struct GlobalCacheLoader<L> where L: ResourceLoader {
delegate: L,
pub struct GlobalCacheLoader {
delegate: ArcLoader,
}

impl<L> GlobalCacheLoader<L> where L: ResourceLoader {
pub fn new(delegate: L) -> Self {
impl GlobalCacheLoader {
pub fn new(delegate: ArcLoader) -> Self {
Self {
delegate,
}
Expand All @@ -20,7 +20,7 @@ impl<L> GlobalCacheLoader<L> where L: ResourceLoader {

#[cfg_attr(not(feature = "wasm"), async_trait::async_trait)]
#[cfg_attr(feature = "wasm", async_trait::async_trait(?Send))]
impl<L> ResourceLoader for GlobalCacheLoader<L> where L: ResourceLoader {
impl ResourceLoader for GlobalCacheLoader {

async fn load_raw(&self, r: &str) -> PackerResult<Vec<u8>> {
self.delegate.load_raw(r).await
Expand All @@ -44,7 +44,7 @@ impl<L> ResourceLoader for GlobalCacheLoader<L> where L: ResourceLoader {
// TTL of 5 minutes
time=300,
)]
async fn load_structured_internal(loader: &dyn ResourceLoader, path: &str) -> PackerResult<Value> {
async fn load_structured_internal(loader: &ArcLoader, path: &str) -> PackerResult<Value> {
loader.load_structured(path).await
}

2 changes: 1 addition & 1 deletion compiler-core/src/pack/resource/resource.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use crate::util::Path;
use super::ResourceLoader;

#[cfg(not(feature = "wasm"))]
pub type ArcLoader<R> = Arc<dyn ResourceLoader<Ref=R> + Send + Sync>;
pub type ArcLoader = Arc<dyn ResourceLoader + Send + Sync>;
#[cfg(not(feature = "wasm"))]
pub type ArcResolver = Arc<dyn ResourceResolver + Send + Sync>;
#[cfg(feature = "wasm")]
Expand Down
3 changes: 2 additions & 1 deletion compiler-core/src/util/async_macro.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ macro_rules! async_for {
tokio::task::yield_now().await;
$body
}
Ok(())
let r: Result<(), std::convert::Infallible> = Ok(());
r
}};
}
pub(crate) use async_for;
Expand Down
2 changes: 1 addition & 1 deletion compiler-core/src/util/async_macro_wasm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ pub async fn set_timeout_yield() -> Result<(), WasmError> {
macro_rules! async_for {
($v:pat in $iter:expr, $body:stmt) => {
{
let mut result = Ok(());
let mut result: Result<(), $crate::util::async_macro_wasm::WasmError> = Ok(());
for $v in $iter {
result = $crate::util::async_macro_wasm::set_timeout_yield().await;
if result.is_err() {
Expand Down
21 changes: 1 addition & 20 deletions compiler-types/src/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,7 @@ fn main_internal() -> io::Result<()> {
OUTPUT_FILE,
output)?;

// run prettier
run_prettier()
Ok(())
}

fn generate_bindings() -> io::Result<()> {
Expand Down Expand Up @@ -82,21 +81,3 @@ fn transform_file(file_path: &Path) -> io::Result<String> {
Ok(transformed)
}

fn run_prettier() -> io::Result<()> {
println!("formatting with prettier");
let result = process::Command::new("npm")
.args(&["run", "fmt:compiler"])
.current_dir("../web-client")
.spawn()?
.wait_with_output()?;

if !result.status.success() {
eprintln!("prettier finished with error");
eprintln!("{}", String::from_utf8_lossy(&result.stderr));
return Err(io::Error::new(io::ErrorKind::Other, "prettier failed"));
} else {
println!("{}", String::from_utf8_lossy(&result.stdout));
}
Ok(())
}

9 changes: 9 additions & 0 deletions compiler-types/src/map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,15 @@ pub enum Axis {
Y,
/// Height axis
Z,
/// Negative Horizontal axis
#[serde(rename = "-x")]
NegX,
/// Negative Vertical axis
#[serde(rename = "-y")]
NegY,
/// Negative Height axis
#[serde(rename = "-z")]
NegZ,
}

/// Map features for one section
Expand Down
1 change: 1 addition & 0 deletions compiler-wasm/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ js-sys = "0.3.64"
async-trait = "0.1.73"
log = { version = "0.4.20", features = ["std"] }
web-sys = { version = "0.3.64", features = ["console"] }
base64 = "0.21.4"

[lib]
name = "celercwasm"
Expand Down
2 changes: 1 addition & 1 deletion compiler-wasm/src/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ thread_local! {
}

thread_local! {
static URL_LOADER: ArcLoader = Arc::new(GlobalCacheLoader::new(UrlLoader));
static URL_LOADER: ArcLoader = Arc::new(GlobalCacheLoader::new(Arc::new(UrlLoader)));
}

thread_local! {
Expand Down
15 changes: 10 additions & 5 deletions compiler-wasm/src/resource.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
//! Compiler resource resolver and loader implementation for WASM context
use std::cell::RefCell;
use base64::Engine;
use base64::engine::general_purpose;

use celerc::pack::{PackerResult, ResourceLoader, PackerError};
use celerc::pack::{PackerResult, ResourceLoader, PackerError, ImageFormat};
use celerc::yield_now;
use js_sys::{Function, Uint8Array};
use wasm_bindgen::{JsValue, JsCast};
Expand All @@ -10,7 +12,6 @@ use crate::wasm::{into_future, stub_function};

/// Loader for files from web editor
pub struct FileLoader {

/// Callback function to ask JS to load a file
///
/// Takes in a string as argument.
Expand Down Expand Up @@ -46,9 +47,13 @@ impl ResourceLoader for FileLoader {
}

async fn load_image_url(&self, path: &str) -> PackerResult<String> {
Err(PackerError::NotImpl(
"FileLoader::load_image_url is not implemented".to_string(),
))
let image_format = ImageFormat::try_from_path(path).ok_or_else(|| {
PackerError::LoadFile(format!("Cannot determine image format from path: {path}"))
})?.media_type();
let mut data_url = format!("data:{image_format};base64,");
let vec = self.load_raw(path).await?;
general_purpose::STANDARD.encode_string(&vec, &mut data_url);
Ok(data_url)
}
}

Expand Down
Loading

0 comments on commit 1be178a

Please sign in to comment.