3D and 2D... together? (+ WASM/WASI Mods)
- Godot (Rust & gdext):
pub mod mouse_utils {
use godot::prelude::*;
use godot::classes::{World3D, PhysicsRayQueryParameters3D};
fn cast_ray_from_mouse(
mouse_position: Vector2,
camera: &Gd<Camera3D>,
mut world_3d: Gd<World3D>,
) {
let origin = camera.project_ray_origin(mouse_position);
let direction = camera.project_ray_normal(mouse_position);
let ray_length: f32 = 30000.0;
let end = origin + (direction * ray_length);
//godot_print!("origin: {origin}, direction: {direction}, end: {end}");
let mut space_state = world_3d.get_direct_space_state().unwrap();
let mut params = PhysicsRayQueryParameters3D::create(origin, end).expect("whynt");
params.set_collide_with_bodies(true);
params.set_collide_with_areas(true);
params.set_hit_back_faces(true);
params.set_collision_mask(1);
let mouse_ray = space_state.intersect_ray(params);
}
}- Roblox (LuaU):
function Mouse:CastRayToMouse(whitelist, ignoreWater, length)
local mouseLocation = UserInputService:GetMouseLocation()
-- warn(mouseLocation)
if not length then
length = 2048
end
local unitRay = camera:ViewportPointToRay(mouseLocation.X, mouseLocation.Y, 0)
-- local ray = Ray.new(unitRay.Origin, unitRay.Direction * length)
local raycastParams = RaycastParams.new()
if whitelist then
raycastParams.FilterType = Enum.RaycastFilterType.Whitelist
raycastParams.FilterDescendantsInstances = whitelist
end
raycastParams.IgnoreWater = ignoreWater or true
local raycastResult = workspace:Raycast(unitRay.Origin, unitRay.Direction * length, raycastParams)-- or {Position = unitRay.Origin + unitRay.Direction}
return raycastResult
endThese two pieces of code do the same thing in Godot (Rust gdext) and Roblox (LuaU). I made the cleanest piece of Lua code I've ever written to date for a Roblox game I was passionate about, only to get scared off (rightly so) by Roblox's increasingly negative practices that boiled over earlier last year, rewrote the whole thing in the cleanest Rust code I've ever written to date, whilst simultaneously learning a new game engine (Godot) on the spot, only to abandon it due to exam & highschool stress.
Chapter 1: What even is Toolkit anyway?
The idea of Toolkit was a building game where you create builds that use a combination of block-based building, scripting, and animations. You can then take these creations and create adventures that other people online could join, explore, and build on top of. I built an initial version of this in Roblox with a working Firebase database, multiplayer worlds that save, and a coherent building system. I then re-did the basic building system in Godot with Rust, but didn't get around to multiplayer (which Roblox has mostly built-in) & database.
The godot build was also an attempt to make the game entirely 3D but use shaders to create a 2D pixel art style, which would have been very hard to do in Roblox, I think it worked really well:
Chapter 2: Double-raycasting
So initially I cast a ray here by getting the space state, using a helper function for camera ray parameters, and intersecting it.
// Cast a ray to try to hit someplace in the `Area` boundary
let mut space_state = self
.base().get_world_3d().expect("world 3d breh")
.get_direct_space_state().expect("direct space.. state");
self.hovered_block = None;
let params = new_camera_ray_parameters(origin, end);
let mouse_ray = space_state.intersect_ray(params);Then I get the initial ray, if it lands thats it, if it doesnt, then we offset it slightly to get into our AABB (ignore the debugging code), and we repeat the exact same raycast step as before, before returning. Using new rust conventions you could replace flatten.map.flatten -> and_then in this chunk here.
mouse_ray.get("position").map(|position| {
let position: Vector3 = position.to();
let camera_position = self.camera.get_position();
if self.aabb.has_point(origin) {
Some((position, end, origin))
} else {
let offset = (end - origin).normalized() * 0.1;
//godot_print!("offset: {offset}");
let position = position + offset;
/*
let mut x = self.block_mesh.duplicate().unwrap().cast::<MeshInstance3D>();
x.set_position(end);
x.set_scale(Vector3::new(10.0, 10.0, 10.0));
self.root_node.add_child(x);
*/
let params = new_camera_ray_parameters(position, end);
let mouse_ray = space_state.intersect_ray(params);
mouse_ray.get("position").map(|position2| {
let position2: Vector3 = position2.to();
let position2 = position2 + offset;
(position2, end, origin)
})
}
}).flatten().map(|(position, end, origin)| {Chapter 3: User-made mods & What the hell is a "wasm-wasip2"
The next part of the plan was a scripting engine. This was an extremely rough sketch in WIT:
package toolkit:block-script;
// record -> struct
// variant -> enum
// enum -> enum [no data]
interface block-definitions {
//use run.{rune};
resource block {
constructor(metadata: block-metadata, fn-key: s64);
run: func() -> list<string>;
}
record date {
year: string,
month: string,
day: string,
}
record block-metadata {
name: string,
date-authored: option<date>,
}
blocks: func() -> list<block>;
/*
record block {
metadata: block-metadata,
//run: func(params: list<string>) -> string,
}
*/
}
world block-script {
//use block-definitions.{block};
export block-definitions;
//import nameeefefef: func() -> string;
//export blocks: func() -> list<block>;
}At the time at least, the standards for WASI (WASM outside of the Web, for sandboxed applications etc) were very under-developed and WIT was very limited, which was one of my main frustrations writing the syntax here. After a bit of messing around in wasmtime though, I was able to import & run primitive scripts that gave a single output:
fn run(&mut self) -> wasmtime::Result<()> {
let bytes = std::fs::read(concat!(
env!("CARGO_MANIFEST_DIR"),
//"/tests/wasi-wast/wasi/unstable/hello.wasm"
"/vigor_std.wasm"
))?;
let component = Component::new(&self.engine, bytes)?;
//block_definitions::add_to_linker(&mut *self.component_linker, |state: &mut ServerWasiView| state)?;
//block::BlockScript::add_to_linker(&mut *self.component_linker, |state: &mut ServerWasiView| state)?;
let bindings = block::BlockScript::instantiate(&mut *self.store, &component, &*self.component_linker)?;
let block_defs = bindings.toolkit_block_script_block_definitions();
let block_resource = block_defs.block();
let blocks = block_defs.call_blocks(&mut *self.store)?;
godot_print!("{:#?}", blocks);
for block in blocks {
//godot_print!("type:");
//godot_print!("{:#?}", x.ty());
let y = block_resource.call_run(&mut *self.store, block);
//let y = block_definitions::Block;
godot_print!("{:#?}", y);
}
Ok(())
}Conclusion
Toolkit was an ambitious project for me that taught me a lot about Godot, WebAssembly, Rust, Lua, and gamedev in general. Although I couldn't complete it, I'm happy to have worked on it and to have a working demo by the end of it nonetheless.