lua: create type defs for World, Entity, ActionHandler, all asset handlers, add globals file

This commit is contained in:
SeanOMik 2024-10-04 23:48:58 -04:00
parent 06a4301c23
commit 140ca506d6
Signed by: SeanOMik
GPG Key ID: FEC9E2FC15235964
26 changed files with 485 additions and 50 deletions

View File

@ -17,7 +17,7 @@ end
function on_init()
local cube = world:request_res("../assets/cube-texture-embedded.gltf")
local cube = world:request_asset("../assets/cube-texture-embedded.gltf") --[[@as GltfHandle]]
print("Loaded textured cube (" .. udname(cube) .. ")")
cube:wait_until_loaded()

View File

@ -358,66 +358,61 @@ impl ActionHandler {
/// Returns true if the action is pressed (or was just pressed).
///
/// This will panic if the action name does not correspond to an action.
pub fn is_action_pressed<L>(&self, action: L) -> bool
/// Returns `None` if the action was not found.
pub fn is_action_pressed<L>(&self, action: L) -> Option<bool>
where
L: ActionLabel
{
let action = self.actions.get(&action.label_hash())
.unwrap_or_else(|| panic!("Action {action:?} was not found"));
let action = self.actions.get(&action.label_hash())?;
matches!(action.state, ActionState::Pressed(_) | ActionState::JustPressed(_))
Some(matches!(action.state, ActionState::Pressed(_) | ActionState::JustPressed(_)))
}
/// Returns true if the action was just pressed.
///
/// This will panic if the action name does not correspond to an action.
pub fn was_action_just_pressed<L>(&self, action: L) -> bool
/// Returns `None` if the action was not found.
pub fn was_action_just_pressed<L>(&self, action: L) -> Option<bool>
where
L: ActionLabel
{
let action = self.actions.get(&action.label_hash())
.unwrap_or_else(|| panic!("Action {action:?} was not found"));
let action = self.actions.get(&action.label_hash())?;
matches!(action.state, ActionState::JustPressed(_))
Some(matches!(action.state, ActionState::JustPressed(_)))
}
/// Returns true if the action was just released.
///
/// This will panic if the action name does not correspond to an action.
pub fn was_action_just_released<L>(&self, action: L) -> bool
/// Returns `None` if the action was not found.
pub fn was_action_just_released<L>(&self, action: L) -> Option<bool>
where
L: ActionLabel
{
let action = self.actions.get(&action.label_hash())
.unwrap_or_else(|| panic!("Action {action:?} was not found"));
let action = self.actions.get(&action.label_hash())?;
matches!(action.state, ActionState::JustReleased)
Some(matches!(action.state, ActionState::JustReleased))
}
/// Returns an action's state.
///
/// This will panic if the action name does not correspond to an action.
pub fn get_action_state<L>(&self, action: L) -> ActionState
/// Returns `None` if the action was not found.
pub fn get_action_state<L>(&self, action: L) -> Option<ActionState>
where
L: ActionLabel
{
let action = self.actions.get(&action.label_hash())
.unwrap_or_else(|| panic!("Action {action:?} was not found"));
let action = self.actions.get(&action.label_hash())?;
action.state
Some(action.state)
}
/// Returns the action's modifier if it is pressed (or was just pressed).
/// Returns `None` if the action's state is not `ActionState::Pressed` or `ActionState::JustPressed`.
///
/// This will panic if the action name does not correspond to an action.
/// Returns `None` if the action's state is not `ActionState::Pressed`, `ActionState::JustPressed`,
/// or if the action was not found.
pub fn get_pressed_modifier<L>(&self, action: L) -> Option<f32>
where
L: ActionLabel
{
let action = self.actions.get(&action.label_hash())
.unwrap_or_else(|| panic!("Action {action:?} was not found"));
let action = self.actions.get(&action.label_hash())?;
match action.state {
ActionState::Pressed(v) | ActionState::JustPressed(v) => Some(v),
@ -426,15 +421,14 @@ impl ActionHandler {
}
/// Returns the action's modifier if it was just pressed.
/// Returns `None` if the action's state is not `ActionState::JustPressed`.
///
/// This will panic if the action name does not correspond to an action.
/// Returns `None` if the action's state is not `ActionState::JustPressed`,
/// or if the action was not found.
pub fn get_just_pressed_modifier<L>(&self, action: L) -> Option<f32>
where
L: ActionLabel
{
let action = self.actions.get(&action.label_hash())
.unwrap_or_else(|| panic!("Action {action:?} was not found"));
let action = self.actions.get(&action.label_hash())?;
match action.state {
ActionState::JustPressed(v) => Some(v),
@ -443,15 +437,14 @@ impl ActionHandler {
}
/// Returns the action's modifier if its an updated axis.
/// Returns `None` if the action's state is not `ActionState::Axis`.
///
/// This will panic if the action name does not correspond to an action.
/// Returns `None` if the action's state is not `ActionState::Axis`,
/// or if the action was not found.
pub fn get_axis_modifier<L>(&self, action: L) -> Option<f32>
where
L: ActionLabel
{
let action = self.actions.get(&action.label_hash())
.unwrap_or_else(|| panic!("Action {action:?} was not found"));
let action = self.actions.get(&action.label_hash())?;
match action.state {
ActionState::Axis(v) => Some(v),

View File

@ -0,0 +1,9 @@
---@enum ActionState
ActionState = {
IDLE = "idle",
PRESSED = "pressed",
JUST_PRESSED = "just_pressed",
JUST_RELEASED = "just_released",
AXIS = "axis",
OTHER = "other",
}

View File

@ -0,0 +1,12 @@
---@enum HandleState
HandleState = {
LOADING = "loading",
READY = "ready",
ERROR = "error",
}
---@enum ActionKind
ActionKind = {
BUTTON = "button",
AXIS = "axis",
}

View File

@ -0,0 +1,23 @@
---@meta
---@class GltfHandle: Handle
---
---A handle to a GLTF asset.
GltfHandle = {
}
---Get a list of scenes in the GLTF file.
---
---@return SceneHandle[]
function GltfHandle:scenes() end
---Get a list of materials in the GLTF file.
---
---@return MaterialHandle[]
function GltfHandle:materials() end
---Get a list of meshes in the GLTF file.
---
---@return MeshHandle[]
function GltfHandle:meshes() end

View File

@ -0,0 +1,43 @@
---@meta
---@class Handle: userdata
---
---A handle to an asset. Assets are loaded asynchronously, so you cannot immediately
---use them after you request them from the World.
Handle = {
---The path the asset was loaded from.
---
---@type string
path = nil,
---The version of the resource.
---
---Increments every time a resource is loaded.
---
---@type number
version = nil,
---The unique id of the resource.
---
---This is not changed for the entire lifetime of the handle, it does not change
---when an asset is reloaded.
---
---@type string
uuid = nil,
---Current state of the asset handle.
---@type HandleState
state = nil,
}
---Returns true if the asset is watched for auto-reloading.
---
---@return boolean
function Handle:is_watched() end
---Returns true if the asset is loaded.
---@return boolean
function Handle:is_loaded() end
---Blocks execution until the asset and its dependencies are loaded.
function Handle:wait_until_loaded() end

View File

@ -0,0 +1,102 @@
---@meta
---@class MaterialHandle: Handle
---
---A handle to a material asset in a GLTF file.
MaterialHandle = {
---The unique id of the GPU shader.
---@type number?
shader_uuid = nil,
---The name of the material from GLTF.
---@type string?
name = nil,
---@type boolean
double_sided = nil,
---The RGBA base color of the model.
---
---If a texture is supplied with `base_color_texture`, this value will tint the
---texture. If a texture is not provided, this value would be the color of
---the Material.
---
---@type Vec4
base_color = nil,
---The metalness of the material
---
---From 0.0 (non-metal) to 1.0 (metal).
---
---@type number
metallic = nil,
---The roughness of the material
---
---From 0.0 (smooth) to 1.0 (rough)
---
---@type number
roughness = nil,
---The base color texture of the model.
---@type TextureHandle?
base_color_texture = nil,
---The metallic-roughness texture.
---
---The metalness values are sampled from the B channel. The roughness values are sampled from
---the G channel. These values are linear. If other channels are present (R or A), they are
---ignored for metallic-roughness calculations.
---@type TextureHandle?
metallic_roughness_texture = nil,
---A set of parameter values that are used to define the specular-glossiness material model
---from Physically-Based Rendering (PBR) methodology.
---GLTF extension: [KHR_materials_pbrSpecularGlossiness](https://kcoley.github.io/glTF/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness)
---@type TextureHandle?
pbr_glossiness = nil,
---The optional alpha cutoff value of the material.
---
---This will be used instead of the renderer's default.
---
---@type number?
alpha_cutoff = nil,
---The alpha rendering mode of the material.
---
---The material's alpha rendering
---mode enumeration specifying the interpretation of the alpha value of the main
---factor and texture.
---
---* In `Opaque` mode (default) the alpha value is ignored
--- and the rendered output is fully opaque.
---* In `Mask` mode, the rendered
--- output is either fully opaque or fully transparent depending on the alpha
--- value and the specified alpha cutoff value.
---* In `Blend` mode, the alpha value is used to composite the source and
--- destination areas and the rendered output is combined with the background
--- using the normal painting operation (i.e. the Porter and Duff over
--- operator).
---
---@type AlphaMode
alpha_mode = nil,
---@type Specular?
specular = nil,
}
---@enum AlphaMode
AlphaMode = {
OPAQUE = "opaque",
MASK = "mask",
BLEND = "blend",
}
---@class PbrGlossiness
---TODO: implement
PbrGlossiness = {}
---@class Specular
---TODO: implement
Specular = {}

View File

@ -0,0 +1,14 @@
---@meta
---@class MeshHandle: Handle
---
---A handle to a mesh in a GLTF file.
MeshHandle = {
---The material of the mesh
---@type MaterialHandle
material = nil,
}
---Get the indices in the mesh.
---@return number[]
function MeshHandle:indices() end

View File

@ -0,0 +1,9 @@
---@meta
---@class SceneHandle: Handle
---
---A handle to a scene asset in a GLTF file.
SceneHandle = {
}

View File

@ -0,0 +1,4 @@
---@meta
---@class TextureHandle
TextureHandle = {}

View File

@ -0,0 +1,125 @@
---@meta
---@class ActionHandler: userdata
ActionHandler = {}
--- Create a new `ActionHandler`.
---
--- ```lua
--- local handler = ActionHandler.new {
--- -- A list of layout IDs
--- layouts = { 0 },
--- actions = {
--- -- A list of action names and the `ActionKind`s.
--- -- Actions can be buttons or axes.
--- MoveForwardBackward = ActionKind.AXIS,
--- MoveLeftRight = ActionKind.AXIS,
--- MoveUpDown = ActionKind.AXIS,
--- LookLeftRight = ActionKind.AXIS,
--- LookUpDown = ActionKind.AXIS,
--- LookRoll = ActionKind.AXIS,
--- ObjectsMoveUpDown = ActionKind.AXIS
--- },
--- mappings = {
--- -- Each entry here is a mapping of actions for a layout.
--- -- This can be used so that when the current layout is changed,
--- -- the mapping would also change.
--- {
--- -- Specify the layout id that this mapping is for.
--- layout = 0,
--- binds = {
--- -- This is an Action bind. A bind is used to bind an input to an action.
--- -- These actions are defined above in "actions".
--- MoveForwardBackward = {
--- -- This is how you bind a button. In this case the button is a key.
--- -- "key" is the device the bind comes from, then after the colon is the
--- -- input name, in this case a specific key. We specify a modifier to the bind
--- -- after the equal sign.
--- "key:w=1.0",
--- "key:s=-1.0"
--- },
--- MoveLeftRight = {
--- "key:a=-1.0", "key:d=1.0"
--- },
--- MoveUpDown = {
--- "key:c=1.0", "key:z=-1.0"
--- },
--- LookLeftRight = {
--- "key:left=-1.0", "key:right=1.0",
--- -- Here is a bind to an axis.
--- -- We use "mouse", for the device the bind is from, then "axis" to specify
--- -- that we want to bind a specific axis, then we use the name of the axis,
--- -- in this case "x".
--- -- So this binds to the x axis of the mouse.
--- "mouse:axis:x"
--- },
--- LookUpDown = {
--- "key:up=-1.0", "key:down=1.0",
--- -- Here we bind to the y axis of the mouse.
--- "mouse:axis:y",
--- },
--- LookRoll = {
--- "key:e=-1.0", "key:q=1.0",
--- },
--- ObjectsMoveUpDown = {
--- "key:u=1.0", "key:j=-1.0"
--- }
--- }
--- }
--- }
--- }
---
--- -- Add the handler to the world so the host will process it.
--- world:add_resource(handler)
--- ```
---
---@param table table See above example to see the format of this table.
function ActionHandler.new(table) end
---Returns the action's modifier if its an updated axis.
---
---Returns `nil` if the action's state is not `ActionState::Axis`, or if the
---action was not found.
---@param action string
---@return number?
function ActionHandler:get_axis(action) end
---Returns true if the action is pressed (or was just pressed).
---
---Returns `nil` if the action's was not found.
---@param action string
---@return boolean?
function ActionHandler:is_pressed(action) end
---Returns true if the action was **just** pressed.
---
---Returns `nil` if the action was not found
---
---@param action string
---@return boolean?
function ActionHandler:was_just_pressed(action) end
---Returns true if the action was just released.
---
---Returns `nil` if the action was not found
---
---@param action string
---@return boolean?
function ActionHandler:was_just_released(action) end
---Returns the action's modifier if it was just pressed.
---
---Returns `nil` if the action's state is not `ActionState.JUST_PRESSED`,
---or if the action was not found.
---
---@param action string
---@return number?
function ActionHandler:get_just_pressed(action) end
---Returns the current state of the action.
---
---The first element in the returned tuple is the state enum, and the second
---is the state modifier. The modifer will be `nil` if the state is "idle"
---
---@return [ActionState, number?]
function ActionHandler:get_action_state(action) end

View File

@ -1,6 +1,6 @@
---@meta
---@class DeltaTime
---@class DeltaTime: userdata
---
---DeltaTime is an ECS world resource. When its requested from the world, a `number`
---is returned.

View File

@ -0,0 +1,4 @@
---@meta
---@class Entity: userdata
Entity = {}

View File

@ -1,4 +1,4 @@
---@class Window
---@class Window: userdata
Window = {
---Gets or sets the window's focus.
---@type boolean

View File

@ -0,0 +1,75 @@
---@meta
---@class World: userdata
World = {}
---Spawn an entity with components.
---
---@param ... userdata The components to spawn on the new entity, currently must be userdata.
---@return Entity
function World:spawn(...) end
--- Query components from the world.
---
--- The `system` parameter is a function with the requested components. The function
--- is ran every time for an entity. If you modify a component and want the changes to be
--- stored, return it in the function. The order of the returned components do not matter.
---
--- Example:
--- ```lua
--- ---@type number
--- local dt = world:resource(DeltaTime)
---
--- world:view(
--- ---@param t Transform
--- function (t)
--- -- Move the transform of the entity a bit
--- t:translate(0, 0.15 * dt, 0)
--- -- Since the transform was modified, it must be returned so
--- -- the engine can store the changes.
--- return t
--- end,
--- -- Specify the requested components here
--- Transform
--- )
--- ```
---
---@param system fun(...): ...
---@param ... userdata
function World:view(system, ...) end
---Get an ECS resource.
---
---Returns `nil` if the resource was not found in the world. Many resources will
---return userdata, however some may return Lua types like `DeltaTime`
---returning a `number`.
---
---Example:
---```lua
------@type number
---local dt = world:resource(DeltaTime)
---
---print(type(dt)) --> number
---```
---
---@param resource userdata This shouldn't be an instance of userdata.
---@return any?
function World:resource(resource) end
---Add a resource to the world.
---
---If the resource already exists, it will be overwritten.
---
---@param resource userdata
function World:add_resource(resource) end
---Request an asset.
---
---Assets are loaded asyncronously, so you must wait before trying to access fields on
---the asset. You can spawn an entity with it when its still loading.
---
---Returns an asset handle to the requested resource type
---
---@param path string
---@return Handle asset An asset handle to the requested resource type.
function World:request_asset(path) end

View File

@ -0,0 +1,5 @@
---@meta
---The world global that is provided to every Lua script.
---@type World
world = nil

View File

@ -5,4 +5,6 @@ require "math.quat"
require "math.transform"
require "ecs.window"
require "ecs.delat_time"
require "ecs.delta_time"
require "asset.handle"

View File

@ -1,6 +1,6 @@
---@meta
---@class Quat
---@class Quat: userdata
---This is a Lua export of [`glam::Quat`](https://docs.rs/glam/latest/glam/f32/struct.Quat.html)
---
---@operator add(self): self

View File

@ -1,6 +1,6 @@
---@meta
---@class Transform
---@class Transform: userdata
---
---A Transform represents a transformation of an object. A transform includes the position
---(called translation here), rotation, and scale. Rotation is represented using a Quaternion

View File

@ -1,6 +1,6 @@
---@meta
---@class Vec2
---@class Vec2: userdata
---This is a Lua export of [`glam::Vec2`](https://docs.rs/glam/latest/glam/f32/struct.Vec2.html)
---
---@operator add(self|number): self

View File

@ -1,6 +1,6 @@
---@meta
---@class Vec3
---@class Vec3: userdata
---This is a Lua export of [`glam::Vec3`](https://docs.rs/glam/latest/glam/f32/struct.Vec3.html)
---
---@operator add(self|number): self

View File

@ -1,6 +1,6 @@
---@meta
---@class Vec4
---@class Vec4: userdata
---This is a Lua export of [`glam::Vec4`](https://docs.rs/glam/latest/glam/f32/struct.Vec4.html)
---
---@operator add(self|number): self

View File

@ -40,14 +40,18 @@ impl ScriptApiProvider for LyraEcsApiProvider {
fn expose_api(&mut self, _: &ScriptData, ctx: &mut Self::ScriptContext) -> Result<(), crate::ScriptError> {
let ctx = ctx.lock().unwrap();
// load window util
// load window enums
let bytes = include_str!("../../../scripts/lua/window.lua");
ctx.load(bytes).exec().unwrap();
// load asset handle enums
let bytes = include_str!("../../../scripts/lua/asset_handle.lua");
ctx.load(bytes).exec().unwrap();
let globals = ctx.globals();
globals.set("World", ctx.create_proxy::<ScriptWorldPtr>()?)?;
globals.set("DynamicBundle", ctx.create_proxy::<ScriptDynamicBundle>()?)?;
globals.set("SceneComponent", ctx.create_proxy::<LuaSceneHandle>()?)?;
globals.set("SceneHandler", ctx.create_proxy::<LuaSceneHandle>()?)?;
globals.set("ActionHandler", ctx.create_proxy::<LuaActionHandler>()?)?;
globals.set("Window", ctx.create_proxy::<LuaWindow>()?)?;

View File

@ -294,7 +294,7 @@ impl mlua::UserData for ScriptWorldPtr {
Ok(())
});
methods.add_method_mut("request_res", |lua, this, path: String| {
methods.add_method_mut("request_asset", |lua, this, path: String| {
let world = this.write();
let man = world.get_resource_mut::<ResourceManager>().unwrap();
let handle = man.request_raw(&path).unwrap();

View File

@ -111,9 +111,12 @@ impl mlua::FromLua for LuaResHandle {
}
}
// TODO: fields
wrap_lua_struct!(lyra_resource::gltf::PbrGlossiness, skip(lua_reflect)); // doesn't need internal lua reflection methods
// TODO: fields
wrap_lua_struct!(lyra_resource::gltf::Specular, skip(lua_reflect)); // doesn't need internal lua reflection methods
// TODO: fields
lua_wrap_handle!(SceneGraph, name=Scene, {});
lua_wrap_handle!(Mesh,

View File

@ -127,13 +127,21 @@ impl mlua::UserData for LuaActionHandler {
methods.add_method("get_action_state", |lua, this, action: String| {
let state = this.handler.get_action_state(action);
// if the state wasn't found, return Nil.
if state.is_none() {
let mut v = mlua::MultiValue::new();
v.push_back(mlua::Value::Nil);
return Ok(v);
}
let state = state.unwrap();
let (name, val) = match state {
ActionState::Idle => ("Idle", None),
ActionState::Pressed(v) => ("Pressed", Some(v)),
ActionState::JustPressed(v) => ("JustPressed", Some(v)),
ActionState::JustReleased => ("JustReleased", None),
ActionState::Axis(v) => ("Axis", Some(v)),
ActionState::Other(v) => ("Other", Some(v)),
ActionState::Idle => ("idle", None),
ActionState::Pressed(v) => ("pressed", Some(v)),
ActionState::JustPressed(v) => ("just_pressed", Some(v)),
ActionState::JustReleased => ("just_released", None),
ActionState::Axis(v) => ("axis", Some(v)),
ActionState::Other(v) => ("other", Some(v)),
};
let mut multi = Vec::new();