Passing int array to fragment shader - arrays

I'm attempting to plot an iterative function in OpenGL ES. An array of ints is being updated with how often a given pixel is hit by the iterative function. I'd like to pass this density array to a fragment shader and use it to plot the result on a simple quad covering the whole screen.
My question is: can I pass this array directly to the shader as a uniform and generate pixels by using gl_FragCoord to look up the density for the given position
or
should I rather use the array to create a texture with one channel using GL_LUMINANCE and pass that to the shader?

You have a limited number of uniforms available, and the indexing might be troubling since not all GPUs support non-constant indexing. A 2D Nx1 texture doesn't have any of these issues but will return values into the [0, 1] range. You can scale back this values to obtain the original integer and use it.

Related

How to pass variable length float array to GPUImageFilter Shader?

I want to pass my touch points to GPUImage (iOS)
The Point can be translate to float array, the length of the array is variable length.
But I must direct the length of array in shader.
Disclaimer: not a glsl expert
AFAIk you can't have variable length arrays like what you want. This is a GLSL limitation, not GPUImage so it's not a quick fix- the work you'll be doing will be with textures or glsl, not GPUImage.
Here's another stack overflow post about glsl: GLSL indexing into uniform array with variable length
There's two solutions that could work:
1) Limit the number of points. It's reasonable to limit touches but in practice may be hard to narrow them down if there's too many. You could pass these points in to a fixed length array or as individual constants (one for each point). If you really care about scalability with the number of points this isn't a great method because in your shader you'll have to do check each of these points and perform the relevant computation, which could be expensive when performed for the entire image (again, depending on your use case). If for each pixel you're checking a distance to point, this could be too expensive.
2) Input your points in a texture. You can either have 2 1D textures with the x&y coordinates and then treat them like an array (then go to option 1), or you can create a 2D texture, all 0, and set parts to 1 where there are touches. The 2D texture can have a lower resolution than the actual screen. This method could be a lot less work for the shader if you're doing something simple like turning finger touches black.
Your choice depends largely on what you're doing with the points in the shader.

GLSL indexing into uniform array with variable length

I am passing an uniform array to geometry shader and want to index into it using a variable. I can use variable length array & index with fixed number (numeric constant) OR I can define a fixed length array & index using varible. However I can't index into variable length array using a variable.
Below is pseudo code for geometry shader with cases that work & case that doesn't work
This works:
uniform vec2 dimensions[2];
// some code which computes index which is an int
float dimX = dimensions[index].x;
This works:
uniform vec2 dimensions[];
// some code which computes index which is an int
float dimX = dimensions[0].x;
This doesn't work:
uniform vec2 dimensions[];
// some code which computes index which is an int
float dimX = dimensions[index].x;
Is it possible to do something like this?
Sadly, no this is not possible. You did not include the GLSL version you are targeting but did mention geometry shaders, so I have included the relevant part of the GLSL 1.5 spec. below:
GLSL Specification (Version 1.5) - 4.1.9 Arrays - pp. 25.
Variables of the same type can be aggregated into arrays by declaring a name followed by brackets ( [ ] ) enclosing an optional size. When an array size is specified in a declaration, it must be an integral constant expression (see Section 4.3.3 “Constant Expressions” ) greater than zero. If an array is indexed with an expression that is not an integral constant expression, or if an array is passed as an argument to a function, then its size must be declared before any such use.
While desktop GLSL is much more forgiving when it comes to indexing arrays with non-const expressions than GLSL ES, you still have to work within some limitations. The same way that texture lookups are often used to overcome non-const array indexing in OpenGL ES, you may be able to work around this by using a 1D texture lookup in your geometry shader. I have to wonder if you really need this functionality that badly though?
It is a good idea to define an upper limit to your uniform array anyway, because the GLSL spec. only requires an implementation provide 1024 uniform components (e.g. 1024 float, 256 vec4, 64 mat4 or some combination of each) in the geometry shader stage. If your array has a known maximum size at compile time you can avoid trouble later down the road associated with unknowingly exceeding this limitation.
UPDATE:
Since you mentioned GLSL 4.x, I would like to point out a newer feature in OpenGL known as Shader Storage Buffer Objects. Using SSBOs, it may be possible to use an array with dynamic length at run-time for your purposes. You can query the length of an SSBO using .length () in the shader, and handle range validation yourself. However, I think this is probably overkill but worth mentioning nevertheless.

Passing varying array from vertex to geometry shader on Mac

I'd like to be able to pass an arbitrary number of varying values per vertex from the vertex shader to the geometry shader. I know that OpenGL has no dynamic arrays, so the number should be specified at compile time. The whole thing should run on an Apple MacBook with a NVIDIA GeForce 9400M graphics card and a driver that only offers OpenGL 2.1, along with some extensions.
The problem here seems to be that the geometry shader takes its input in the form or an array with one element per vertex. As far as I can tell, there are no arrays of arrays available in my setup, and no arrays of interface blocks containing arrays either. So far, the best solution I could come up with is specifying a number of variables to pass this information, extracted from an array in the vertex shader and turned back into an array with a certain stride length in the geometry shader. That way, access to the values can still be performed using computed indices.
Is there a better, more elegant way?
From EXT_geometry_shader4 specification:
User-defined varying variables can be declared as arrays in the
vertex shader. This means that those, on input to the geometry shader,
must be declared as two-dimensional arrays. See sections 4.3.6 and 7.6 of
the OpenGL Shading Language Specification for more information.
For example, in the vertex shader, you may specify
varying vec2 value[2];
and in the geometry shader, this becomes a two-dimensional array, e.g. with triangles as input primitives
varying in vec2 value[3][2];
Note the counterintuitive order of array indices! Also beware that the array dimensions must be specified explicitly, using an integer constant. Using a non-constant integer variable or gl_VerticesIn yields a compiler error. Both remarks have been tested on the very MacBook Pro model mentioned in the question.
There are reasons why core OpenGL's geometry shaders don't work the way EXT_geometry_shader4 does. This is one of them. EXT_geometry_shader4 doesn't allow arrays of inputs because that would mean allowing arrays of arrays of values. And GLSL can't handle that (well, until recently, but that's only 2 months old).
Interface blocks can have arrays in them. Your problem is that GLSL 1.20 doesn't have interface blocks.
There's not much you can do besides use different variables and manually unroll all your loops. You could write a function that takes an integer value and conditionally returns one of the different values that correspond to that index, but that's about the best you're going to get with old-school GLSL.

What does glDrawElements() expect the normals array to contain?

I'm writing a decoder for MilkShape 3D models.
I load the contents to a vertex array and a face index array (as std::vector), then use glDrawElements() to render it, so far so good.
But the problem is with the normals array. In what order does OpenGL expect the normals? The MilkShape 3D file contains three float[3] normals which are the same, following the face (triangle) indices. But if I simply push_back() what I read into the normals array, OpenGL won't apply lighting correctly.
So I think I'm messing up the order. How to do it right?
Thanks for reading.
OpenGL assumes the normals being indexed the very same like the vertex positions. One must understand, that a vertex itself is a vector of attribute vectors, or in other words a vector of all the attribute values (position, normal, colour, texture coordinate(s), etc.). The glDrawElements index array addresses the array of vertices, where each vertex is such a higher dimensional vector.
Now what could happen is, that Milkshape mixes the face winding and gives you normals of which some have been flipped into the opposite direction (inwards instead of outwards). I don't know about how it's done in Milkshape, but in Blender there is a function "Recalculate Normals" (accessed by CTRL+N hotkey), that fixes this.
If you don't want to fix the normals, you must enable double sided lighting (this has a performance impact).
glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE);
What you describe sounds like MilkShape3D gives you per-face normals. OpenGL expects per-vertex normals.
So you need to process your data to generate per-vertex from per-face. There's a lot of literature on the web for this, one hit on Google gives this.
I was indeed messing up the order of the normals.
A MilkShape 3D model file structure can be approximated as:
vertex list, float[3]
vertex index list as short[3] for the triangles + 3 normals as float[3] each
You need to load the normals at normals[currentFace.index123]. In plain English, the normals' indices from the normals array must correspond to the vertex indices from the vertices array.

Image/2D array resampling in C

I am looking to implement a resampling algorithm for a 2D array(it could be grayscale image or some 2D array of floating point values).
The steps involved in this particular operation are:
Given a 2D array, I first downsample it to size of 8x8 or 16x16, using some down-sampling method(preferably with a preceeding anti-aliasing filtering).
Some nuemrical operation on this.
Then upsample it back to its original size by doing, bilinear interpolation.
As a prototype I coded it as shown below in Octave. It gives decent results. I am looking to get some reference on C implementation.
fid = fopen("anti_vig_gain_map.txt","r");
fid2 = fopen("ds_us_anti_vig_gain_map.txt","w");
for i=1:1968
for j=1:2592
map(i,j) = fscanf(fid,'%f\n',1);
end
end
%downsample
ds_map = imresize(map,[8 8],'linear');
%% some processing on ds_map
%upsample
us_map = imresize(ds_map,[1968 2592],'linear');
I tried to see the code in imresize.m but it gets complicated after sometime and could not extract C code out of it.
Any pointers to reference C code for bilinear interpolation to perform the upsampling.
Also looking to get some pointers for the the anti-aliasing filter and down-sampling method using bilinear method.
I think what you are looking for is contained in the NetPBM suite. Specifically, pamscale which handles both up and down sampling with multiple possible filtering schemes for both directions. The code is both well-written and self-contained.

Resources