I am using an external api to generate some textures. I need to load them in terms of gui textures to display them. This api provides the picture as a matrix of colors as nested Lua tables. How can I use them as a texture?
You can create a new texture using resource.create_texture()
. The function needs a buffer with image data. You should be able to create this buffer from your Lua table.
Example from the API reference:
function init(self)
-- Create a new buffer with 4 components and FLOAT32 type
local tbuffer = buffer.create(128 * 128, { {name=hash("rgba"), type=buffer.VALUE_TYPE_FLOAT32, count=4} } )
local tstream = buffer.get_stream(tbuffer, hash("rgba"))
-- Fill the buffer stream with some float values
for y=1,128 do
for x=1,128 do
local index = (y-1) * 128 * 4 + (x-1) * 4 + 1
tstream[index + 0] = 999.0
tstream[index + 1] = -1.0
tstream[index + 2] = 0.5
tstream[index + 3] = 1.0
end
end
-- Create a 2D Texture with a RGBA23F format
local tparams = {
width = 128,
height = 128,
type = resource.TEXTURE_TYPE_2D,
format = resource.TEXTURE_FORMAT_RGBA32F,
}
-- Note that we pass the buffer as the last argument here!
local my_texture_id = resource.create_texture("/my_custom_texture.texturec", tparams, tbuffer)
-- assign the texture to a model
go.set("#model", "texture0", my_texture_id)
end
You would also need to create an atlas for the texture before you assign it to you gui. You use resource.create_atlas()
for that. Then you can use go.set()
to set the atlas on the gui:
The other option you have is to use gui.new_texture()
and gui.set_texture()
:
I had a problem with especially this part of the code. I did not understand how you calculated the index (in terms of context). In addition the api uses a different scheme for colors not rgba32. It uses a scheme of 0xrrggbb and transparent is -1. How can I convert it to this format?
The buffer is a one dimensional array of float values (rgba). The array holds the pixels of an image where the pixels are ordered row by row. The first four floats are the first pixel of the first row. The second group of four floats represents the second pixel of the first row and so on.
I have attempted to use gui.new_texture() function but it wants the buffer as a string and I still cannot separate the hexadecimal value to individual r g b values. Can you help me with that?