lyra-engine/examples/lua-scripting/scripts/test.lua

123 lines
3.4 KiB
Lua

local is_window_setup = false
local cube_entity = nil
---Return the userdata's name from its metatable.
---
---Returns nil if the userdata doesn't have a metatable.
---@param val userdata
---@return string|nil
function udname(val)
local tbl = debug.getmetatable(val)
if tbl == nil then
return nil
end
return tbl.__name
end
function dump(o)
if type(o) == 'table' then
local s = '{ '
for k,v in pairs(o) do
if type(k) ~= 'number' then k = '"'..k..'"' end
s = s .. '['..k..'] = ' .. dump(v) .. ','
end
return s .. '} '
else
return tostring(o)
end
end
function on_init()
local cube = world:request_asset("../assets/cube-texture-embedded.gltf") --[[@as GltfHandle]]
print("Loaded textured cube (" .. udname(cube) .. ")")
cube:wait_until_loaded()
local scenes = cube:scenes()
local cube_scene = scenes[1]
local pos = Transform.from_translation(Vec3.new(0, 0, -8.0))
local e = world:spawn(pos, cube_scene)
cube_entity = e
print("spawned entity " .. tostring(e))
end
function on_first()
if not is_window_setup then
local view = View.new(Window)
local res = world:view(view)
---@param w Window
for en, w in res:iter() do
if w.cursor_grab == CursorGrabMode.NONE then
w.cursor_grab = CursorGrabMode.LOCKED
w.cursor_visible = false
en:update(w)
else
is_window_setup = true
print("Window setup")
end
end
end
---@type EventReader
local reader = world:read_event(DeviceEvent)
---@param ev DeviceEvent
for ev in reader:read() do
if ev.event.kind == DeviceEventKind.MOTION then
local motion_ev = ev.event --[[@as DeviceEventMotion]]
print("axis: " .. tostring(motion_ev.axis) .. " = " .. tostring(motion_ev.value))
end
end
end
--[[ function on_pre_update()
print("Lua's pre-update function was called")
end ]]
function on_update()
-- Get entities without WorldTransform
local view = View.new(Transform, Not(Has(WorldTransform)), Res(DeltaTime))
local res = world:view(view)
---@param transform Transform
---@param dt DeltaTime
for entity, transform, dt in res:iter() do
transform:translate(0, 0.15 * dt, 0)
entity:update(transform)
end
local changed_view = View.new(Changed(Transform))
local changed_res = world:view(changed_view)
---@param transform Transform
for _, transform in changed_res:iter() do
print("Entity transform changed to: '" .. tostring(transform) .. "' on tick " .. tostring(world:get_tick()))
end
local tick_view = View.new(TickOf(Transform))
local tick_res = world:view(tick_view)
---@param tick number
for _, tick in tick_res:iter() do
print("Entity transform last changed on tick " .. tostring(tick))
end
local pos_view = View.new(Transform)
local vone = world:view_one(cube_entity --[[@as Entity]], pos_view)
local r = vone() -- short hand for 'vone:get()'
if r then
---@type Transform
local pos = r[1]
print("Found cube entity at '" .. tostring(pos) .. "'")
end
end
--[[ function on_post_update()
print("Lua's post-update function was called")
end
function on_last()
print("Lua's last function was called")
end ]]