Create shader that draws a grid

I’m new to the whole GL ES thing and have a question about how to create a grid using shaders only since I’m playing around with them at the moment I want to use this seemingly static grid as the base of a game.

The inputs I need are just the number of divisions for the screen, so something I’d usually do like this

local cols = WIDTH / 25
local rows = HEIGHT / 25

This gives me the cells size and the right number of columns and what not, how would I achieve making a grid with shaders only?

To be clear, I just want the grid lines; I plan to fill the cells with touch and using the Lua side of things.

If shaders here work like shaders I’ve written in the past, a shader outputs a single pixel at a time.

So what you’d need to do is get the screen coordinate of each pixel, check its dimension, and output a color if the x and y value are both divisible by your grid size.

Here’s a discussion about a similar issue over on Maybe that can give you some ideas:

I don’t see why a shader would be the most efficient answer. It’s not really designed for that.

What I would do is create a new image, then use setContext to draw all the lines for the whole grid onto it, as part of setup, so now you have an image containing the grid and you can just sprite it on the screen on every draw. This means you only need to draw the grid lines once.

Here’s a quick fragment sample to get you started.

// Grid shader

//Default precision qualifier
precision highp float;

//This represents the current texture on the mesh
uniform lowp sampler2D texture;

//The interpolated vertex color for this fragment
varying lowp vec4 vColor;

//The interpolated texture coordinate for this fragment
varying highp vec2 vTexCoord;

void main()
    //Sample the texture at the interpolated coordinate
    lowp vec4 col = texture2D( texture, vTexCoord ) * vColor;

    float x,y;

    // Draw a black and white grid.
    if(x > 0.9 || y > 0.9) {
        gl_FragColor = vec4(1,1,1,1);
        gl_FragColor = vec4(0,0,0,0);

@Ignatz your solution is good, too. That’s what I was going to suggest, until I thought about using this on a 3D object… and then I realized I just wanted to try it myself…

I like that Codea supports shaders. I’m going to use this for my next project.

I’ve been collecting shaders, mostly pretty simple ones that can create nice effects. My favourite is one of spacemonkey’s, that helps you tile a texture across an irregular shape or a large area using minimal triangles. I described it here

If you have any interesting shaders, please share! :smiley: