Img:set in Codea4

In Codea4 how does one do the equivalent of img:set(i,j,thiscol) in Codea3?

@John is there an img:set or equivalent in codea v4?

Sorry, I missed this question. There is but it works a little differently than in V3

You have img:setPixel(x, y, color) and img:setPixel(x, y, r, g, b, a) as well as img:setValue(x, y, r, g, b, a)

Why the distinction between setPixel() and setValue()? setPixel() assumes values are between 0 and 255 while setValue() just sets the data directly. To better match how modern GPUs work and to simplify the engine, you need to call img:apply() when you are finished setting values on your image to have them show up. You can also use img:readback() to get data back so you can use getPixel(x, y) and getValue(x, y) on the latest data. You can also use:

-- Modern
-- Create a random noise image using image:setForEach()

function setup()
    img = image(255, 255)
    img:setForEach(function(x, y)
        return math.random(), math.random(), math.random(), 1

function draw()
    background(40, 40, 50)
    sprite(img, WIDTH/2, HEIGHT/2)

And here’s an example of reading back some image data generated by a shader:

-- Modern

function setup()
   print("Hello World!")
   -- The code below is a bit of overkill but I wanted some noise values
   img = image(512, 512)
      -- Use a shader to draw noise values to the image
      :include "codea/noise/noise.glsl" -- include built-in GPU noise library
         float n = Perlin2D(getUV0() * 10) * 0.5 + 0.5;
         material.baseColor = vec4(n, n, n, 1);
   img:readback(true) -- use true to perform readback immediately (normally it takes a frame)
   print(img:getValue(255, 255))

function draw()
    background(40, 40, 50)
    sprite(img, WIDTH/2, HEIGHT/2)    

Why is it so different? The use of apply and readback is an attempt to reflect what’s actually going on. The V3 version kept causing problems as it tries to automatically transfer data back and forth based on the use of set and get functions. This ended up causing several scenarios where users would cause huge performance hits without realising it since they didn’t know that reading and writing data to the GPU requires the entire image to be sent back and forth each time

1 Like

@John - thanks for the info. I’ve used the V3 version to build points/pixels into an image then used the image as a sprite. Didn’t ever think of using it in any form of animation, thought it would be too hard on the pad hardware.

Looks like in V4 it will be more powerful - does this require metal?

Thanks again.

@John thanks that works.

@John are you sure the texture is mapped correctly to a sphere? There is a black line at the join of the left and right edges of the texture.

Actually, in v3 it didn’t work correctly either with the native spheres. I was obliged to use @LoopSpace ’s pseudomodel sphere to get a correct wrapping.