Skip to content

Commit

Permalink
wasm32-unknown-unknown
Browse files Browse the repository at this point in the history
  • Loading branch information
caiiiycuk committed Dec 9, 2021
1 parent bb1cb0b commit 3a79885
Show file tree
Hide file tree
Showing 18 changed files with 910 additions and 42 deletions.
6 changes: 6 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,9 @@
.fuse_hidden*
.DS_Store
last-shader.wgsl

# web version
web/assets/res
web/assets/road.css
web/road*
res_linux
17 changes: 17 additions & 0 deletions Cargo.lock

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

12 changes: 8 additions & 4 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -60,13 +60,17 @@ rust-ini = "0.17"
serde = "1.0"
serde_derive = "1.0"
serde_scan = "0.4"
wgpu = { git = "https://github.com/gfx-rs/wgpu", rev = "c8d572a", features = [] }
wgpu = { git = "https://github.com/gfx-rs/wgpu", rev = "c8d572a", features = ["webgl"] }
# binaries
env_logger = "0.8"
getopts = "0.2"
obj = "0.10"
png = "0.16"
winit = "0.26"
winit = { version = "0.26", features = [] }
web-sys = { version = "0.3.55", features = ["EventListener"] }
wasm-bindgen = "0.2.78"
wasm-bindgen-futures = "0.4"
console_error_panic_hook = { version = "0.1.7" }

[dev-dependencies]
naga = { git = "https://github.com/gfx-rs/naga", rev = "c69f676", features = ["wgsl-in"] }
Expand All @@ -82,5 +86,5 @@ default-features = false
#wgpu-core = { path = "../wgpu/wgpu-core" }
#wgpu-types = { path = "../wgpu/wgpu-types" }

[patch."https://github.com/gfx-rs/naga"]
#naga = { path = "../naga" }
[dependencies.getrandom]
features = ["js"]
33 changes: 33 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,39 @@ Controls:

<img alt="game" src="etc/shots/Road11-pause.png" width="25%">

### Web version

Work in progress, stage matrix:

Stage | State |
-------------------- | ------------------ |
Support FS | :white_check_mark: |
WebGL Initialization | :white_check_mark: |
Loading worlds | :white_check_mark: |
Loading heights | :white_check_mark: |
Loading data | :white_check_mark: |
Loading flood | :white_check_mark: |
Render | :white_check_mark: |


Build for web (DEBUG):

```sh
PATH=$PATH:/home/caiiiycuk/rust/rust/build/x86_64-unknown-linux-gnu/stage0/lib/rustlib/x86_64-unknown-linux-gnu/bin/ LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/home/caiiiycuk/rust/rust/build/x86_64-unknown-linux-gnu/stage0/lib/ cargo build --target wasm32-unknown-unknown --bin road --verbose && wasm-bindgen --out-dir web/ --target web --keep-debug target/wasm32-unknown-unknown/debug/road.wasm
```


Build for web (RELEASE):
```sh
PATH=$PATH:/home/caiiiycuk/rust/rust/build/x86_64-unknown-linux-gnu/stage0/lib/rustlib/x86_64-unknown-linux-gnu/bin/ LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/home/caiiiycuk/rust/rust/build/x86_64-unknown-linux-gnu/stage0/lib/ cargo build --target wasm32-unknown-unknown --bin road --verbose --release && wasm-bindgen --out-dir web/ --target web --keep-debug target/wasm32-unknown-unknown/release/road.wasm
```

Build web page:
```sh
cd web
./build.sh
```

### Mechous viewer/debugger
`car` binary allows to see the mechos with items selected by the configuration. It also shows the debug collision info.
```bash
Expand Down
76 changes: 57 additions & 19 deletions bin/boilerplate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,17 @@ use vangers::{
render::{ScreenTargets, DEPTH_FORMAT},
};

use futures::executor::{LocalPool, LocalSpawner};
use futures::executor::{block_on, LocalPool, LocalSpawner};
use log::info;
use winit::{
event,
event_loop::{ControlFlow, EventLoop},
window::{Window, WindowBuilder},
};

#[cfg(target_arch = "wasm32")]
use crate::web;

pub trait Application {
fn on_key(&mut self, input: event::KeyboardInput) -> bool;
fn on_mouse_wheel(&mut self, _delta: event::MouseScrollDelta) {}
Expand Down Expand Up @@ -54,11 +57,13 @@ pub struct HarnessOptions {

impl Harness {
pub fn init(options: HarnessOptions) -> (Self, config::Settings) {
env_logger::init();
let mut task_pool = LocalPool::new();
block_on(Harness::init_async(options))
}

pub async fn init_async(options: HarnessOptions) -> (Self, config::Settings) {
info!("Loading the settings");
let settings = config::Settings::load("config/settings.ron");

let extent = wgpu::Extent3d {
width: settings.window.size[0],
height: settings.window.size[1],
Expand All @@ -76,19 +81,25 @@ impl Harness {
.unwrap();
let surface = unsafe { instance.create_surface(&window) };

info!("Initializing the device");
let adapter = task_pool
.run_until(instance.request_adapter(&wgpu::RequestAdapterOptions {
info!("Initializing the device:adapter");
let adapter = instance
.request_adapter(&wgpu::RequestAdapterOptions {
power_preference: wgpu::PowerPreference::HighPerformance,
compatible_surface: Some(&surface),
force_fallback_adapter: false,
}))
.expect("Unable to initialize GPU via the selected backend.");
})
.await
.expect("Unable to initialize GPU via the selected backend (adapter).");

let downlevel_caps = adapter.get_downlevel_properties();
let adapter_limits = adapter.limits();

#[cfg(target_arch = "wasm32")]
let mut limits = wgpu::Limits::downlevel_webgl2_defaults();

#[cfg(not(target_arch = "wasm32"))]
let mut limits = wgpu::Limits::downlevel_defaults();

if options.uses_level {
let desired_height = 16 << 10;
limits.max_texture_dimension_2d =
Expand All @@ -102,8 +113,10 @@ impl Harness {
desired_height
};
}
let (device, queue) = task_pool
.run_until(adapter.request_device(

info!("Initializing the device:request");
let (device, queue) = adapter
.request_device(
&wgpu::DeviceDescriptor {
label: None,
features: wgpu::Features::empty(),
Expand All @@ -114,8 +127,9 @@ impl Harness {
} else {
Some(std::path::Path::new(&settings.render.wgpu_trace_path))
},
))
.unwrap();
)
.await
.expect("Unable to initialize GPU via the selected backend (request).");

let config = wgpu::SurfaceConfiguration {
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
Expand All @@ -141,7 +155,7 @@ impl Harness {
.create_view(&wgpu::TextureViewDescriptor::default());

let harness = Harness {
task_pool,
task_pool: LocalPool::new(),
event_loop,
window,
device,
Expand All @@ -158,9 +172,15 @@ impl Harness {
}

pub fn main_loop<A: 'static + Application>(self, mut app: A) {
#[cfg(not(target_arch = "wasm32"))]
use std::time;

#[cfg(target_arch = "wasm32")]
let mut last_time = web::now();

#[cfg(not(target_arch = "wasm32"))]
let mut last_time = time::Instant::now();

let mut needs_reload = false;
let Harness {
mut task_pool,
Expand All @@ -181,6 +201,9 @@ impl Harness {
*control_flow = ControlFlow::Poll;
task_pool.run_until_stalled();

#[cfg(target_arch = "wasm32")]
web::bind_once(&mut app);

match event {
event::Event::WindowEvent {
event: event::WindowEvent::Resized(size),
Expand Down Expand Up @@ -241,13 +264,28 @@ impl Harness {
},
event::Event::MainEventsCleared => {
let spawner = task_pool.spawner();
let duration = time::Instant::now() - last_time;
last_time += duration;
let delta = duration.as_secs() as f32 + duration.subsec_nanos() as f32 * 1.0e-9;

let update_command_buffers = app.update(&device, delta, &spawner);
if !update_command_buffers.is_empty() {
queue.submit(update_command_buffers);
let delta: f32;

#[cfg(target_arch = "wasm32")]
{
let duration = web::now() - last_time;
last_time += duration;
delta = (duration / 1000.0) as f32;
}

#[cfg(not(target_arch = "wasm32"))]
{
let duration = time::Instant::now() - last_time;
last_time += duration;
delta = duration.as_secs() as f32 + duration.subsec_nanos() as f32 * 1.0e-9;
}

if (delta > 0.0) {
let update_command_buffers = app.update(&device, delta, &spawner);
if !update_command_buffers.is_empty() {
queue.submit(update_command_buffers);
}
}

match surface.get_current_texture() {
Expand Down
9 changes: 8 additions & 1 deletion bin/road/game.rs
Original file line number Diff line number Diff line change
Expand Up @@ -811,14 +811,21 @@ impl Application for Game {
}

{
#[cfg(not(target_arch = "wasm32"))]
use rayon::prelude::*;

let clipper = Clipper::new(&self.cam);
let max_quant = self.max_quant;
let common = &self.db.common;
let level = &self.level;

self.agents.par_iter_mut().for_each(|a| {
#[cfg(not(target_arch = "wasm32"))]
let agent_iter = self.agents.par_iter_mut();

#[cfg(target_arch = "wasm32")]
let agent_iter = self.agents.iter_mut();

agent_iter.for_each(|a| {
let mut dt = physics_dt;
a.cpu_apply_control(input_factor, common);

Expand Down
60 changes: 54 additions & 6 deletions bin/road/main.rs
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
#![allow(irrefutable_let_patterns)]

use log::info;

#[path = "../boilerplate.rs"]
mod boilerplate;

#[path = "../web.rs"]
mod web;

mod game;
mod physics;

#[cfg(not(target_arch = "wasm32"))]
fn main() {
use std::env;

let (harness, settings) = boilerplate::Harness::init(boilerplate::HarnessOptions {
title: "road",
uses_level: true,
});
env_logger::init();

info!("Parsing command line");
let args: Vec<_> = env::args().collect();
Expand All @@ -30,6 +30,11 @@ fn main() {
return;
}

let (harness, settings) = boilerplate::Harness::init(boilerplate::HarnessOptions {
title: "road",
uses_level: true,
});

let game = game::Game::new(
&settings,
harness.color_format,
Expand All @@ -41,3 +46,46 @@ fn main() {

harness.main_loop(game);
}

#[cfg(target_arch = "wasm32")]
fn main() {
#[path = "../web.rs"]
mod web;

use env_logger::Builder;
use log::LevelFilter;

console_error_panic_hook::set_once();

Builder::new()
.format(|_buf, record| {
let message = format!("{}: {}", record.level(), record.args());
web::log(&message);
Ok(())
})
.filter(None, LevelFilter::Error)
.init();

web::create_fs();

async fn run() {
let (harness, settings) = boilerplate::Harness::init_async(boilerplate::HarnessOptions {
title: "road",
uses_level: true,
})
.await;

let game = game::Game::new(
&settings,
harness.color_format,
harness.extent,
&harness.device,
&harness.queue,
&harness.downlevel_caps,
);

harness.main_loop(game);
}

wasm_bindgen_futures::spawn_local(run());
}
Loading

0 comments on commit 3a79885

Please sign in to comment.