From de672a85d2778c47fce0d412cea787405388330c Mon Sep 17 00:00:00 2001 From: jussi Date: Sat, 30 Aug 2025 16:41:05 +0300 Subject: DrawMeshInstanced takes transforms as Buffer. --- examples/instancing/main.lua | 15 ++++++++++++--- examples/resources/lib/matrix.lua | 9 +++++++++ 2 files changed, 21 insertions(+), 3 deletions(-) (limited to 'examples') diff --git a/examples/instancing/main.lua b/examples/instancing/main.lua index 1966479..9e14383 100644 --- a/examples/instancing/main.lua +++ b/examples/instancing/main.lua @@ -8,10 +8,14 @@ Modified by Jussi Viitala (@nullstare) for ReiLua style. ]] +package.path = package.path..";"..RL.GetBasePath().."../resources/lib/?.lua" + +Matrix = require( "matrix" ) + local MAX_INSTANCES = 10000 local cube -local transforms = {} +local transformsBuf local camera local shader @@ -41,6 +45,9 @@ function RL.init() -- Define mesh to be instanced cube = RL.GenMeshCube( { 1, 1, 1 } ) + transformsBuf = RL.LoadBufferFormatted( MAX_INSTANCES * 16, RL.BUFFER_FLOAT, 0 ) + local bufPos = 0 + -- Translate and rotate cubes randomly for i = 1, MAX_INSTANCES do local translation = RL.MatrixTranslate( { math.random( -50, 50 ), math.random( -50, 50 ), math.random( -50, 50 ) } ) @@ -48,7 +55,8 @@ function RL.init() local angle = math.rad( math.random( 0, 10 ) ) local rotation = RL.MatrixRotate( axis, angle ) - table.insert( transforms, RL.MatrixMultiply( rotation, translation ) ) + RL.SetBufferData( transformsBuf, bufPos, Matrix:temp( RL.MatrixMultiply( rotation, translation ) ):arr() ) + bufPos = bufPos + 16 end -- Load lighting shader @@ -101,7 +109,7 @@ function RL.draw() -- Draw meshes instanced using material containing instancing shader (RED + lighting), -- transforms[] for the instances should be provided, they are dynamically -- updated in GPU every frame, so we can animate the different mesh instances - RL.DrawMeshInstanced( cube, matInstances, transforms, MAX_INSTANCES ) + RL.DrawMeshInstanced( cube, matInstances, transformsBuf, MAX_INSTANCES ) -- Draw cube mesh with default material (BLUE) RL.DrawMesh( cube, matDefault, RL.MatrixTranslate( { 10.0, 0.0, 0.0 } ) ) @@ -113,4 +121,5 @@ end function RL.exit() RL.UnloadMaterial( matInstances, true ) RL.UnloadMesh( cube ) + RL.UnloadBuffer( transformsBuf ) end diff --git a/examples/resources/lib/matrix.lua b/examples/resources/lib/matrix.lua index 2ed0ffb..d540d28 100644 --- a/examples/resources/lib/matrix.lua +++ b/examples/resources/lib/matrix.lua @@ -58,6 +58,15 @@ function Matrix:set( m ) self:copyMatrix( m ) end +function Matrix:arr() + return { + self[1][1], self[2][1], self[3][1], self[4][1], + self[1][2], self[2][2], self[3][2], self[4][2], + self[1][3], self[2][3], self[3][3], self[4][3], + self[1][4], self[2][4], self[3][4], self[4][4], + } +end + function Matrix:serialize() local str = { "Matrix:new({" } -- cgit v1.2.3