# Question
Title: How do I reuse the same vertex data, but with different colors, for my sphere objects?
I'm using OpenGL to display a 3D network, with nodes represented as spheres (I haven't gotten to edges yet). I'm a total novice, and having a bit of trouble wrapping my head around OpenGL.

These networks need to be generated programmatically, so I've got a function that produces vertices for a sphere with radius 1 centred at the origin, and I'm translating and scaling it to produce each of the nodes in the network. I'm using `glDrawElements()` to draw my nodes, so I'm storing indices for the vertices of my sphere as well.

Once a network is produced, it doesn't change. The camera position can change, but nothing else will. My current strategy is the following:

* When a network is generated, for each node, make a copy of the unit sphere, and apply the appropriate translation * scale matrix. Store all of the vertices (and associated colours) in a single array/VBO.
* When drawing, set the scene-to-camera and perspective matrices to a uniform, then use a single `glDrawElements()` call to draw all my nodes.

So a couple of questions about this:

1. Since all my nodes are essentially identical, I could just store vertices for one sphere, and transform the sphere on the fly when I render the scene. There might be a lot of nodes, so this could save substantial memory. But each sphere has quite a different set of colours... is there a way to tell OpenGL to use an offset for the colour data but not the vertex data?
2. Assuming the answer to part 1 is no, would it be better to keep vertices for a single sphere in my VBO, and then substitute the colour data and draw each node with a separate call to `glDrawElements()`? Or is there some other solution that I'm not thinking of?

# Answer
You have several options.

* You don't need to use interleaved buffers (where the positions, normals, colors, et cetera are all in one buffer separated by `stride` bytes). When you specify vertex data (specifically when making calls to `glVertexAttribPointer`), you can specify distinct buffers for each attribute. So you could have one buffer for positions, and other buffers for all your colors, and you can enable or disable them as needed.
* You could use instancing, passing the color data as per-instance data rather than shared data.
* You could eschew storing the color data in the vertex buffer at all. After all, if it's just a flat color per vertex, that's a lot of redundancy itself. Instead, pass a shader uniform into your shader that defines the color of the sphere when rendered, and use that color in the fragment shader.

I would recommend the last approach. This way, you create one vertex buffer defining your sphere positions relative to the origin in model space. You can render this buffer many times, setting a different world transformation matrix (which is itself just a shader uniform) as well as a different appropriate color. The world transformation matrix is how you position each sphere in the world, and the color is obviously what controls the color value.

This way you only have a single copy of the geometry (which itself does not contain a lot of redundant extra bytes to specify color data, unless you really need multi-colored spheres), you have support for uniquely coloring each node in your network, and you let the GPU do the transformation work it's designed to do rather than doing it yourself CPU-side.
> 2 votes

---
Tags: opengl
---


# Question
Title: Side scroller terrain generating and scrolling
I am creating a side scroller game for android devices but I encountered a problem. The game looks like this:

The black dot is a player. Player's x doesn't change, only the y does. When the player collides with the green terrain the game is over.

I have a problem with how should I handle a map storing and drawing. What I did is store the level file in a large png file (like 1k px height and 20k px width), same with the collision mask (basically the same file but with black colored collision terrain). I guess this approach isn't to good beacuse I was getting the out of memory exceptions due to large bitmap on some devices. I've learned that some people use tile based maps but with this sinusoidal map it could be to hard for me to do small tiles and collsion masks for them. I want the map to be as long as possible and if it's possible random-generated but I don't know what's the best approach to do this with this kind of terrain and how to handle pixel perfect collisions when doing so.

# Answer
> 14 votes
You should definelty use multiple smaller images. However, smaller images doesn't necessarily means something like this:

<sub>(source: refrag.com)</sub>

You can just have few map parts that fit together nicely. When the player arrives in a new zone you check the collision for this new part. For example you have tiles like this (they can/should be larger):

```
1     2       3        4           5

```

Your goal is to make them in such a way that the end of one correspond to the beginning of multiple ones. Then, in your game you create the map by putting side by side different tiles. You can mix them randomly as long as one's end fits with the other one's beginning

Here is an example of map that is bigger in total than the images I used.

Without spaces

With spaces to see the tiles

```
1     1     2      3          4            4            5      2

```

It doesn't work perfectly here, but the idea is that tiling isn't just 32x32px squares.

# Answer
> 9 votes
**Disclaimer**: If you want to expand the road with more complex imagery - using detailed textures etc - then the following technique isn't very straight forward, but if it's as simple as the example image then this technique is an option. It seemed worth mentioning should anyone else have a similar problem.

## Raster Roads

Although your specific game runs right to left, consider the following method which demonstrates how to create those old style pseudo-3d racing tracks;

Although not directly what you are after, the principles are the same; describe the road line by line stating it's position/size. You can loop the array rather than have a goal to make it endless.

The principles of this technique can be used to index chunks of terrain types instead of describing just a single pixel width line on the screen.

As you don't require pseudo-3d, you can skip the parts in the tutorial relating to distance relative scaling, but you could do something similar to narrow the road.

Collision detection with this technique is also rather simple, you check the players y position against the line which corresponds to the players x (usually you have a linear mapping from x position to array index, but it depends on what proportion of the x-axis one array element represents).

# Answer
> 8 votes
## Generation

For generating a world, I recommend the Perlin noise algorithm. I'm sure there are dozens of good tutorials and explanations elsewhere on the internet, so I won't go into detail here. There is a less well-known noise generation algorithm, Simplex noise, that is better than Perlin noise, but you are less likely to find a tutorial about that for Android. The advantage Perlin noise has over many other generation methods is that each column is generated independently of the others, so you can generate the column only when you need it.

## Storing

So you have used your generation algorithm to make a world like this (except a lot bigger than 10x20):

```
██▀▀▀▀▀████████▀▀▀██
▀          ▀▀

      ▄███████▄▄▄
█▄▄▄████████████████

```

Look at the first column:

```
█
▀

█

```

By storing it as a basic image, you would need a color for each of the ten pixels. Assuming the image format doesn't support an alpha channel, a color is 24 bits, so a list of ten colors is 240 bits.

```
(0,  0,  0)
(0,  0,  0)
(0,  0,  0)
(255,255,255)
(255,255,255)
(255,255,255)
(255,255,255)
(255,255,255)
(0,  0,  0)
(0,  0,  0)

```

Expand that to 1000 pixels tall, and you're using 24,000 bits per column. There are 20,000 columns, so that's 480,000,000 bits or **60,000,000 bytes**. You were trying to load about 57 megabytes at once.

Now, what if you just stored it as a bunch of bits, one bit per pixel? Ten pixels would be 10 bits.

```
1110000011

```

Expand that out to the entire map and you get 20,000,000 bits or **2,500,000 bytes**.

But you can still store it with far less memory. There are only two places where it changes between 1s and 0s, so you could store that like this:

```
3, 8

```

If you give each number 10 bits to be able to store values up to 1,000, that's 20 bits per column. Multiply that for all the columns, and that's only 400,000 bits or **50,000 bytes** to store the entire map.

However, you don't need to store the entire map in RAM; you can load/generate only the part of the map you need a second before you need it. Assuming you have a 1000 pixel wide screen and you pre-load/-generate another 1000, that's 2000 columns loaded at once. 2,000 x 20 bits is 40,000 bits, or only **5,000 bytes** stored on RAM at once. That is less than a ten-thousandth of what you were trying to store originally.

---

## Collision detection

To detect if the player has collided with a wall, look at it column by column. Take the leftmost column that the player is still a part of, i.e. this one:

```
  ↓
██▀█▀▀▀████████▀▀▀██
▀          ▀▀
  ▄▄
  ▀▀  ▄███████▄▄▄
█▄▄▄████████████████

```

Check whether the top pixel of the player:

```
 ▀

→▄
 ▀
 ▄

```

is above the first value stored in the map, which would be about here:

```
→▀

 ▄
 ▀
 ▄

```

If it is (which it isn't in this case), you have a collision. Next, do the same for the bottom:

```
 ▀

 ▄
→▀
→▄

```

No collision there, either. Do the same for the rest of the columns the player is a part of. If the player's top pixel is ever above the first value for that column or the bottom pixel is ever below the second value, you know you have a collision.

# Answer
> 1 votes
One approach could be that you split the big bitmap up in chunks along the y-axis, and show/hide the appropriate chunk when they go in/out of screen. This might also of course also cause the problem you mentioned with too large bitmaps on certain hardware, but is well worth checking out.

https://stackoverflow.com/questions/22471655/what-will-be-the-best-approach-implementing-infinite-repeating-scrolling-world-i

Another approach that will be much more easy on your disk usage is to procedurally generate the world. You "simply" draw the outline of the ground and the roof in your editor of choise, and use this as input to an algorithm that produces ground.

http://www.iforce2d.net/blog/2013-07-20

---
Tags: android, side-scroller
---


# Question
Title: Getting access violation because of ID3D11Buffer
I try to create a simple class store my model variables vertex array and vertexbuffer. So I create an array of myclass to create and manage object dynamically. But when

```
 hr = g_pd3dDevice->CreateBuffer( &bd, &InitData, &pieces[counter].g_pVertexBuffer);

```

this line run I get the error "Access violation reading location". I try to many things but I never success. If I don't use class and array I don't get this error. Porgram runs without error.

MyClass:

```
class Piece
{
public:
  double positionX, positionZ,
    red, green,blue;
  bool renderable;
  int type, color, vertexCount;
  XMMATRIX g_WorldPieces;
  ID3D11Buffer* g_pVertexBuffer;
  SimpleVertex* vertices;
  Piece();
  void create(int, int, double, double);
};
Piece::Piece()
{
   g_pVertexBuffer = NULL;
}
 void Piece::create(int t, int c, double pX, double pZ)
{
   g_pVertexBuffer = NULL;
   renderable = true;
   type = t;
   color = c;
   red=green=blue=0.0f;
   if(color == 1)
     red=green=blue=1.0f;
   positionX = pX;
   positionZ = pZ;
   vertexCount = 0;
}

  Piece *pieces;//Global variable which define after defining "ID3D11Device*                       g_pd3dDevice = NULL"

```

and using objects of myclass:

```
for(int x=0;x<4;x++)
{
if(x==2)
{
    c=0;
    positionZ = 12.5;
}

for(int y=0;y<8;y++)
{
    pieces[counter].create(typeArray[x][y],c,positionX,positionZ);
    positionX += 5;
    switch(pieces[counter].type)
    {
         //Switching object txt. All cases and breaks are fine.
    }
    fin >> pieces[counter].vertexCount;
    pieces[counter].vertices = new SimpleVertex[vertexCount];
    for(int i=0; i<vertexCountpiyon; i++)
    {
        fin >> pieces[counter].vertices[i].Pos.x >> pieces[counter].vertices[i].Pos.y >> pieces[counter].vertices[i].Pos.z;
        fin >> pieces[counter].vertices[i].Tex.x >> pieces[counter].vertices[i].Tex.y;
        fin >> pieces[counter].vertices[i].Normal.x >> pieces[counter].vertices[i].Normal.y >> pieces[counter].vertices[i].Normal.z;
    }
    fin.close();
    bd.ByteWidth = sizeof( SimpleVertex ) *pieces[counter].vertexCount;
    ZeroMemory( &InitData, sizeof(InitData) );
    InitData.pSysMem = pieces[counter].vertices;
    hr = g_pd3dDevice->CreateBuffer( &bd, &InitData, &pieces[counter].g_pVertexBuffer);//THIS LINE IS MY PROBLEM!
    if( FAILED( hr ) )     return hr;
    counter++;
}
positionX = -17.5;
positionZ += 5;
}

```

When I get access violation counter is 0.

Source code of my project: http://1drv.ms/1nKdoUf

# Answer
> 1 votes
You problem is that you are trying to create a vertex buffer with invalid initial data because you have actually no vertices in your array.

```
for(int i=0; i<vertexCountpiyon; i++)

```

If you inspect this loop (line 748 in your code) then you see that it is not entered by the program because *vertexCountpiyon* variable is zero. So your vertex array is not filled and you are trying to read from it that's why you get an access violation error. (Please note that debugging your code questions is usually not warmly welcome on this site, this time you got lucky I guess :) )

---
Tags: directx, directx11, vertex-arrays
---


# Question
Title: How can I find the valid words in a grid of characters?
I am creating a game similar to Tetris, with two main differences: the screen already begins filled with tiles (like in Puzzle Quest for Nintendo DS and PC) and each individual tile has a letter in it. The player's objective is to eliminate tiles by forming valid words with them. Words are formed by placing letters next to each other, in any direction, except diagonally.

The player can move an entire row of tiles to the left or to the right or an entire column of tiles up or down, for as many spaces as he desires (if the movement of a row/column surpasses the limits of the board, the letter that crosses the limit will "cycle", appearing at the other end of the row/column). After the player's action, the game should check the entire board to look for valid words and remove the letters that form those words from the board. The letters above those that were removed will fall down in the place of those letters that were removed and new letters will drop from the top of the screen until the board is filled up again.

I have already written a linear algorithm that, given a sequence of characters, determines if it is a valid english word. The problem I am having is: how can I check for valid words on the board? Is brute force the only way? Testing all possible combinations from the board to see if they are valid is very slow, even for a small (5x5) board. Any help will be very appreciated, thanks!

# Answer
> 22 votes
Brute force is not the only way.

Solving your game board is similar to solving a Boggle board, except simpler. You want to check every tile in the board, looking to see if there are any words that can be made along the appropriate directions.

You'd still like to refine your search space further so you don't bother searching along a direction if you know you can't make a word. For example, if you find two `q`s in a row, you should abort. To that end, you'll want some kind of data structure that allows you to tell if a given set of characters is a prefix of a valid word. For this, you can use a trie, or prefix tree; a useful data structure when solving problems like this.

A prefix tree is a hierarchical node-based structure, where every node represents some prefix of its children, and the leaf nodes (generally) represent the final values. For example, if your dictionary of valid words contains "cat," "car," and "cell," a trie might look like:

```
    0        The root of the trie is the empty string here, although you
    |        can implement the structure differently if you want.
    c
   / \
  a   e
 / \   \
t  r    l
         \
          l

```

Thus, begin by filling a prefix tree with every valid word in your game.

The actual process of finding valid words on the board at any given time will involve starting a recursive search from each tile on the board. Because each search through the board space starting at some given tile is independent, these can be parallelized if needed. As you search, you "follow" the prefix tree based on the value of the letter in the direction you are searching.

You will eventually reach a point where none of the surrounding letters are children of your current prefix tree node. When you reach that point, if it is also true that the current node is a leaf, you have found a valid word. Otherwise, you have not found a valid word and you may abort the search.

Example code and a discussion of this technique (and others, such as a dynamic programming solution that can be even faster by "inverting" the search space after a fashion) can be found on this fellow's blog here; he discusses solving Boggle, but adapting the solutions to your game is more or less a matter of changing which directions you allow searching to occur in.

# Answer
> 3 votes
You might have tried this, already implemented this, maybe better accompanied by another answer, etc. But I didn't see them mentioned (yet), so here it is:

You can discard a lot of the checks by keeping track of what changed and what didn't. For example:

```
On a 5x5 field, A vertical word is found on base of the third column,
All the rows change. However, the first, second, fourth, and fifth,
columns do not change, so you dont need to worry about them (the third did change.)

On a 5x5 field, A 3 letter word is found horizontally on row 2, column 3, to column 5.
So you need to check row 1 and 2 (row 1 because the words on that one
fell down and where replaced), as-well as columns 3, 4, and 5.

```

or, in psudo code

```
// update the board

// and check
if (vertical_word)
{
    check(updated_column)

    for (i in range 0 to updated_row_base)
        check(i)
}
else // horizontal word
{
    for (i in range 0 to updated_row)
        check(i)

    for (i in range 0 to updated_column_start)
        check(i)

    for (i in range updated_column_end+1 to final_column)
        check(i)
}

```

And the trivial questions:

Do you have the compilers speed optimizations set? (if your using one)

Can your word searching algorithm be optimized at all? In any way?

# Answer
> 2 votes
Remember that every character is a value. So use that to your advantage. There are some hash functions that could be computed quickly when iterating on substrings. For instance, lets say we give every letter a 5 bit code (just do `c - 'a' + 1` in C):

```
space = 00000;
a = 00001;
c = 00011;
e = 00101;
t = 01100;

```

Than you could quickly run over all substrings of a certain size:

```
a b [c a t] e t h e = 00011 00001 01100;
//Now we just remove the 5 msb and shfit the rest 5 bits left and add the new character.
a b  c [a t e] t h e = (([c a t] & 0xffff) << 5) | e; // == a t e

```

We can check substrings up to 12 letters this way on most common architectures today.

If a hash code exists in your dictionary you can pull the word from there quickly cause hash codes like this are unique. When you reach the max of 12 letters, you may wish to add another data structures for words starting with those 12 letters. If you find a word that starts with a specific 12 letters than simply create a list or another tiny hash table for the suffixes of each word that starts with that prefix.

Storing a dictionary of all existing word codes should not take more than a few megabytes of memory.

# Answer
> 0 votes
Are you limited only to the classical Tetris shapes when forming words, or will any formation do? Can words bend indefinitely or only once? Can a word be as long as it wants? This get's quite complex if you can do as many bends as you like, effectively making the longest possible words 25 characters long. I would assume you have a list of accepted words. On that assumption I suggest you try something like this:

```
At the start of the game:
  Iterate tiles:
    Use tile as starting letter
      Store previous tile
      Check the four adjacent tiles
      If a tile can continue a word started by the previous tile, carry on
      Store the next tile
      Move check to next tile

```

This will create a map on each tile with information how this tile is connected to words around it in the grid. When a column or row is moved check all tiles that has been, or is adjacent to the movement and recalculate the information. When you find a word, and no more tiles can be added to that word; remove it. I'm not sure if this will be faster, it really boils down to how many words are half created. The benefit to this is that the user is most likely trying to create a word from a half complete word on the board. By keeping all these words stored, it is easy to check if a word has been completed.

---
Tags: game-design
---


title: Convert triangles to quads of a Mesh

text:
# Question
Title: Convert triangles to quads of a Mesh
Supposing I have applied delaunay triangulation on a convex mesh, and I have all information (edges, vertices etc.) I would like to transform the triangles to quads

I was reading that inverse process, quad to triangle, one takes the vertices like:

```
quad 1 2 3 4
==>
triangle 1 2 3
triangle 3 4 1

```

each time we read a quad (4 vertices), we transform it to 2 triangles using these 4 vertices.

What would be the best approach to do triangles to quad?

I was thinking on pairing together adjacent triangular elements, and converting them into quadrilateral elements by eliminating their shared edges

Do you know any sample code, would be best in c#

# Answer
> 1 votes
Any 2 triangles that share an edge and have identical normals (or are very close) can be candidates for turning into a quad. The pseudo code for something like this would be: `List triangleList;
List quadList;`

`foreach(Triangle currentTriangle in triangleList)
{
 foreach(Triangle checkTriangle in triangleList)
 {
 if (currentTriangle != checkTriangle &&
 currentTriangle.sharesEdge(checkTriangle) == true &&
 currentTriangle.normal.dotProduct(checkTriangle.normal) > 0.99)
 {
 quadList.add(makeQuad(currentTriangle, checkTriangle));
 triangleList.remove(currentTriangle);
 triangleList.remove(checkTriangle);
 break;
 }
 }
}`

This solution wouldn't give you the ideal list of quads, but it will be good enough in most cases. Where this solution would give a less than ideal solution would be in the case below:

I've numbered the triangles here. Assuming they are all co-planar, you could certainly end up with a quad consisting of triangles 2 & 3, and then 2 triangles that can't be turned into quads with 1 & 4. The ideal solution of course would be 1 & 2 being a quad and 3 & 4 being another quad. I haven't done the math to prove it, but I think your worst case would be in a completely flat plane, you could end up with half quads and half triangles when the whole thing could be quads. Either way, it's a difficult problem to solve and the performance implications are likely to be negligible, so it's probably best to not bother optimizing.

---
Tags: c#, 3d-meshes
---


# Question
Title: Achieving a fixed frame-rate with varying scenes
I am working on an OpenGL 3D model viewer app for iOS.

I have to load, view and navigate extra detailled 3D models on an iPad. I hardly achieve 2 fps, if i load and navigate a very complex model. I tried some optimizations like view-frustum-culling, area in pixel space, back-face-culling etc but still i am unable to improve the frame rate.

I would like to set fixed frame-rate to some X fps for my app and drop-out all the objects which don't have enough time to render at run-time. I would like to know if there is any algorithm to achieve this fixed frame-rate. I would appreciate any ideas.

# Answer
> 1 votes
The idea of dropping objects that do not have enough time is a very bad idea for an object viewer. Different devices (such as older hardware or different performance settings) will render your object differently and you'll never be able to view the complete object.

In games, there is often not enough time to do things completely on one frame, and the common solution for your problem is to time-slice the rendering.

What that that means in pseudo-code is the following:

```
while(running)
{
    if (cameraMoved())
    {
        clear();
        modelToDraw.resetVertices();
    }

    frameTimer.start()
    do
    {
        meshData = modelToDraw.selectNextVertices(10000);
        draw(meshData);
    } while (frameTimer.elapsed() < maxFrameTime);
}

```

Basically you don't clear your buffers and just render blocks of 10000 vertices until the frame timer runs out. On the next frame you just keep on rendering until you have drawn all vertices and the object is complete.

As soon as the current scene is invalidated (in the pseudo code this happens when the camera moves, but it might as well happen if you change any rendering setting (such as light properties, object location, etc.)), you clear the buffers and start rendering from the first 10000 vertices again.

This time slicing algorithm is demonstrated nicely in the Brigade Path Tracing engine: The longer the camera stays still, the better the correct solution is approximated. As soon as the camera moves, the buffers are cleared and the rendering starts anew.

A further improvement could be importance sampling: select the vertices that are the most important first. Split up the model in sections (using some space partitioning scheme such as an octree) and select the nodes that are the closest to the camera first, so that the most important vertices are drawn first.

# Answer
> 0 votes
Basically, what you're most likely looking for and what I'd try as well would be something like this:

```
while (running) {
    clear();

    timer_start();

    for_each(stuff in stuff_to_draw) {
        draw(stuff);
        if (timer_elapsed() > frame_time)
            break;
    }

    display();
}

```

In this example, `stuff_to_draw` would be sorted by priority (and possibly distance). `frame_time` would be the time allowed per frame (leaving some room for final processing of the scene).

As an alternative, you could just adjust your level of detail or drawing distance based on the framerate, i.e. the higher the framerate, the further you draw your scene:

```
while (running) {
    clear();

    timer_start();

    for_each(stuff in stuff_to_draw) {
        draw(stuff);
    }

    if (timer_elapsed() > frame_time)
        reduce_drawing_distance();
    else
        increase_drawing_distance();

    display();
}

```

---
Tags: opengl, 3d, models, frame-rate
---


title: DepthStencilView and alphaBlendState

text:
# Question
Title: DepthStencilView and alphaBlendState
I have create a 2D game with directx11 and i want to use a depth buffer instead of a painter's algorithm to draw the sprites but i have a problem since i'm not really good with directx 3d programming. I can create a depthstencilview and it works but look at the following image: the darker circle is not a semi-circle, they use the same texture and the same mesh: a quad. First i render the light red circle( with 0.5 depth) and then the darker one(1.0f depth). the alpha pixels of the first subscribe the depth buffer so the second isn't displayed correctly. I need aplha pixels don't subscribe depth buffer I can i set depth stencil / alpha blend state to do this?

Sorry for the bad english

# Answer
> 1 votes
If you draw your upper circle first you are blending the quad with the background color not the other circle (because it was not drawn yet). For a 2D game you are most likely better off using painter's algorithm. Depth buffer is usually used with 3D geometry where we can't determine a correct sorting between polygons and this way one has to use some nasty tricks to display transparent geometry (which always result in either quality loss or impact the performance geatly). If you are convinced that you must use depth buffer refer to my answer in a previous question like this: QUESTION

---
Tags: c++, directx, directx11, depth-buffer, alpha-blending
---


# Question
Title: Is there a tool to batch resize images to nearest power of two, on a specific side?
For example, i have multiple images with similar properties like `width = 66` and `height = 62`, i would need the resulting image to be `64x60`, keeping its ratio. is there any Gimp plugin example, or a simple and fast to use tool that already does this?

My main problem is that the art department guys sometimes save hundreds of textures with the wrong resolution, for example, 1025x1025, which occupy 4 times as much memory as a 1024x1024 image, or or 560x520, which could be scaled down to not use too much memory. I know they should be the ones doing the resizing but at this point, but i would like to quickly correct the error for the sake of the whole team.

I am using Corona SDK, and using OSX Mavericks. A relevant document about image optimization on Corona can be found here. (Nothing we do not know about, basically power of two stuff.)

I have tried ImageMagick before, but right now i already started building my own gimp plugin thanks to the examples provided below, have done 1 gimp plugin before but this will be a new challenge.

# Answer
## Gimp Script-Fu

You can batch resize images with Gimp thanks to **scripts**. You should probably look at some tutorials since it doesn't look very simple.

Here is an example of batch resize, and here is an example that keeps aspect ratio. The intro is in french, it basically means:

> Here is an example of script that resize the current image to a 600 pixels width, keeping the same ratio. The function is inserted inside a menu *created for the occasion* called "mon\_menu".
>
> To be able to work, the script has to be place inside the correct directory: `C:\Program Files\GIMP-2.0\share\gimp\2.0\scripts`. We will call it with a custom name like "custom\_name.scm".

I can't provide a ready-made script.
> 2 votes

# Answer
What I usually do when I need some very specific image manipulation (but also text, sound and pretty much anything), is to make a trivial throwaway program that does it for me.

It may sound really difficult, but it's not if you use a language and a library that lets you do stuff like that.

For example, in C# using `System.Drawing`, you can make a program that resizes an image to 64x64 (I know this is not exactly what you need. I just want to illustrate how simple it is to write a simple image manipulation program):

```
using System;
using System.Drawing;
using System.Drawing.Imaging;

static class Program
{
    [STAThread]
    static void Main()
    {
        var originalImage = (Bitmap)(Image.FromFile("original.png"));
        var convertedImage = new Bitmap(64, 64, PixelFormat.Format32bppArgb);
        using (Graphics g = Graphics.FromImage(convertedImage))
        {
            g.Clear(Color.Black);
            g.DrawImage(
                originalImage,
                new Rectangle(0, 0, 64, 64),
                new Rectangle(0, 0, originalImage.Width, originalImage.Height),
                GraphicsUnit.Pixel);
        }
        convertedImage.Save("converted.png");
    }
}

```

If you want to do it for all the images in a directory, you may want to look into `System.IO.Directory.EnumerateFiles()`. If you want to do it to the nearest power of two, you can change the way you determine the width and height, and so on.

With throwaway programs like these, you can do lots and lots of stuff.
> 1 votes

# Answer
You could use imagemagick.

For a single image:

```
convert -resize 64x60! input.png

```

To convert all image you would:

```
mogrify -resize 64x60! *.png

```

http://www.imagemagick.org/script/mogrify.php

If you want it to calculate the size on the fly you do something like this:

http://www.imagemagick.org/discourse-server/viewtopic.php?f=1&t=11979#p39254
> 1 votes

---
Tags: corona-sdk, gimp
---


# Question
Title: OpenGL - How to draw each nth triangle using glVertexAttribPointer
I have a vertex buffer. There are situations when I don't want to render the whole mesh, but let's say each nth triangle of the mesh. I am using VAOs and VBOs.

My data in the buffer is like this:

```
first triangle indx        seciond triangle indx
0 1 2   3 4 5   6 7 8    | 9 10 11   12 13 14   15 16 17 ...

```

What I want to do is - render first triangle, then skip second, then render 3d and so on. Can it be done with adjusting `glVertexAttribPointer()` or are there some other `gl` methods that can manipulate the data like that, or I have to create a new buffer with skipped triangles ?

# Answer
I have no idea why would you want to draw each n-th triangle, and I cannot imagine a situation in which you would want to do that.

...but supposing you do have a legitimate reason to do that...

I would say you can't, because `glVertexAttribPointer` is used to set the layout for the data at the *vertex* level, not the *triangle* level. In fact, OpenGL has no idea of how are you going to use the vertices inside the vertex buffer until you make a draw call.

I suppose you were thinking about playing with the `stride` parameter, but once again, `glVertexAttribPointer` works at the vertex level, so the most you can do is make triangles out of each n-th vertex, which is not what you want.

Short of creating a new vertex buffer, you can handle this when making the draw call. `glDrawArrays` takes the amount of triangles you want to draw and the offset from which you want to draw them, so you would have to do something like

```
for (int k = 0; k < totalTriangleCount; k += n)
    glDrawArrays(GL_TRIANGLES, k * 3, 3);

```

You might be tempted to think that this is a performance killer, but it's most likely not. You will most likely not be issuing an OpenGL flush on each `glDrawArrays` call, so I wouldn't say performance would drop noticeably. At least compared with creating and uploading a new vertex buffer each frame.

Now, the real question is "why would you want to do such a thing?", but we may never know...
> 2 votes

# Answer
you can step away from `glDrawArrays` and instead use `glDrawElements` and use a `GL_ELEMENT_ARRAY_BUFFER` buffer that hold the indexes of the vertexes you want to draw

the element buffer would then contain `{0,1,2,9,10,11,...}` and so on.

In you comments I see that you want this to draw a "light" object for quick updates, you can add all other triangles after the first third and draw all triangles that way
> 3 votes

---
Tags: opengl, vbo, vao
---


# Question
Title: OpenGL - What steps to take to correctly set up an Uniform Block Array
I have managed to get uniform blocks to work, but I seem to make something wrong when trying to setup an array of uniform blocks.

Assume this glsl:

```
layout(std140, binding=1) uniform LightingBlock
{
    vec4 ambient;
    vec4 diffuse;
    vec4 specular;
    vec3 factors;
    float shininess;
} lighting[3];

```

What's the exact procedure to bind this? What I am doing (and what works for a single block, not an array):

```
GenBuffer...
BindBuffer...
BindBufferRange(UNIFORM_BUFFER, 1, buffer_id, 0, size_in_bytes)
index = GetProgramResourceIndex(program_id, UNIFORM_BLOCK, "LightingBlock")
UniformBlockBinding(program_id, index, 1);

```

I read that I should replace the LightningBlock with lighting\[0\], \[1\] etc, but this only returns invalid indices. So my current attempt looks like this:

```
GenBuffer...
BindBuffer...
binding = 1
for(int i = 0; i < 3; ++i)
{
    BindBufferRange(UNIFORM_BUFFER, binding + i, buffer_id, 0, size_in_bytes)
    index = GetProgramResourceIndex(program_id, UNIFORM_BLOCK, "lighting[" + str(i) + "]")
    UniformBlockBinding(program_id, index, binding+i);
}

```

What am I doing wrong? How to do this correctly?

# Answer
> 3 votes
### As-per comments, an array of 3 structs in a Uniform Block would look like this:

```
struct Lighting {
  vec4 ambient;
  vec4 diffuse;
  vec4 specular;
  vec3 factors;
  float shininess;
};

layout(std140, binding=1) uniform LightingBlock {
  Lighting lights [3];
};

```

Now, your uniform buffer would be a contiguous array of data using the same general structure as in GLSL.

This is why alignment is important, for `std140`, an array of structs must have a size that is a multiple of `vec4` in length or GL adds padding. Having you swap `factors` and `shininess` originally avoids 3\*sizeof (float) worth of alignment padding GL would otherwise have added.

---
Tags: opengl, opentk
---


# Question
Title: Is there a penalty to using render targets versus textures?
I figured that the best way to ship 2D art for multiple resolutions is to instruct my artist to create the fullscreen background images sized for the highest resolution and then scale them down during the loading stage.

To scale them, during load, I setup a render target sized to the current resolution, SpriteBatch.Draw the assets scaled to the current resolution and then use that render target throughout the game. The render target serves as a SpriteSheet throughout the game. I only do this once (in LoadContent) and not every frame.

My question is whether or not there is a memory/performance penalty for using render targets instead of whatever the ContentManager would've set the textures as. Is there a meaningful way to measure this? Or is there a better way of doing this altogether?

# Answer
> 1 votes
There won't be an appreciable memory pressure differential using a render target texture to hold your resized images versus what the content manager would have loaded them as: it would just load them as textures, which is basically the same data.

Your alternative approach (load them at native resolution and allow the GPU to scale them down during rendering) will also work. It will consume more memory, of course, since you have larger-resolution textures loaded. It will take some non-appreciable amount of time for the GPU to downsample the textures on render, but it won't be a concern. The bigger issue is the extra memory the full-resolution images would consume.

I'd stick with your initial approach until profiling deems it necessary to adjust it.

---
Tags: xna, directx, monogame, sharpdx
---


# Question
Title: Can a UIKit application co-exist with a Unity game as a single application?
I have a typical UIKit application with three buttons - one opens an RSS feed in a `UITableView`, the second opens some kind of gallery view, and the third opens a Unity 3D game.

Is it possible and how easy it is to support both in one application?

# Answer
> 4 votes
This will be improbably difficult. Unity is not a standalone view wholly contained within a `UIView` subclass instance; if it were, this would be easy enough, you'd just add the view as a subview when you wanted to activate the Unity game and remove it when you were done (or use any number of similar `UIView` manipulation techniques).

Unity, however, expects to be the authoritative source of the application's behavior, so trying to host a Unity game within a "regular" iOS application is going to result in you fighting that behavior and spending a lot of effort for minimal gain.

You should consider implementing the behavior the other way around: have a Unity game which occasionally defers to some Objective-C based UIKit code via native plugins, which basically involves:

* creating an Xcode project or target that contains the Objective-C code for manipulating the desired `UIView` objects.
* conforming to the Unity plugin API so you have an entry point into your plugin from the rest of your Unity project.
* invoking that entry point as-needed.

If you are not keen on building all that yourself, something like the iOS bridge, or just resign yourself to building your GUI with Unity's built-in primitives.

---
Tags: unity
---


title: 'Dynamic' textures?

text:
# Question
Title: 'Dynamic' textures?
I am creating a 3D game in Unity. The main game mechanic involves a large open world area. In various places throughout this world are billboards and other devices that would show 'adverts' etc in the game.

I have several textures that I would wish to place on these billboards. The game would select a texture at random and display it for a set period of time on the surface, before choosing another - giving a similar effect to billboards in the real world. Another implementation of this could perhaps involve adverts being embedded into the game world in this way.

What is the way about this? Any help would be gratefully appreciated.

# Answer
> 1 votes
Create a texture atlas. You can do this either manually or using tools.

Once you've done so, assuming that the ads are all the same size, all you need to do is shift the UV positions, and voila, you are looking at a different ad on that billboard. This is a more efficient solution than switching textures.

---
Tags: unity, textures
---


title: Check legal movement on grid map

text:
# Question
Title: Check legal movement on grid map
i'm trying to develop a simple multiplayer turn base game, i'm start creating the grid map, i have already write the javascript script to display the range movement for the specific unit, but my problem is how to check if the grid position sent to server by the client is a valid position, i think this is a operation to do on server side (i use php) because javascript is easy editable by the user, my first throught is to save in a database each tile and its data (example: is a water tile, a forest tile...), so when the position is send to server i can read the db and check if the position is valid, but i think this method is very slow and require a lot of server resources, so there is a better way to do this? (i don't know if this is the correct site or is a question for StackOverflow)

# Answer
Your idea is not a bad solution in this case. Because your game is turn based, the amount of time it takes to do a database search shouldn't be noticeable. Because you are checking in a PHP script, which I assume is not constantly running, you can't keep the map data in memory at all times so storing it on the file system is the other solution (unless you want to use a in-memory database like Redis). If you want to ensure that the database lookup is quick...make sure the primary key is the index of the tile. To calculate the index of the tile, use the formula: `x + (y*mapWidth)` where mapWidth is the number of tiles in each row and x/y is the position of the tile in the grid. If you don't want to store the tile data per-row (I would recommend against storing each tile in a table row) you can store map data in a text blob as a comma-separated list of all the tiles, then convert that to an array and search by the index.
> 0 votes

---
Tags: javascript, html5, grid, php
---


# Question
Title: Why bother with server-side hit detection?
Valve's hit detection tracks player positions from when the bullet fired and then tells clients only whether the hit happened, but I can't see why that is necessary in the first place. Does server-side hit detection do anything but slow down the action?

What is the purpose of server-side hit detection when malicious players could cheat with an aimbot anyway?

# Answer
> 13 votes
Server-side hit detection isn't to prevent aimbots, it's to prevent cheaters who simply tell the server "I hit!" regardless of where they are aiming.

---
Tags: networking, multiplayer, anti-cheat, shooter
---


# Question
Title: Light direction not being calculated correctly
I'm trying to implement deferred lighting in my game, and have run into an issue with normals.

The image above shows the lighting being applied to a tile map. The yellow shade represents the direction of the light at that pixel. The character has a green normal so when he is below the light as he is in the screenshot, he doesn't get lit. I was working through the problem of the character always being lit, and it seems to be because the light direction isn't calcualted correctly. I expect the light direction color to be a rainbow of colors, however the yellow means that the light is always point down X and Y axis instead of radiating out in a circle. I'm certain that worldPos is coming out correct because the diffuse/normal colors are being displayed correctly.

Fragment shader for the light:

```
#version 330

uniform sampler2D diffuseTexture;
uniform sampler2D normalsTexture;
in vec2 TexCoords;

out vec4 outColor;

void main(void) {
    vec2 resolution = vec2(200, 200);
    float distance = length(vec3((TexCoords*resolution) - (resolution / 2),
                                0.0));
    float constantAttenuation = 1.0;
    float linearAttenuation = 0.1;
    float quadradicAttenuation = 0.01;

    float attenuation = 1.0 / (constantAttenuation +
    (linearAttenuation*distance) + (quadradicAttenuation*distance*distance));

    vec3 worldPos = gl_FragCoord.xyz / vec3(1024, 768, 1.0);
    vec3 lightDir = normalize(vec3(50,50,10) - worldPos);

    float diffuseFact = dot(normalize(texture2D(normalsTexture, worldPos.xy).rgb), lightDir);

    vec4 diffuse = vec4(0.0);

    if(diffuseFact > 0.0) {
        diffuse = vec4(texture2D(normalsTexture, worldPos.xy).rgb, 1.0);
        diffuse = diffuse * diffuseFact * 10;
    }

    outColor = vec4(lightDir, 0.5) + (diffuse*attenuation);
}

```

# Answer
At rcapote's suggestion, here's my answer as an answer:

Ah, so your light rectangle is 200 by 200, and distance is from the center of that? In that case, I believe that lightDir should be also be based on the center of that rectangle and not world coordinates. Probably lightDir = vec3(0.5, 0.5, 0.1) - vec3(TexCoords, 0.0).

Glad I could help!
> 0 votes

---
Tags: 2d, glsl, lighting, deferred-rendering
---


# Question
Title: How to implement "move to touch location" function?
What is the formula/logic to implement moving an object towards a TOUCHED location. I want character A to move to my finger and it must be accurate. Here is what I have tried so far:

```
    @Override
    public boolean touchDown(int screenX, int screenY, int pointer, int button) {
        // coordinates come in pixels so convert to world units
        scaleX = screenX / (Gdx.graphics.getWidth() / 10f);
        scaleY = screenY / (Gdx.graphics.getHeight() / 7f) * -1;

        float angle = new Vector2(scaleX - mishi.getPosition().x, scaleY
                - mishi.getPosition().y).angle();
....
....
        mishi.getVelocity().x = (float) (Math.cos(angle) * 13);
        mishi.getVelocity().y = (float) (Math.sin(angle) * 13);

```

This gets my character moving but basically no where in the direction I click. If I click in the same point twice, it will move him in 2 different directions

# Answer
> 1 votes
This simply sets the acceleration to a factor proportional to the distance between the points.

If you want the character to move at a constant velocity, you should instead get the angle between points and cast them to a static vector.

To make the character stop, set its velocity and acceleration to 0.

# Answer
> 0 votes
I can't guarantee that this is your problem, but are you taking into consideration that the coordinate system for input starts at the top left, with **x** growing to the right as usual, but **y** growing downwards?

In other words, the **x**-value is the same in world coordinates as in the screen coordinates, but the **y** differs. To get the **y**-value from screen to world coordinates, simply use

```
yWorld = Gdx.graphics.getHeight() - Gdx.input.getY();

```

Or do it as outlined in this answer: https://stackoverflow.com/questions/16514152/libgdx-coordinate-system-differences-between-rendering-and-touch-input

---
Tags: java, android, libgdx
---


# Question
Title: Free Look Camera Like Arma 2 while pressing ALT
I'm trying to create a simple script that give me the possibility to rotate the camera while pressing a key. So, in a pseudo-code way, how I can intercept the Input event and limit the player's movements to hold the character direction? I should tweak the MouseLook script? Or completely create a new one?

# Answer
> 1 votes
If user is holding `Alt`, do camera stuff, otherwise let player move as normal.

```
void Update(){
    if (Input.GetKey(KeyCode.LeftAlt) || Input.GetKey(KeyCode.RightAlt)) {
        // Process mouse movement and camera rotation here
    } else {
        // Process player movement here
    }
}

```

**Edit:** Create a C# Script and add it to your camera, change the Update() function to look like the above and then insert your camera movement logic as needed.

---
Tags: unity, camera, first-person-shooter, unityscript
---


# Question
Title: Which buffering process would be more efficient?
I'm working on the base engine of my game right now, specifically converting a text file into a level on-screen. As a 2D platformer, each level has an array of rectangles that can be drawn to the screen. Obviously I don't want to draw all these bad boys to the screen every frame, as that would slow everything down. I've thought up two solutions to this problem myself:

* Draw these rects to a separate texture (I'm using SDL2, by the way) and paint a specific portion to the screen every frame
* Choose which rects to draw every frame based on the player's position by checking collision between every rect and an imaginary moving "chunk"

My question: Which of these two processes, if either, would be less of a burden to the cpu? If neither seem reasonable, what other alternatives are there?

# Answer
> 1 votes
I found that with plain SDL2, even using the accelerated renderer, that redrawing all the tiles every frame was a huge bottleneck. I would suggest drawing as much as you can to a static texture that you then draw using the camera's clipping rectangle. Now, I was drawing around 3600 tiles per frame (8x8 tiles at 640x360) on a relatively low-powered laptop, so your use case may not be a problem.

The best solution would probably be to dip into OpenGL and store all the tiles in a vertex buffer (or a grid of vertex buffers) and draw those instead. Advantage being that it would save memory and you wouldn't be constricted to using basically only one tile layer per texture.

---
Tags: c++, rendering, sdl
---


# Question
Title: Techniques for managing vertex buffer memory
I'm learning OpenGL and I haven't seen any advice on managing vertex buffers in all of the tutorials I've read.

The basic problem is that I have some memory allocated as a buffer B in which I'm going to store vertex data to send to the graphics card.

Then I have the data that represents my domain D. This is the data that the game's simulation is run against. Let's say in a simple case it's just a list of 100,000 circles that will be moving around. Let's also assume that all of the data can, but might not, change every frame. Nothing is necessarily static.

I'm looking for the techniques people use to efficiently fill B with D.

I could create a new B each frame, but I imagine that would be very expensive.

I could give every object in D a pointer to a location in B and have it update that pointer directly, but that strikes me as error prone as then I have to manage all of these pointers.

I could also traverse D and fill a reused B every frame. This is what I'm currently leaning towards. The only problem here is that I'm forced to update every vertex in B every frame (because the location of the vertex data for a particular D could change within B) unless I come up with a more sophisticated scheme that guarantees that that an object in D always gets the same spot in B.

So I can think of several options, but I'm wondering what people typically do. I imagine almost everyone has to solve this problem at some point.

# Answer
Based on what I know from reading, your best bet is fully orphaning the buffer each frame and filling the entire thing. As far as how you architect your rendering engine, it depends on the scene. To use your example, if all you're drawing is 100,000 circles, you're best off having D be stored in a format that can be written directly to B and used for instanced rendering.

In any case, you should be trying to reduce the time it takes to translate D to B as much as possible. I would suggest architecting D in a data-oriented way - contiguous and using a structure-of-arrays design rather than array-of-structures - so that you can boil it down to a few straight `memcpy()`'s.
> 0 votes

---
Tags: opengl, memory, vertex-buffer
---


title: Windows 7/8 imcompatibility via XNA?

text:
# Question
Title: Windows 7/8 imcompatibility via XNA?
I have MS Visual Studio 2010 installed on my machine (a Windows 7 Pro 64-bit), and im developing a game in XNA 4.0 with it. I can run the program just fine from the .exe file in the bin directory, and it appears to have no bugs.

But when trying it on Windows 8 64-bit, it just doesn't run. Am I doing something wrong or is XNA suddenly incompatible in this case?

BTW this game has no 3d graphics at all, just 2D stuff, but iirc every texture2D is rendered through the GPU thing as some sort of flat 3D surface, so idk.

# Answer
> 1 votes
I recall having the same problem. Uninstalling the Games for windows Live client (if present) then reinstalling, **then after that** intalling XNA framework helped for me.

# Answer
> 0 votes
As ashes999 pointed, out, Microsoft's official implementation of XNA is now dead; it's not supported on any new Microsoft products (like Windows 8 and Xbox One). However, the MonoGame project is a viable and very active replacement. Use that.

---
Tags: xna
---


# Question
Title: Can't get the logic behind my AABB collision
This is my collision detection function in the maze game im working at. I never made a game before and I dont have that much programming experience.

The question I keep asking me continously is why this isn't working. The Solids are instances of the class Solids with rectangular shape(X(Top-left-corner),Y(Top-left-corner),width,height) which are stored in a List\< T \>. The function below iterates through the List and calls the second function below. checkForCollision is called every FrameUpdate.

Can somebody please help me. I'm becoming desperate :)

```
private void checkForCollision()
        {
            foreach (Solids wall in level1.WallObjects)
            {
                if (IsCollidedSolids(ref Pl1, wall))
                {
                    Pl1.OnCollision();
                    break;
                }
            }
        }

public bool IsCollidedSolids(ref Player Pl ,Solids act)
        {
            if (Pl.X+Pl.width >= act.X && Pl.Y >= act.Y - act.height)
                return true;
            if (Pl.X + Pl.width >= act.X && Pl.Y -Pl.height <= act.Y)
                return true;
            if (Pl.X <= act.X + act.width && Pl.Y - Pl.height <= act.Y)
                return true;
            if (Pl.X <= act.X + act.width && Pl.Y >= act.Y - act.height)
                return true;
            else
                return false;
        }

```

# Answer
> 0 votes
First, seems like you are confusing your coordinate system. If its origin is top-left corner of screen, then its axes pointing towards bottom and right respectively. Thus to find bottom of a axis aligned box add height to top, instead of substractng it.

Second, logic is just wrong. First condition states: "if top-right point of first object is farther from coordinate center than bottom-left point of second object". There still can be gap between objects.

It may be easier to check for conditions that guarantee objects are not interecting, f.e.:

```
if(a.top > b.bottom) return false;
if(b.top > a.bottom) return false;
if(a.left > b.right) return false;
if(b.left > a.right) return false;
return true;

```

Or we may think more carefully about uderlying structure of axis aligned box. It may be represented as two ranges, one per each axis. To check if two boxes are intersecting is to check that two pairs of ranges are intersecting. Now this is trivial to google or remember from math class.

```
bool RangesIntersecting(start1, end1, start2, end2)
{
    return max(start1, start2) < min(end1, end2);
}

bool AABBsIntersecting(a, b)
{
    return RangesIntersecting(a.x, a.x + a.width, b.x, b.x + b.width)
        && RangesIntersecting(a.y, a.y + a.height, b.y, b.y + b.height);
{

```

---
Tags: c#, collision-detection, procedural-generation, aabb
---


# Question
Title: How to display Textures, Buttons, Created with Unity's GUI (OnGUI()) to get displayed behind other objects in Scene
I am making a game in which I am using OnGUI() to make Texture. I want this texture to display behind my Regular 3D objects like cube, spheres in the scene. I have tried and searched but I am unable to figure it out. Is this Possible?

# Answer
Any thing drawn by OnGUI will be rendered or drawn in front of all 3d objects.

however if your creating the GUITexture GameObject Then there is a way to do that

The way to do this is to use two cameras. one purely a GUI camera with depth lower than that camera used to render 3d object.

In the 3d cam set the culling mask to the layer on which your 3d objects lie. set this cameras depth to 0.

the GUI camera should be set to depth only(Clear flags) and set its depth to -1. all the GuiTextures should be on the useer defined layer and set its culling mask to that specific layer.

in the 3d cams culling mask the layer you defined for 2d objects should be unchecked.
> 3 votes

---
Tags: unity, textures
---


# Question
Title: Identify a selected prefab rather than all of them
I am trying to play a particle effect when an enemy is killed but it seems to play on a randomly selected one rather than the one that was hit. However the enemy that was hit still disappears and still add points to the score.

At the moment I have three scripts to carry this out (All have been shortened so I'm only showing the relevant code):

One which is attached to boxes that are thrown at enemies that detects if they have collided with an enemy prefab.

```
void OnCollisionEnter (Collision theCollision) {

        if (canProjectileKill == true) {
            // If the projectile hits any game object with the tag "Enemy" or "EnemyContainer".
            if (theCollision.gameObject.tag == "Enemy") {
                GameObject.Find("EnemyExplosion").GetComponent<enemyDeath>().ProjectileHasHitEnemy();
                // Destroy the projectile itself.
                Destroy (gameObject);
                // Destroy the game object that the projectile has collided with (E.g. the enemy).
                Destroy (theCollision.gameObject);
                GameObject.Find("Manager").GetComponent<projectileSpawner>().deleteProjectile();
            }
        }
    }

```

Another that is attached to the enemy prefabs which detects if they have been hit by a box.

```
void OnCollisionEnter (Collision theCollision) {
        if(theCollision.gameObject.tag == "Projectile") {
            GameObject.Find("EnemyExplosion").GetComponent<enemyDeath>().EnemyHasBeenHit();
        }
    }

```

I then run an if statement asking if both the box has hit the enemy prefab AND if the enemy prefab has been hit by the box in an attempt to identify a single prefab rather than all of them. However this still doesn't work.

```
    public bool HasProjectileHitEnemy;
    public bool HasEnemyBeenHitByProjectile;

    void Start () {
        gameObject.particleSystem.Stop();
        HasProjectileHitEnemy = false;
        HasEnemyBeenHitByProjectile = false;
    }

    public void ProjectileHasHitEnemy () {
        // From projectile.
        HasProjectileHitEnemy = true;
    }

    public void EnemyHasBeenHit () {
        // From enemy.
        HasEnemyBeenHitByProjectile = true;
        PlayParticleSystem();
    }

    public void PlayParticleSystem () {
        if (HasEnemyBeenHitByProjectile == true && HasProjectileHitEnemy == true) {
            gameObject.particleSystem.Play();
            HasProjectileHitEnemy = false;
            HasEnemyBeenHitByProjectile = false;
        }
    }
}

```

I am aware this is a long question but I have been stuck on this for over a week, so any help would be much appreciated. Thank you :)

# Answer
Once you have detroyed a gameobject it will not play the particle system attached to it. This should work. Try it.

```
void OnCollisionEnter (Collision theCollision) {
    if (canProjectileKill == true) {
        // If the projectile hits any game object with the tag "Enemy" or "EnemyContainer".
        if (theCollision.gameObject.tag == "Enemy") {
            // GameObject.Find("EnemyExplosion").GetComponent<enemyDeath>().ProjectileHasHitEnemy();
            // Destroy the projectile itself.
            Destroy (gameObject);
            // Destroy the game object that the projectile has collided with (E.g. the enemy).
            //dont do this Destroy (theCollision.gameObject);
            // GameObject.Find("Manager").GetComponent<projectileSpawner>().deleteProjectile();
        }
    }
}

```

Enemy Script. Attach the particleSystem to the enemy Prefab

```
float timetoplay = 0.3f; //lets say 0.3 seconds.
void OnCollisionEnter (Collision theCollision) {
        if (theCollision.gameObject.tag == "Projectile") {
            Destroy(gameObject,timetokill);
            gameObject.renderer.enabled = false; //so as to hide the mesh
            gameObject.GetComponent<particleSystem>.Play();
        }
    }
}

```
> 1 votes

# Answer
I would remove the OnCollisionEnter script from the enemy and have the projectile obtain the game object ID from the enemy object it hits BEFORE it is destroyed. Store that to a game object variable or just its transform.position to a Vector3. Then have the instantiation occur at that location.
> 0 votes

# Answer
I seem to have found a way around this. Instead I've just set it to instantiate the particle system whenever an enemy detects that it has collided with a projectile. I then use a Coroutine to delete the particle system 2 seconds after.
> 0 votes

---
Tags: c#, unity, particles
---


# Question
Title: Unity what are the rules for determining sizes of gameobjects
I am making a game for windows phone. I am a newbie so currently I am unable to understand if I have to make a simple menu for a game targeting portrait mode always, what should I give the background size ,camera size ,button size , position? For example I have to set a background on renderer full screen size in portrait mode and fis a gui test between it.. I am using 2d orthographic camera

# Answer
> 1 votes
I would suggest that you design a UI according to a fixed screen size like (480X800 WP) then use GUI.matrix (see the script reference) to scale it to different resolutions.

GUI.matrix is really useful but a very heavy function. so make sure you use less OnGUI objects like buttons, boxes, and textures.

A better way to implement textures is using Quads. Quads are rendered by the camera and the Camera Scale is taken care by unity.

---
Tags: unity
---


# Question
Title: Endless 2d runner with increasing speed, how to adjust jump behavior?
I am making an endless 2d runner with unity. my player object is not moving at all, i move all the other game objects. I have a SpeedManager script which increases the "speed" at every update by a short amount. The movement speed of every gameObject which is streaming towards the player is now multiplied with the SpeedManager "speed".

One controll of my player is a jump. Currently i am using

> public Vector2 jumpForce = new Vector2(0, 350);
> rigidbody2D.AddForce(jumpForce);

The problem now is, as the game goes on, the game objects pass faster and faster but the player jump remains the same. What i want is a jump that goes as far as before, which means, the player should jump faster into the air, reach the same height and drop faster to the ground, so the jump distance is the same.

I tried some stuff like multiplying both the jumpForce.y and the gravity of my player object with my SpeedManager.speed, but i did not achieve anything yet. :)

Greetings.

# Answer
Easy way to implement an increasing speed game is to adjust the time scale component. instead of increasing the player speed. keep it constant.

scale the time so that it appears its going fast.

Time.timeScale is 1 for normal speed. increase this in fixed amounts (needless to mention till a certain point otherwise it would just go faster and faster.)
> 3 votes

# Answer
Hello and welcome to "Linear Acceleration and You: How To Use Math To Throw An Object The Right Way".

Assuming an initial horizontal speed of *s* (in distance per time unit), a jump speed of *j* (distance per time unit), maximum jump height of *h* (distance) and gravity of *g* (distance per time unit squared). Time to reach maximum jump height is *t* (time units).

Your basic jump will take t = j/g time units to reach the top of the jump, and 2j/g from start to end. Therefore, it should cover a horizontal distance of d = s\*(2j/g).

The maximum jump height, using the basic equation for linear acceleration you learned in Physics 101, is h = g/2 * t² = g/2 * (j/g)² = g/2\*j²/g² = j²/2g.

And now we have a two-equation system:

```
d = s*(2j/g)
h = j²/2g

```

Five terms. h and d are constant, and we want to know j and g based on a variation of s.

Let's use one of these equations to define j in terms of g.

```
h = j²/2g
2g = j²/h
g = j²/2h

```

Now we replace g on the first equation with the above, and try to isolate j:

```
d = s*(2j/(j²/2h))
d = s*((2j/j²)*2h)
d = s*4h/j
j = s*4h/d

```

And voila. j is *directly proportional* to s, and g is directly proportional to the *square* of s.

Going back to code:

```
CONSTANT_VALUE_1 = 4 * maxJumpHeight / jumpDistance
CONSTANT_VALUE_2 = 0.5 / maxJumpHeight

jumpForce.y = SpeedManager.speed * CONSTANT_VALUE_1
gravity = jumpForce.y * jumpForce.y * CONSTANT_VALUE_2

```

I'm not accounting for air friction here or other physics engine shenanigans, so you might need to test various constant values to see if you get the right distance and height.
> 2 votes

---
Tags: unity
---


# Question
Title: I found a game with the same name as mine! What should I do?
I published my game *Eyeroller* on Google Play the other day. I checked there was no game on Google Play with the same name. But today I searched for "eyeroller" on Google (Yes, I should have done it a long time ago) and realized there is a game named *eyeRoller* on the AppStore. They are completely different games, as you can see.

What are the legal implications of this? Can things like trademarks and copyrights be a problem? Should I change my game's name?

# Answer
First - IANAL - Want legal advice call a lawyer.

Do you own a trademark on the name eyeRoller? My guess is no.

There are two kinds of trademarks. One is a registered trademark. That is shown with an (R). And this means that you filed it with the uspto and obtained a registered mark. Then there is unregistered trademark which is shown with a TM. This is also known as a common-law trademark and is also valid in the united states and canada and some other countries. For that you just stick TM on something and use that mark in print or advertising.. like on a website or inside a published app.

If you do own a trademark and you believe the other party does not - you can contact apple legal (AppStoreNotices@apple.com) and they will ask the other party to either prove that they own the rights to use that name or take down the app in the USA store. I have followed this method and have gotten other apps taken down. But if it gets ugly you might both have to take the app down until going through an expensive legal battle.

But looking at your case, I doubt that you own the trademark over them since their game was released in 2010. Actually it's more likely that you are infringing on their trademark. And in that case it might be you that gets the takedown letter. Has your game been advertised since 2010? Sounds like you just published it the other day.

So here's what you can do:

1. Change the name of your app to something that doesn't infringe on someone else's trademark.
2. Or leave it up and don't worry about it. Wait and see what happens. Tons of apps have similar names. Probably no one will do anything. But if they do you'll have to take yours down.
3. In the iOS app store there are easy tricks to get around taken names. The name of your app in the app store can be something like "eyeRoller game" and the app icon can still say "eyeRoller". So you can still publish on the app store.

*** EDIT ***

I reread your question and realized that you know that you might have to change your name. So hope I didn't come off too harsh.

The easiest thing to do is to change your name very slightly. "eyeRoller Prime" or extreme or whatever. Having more words in your app name adds to your SEO. It's like getting extra keywords. So it won't hurt sales to have a longer more descriptive app name. And the visible name can still be the shorter version if you want.

I did a photo editing app called "Silver" - but there were lots of other apps called Silver so I called it "Silver photo effects and editing". This isn't a plug cause the app is no longer available. But the point is that the more descriptive name isn't a bad thing. And you can wait to worry about a takedown notice until you get one.
> 16 votes

---
Tags: copyright, appstore, google-play, trademark
---


# Question
Title: applyAngularVelocity causes error when called right after object instantiation
I'm trying to make a `physicsBody` rotate as soon as it is instantiated.

`CCNode* ball = [CCBReader load:@"Ball"];
[ball.physicsBody applyForce:force];
[ball.physicsBody applyAngularImpulse:arc4random_uniform(360) - 180];`

Applying force works fine, the last line however throws an error in `cpBody.c` line 123: `cpAssertHard(body->w == body->w && cpfabs(body->w) != INFINITY, "Body's angular velocity is invalid.");`

When I don't apply force and merely rotate the problem persists. If I send `applyAngularImpulse` at some later point (in this case on a touch) it does work. Is this function not supposed to be called right after instantiation, or is this a bug?

# Answer
> 0 votes
The problem was in CCPhysicsBody.m. Upon instantiation the body's moment is 0, causing divide by zero errors, making the angular velocity NaN.

I fixed it by changing the function to the code below:

`-(void)applyAngularImpulse:(CGFloat)impulse {
 if (_body.moment == 0)
 _body.angularVelocity += impulse;
 else
 _body.angularVelocity += impulse/_body.moment;
}`

Another error in my code was that arc4random\_uniform returns an unsigned integer, thus creating very large numbers when going below 0. Casting to a signed integer solves that problem.

EDIT: This fix does however cause the object to go spinning wildly. In the `didLoadFromCCB` override I start a timer spawning these objects. Apparently, creating objects with physics while in this method doesn't end well. A proper workaround would be to call `scheduleOnce` with a delay of 0.1 on a function to apply the angular velocity properly.

---
Tags: cocos2d, objective-c, chipmunk
---


title: storing user data for rpg

text:
# Question
Title: storing user data for rpg
I'm creating a single player Web rpg that will store a decent amount of information about the player, items, map, npcs, etc.

I have been developing html5, javascript, php, and the mysql database approach and saving/retrieving with json.

Someone mentioned for my purposes, using 'localStorage' persistent user storage would remove much complexity and help with performance.

Is localStorage the better way to go here? If I wanted to find out information about my players, or ensure that esch player profile is saved... can I rely on localStorage?

What are the pros and cons of each?

# Answer
window.localStroage is a more modern alternative to cookies. It allows you to store (semi-)persistent data in the users web browser which will survive a browser restart. The client-sided javascript can access it without having to consult a server, which makes it quite fast to access from the client. But contrary to cookies, localstorage is not directly accessible for the server. When you need data from localstorage on the server, you need to send it to the server via AJAX or websockets after the website has loaded.

localStorage has a much higher capacity than cookies, but not unlimited. The standard suggests 5MB, but that's just a suggestion. Most browsers have a higher limit and react differently when it is exceeded. Some ask the user for permission to store more, some just drop any excess data. But you can not be sure how the browser reacts, so you should try to stay below the 5MB limit.

Keep in mind that localStorage doesn't guarantee persistence. The user can accidentally or intentionally delete their localstorage, just like they can delete cookies. Also, the web browser might have a combined hard-drive quota for localstorage for all websites and delete arbitrary data when running out.

The localstorage also doesn't guarantee integrity. The user can manipulate their localstorage. That means when you store any game state in it, you have to assume that the user will be able to edit it in any way they want, allowing them to cheat. When your game is single-player, that might not be that much of an issue. But when your game has any interaction between players (and when it's just a public scoreboard), cheaters might be quite an annoyance for the more honest players.

However, localstorage has the advantage over server-sided persistence that you do not need personalized user accounts. The data is bound to the web browser installation, so the user can save their game without having to register and log into an account. You also don't need a server-sided database which greatly simplifies your server infrastructure.
> 7 votes

---
Tags: architecture, javascript, performance, rpg, storage
---


title: RPG: store dialog

text:
# Question
Title: RPG: store dialog
I'm creating a single player web RPG. I was originally storing NPC dialog in a JS object. I could cycle through lengthy dialog in an array as I wanted. I can also store objects with K:V pairs.

That being said, is it **easier/faster** to manage, store and retrieve dialog in the following three methods:

Also, can you tell me **why** one is better over another for running a single player web rpg:

**a JS Object:**

```
var dialog = {
    quests : {
        quest1 : {
            NPCName: {
                "Task 1 - Introductions" :
                {
                    "dialog" :
                    [
                        "I'm Pedro",
                        "Welcome to my neighborhood",
                         etc...,
                    ],
                    "wordBank" :
                    {
                        "Hola" : "Hello",
                        "Como" : "What",
                    }

```

**In pure JSON:**

```
{
"quests" : {
    "quest1" : {
        "Lee" : {
            "Introductions" :
            {
                "this" :
                [
                    "Hello"
                ],
                "that" :

```

**Or in a database:**

# Answer
> 4 votes
## The content creation perspective:

RPGs tend to be quite text-heavy so you and your team will spend quite a lot of man-hours writing, proof-reading and maybe even translating the dialogs. It might pay off to make this process as comfortable as possible.

Pure Javascript objects have the advantage that you can more easily integrate functions into your dialog system than with JSON. Also, the syntax is a bit more lax than with pure JSON. Otherwise there isn't much of a difference between the two approaches.

Having the dialog options in a database could be more manageable when you plan to write a specialized GUI tool to create and edit the dialog trees (When your project is going to be very large, this might pay off after all). But when you plan to enter and edit your dialog directly in the database with a general-purpose SQL management tool or even worse typing out SQL queries, you will have quite a hard time ahead of you.

## The performance perspective:

Storing the dialogs client-sided could be quite a lot of data which - in the worst case - might have to be loaded all at once when the application starts. That could take a few seconds and also quite a lot of bandwidth.

When you store it on the server, the dialog options will be loaded on demand. That means shorter load-time, but worse responsiveness during the dialogs. A simple tradeoff you have to decide for yourself.

Keep in mind that you can also store your dialog as JSON *and* store it on the server. You can have the client request individual JSON files on demand with `XmlHttpRequest`.

## The piracy perspective:

When your game runs completely in the web browser without having to rely on any server-sided components, it is trivially easy to pirate. Someone who wants to plagiarize your game just needs to download all the files referred to in the HTML, rebrand it and put it on their own webserver. But when you keep some of your content server-sided, it becomes far more difficult to rip it all.

# Answer
> 2 votes
This is a very low level implementation detail, given there are very loose requirements for this kind of stuff (loaded once during game startup, only the game needs to parse it, it's plaintext so very little data). The default answer for this is **whatever you / your team are most comfortable with**.

Having said that, I'd consider JSON *a little bit* better:

* It's extensible
* Doesn't need a DBMS to view/edit

Furthermore, the advantages of database don't apply here:

* You don't need to perform queries/joins, everything is loaded during startup into your game directly
* You don't need to modify this data during gameplay, let alone having performance or ACID requirements

The differences between JS object and JSON file are moot as you can go from one to the other using `getJSON()`.

---
Tags: javascript, databases, mysql, dialogue-tree
---


# Question
Title: Manually remove inactive CCParticleSystem from scene?
When using particle systems that have a lifetime, with `CCParticleSystem` and its derived classes, should I manually remove the finished systems from their parent nodes once the particle animations are complete? Or this is done automatically? I don't want to leave dead particle systems in my scene, for obvious reasons.

# Answer
`CCParticleSystemBase` has an `autoRemoveOnFinish` property. The name is self explanatory. This property is `NO` by default. So should be set to `YES` on creation for particles that have a finite lifetime.
> 0 votes

---
Tags: cocos2d-iphone, objective-c
---


# Question
Title: Same name and copyright / fanfiction question
OK, so this is still about a game... only a web-based browser game, in this case NationStates, a political/social role-playing game that's text/image-based, interactive fiction.

It's a political/social satire, basically.

I'm creating fictional magazines for a fictional nation, and they're being hosted on a flipbook site. My question relates to titles and same names.

I obviously can't call my fictional newspaper relating to the nation The Times or my fictional car magazine Auto Trader, as they're trademarked - I checked on ipo.gov.uk, but if I was to call them The Anytown Express The Times or The Anytown Express Auto Trader (with different logos than the original to avoid copyright infringement, as well), would that fall under copyright infringement / trademark infringement, and is adding an affix sufficient enough to differentiate themselves?

I don't actually have anything yet on the site about my fictional nation's media... so am OK for now, but when I actually ***do***, what's the right way to go about it?

Since this game is a parody/satire/social commentary, what's the right way to do a parody successfully?

All help is gratefully appreciated.

# Answer
> 0 votes
As with any legal questions, you really should speak to a lawyer who specializes in the specific branch of law you're concerned in, rather than asking the internet for legal advice, before making any decisions that could potentially risk getting you sued. That being said, trademarks are a bit more fickle than standard copyright law. They operate similarly in that they both take into account the similarity of the disputed "infringing" work to the original, protected work, but copyrights also take into consideration a few other aspects, and apply to situations a bit differently.

Trademark law, as I'm sure you've found, is more intended to protect an identifying symbol than it is about protecting an exact rendition of said symbol, which is what copyrights would do. That being said, I, personally, would *not* put trademarked materials intermixed so homogeneously with other words and hope that I wouldn't get sued.

Generally, from what I've seen, you can get away with paraphrasing the words, though. So, maybe instead of "Auto Trader" you could call it something like "Motor Car Merchant" or something along those lines. I'm not the most clever at naming things on the spot, but you get the idea.

If you're looking for some inspiration for renaming things such that they are recognizable enough by the fans, but clearly not representing the same product (from a legal stance), take a look at how the GTA series has done this. They've done a pretty fantastic job of making fun of big companies, in this way.

---
Tags: copyright, interactive-fiction
---


# Question
Title: Can't read .cso files but I can read their .hlsl versions?
Well I've been trying to read a .cso file to use as a shader for a DirectX program I'm currently making.

Problem is no matter how I implemented a way to read the file it never worked. And after fidgeting around I discover that it's only the .cso files I can't read.

I can read anything else (which means it works) even their .hlsl files. Which is strange because the .hlsl (high level shader language) files are supposed to turn into .cso (compiled shader object) files.

What I'm currently doing is:

```
vector<byte> Read(string File){
    vector<byte> Text;
    fstream file(File, ios::in | ios::ate | ios::binary);

    if(file.is_open()){
        Text.resize(file.tellg());
        file.seekg(0 , ios::beg);
        file.read(reinterpret_cast<char*>(&Text[0]), Text.size());
        file.close();
    }

    return Text;
};

```

If I then implement it.

```
Read("VertexShader.hlsl"); //Works
Read("VertexShader.cso"); //Doesn't Works?!?!

```

And I need the .cso version of the shader to draw my sexy triangles. Without it my life and application will never continue and I have no idea what could be wrong.

EDIT #1: When I read the .hlsl file the vector get's filled whit what was written in the file. For the .cso ones the function doesn't even pass the "if(file.is\_open)" test and stays empty.

# Answer
Finally found the problem.

Seems that the .hlsl turns into .cso files automatically for Windows 8 Applications but not for Windows 7 Applications (and others I guess). So my previous attempt to read the .cso file directly wouldn't work since the file never existed to begin with. Though I thought it would since I started to learn DirectX for Windows 8 first.

For windows 7 you have to compile the shader yourself and use that information.

Here's what I did:

```
#include <d3dcompiler.h>
#pragma comment(lib, "d3dcompiler.lib")

ID3D10Blob *blob, *blob2; //these hold the compiled shader data

D3DCompileFromFile(
    L"VertexShader.hlsl", NULL, NULL, "main", "vs_5_0", 0, 0, &blob, 0);

D3DCompileFromFile(
    L"PixelShader.hlsl", NULL, NULL, "main", "ps_5_0", 0, 0, &blob2, 0);

//Now you can just use the data with blob->GetBufferPointer();
//Or it's size with blob->GetBufferSize();

md3device->CreateVertexShader(
    blob->GetBufferPointer(), blob->GetBufferSize(), nullptr, &mVertexShader);

md3devicecontext->VSSetShader(mVertexShader, nullptr, 0);

```

Hope other people find this useful and helpful.I couldn't find info on this anywhere but found the function syntax on msdn and decided to try it since I had no other lead and it worked. (Hence I came up with the fact that Windows 7 doesn't compile it for you)
> 1 votes

---
Tags: c++, directx, hlsl
---


# Question
Title: How should I traverse entities and components for their per-frame updates?
I am implementing a simple entity/component-based engine in C++ and am unsure about the best way to store references to entities/components and what the best way to traverse them each game step would be.

My current thoughts are to:

* Store a reference to the parent entity of each entity in the game.
* Instantiate the game engine with a root entity (e.g. a `Scene` entity).
* Traverse all entities in the game starting from the root entity and call the update method.

My entity interface is such that each entity in the game will have an update method which will call the update method for each of the entities components:

```
class Entity
{
public:
    virtual void update();
};

```

However I don't think a tree traversal would be the most optimal solution - would it be better to store references to every entity in the game in a flat data structure and loop this every game step?

# Answer
> 8 votes
Storing components within the entity objects, and then doing a "for each entity, for each component, update" loop is a fairly straightforward and obvious solution. It's also not very good for cache coherency and creates problems for concurrent update scheduling.

Consider an outboard storage approach, where component instances are stored in large homogeneous lists within the subsystem that is responsible for them. For example, physics components all live in what is effectively a big `std::vector<PhysicsComponent>` within the physics simulation object.

In this system, entities only store IDs (possibly simple integers) or some other similar form of *reference* to components that comprise the entity. In fact, it's possible (and in some cases beneficial) to take this to the Nth degree and eschew an entity *object* altogether, binding components together only implicitly by storing an entity ID number.

To update components, you simply update the owning system (that is, `physicsSimulator.Update(deltaTime)` or similar). This update traverses each component in order and does whatever updating is needed. This is much more cache-friendly, and affords you a much coarser organization of update dependencies. This allows you to more easily reason about which systems have dependencies on the updated data from other systems and order their relative updates accordingly. It allow allows you to easily process updates for entire batches of components in parallel if you know the two relevant systems do not need to directly interact in the same frame.

---

Storing the *entities themselves* in a large tree is also not something I think you should do unless you have a really compelling need for it. It sounds like you are conflating the idea of a scene graph with the idea of your entity system: thus the assumption that every entity has a parent that ultimately leads back to a "root" entity.

This is probably a bad idea for the very same reason that (most) scene graph implementations are a bad idea: you end up with a very deep tree, the leafs of which constantly need reshuffling based on new parents or due to lifetime goods (good scene graphs tends not to be particularly deep, and do not try to include "every" object at an extremely granular level). Plus, this design will force you to find physical parents for entities that don't logically need them just because your system says everybody must be parented to the root.

A flat list of entities is a more common, and generally better, solution. I would go with that until can demonstrate a very compelling need to organize them otherwise.

---
Tags: c++, entity-component
---


# Question
Title: Saving and retrieving high-score data in XNA 4.0
I made a game in XNA 4.0 and now I need to save the points in a database or in a file (or in something else). My goal is to store and retrieve the highest score if I choose that option in the main menu. What I found on the internet is not complete, or whatever, useless for me.

What techniques can I use with XNA to save and load data?

# Answer
> 2 votes
For XNA you can use isolated storage to be able to store data in a cross-platform manner.

You can find the documentation here: http://msdn.microsoft.com/en-us/library/ff604992.aspx it includes an example that works on both Windows, Xbox 360 and PC.

If you're only developing for Windows you can also use the normal C# IO functions like File.Create, File.Open and the stream functions to save and load data. A short tutorial can be found here http://support.microsoft.com/kb/304430/EN-US

---
Tags: xna, c#, xml, sql
---


# Question
Title: What is the maximum number of shaders I can have in OpenGL 4?
What is the maximum limit of shaders I can have on the GPU?

With 1000 different objects, I might have 1000 * 5 shaders (vertex, tcs, tes, geo, frag) on the GPU at a time. Though only one will be active at once, I wonder what the upper limit is.

# Answer
There is no specific upper limit on the number of shaders that can be created. Many games do have thousands of individual shaders.

With *very* large numbers of shaders, it's conceivable you could run out of GPU memory to store the binary code for all of them, but that would probably require millions of shaders.
> 11 votes

---
Tags: opengl, shaders
---


# Question
Title: Use different values for Depth Test and Depth Write in OpenGL
Is there a way to use something similar to PolygonOffset to make a depth test more permissive (move fragment depth towards eye) but still write the original depth value to the depth buffer? The only thing I can come up with is a tricky two pass solution using a stencil buffer, but I'd like to avoid that if possible.

Context of my question: We have an entity with a particle based smoke plume that is often in front of a semi-transparent building. Do to some constraints with batching, the building gets drawn after the smoke plume. Originally the smoke plume particles were rendered with a depth test but no depth write. This caused the building to be drawn on top of the smoke.

Turning the depth write on for the smoke particles fixes the building, but now the smoke particles interfere with each other. Ideally, I'd like to find a way for them to stop interfering while still writing to the depth buffer.

# Answer
I ***think*** you may be interested in `glDepthRange (...)`. That affects the mapping from NDC \[**-1.0**,**1.0**\] to window-space Z (the depth buffer stores window-space Z) during the viewport transformation. Effectively the nearplane becomes `nearVal` and the farplane becomes `farVal`. You can fool with this to bias and/or rescale your assigned depth values, but GL clamps these values to \[**0.0**,**1.0**\].

Since all testing is done in window-space, you can simply modify the mapping between passes to make depth tests more *"permissive."* If you are clever, you can even reverse the mapping and the direction of the test to alter precision distribution.
> 1 votes

---
Tags: opengl, particles, depth-buffer, alpha-blending
---