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

支持多个 WASM 运行时 #30

Merged
merged 23 commits into from
Nov 29, 2022
Merged
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
4 changes: 2 additions & 2 deletions bins/Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ release-cross: dist

.PHONY: run run-gui run-latex
run:
RUST_LOG=info cargo run --package ayaka-check -- $(FILE) --auto
cargo run --package ayaka-check -- $(FILE) --auto
run-gui:
cd ayaka-gui && $(MAKE) run FILE=$(FILE)
run-latex:
RUST_LOG=info cargo run --package ayaka-latex -- $(FILE) -o $(basename $(FILE)).tex
cargo run --package ayaka-latex -- $(FILE) -o $(basename $(FILE)).tex
2 changes: 1 addition & 1 deletion bins/ayaka-check/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,4 @@ edition = "2021"
ayaka-runtime = { path = "../../utils/ayaka-runtime" }
tokio = { version = "1", features = ["macros", "rt"] }
clap = { version = "4.0", features = ["derive"] }
env_logger = "0.9"
flexi_logger = { version = "0.24", default-features = false, features = ["colors"] }
12 changes: 8 additions & 4 deletions bins/ayaka-check/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use ayaka_runtime::{anyhow::Result, log::LevelFilter, *};
use ayaka_runtime::{anyhow::Result, *};
use clap::Parser;
use flexi_logger::{LogSpecification, Logger};
use std::{
ffi::OsString,
io::{stdin, stdout, Write},
Expand Down Expand Up @@ -34,9 +35,12 @@ fn pause(auto: bool) -> Result<()> {
#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<()> {
let opts = Options::parse();
env_logger::Builder::from_default_env()
.filter_module("wasmer", LevelFilter::Warn)
.try_init()?;
let spec = LogSpecification::parse("warn,ayaka=debug")?;
let _log_handle = Logger::with(spec)
.log_to_stdout()
.set_palette("b1;3;2;4;6".to_string())
.use_utc()
.start()?;
let context = Context::open(&opts.input, FrontendType::Text);
pin_mut!(context);
while let Some(status) = context.next().await {
Expand Down
33 changes: 24 additions & 9 deletions bins/ayaka-gui/src-tauri/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
all(not(debug_assertions), target_os = "windows"),
windows_subsystem = "windows"
)]
#![feature(absolute_path)]

use ayaka_runtime::{
anyhow::{self, anyhow, Result},
Expand All @@ -13,6 +14,7 @@ use serde::{Deserialize, Serialize};
use std::{
collections::{HashMap, HashSet},
fmt::Display,
path::PathBuf,
};
use tauri::{async_runtime::Mutex, command, AppHandle, Manager, State};
use trylog::TryLog;
Expand Down Expand Up @@ -68,6 +70,7 @@ impl OpenGameStatus {
struct Storage {
ident: String,
config: String,
root_path: PathBuf,
records: Mutex<Vec<ActionRecord>>,
context: Mutex<Option<Context>>,
current: Mutex<Option<RawContext>>,
Expand All @@ -77,9 +80,16 @@ struct Storage {

impl Storage {
pub fn new(ident: impl Into<String>, config: impl Into<String>) -> Self {
let config = config.into();
let root_path = std::path::absolute(&config)
.unwrap()
.parent()
.unwrap()
.to_path_buf();
Self {
ident: ident.into(),
config: config.into(),
config,
root_path,
..Default::default()
}
}
Expand All @@ -102,6 +112,11 @@ impl GameInfo {
}
}

#[command]
fn absolute_path(storage: State<'_, Storage>, path: String) -> CommandResult<String> {
Ok(storage.root_path.join(path).to_string_lossy().into_owned())
}

#[command]
async fn open_game(handle: AppHandle, storage: State<'_, Storage>) -> CommandResult<()> {
let config = &storage.config;
Expand Down Expand Up @@ -415,16 +430,15 @@ fn main() -> Result<()> {
.plugin(tauri_plugin_localhost::Builder::new(port).build())
.setup(|app| {
let ident = app.config().tauri.bundle.identifier.clone();
let spec = LogSpecification::parse("warn,ayaka=debug")?;
let log_handle = if cfg!(debug_assertions) {
Logger::with(LogSpecification::parse(
"debug,wasmer=warn,regalloc=info,cranelift=info",
)?)
.log_to_stdout()
.set_palette("b1;3;2;4;6".to_string())
.use_utc()
.start()?
Logger::with(spec)
.log_to_stdout()
.set_palette("b1;3;2;4;6".to_string())
.use_utc()
.start()?
} else {
Logger::with(LogSpecification::parse("info,wasmer=warn")?)
Logger::with(spec)
.log_to_file(
FileSpec::default()
.directory(app.path_resolver().app_log_dir().unwrap())
Expand Down Expand Up @@ -458,6 +472,7 @@ fn main() -> Result<()> {
})
.invoke_handler(tauri::generate_handler![
ayaka_version,
absolute_path,
open_game,
get_settings,
set_settings,
Expand Down
2 changes: 1 addition & 1 deletion bins/ayaka-gui/src/components/Live2D.vue
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ export default {
for (const name of this.names) {
let m = this.models.get(name)
if (!m) {
const path = conv_src((this.game.props as any)["ch_" + name + "_model"]) ?? ""
const path = await conv_src((this.game.props as any)["ch_" + name + "_model"]) ?? ""
m = await Live2DModel.from(path)
m.name = name
console.log("Loaded Live2D model: %O", m);
Expand Down
4 changes: 2 additions & 2 deletions bins/ayaka-gui/src/interop/index.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { convertFileSrc, invoke } from "@tauri-apps/api/tauri"
import { Locale } from 'vue-i18n'

export function conv_src(path?: string): string | undefined {
export async function conv_src(path?: string): Promise<string | undefined> {
if (path) {
return decodeURIComponent(convertFileSrc(path))
return decodeURIComponent(convertFileSrc(await invoke("absolute_path", { path: path })))
}
return undefined
}
Expand Down
17 changes: 12 additions & 5 deletions bins/ayaka-gui/src/views/GameView.vue
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,10 @@ export default {
type_text_buffer: [] as ActionLine[],
type_sub_text: "",
type_sub_text_buffer: [] as ActionLine[],
bg: undefined as string | undefined,
bgm: undefined as string | undefined,
voice: undefined as string | undefined,
video: undefined as string | undefined,
play_state: PlayState.Manual,
mutex: new Mutex(),
}
Expand All @@ -67,6 +71,8 @@ export default {
// Should be called in mutex
async fetch_current_run() {
const ctx = await current_run()
this.bg = await conv_src(ctx?.locals.bg)
this.bgm = await conv_src(ctx?.locals.bgm)
const actions = await current_action()
this.title = await current_title() ?? ""
console.info(actions)
Expand Down Expand Up @@ -103,6 +109,8 @@ export default {
}
break
}
this.voice = await conv_src(this.action.vars.voice)
this.video = await conv_src(this.vars.video)
}
},
// Should be called in mutex
Expand Down Expand Up @@ -245,9 +253,9 @@ export default {
</script>

<template>
<audio ref="bgm" :src="conv_src(raw_ctx.locals.bgm)" type="audio/mpeg" autoplay hidden loop></audio>
<audio ref="voice" :src="conv_src(action.vars.voice)" type="audio/mpeg" autoplay hidden></audio>
<img class="background" :src="conv_src(raw_ctx.locals.bg)">
<audio ref="bgm" :src="bgm" type="audio/mpeg" autoplay hidden loop></audio>
<audio ref="voice" :src="voice" type="audio/mpeg" autoplay hidden></audio>
<img class="background" :src="bg">
<Live2D :names="live2d_names(raw_ctx.locals)"></Live2D>
<div class="card-lines">
<ActionCard :ch="action.character" :line="type_text" :sub_line="type_sub_text"></ActionCard>
Expand All @@ -259,8 +267,7 @@ export default {
<span>Powered by Ayaka.</span>
</div>
<div class="content-full bg-body" :hidden="!vars.video">
<video ref="video" class="background" @ended="onvideoended" :src="conv_src(vars.video)" type="video/mp4"
autoplay></video>
<video ref="video" class="background" @ended="onvideoended" :src="video" type="video/mp4" autoplay></video>
</div>
<div class="backboard" @click="next"></div>
<div class="commands">
Expand Down
4 changes: 2 additions & 2 deletions bins/ayaka-gui/src/views/HomeView.vue
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ export default {
async created() {
const res = await info()
this.title = res.title
this.bg = res.props.bg
this.bg = await conv_src(res.props.bg)
},
methods: {
async new_game() {
Expand All @@ -28,7 +28,7 @@ export default {
</script>

<template>
<img class="background" :src="conv_src(bg)">
<img class="background" :src="bg">
<div class="content-full bg-body backboard-bg"></div>
<div class="content">
<div class="d-grid gap-4 col-4 mx-auto">
Expand Down
2 changes: 1 addition & 1 deletion bins/ayaka-gui/vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import vue from '@vitejs/plugin-vue'
export default defineConfig({
plugins: [vue()],
clearScreen: false,
envPrefix: ['VITE_', 'TAURI_', 'RUST_'],
envPrefix: ['VITE_', 'TAURI_'],
build: {
target: ['es2021', 'chrome97', 'safari13'],
minify: !env.TAURI_DEBUG ? 'esbuild' : false,
Expand Down
2 changes: 1 addition & 1 deletion bins/ayaka-latex/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,4 @@ edition = "2021"
ayaka-runtime = { path = "../../utils/ayaka-runtime" }
tokio = { version = "1", features = ["fs", "io-util", "macros", "rt"] }
clap = { version = "4.0", features = ["derive"] }
env_logger = "0.9"
flexi_logger = { version = "0.24", default-features = false, features = ["colors"] }
12 changes: 8 additions & 4 deletions bins/ayaka-latex/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
mod writer;

use ayaka_runtime::{anyhow::Result, log::LevelFilter, *};
use ayaka_runtime::{anyhow::Result, *};
use clap::Parser;
use flexi_logger::{LogSpecification, Logger};
use std::ffi::OsString;
use writer::LaTeXWriter;

Expand All @@ -18,9 +19,12 @@ pub struct Options {
#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<()> {
let opts = Options::parse();
env_logger::Builder::from_default_env()
.filter_module("wasmer", LevelFilter::Warn)
.try_init()?;
let spec = LogSpecification::parse("warn")?;
let _log_handle = Logger::with(spec)
.log_to_stdout()
.set_palette("b1;3;2;4;6".to_string())
.use_utc()
.start()?;
let context = Context::open(&opts.input, FrontendType::Latex);
let mut ctx = context.await?;

Expand Down
7 changes: 4 additions & 3 deletions book/src/platforms.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,14 @@ Ensured to work well with these triples:
## Tier 2
Should work well with these triples, but not tested:

* i686-pc-windows-msvc
* aarch64-pc-windows-msvc
* i686-pc-windows-gnu
* x86_64-pc-windows-gnu
* aarch64-unknown-linux-gnu
* aarch64-apple-darwin

## Tier 3
May not build or run because of dependencies:

* i686-pc-windows-msvc
* i686-pc-windows-gnu
* aarch64-pc-windows-msvc
* s390x-unknown-linux-gnu
6 changes: 6 additions & 0 deletions book/src/plugin/summary.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,12 @@ plugins:
```
You don't need to specify the extension.

## WASM directory mappings
The parent directory of the config file (aka. the root directory) is mapped to `/` in the plugins.
Some plugins, e.g. media, need to determine if the resource files exist.
Therefore, the files should be placed under the root directory.
Symbolic links may not work if they point to directories outside the root directory.

## The text processing workflow
``` dot process
digraph {
Expand Down
2 changes: 1 addition & 1 deletion plugins/live2d/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ fn hide(ctx: LineProcessContext) -> LineProcessResult {
fn process_game(mut ctx: GameProcessContext) -> GameProcessResult {
if let Some(names) = ctx.props.remove("ch_names") {
for name in names.split(',') {
if let Some(path) = find_model(name, &ctx.root_path, &ctx.props) {
if let Some(path) = find_model(name, "/", &ctx.props) {
ctx.props.insert(
format!("ch_{}_model", name),
path.to_string_lossy().into_owned(),
Expand Down
9 changes: 3 additions & 6 deletions plugins/media/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,10 +52,7 @@ fn file_ctx(
) -> LineProcessResult {
file(
&ctx.props[prop].get_str(),
ctx.game_props
.get(game_prop)
.map(|game_prop| ctx.root_path.join(game_prop))
.as_deref(),
ctx.game_props.get(game_prop).map(PathBuf::from).as_deref(),
prop,
exs,
temp,
Expand Down Expand Up @@ -84,7 +81,7 @@ fn process_action(mut ctx: ActionProcessContext) -> ActionProcessResult {
&voice_id,
ctx.game_props
.get("voices")
.map(|p| ctx.root_path.join(p).join(&ctx.ctx.cur_para))
.map(|p| PathBuf::from(p).join(&ctx.ctx.cur_para))
.as_deref(),
"voice",
&["mp3"],
Expand All @@ -96,7 +93,7 @@ fn process_action(mut ctx: ActionProcessContext) -> ActionProcessResult {

#[export]
fn process_game(mut ctx: GameProcessContext) -> GameProcessResult {
let base_dir = ctx.props.get("bgs").map(|p| ctx.root_path.join(p));
let base_dir = ctx.props.get("bgs").map(PathBuf::from);
if let Some(bg) = ctx.props.get_mut("bg") {
if let Some(path) = find_exists(bg, base_dir.as_deref(), &["png", "jpg", "gif"]) {
*bg = path.to_string_lossy().into_owned();
Expand Down
5 changes: 5 additions & 0 deletions utils/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,11 @@
members = [
"ayaka-bindings-types",
"ayaka-script",
"ayaka-plugin",
"ayaka-plugin-nop",
"ayaka-plugin-wasmer",
"ayaka-plugin-wasmtime",
"ayaka-plugin-wasmi",
"ayaka-runtime",
]

Expand Down
4 changes: 2 additions & 2 deletions utils/Makefile
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
.PHONY: test nextest clean update doc
test:
cargo test
cargo test --all-features
nextest:
cargo nextest run
cargo nextest run --all-features
clean:
cargo clean
update:
Expand Down
1 change: 0 additions & 1 deletion utils/ayaka-bindings-types/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,3 @@ ayaka-script = { path = "../ayaka-script" }
fallback = "0.1"
serde = { version = "1.0", features = ["derive"] }
log = { version = "0.4", features = ["serde"] }
bitflags = "1.3"
Loading