Skip to content

Commit

Permalink
Overhauled rendering internals and introduced a new workflow
Browse files Browse the repository at this point in the history
  • Loading branch information
BobDaGithubAccount committed Oct 27, 2024
1 parent e5cdd01 commit b4d07bb
Show file tree
Hide file tree
Showing 5 changed files with 111 additions and 32 deletions.
4 changes: 4 additions & 0 deletions .github/workflows/quick-build.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
rm -r dist
mkdir dist
cp src/index.html dist/index.html
cp -r lib/pkg/* dist/
1 change: 1 addition & 0 deletions lib/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ web-sys = { version = "0.3", features = ["Window"] }
three-d = "0.17.0"
log = "0.4"
winit = "0.28"
lazy_static = "1.4.0"

[lib]
crate-type = ["cdylib", "rlib"]
Expand Down
56 changes: 39 additions & 17 deletions lib/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,32 @@
use three_d::{renderer::*, FrameInputGenerator, SurfaceSettings, WindowedContext};
use three_d::{context, renderer::*, FrameInputGenerator, SurfaceSettings, WindowedContext};
use std::sync::Mutex;

#[cfg(target_arch = "wasm32")]
use wasm_bindgen::prelude::*;

lazy_static::lazy_static! {
static ref CAMERA_INSTANCE: Mutex<Option<Camera>> = Mutex::new(None);
}

#[cfg(target_arch = "wasm32")]
#[wasm_bindgen]
pub fn resize_callback(width: u32, height: u32) {
log::info!("Resized to {:?}", (width, height));
if let Some(camera) = CAMERA_INSTANCE.lock().unwrap().as_mut() {
camera.set_viewport(Viewport::new_at_origo(width, height));
}
}

pub fn main() {
let event_loop = winit::event_loop::EventLoop::new();

#[cfg(not(target_arch = "wasm32"))]
let window_builder = winit::window::WindowBuilder::new()
.with_title("winit window")
.with_min_inner_size(winit::dpi::LogicalSize::new(1280, 720))
.with_title("Full-Screen Window")
.with_inner_size(winit::dpi::LogicalSize::new(1920, 1080))
.with_decorations(false)
.with_maximized(true);

#[cfg(target_arch = "wasm32")]
let window_builder = {
use wasm_bindgen::JsCast;
Expand All @@ -18,31 +37,32 @@ pub fn main() {
.unwrap()
.document()
.unwrap()
.get_elements_by_tag_name("canvas")
.item(0)
.get_element_by_id("canvas")
.unwrap()
.dyn_into::<web_sys::HtmlCanvasElement>()
.unwrap(),
))
.with_inner_size(winit::dpi::LogicalSize::new(1280, 720))
.with_inner_size(winit::dpi::LogicalSize::new(1920, 1080))
.with_prevent_default(true)
};

let window = window_builder.build(&event_loop).unwrap();
let context = WindowedContext::from_winit_window(&window, SurfaceSettings::default()).unwrap();

// Create camera
let mut camera = Camera::new_perspective(
Viewport::new_at_origo(1, 1),
vec3(0.0, 2.0, 4.0),
vec3(0.0, 0.0, 0.0),
vec3(0.0, 1.0, 0.0),
degrees(45.0),
0.1,
10.0,
Viewport::new_at_origo(1, 1),
vec3(0.0, 2.0, 4.0), // Camera position
vec3(0.0, 0.0, 0.0), // Target position (where the camera is looking)
vec3(0.0, 1.0, 0.0), // Up direction
degrees(45.0), // Field of view
0.1, // Near clipping plane
100.0, // Far clipping plane
);

*CAMERA_INSTANCE.lock().unwrap() = Some(camera.clone());

let mut control = OrbitControl::new(*camera.target(), 1.0, 100.0);

// Create model
let mut model = Gm::new(
Mesh::new(&context, &CpuMesh::cube()),
ColorMaterial {
Expand All @@ -52,7 +72,6 @@ pub fn main() {
);
model.set_animation(|time| Mat4::from_angle_y(radians(time * 0.0005)));

// Event loop
let mut frame_input_generator = FrameInputGenerator::from_winit_window(&window);
event_loop.run(move |event, _, control_flow| match event {
winit::event::Event::MainEventsCleared => {
Expand All @@ -77,10 +96,13 @@ pub fn main() {
frame_input_generator.handle_winit_window_event(event);
match event {
winit::event::WindowEvent::Resized(physical_size) => {
log::info!("Resized to {:?}", physical_size);
context.resize(*physical_size);
camera.set_viewport(Viewport::new_at_origo(physical_size.width, physical_size.height));
}
winit::event::WindowEvent::ScaleFactorChanged { new_inner_size, .. } => {
context.resize(**new_inner_size);
camera.set_viewport(Viewport::new_at_origo(new_inner_size.width, new_inner_size.height));
}
winit::event::WindowEvent::CloseRequested => {
control_flow.set_exit();
Expand All @@ -90,4 +112,4 @@ pub fn main() {
}
_ => {}
});
}
}
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"run": "bash .github/workflows/run.sh",
"build": "bash .github/workflows/build.sh"
"build": "bash .github/workflows/build.sh",
"quickrun": "bash .github/workflows/quick-build.sh && node index.js"
},
"repository": {
"type": "git",
Expand Down
79 changes: 65 additions & 14 deletions src/index.html
Original file line number Diff line number Diff line change
@@ -1,17 +1,68 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Atomica</title>
</head>
<body>
<canvas id="canvas"></canvas>
<script type="module">
import init from './src.js';
init().then(() => {
console.log("Wasm module initialized");
});
</script>
</body>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Atomica</title>
<style>
body {
margin: 0;
overflow: hidden;
}
#canvas {
display: block;
width: 100vw;
height: 100vh;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script type="module">
import init, * as wasm_bindgen from './src.js';

function jsInit() {
console.log("Wasm module initialized");

if (typeof window.resize_callback === 'undefined' && typeof wasm_bindgen.resize_callback !== 'undefined') {
console.log("Setting resize callback");
window.resize_callback = wasm_bindgen.resize_callback;
}

const canvas = document.getElementById('canvas');

function resizeCanvas() {
const canvas = document.getElementById('canvas');
const width = window.innerWidth;
const height = window.innerHeight;
canvas.width = width;
canvas.height = height;

if (typeof window.resize_callback === 'function') {
window.resize_callback(width, height);
}
}

window.addEventListener('resize', resizeCanvas);
window.addEventListener('load', resizeCanvas);
}
init().then(() => {
jsInit();
}).catch(err => {
if (err.message.includes("Using exceptions for control flow")) {
console.warn("Ignoring expected Wasm initialization exception and proceeding.");
try {
jsInit();
} catch (err) {
console.error("Error in continuing initialisation:", err);
throw err;
}
} else {
console.error("Error initializing wasm module:", err);
throw err;
}
});
console.log("Wasm module initialization call made");
</script>
</body>
</html>

0 comments on commit b4d07bb

Please sign in to comment.