title: How should I do my collision response?

text:
# Question
Title: How should I do my collision response?
I'm making a small lockpicking simulator. Obviously I'll need the pick to not pass through the lock, and I'll need the pins to move when you tap or push them with the pick.

Here's what I have so far, just to give you an idea.

http://megaswf.com/serve/2433982

As you can see, the collision detection is pixel perfect. I've looked into a couple of different ways of doing collision response, but it seems like such a vast and complicated field. Any time I come up with a possible solution I start noticing flaws like what would happen if more than two objects collided and so on.

I've looked into physics engines like Box2D, but it seems like such overkill considering the, I think, simple nature of the game I'm trying to make. I don't like the idea of using a huge library that I don't even begin to understand just because I can't figure out how to do collision response.

But I just don't know where to begin. Maybe I *will* have to use a library. If anyone with experience could, based on that demo and what I'm trying to do, suggest a course of action, I'd really appreciate it.

# Answer
I think you've already pinned down the answer in your question: a physics engine would be overkill for this. The fact that your colliding objects are (mostly) constrained to a single direction of motion and that they're trapped on their sides makes this a complicated situation for most out-of-the-box physics engines, and a nightmare to try and do your own physically-accurate collision response code for. So why worry about physics at all? Hack it!

More precisely, the expectation for a game like this isn't to have the physics be accurate, it's to have the physics *feel* good. I think the step you need to take from here isn't to code your physics, but to **design** it: 'what do I want the responses of the pins to be when the pick is in the right range, and what do I want them to be when they're being pressed off-center by the pick? How do I want them to slide back down when the pick releases, and should they slide back at all?' Decide how *you* want the response to work for these circumstances, and then code your contact response to match your expectations.

This isn't the approach I'd recommend for every problem; in particular, accurate physics and simulated (rather than explicitly designed) systems tend to be a good source of unexpected emergent behavior (occasionally for worse, but mostly for the better). But that's not really what you're looking for for a project like this; here, the most important design element is fidelity to the experience, and you'll almost always get a higher level of fidelity with a custom design than by trying to tweak your simulation to match the target.
> 2 votes

# Answer
You could use a simple Move-Collision-Rollback approach.

1. Move the object by dt * direction.
2. Check collision, if so, go back 1.
> 0 votes

---
Tags: flash, actionscript-3, collision-resolution
---


# Question
Title: Camera placement sphere for an always fully visible object
Given an object:

* With the bounds `[x, y, z, width, height, depth]`
* And an orthographic projection `[left, right, bottom, top, near, far]`

I want to determine the radius of a sphere which allows me to randomly place my camera on so that:

1. The object is fully visible from all positions on this sphere
2. The sphere radius is the smallest possible value while still satisfying 1.

Assume the object is centered around the origin.
How can I find this radius?

I'm currently using `sqrt(width^2 + height^2 + depth^2)` but I'm not sure that's the correct value, as it doesn't take the camera into account.

Thanks for any advice.

---

I'm sorry for confusing a few things here. My comments below should clarify what I'm trying to do actually.

# Answer
> 1 votes
The answer depends on the FOV of your camera (which is why I'm also wondering about lorancou's comment about whether you want orthographic or perspective projection). If your FOV (the smaller of your two FOVs, technically, if your viewport is rectangular) is θ (from top to bottom), then the angle from the center of your viewport to the top of your viewport is θ/2. Now, the 'maximal radius' of your object itself is r=sqrt(w2+l2+h2) (**w** idth, **l** ength, **h** eight), so what you want is the distance away from your object's center such that that radius is less than the (half-height) of your projected viewport. Since at a distance d from the center of your object the 'height' of your projection will be d\*sin(θ/2), you can find your distance d by just setting d=r/sin(θ/2).

# Answer
> 0 votes
You specify the projection transformation but not the view transformation. I will assume that the camera simply looks in the `z` direction. I will also assume that you want the sphere radius to be the *largest* possible, not the smallest (otherwise, just choose `radius = 0`).

Note that since you have an orthographic projection, the `z` coordinates do not really matter apart from ensuring that the object fits inside the near and far planes. Your scene will look exactly the same whatever the `z` coordinates of your objects are. So your problem becomes a matter of fitting your object's rectangle boundaries inside the camera's viewport rectangle.

Because the problem is symmetric, it is obvious that if such a sphere exists, its `x` and `y` coordinates are precisely your object's `x` and `y` coordinates. Then, the radius is:

```
radius = min((right - left - width) / 2,
             (top - bottom - height) / 2,
             (far - near - depth) / 2);

```

Note that the third term (`far - near - depth`) is probably superfluous. You really only care about the `x` and `y` directions.

And the camera coordinates:

```
cx = x
cy = y
cz = z - depth/2 - near - radius;

```

Again, the `z` value is probably not that important and you could just move your camera on a disc rather than a sphere.

---
Tags: mathematics, camera, random
---


# Question
Title: In Socket.IO, should I use JSON for communication between server and client?
I'm building an MMO with Socket.IO and Node.js. It works quite fast (though I don't have 1000 players yet) but my feeling is that it's not very optimized. JSON is super cool and easy to use within Socket.IO but when I see a broadcast from the server (1 player connected):

```
   debug - websocket writing 5:::{"name":"snapshot","args":[{"players":[{"id":1,
"tx":-5.62,"y":23.74,"tz":-5.64,"tRotY":0,"tSpeed":0}]}]}

```

I take it all the variable name are broadcast as well. Isn't that a huge overhead? Wouldn't it be better if I glued all data together using delimiters like this?

```
1;-5.62;23.74;-5.64;0;0

```

The disadvantage here would be that I have to split the string each time I receive it. But isn't that much better for latency?

# Answer
> I take it all the variable name are broadcast as well. Isn't that a huge overhead?

That's the case, and yes that's quite an overhead.

> Wouldn't it be better if I glued all data together using delimiters like this (...)? The disadvantage here would be that I have to split the string each time I receive it. But isn't that much better for latency?

That would be better for latency, but yes, you lose the handiness of JSON.

A middle ground solution:

* Use short variable names, "n" for "names", "a" for "args", etc. Less readable but saves some precious bytes. In the same spirit, try to avoid strings and use enum-like integers wherever possible.
* Compress your messages, for instance using BiSON.js.
> 7 votes

# Answer
Sure it is an overhead, but if your packets generally ain't much larger than the example you give it is not much overhead, pretty insignificant relative to general overhead of sending a package.

Of course a denser format is a small performance improvement, and it should be considered. At the early development however I'd stick to something like JSON for easy debugging.
> 7 votes

---
Tags: node.js, websocket
---


# Question
Title: Method for procedurally creating spawn points
I have a world made of floating islands that are procedurally generated. I would like to spawn enemies or the player in logical-non-falling-into-space spawn points. Ideas on how to accomplish this? My thoughts were this:

1. Drop a bunch of spawn checking items and if they fall for too long then that is a bad spawn point.
2. Build logic into how the randomly generated world is built so that there are regions pre-recongnized as the place to place NPCs, baddies, player, etc.

If anyone has links to some blogs or reports concerning this or your own ideas on this please post!

# Answer
Number 1 would work, but a lot depends on your world. If it is huge, and the islands are far apart, you will spend a lot of time with "misses". Also, can one island be over another? If so, you might end up with just spawns on the upper islands, and nothing on the lower ones.

Number 2 is the right idea. Assuming your islands aren't totally featureless blank shapes, I'm guessing you will be putting other items on the islands beyond spawns, which leads to my suggestion below...

Assuming your world generator has some way to create and place entities on the islands (sprites, NPCs, paths, trigger points, items, what have you), you can just generate a "spawn point" entity as well. It is just an invisible placeholder with a coordinate on your world.

When you want to place (spawn) an enemy or the player, pick one, and put them there. If you want, you can do things like invalidate a spawn point once used so two items won't spawn on top each other. Also, you can filter further to regulate spawns. For example, pick a spawn point, and then search all existing used spawn points. If the new one is closer than some distance to an existing one, reject it. This could be as simple as just keeping your spawners from being too crowded, or even monster distribution - i.e., don't put big strong enemy close together, don't put enemies within X distance of the player, etc.
> 4 votes

---
Tags: procedural-generation, voxels
---


# Question
Title: Graphical quality of open source vs. commercial games
I'm new in Game development. I have researched many open source games. But I have not met any open source game which has high quality graphics, comparable to these found in commercial games.

What is the reason for this? Are open source game engines not advanced enough to support such graphics or is there just a lack of assets, textures and models?

I know that this question is very general, I would like to hear some points of view.

# Answer
The look of a game is rarely down to the code quality, but down to the art quality. Art doesn't really come under the 'open source' concept so getting a coherent set of good art assets for a game for free is very difficult.
> 15 votes

# Answer
My gf is a professional illustrator so I asked her to help me out on my latest game as I wanted more commercial level graphics.

I now know why the credits at the end of the game go on for so long.

In a 2d game each character sprite is drawn 30 to 40 times depending on the depth and that takes a lot of time.

3D textures take even more time when you think of characters, terrain can be faked but character that include complex movement require a huge amount of graphical resources.

The fact that you are asking such a question leads me to believe you have no idea just how much is required for a commercial quality game. Yes the programming plays a big part but the graphics take as long if not longer and you haven't even considered sound or plot.

Bottom line time.
> 7 votes

# Answer
Open source games are usually people who work during their free time, when they want to. They don't have any obligation to work.

For a commercial game, the people working on the game get monetary compensation for their work, and if their work is no good, they get fired. Basically they have more motivation. Another factor is the number of people.
> 3 votes

# Answer
Bad code is far easier to gloss over than bad art or bad design.
> 3 votes

# Answer
From what I have seen It is my firm opinion that what is plaguing open source games is actually gameplay and engines.

It actually stands to reason as uninteresting or "alpha" gameplay will not interest anyone,and if the engine is limited it might deter artist since they can't reach an acceptable level of quality or style.

Most games with solid interesting gameplay and a solid engine I have not seen to have bad art.
> 1 votes

# Answer
The issue comes down to art. Many of the open source programmers either want to moon light as a gamer developer or are game developers by trade and want to help FOSS games get to the next level. Some open source commercial games are rather old, but are a good starting point for some. Let us not forget that you can create a complete modern game using the Unreal Development Kit of even Unity3D. On the other side of the equation you have the Irrlicht Engine and Ogre3d.

In every project, it always comes down to the art assets. Doesn't matter how poor or modern the code is. Textures are fairly easy to find, but an artist who is willing to spend weeks or months to create models for a game for free... thats a much more difficult challenge. Another issue is modeling packages. Not many people have $3,000 or more to buy 3ds Max, Lightwave3d, Maya, SoftImage, etc. That leaves what... MilkShape3d, Blender, trueSpace 7 (released as freeware), and ???
> 1 votes

# Answer
Open source and commercial are not mutually exclusive! Do you know anything about free software? There's a difference between free as in software and free as in beer.

For instance, Quake 3 was a hugely popular, very technical, 3D, high performance, commercial game engine. It sold as its own game, and then Id sold it out to other developers to make lots of games. They didn't do it immediately, but the quake 3 engine is now open source under the GNU public licence v2. Lots of indie / open-source games are being built upon the open sourced Quake 3 engine.

There's tons of other modern games that are open source as well, just look around. Myst URU Online just announced that they are going to be releasing the source code to both the client, the tools, and a server. Thats a modern, totally 3D game. There are tons of others.

"What is the main problem? Engine(Programmable part) or just textures/models?"

I'm not sure you even know what it is you're asking. Are you talking about open source, or are you talking about indie games? There's a HUGE difference.

Also, have you heard of mods?
> -1 votes

---
Tags: open-source
---


title: 2D game with 3D models and terrains

text:
# Question
Title: 2D game with 3D models and terrains
I am approaching OpenGL and general gaming-development. I want to start by coding a simple 2D game in Java (lwjgl) but, since I can create models with Blender, I don't want to use 2D sprites, but a semi-flat environment. My target is to remake a classic game but with some cool stuff like particle emitters, bump mapping, lighting and so on... The basic idea is to make something that looks like Super Mario Bros Wii (or Kirby's Adventures Wii, or Super Smash Bros. etc...).

Do you think I have to use JavaMonkeyEngine? Some hints,code snippets, tutorials, links? Do I have to handle a "z-fixed" camera or set-up OpenGL to render in 2D mode? What about the HUD? Sorry if my question is too generic, but I would like to have a clear idea of what I have to do before starting writing code. As always, thanks for your help!

# Answer
I'll mostly compile what others said in comments. It's definitely possible to make a 2D game using 3D rendering, it's actually what most games do nowadays. So, to answer your questions:

## Do you think I have to use JavaMonkeyEngine?

You *can* use jMonkeyEngine, but you could use *any* 3D engine for that matter

## Do I have to handle a "z-fixed" camera or set-up OpenGL to render in 2D mode?

I'd say you've got 3 options:

* Old-school 2D: render only flat polygons at depth zero, with an orthographic projection; that's basically a sprite engine over a 3D engine. You said you didn't want sprites, so I guess this is a no-go.
* 2.5D: use a "regular" perspective projection but flat polygons only, at different depths layers; that's what's used in Shank or Rayman Origins for instance.
* 3D with 2D gameplay: full 3D assets, but the gameplay sticks to one plane only, e.g. Trine or Donkey Kong Country Returns.

## Some hints, code snippets, tutorials, links?

It all depends on which option you choose, I'm sure you'll find resources by yourself. Still, have a look at Wikipedia for an explanation of orthographic projections, and here for their configuration in jMonkeyEngine.

## What about the HUD?

It's just the same as in a 3D game, rendered in screen-space after all the rest with your favorite lib.
> 1 votes

# Answer
Complementing lorancou's answer, I would add that you also have the option to create the backgrounds and objects in 3d, pre-render them and use the pre-rendered sprites in the game. It is possible to obtain nice visuals doing that.
To create a nice sense of depth, use parallax scrolling, you can find information about the technique here:
Question About An Implementation Of Parallax Scrolling In C++/SDL/OpenGL
and here:
http://shinylittlething.com/2009/08/08/pygame-parallax-scrolling-in-2d-games/
> 1 votes

---
Tags: opengl, java
---


# Question
Title: My GLSL shader isn't compiling even though it should. What should I investigate?
I'm porting an iOS game to Android. One of the shaders I'm using wouldn't compile until I reduced the number of uniform variables. Here are the uniform definitions:

```
uniform highp   mat4 ViewProjMatrix;
uniform mediump vec3 LightDirWorld;
uniform mediump int  BoneCount;
uniform highp   mat4 BoneMatrixArray[8];
uniform highp   mat3 BoneMatrixArrayIT[8];
uniform mediump int  LightCount;
uniform mediump vec3 LightPos[4]; // This used to be 12, but now 4, next lines also
uniform lowp    vec3 LightColour[4];
uniform mediump vec3 LightInnerOuterFalloff[4];

```

My issue is that the GLSL shader wouldn't compile until I reduced the count of the above arrays from 12 to 4. My understanding is that if those 3 lines were arrays of 12 then I would be using 56 vertex uniform vectors. I query the system at startup (GL\_MAX\_VERTEX\_UNIFORM\_VECTORS) and it says that 128 are available. Why wouldn't it compile with 56? I'm having issues on the Kindle Fire.

# Answer
Uniform variables are counted in units of vec4's. So each mat4 counts as four, and each mat3 counts as three. Your BoneMatrixArray is using up 4\*8=32 slots. Your BoneMatrixArrayIT is using 3\*8=16. There's 48 slots right there.

Toss in your three arrays of 12 elements and you're up another 36 slots. Miscellaneous other items you've got there give you another 7. Totals up to 91 slots.

Not 128 still, but some uniform slots may be getting used by other things not in your code. Not sure if built-ins count (don't think so), but samplers and such probably do.

The implementation may also just be lying about its limits. GL does not have a conformance test suite, so many implementations suffer from lots of bugs.
> 5 votes

---
Tags: android, shaders, glsl
---


title: Animated light effects in games

text:
# Question
Title: Animated light effects in games
I have been wondering now for quite some time, how certain animated texture effects are done, specifically involving light effects.

Some good examples of what I mean are the green bridges in Darkspore, who have a pulsating light effect (pic), the light bridges in Portal or some spell effects from Oblivion (pic).

Are those effects purely done with shaders? And if so, how would you go about doing them? If I for example wished to create an effect, which would send little lightning bolts from a character models feet to the top as illustration that he got electrocuted, how would that work?

To my person: Although I am proficient in programming, I am mostly a beginner, when it comes to shaders. I understand most of the math behind it, but have almost no practical experience with them.

I hope you can clear things up for me a bit!

Thanks you for reading and in advance for any help! Christoph

# Answer
> 1 votes
These are most commonly done, as far as I know, with a combination of animated texture maps (along with an alpha channel, obviously) — for instance, in the Darkspore example the animated texture would be laid onto a series of essentially rectangles representing the bridge, or in Oblivion as a second texture on the player mesdh — supplemented in some cases by a simple glow shader. There's really no need for a potentially-complicated shader effect when a texture will do the job equally well (and more efficiently).

---
Tags: shaders, effects, lighting
---


title: Can I use PBOs for textures in iOS?

text:
# Question
Title: Can I use PBOs for textures in iOS?
As far as I can see, there is no `GL_PIXEL_UNPACK_BUFFER`. Also, the OpenGL ES 2.0 specification (and as far as I know, no iOS device currently supports OpenGL ES \> 2.0) states that `glMapBufferOES()` can only use `GL_ARRAY_BUFFER` as a target, yet `glTexImage2D()` and `glTexSubImage2D()` only seem to use PBOs if `GL_PIXEL_UNPACK_BUFFER` is bound.

The OpenGL documentation for `glBindBuffer()` also states that:

> `GL_PIXEL_PACK_BUFFER` and `GL_PIXEL_UNPACK_BUFFER` are available only if the GL version is **2.1 or greater**.

So, can I use PBOs for textures? Am I missing something obvious?

# Answer
OpenGL ES doesn't have pixel buffer objects. So you can not use them there.
> 5 votes

# Answer
OpenGL and OpenGL ES, despite the similar names, are two *different* specifications. They may have similarly named functions, but there will be semantic differences between what these functions do. And of course, there will be differences in what features they support.

PBOs are not supported on ES (except for ES 3.0, which recently came out but isn't widely supported yet), regardless of version. There isn't even an extension for it. Also, you should probably read up on what PBOs actually do; they don't do what you think they do.
> 7 votes

---
Tags: opengl-es, ios, opengl-es2
---


# Question
Title: Do I need to roll my own polygon segmentation algorithm to automate Box2d body creation from a tile map?
Before re-inventing the wheel I figured I'd ask:

I'm working on a tile-based 2d-maze level generator for cocos2d + box2d. The idea is:

1. I'm using one of the well-known graph traversal algorithms to generate a random maze.
2. This data gets encoded as an XML of the type that both Tiled and cocos2d can work with.
3. Based on the generated maze tile data, my program should also generate the polygonal data (vertices) that define the walls of the maze so that I can get them from, for instance, a Tiled's XML's object layer and into Box2d for defining bodies.

However, I'm at step 3 and so far, I'm thinking of solving this step with something along the lines of a flood/segmentation/magic wand algorithm. That is, from step 2 I get the graph's nodes which translate in Tiled's XML to, for instance, a 2d array where walls are marked with a number and open spaces are 0s. This is in the cvs non-compressed XML representation for instance.

So what I need to do now is sort of solve the convex-hull problem for a bunch of points (the non-zero numbers in this 2d array), but actually creating different polygons. I also need to then break any concave ploys into convex, but that can be done easiest with ear-clipping and, should I decided to get fancier, Delaunay or something.

Let me illustrate with images:

And in the next image you can see **A** the set's convex-hull (approximately), and **B** what I'm trying to achieve (concave subsets of the hull):

That is, I need to be able to distinguish separate polys. Of course, but for one, these also turn out to be concave which Box2d will not like. But like I said, I'll turn them to convex sets afterwards.

The question is, is there anything built-in or tested/tried that I could just grab and use or do I need to implement my magic wand algorithm?

I'm also open to different approaches all together.

# Answer
> 1 votes
Make a square body for each tile. Box2D scales up very well when using a large number of static bodies.

If you are very concerned, you could make rectangular bodies along each scanline. This would result in 14 bodies for your sample picture, down from 42 if you make a body per tile. This generates only convex polygons so you don't need more postprocessing, and is also faster than just a flood fill.

(But because of the spatial partitioning algorithms involved it's really not that big a deal - 14 to 42 is only two powers of two.)

---
Tags: collision-detection, box2d, cocos2d-iphone
---


# Question
Title: How can I optimise collision checks for a large number of AI units?
Let's say I got 100 Orcs in my 3D world and they all aim to kill each other.

That means for every 1 Orc I have to check for collision with the 99 others. That will give me 99^2 which is about 10,000! That many collision checks every update (24-60 times a second) only for the AI will probably use my whole GPU + CPU.

How can I handle such a large number of AI?

How is this is done in games with large numbers of NPCs (e.g. *Skyrim*, *Fallout*, *Red Dead Dedemption*...).

# Answer
> 9 votes
Actually, if you have N orcs, you have to check only (1+N)\*(N/2) times (a smart dude named Gauss found this out). In your case, that is 5050. If orc A collides with orc B, that means that orc B collides with orc A. So for the fist orc you have to check 99 times, for the second 98 times, and so on. If you use space partitioning as the suggested in the comments, and check only orcs that are close to each other the number of checks is not so big.

p.s. collision checking should not be performed by the AI. The AI should act based on the result of collision checking

# Answer
> 1 votes
Use spatial partition to reduce collision to O(n logn), not O(n^2). Also, a modern CPU can *easily* push 10k checks 60 times a second. I had an N-body simulation which could push about 2m checks at 30fps. And the GPU does not give a monkey's thrown faeces about your AI.

---
Tags: collision-detection, ai, optimization, npc
---


# Question
Title: FPS networking with server sending input instead of gamestate
Why do all fps games have the server send gamestate instead of input which is smaller?

One reason I can sort of see is that if the server sends input to the clients and a packet gets dropped then the client will not be able to gave an accurate simulation until a resend of that packet occurs which could be an entire timeout plus one way trip latency. Presumably this is considered unreasonable for a real time fps game.

But what if at time T the server sends the input processed at time T to the client and at time T+1 the server sends the input processed at time T and time T+1. This way if the packet containing the input processed at time T is dropped the client will get the next packet sent by the server which contains the input processed at time T and time T+1. Thus the client will not stall on the simulation because the server is redundantly sending previous input. The server stops sending a previous input when it gets an ack from the client.

This seems to avoid sending the entire game state. Can someone tell me why this idea is just bad and why no fps games use it?

# Answer
Non player characters don't have 'input', and neither do projectiles. In fact a lot of the time players aren't acting as a result of input but as a result of physics. So, generating artificial inputs for some of these entities is extra work.

It also assumes that all clients will handle input in exactly the same way, and this won't be the case if there is any interaction between the characters because each player will see a slightly different game state due to latency and their own actions. Clients can fix this with a rollback and replay approach but that is more complicated when you have to do it for every entity and its input instead of just your own input.

Elaboration based on comments:

* Not every server-side action (eg. AI, physics-led behaviour) has a simple or natural representation as 'input', so often it's easier to just send the results, ie. the changed state;
* Even where there is a usable representation, it's not necessarily cheaper to send than the new state. (eg. If you send a vector representing a projectile's movement, that is likely to be exactly the same size as a vector representing its new position.)
* Not every algorithm is trivial to run in exact synchronisation on different machines. eg. Some graphics systems do strange things to the floating point subsystem.
* Every client sees a different view of the world anyway, if you're doing prediction on the client, which is usually necessary for faster games such as FPSes where units move very quickly. Inputs taken based on a predicted state can turn out to be invalid, which means there needs to be some way of resolving them, which can be complex.
* One way of simplifying a system like this involves sticking to discrete timesteps and ensuring that each timestep is identical across all clients (also known as 'lockstep') but this doesn't suit all games, especially faster paced ones, as a reliance on perfect information comes at a latency cost, often covered up by animations and client-side delays.
* resending extra input in the case of error is less efficient in the face of high packet loss than sending new state. There comes a point when it is cheaper both in bandwidth and in processing time to send an updated state than to send a bunch of sequential updates, and in terms of coding time it may not be worth writing both code paths if you know that just sending states will do.
> 6 votes

# Answer
Strategy games usually send input, while shooters usually send gamedata. However there are exceptions. For example Halo : Reach runs in lockstep in some online game modes, sending only input.

There are multiple reasons for this:

1. Shooters have a lot less game data than strategy games
2. It's easier to keep the game in sync
3. It reduces lag as long as the game data to send is small

**Shooters have a lot less game data than strategy games**

A typical shooter has 10 people shooting at each other. The data for this is small, for each player you only need to know the position, direction, speed, health and current weapon. Once people start shooting it's going to be a bit more but that data doesn't need to be retransmitted to every player. In strategy games you have to send this for all 100 units of all the 10 players, which quickly explodes into a gigantic game state.

**It's easier to keep the game in sync**

When everyone sends their game data the server knows exactly the state of each player's game and can thus easily compare everyone's game state to see if it's in sync. If it isn't in sync the server can usually tell who isn't, because the data is received from multiple sources, and can send messages to correct it. If the server only receives input and through some weird errors one player goes out of sync then there is no easy way to repair it so the player has to be dropped.

**It reduces lag as long as the game data to send is small**

When sending input data you are usually running in lockstep. This means that each client get's a turn, the server then decides the outcome and sends the changes (as input) to all the clients. This means that you have to keep waiting on the player with the highest latency. (You could run without lockstep, but I have no idea how that would work on just input since you're bound to desync soon then).

**Why don't all non-RTS games just send game state**

There are also a few good reasons for just sending input data. You can't cheat with input data, while it's fairly easy to cheat with modifying your game state, and it's easier to resolve bug with happen due to lag since everyone is running at the pace of the slowest player so everyone sees the same thing happening for each event.

*Further reading*
> 13 votes

---
Tags: networking, multiplayer, client-server, first-person-shooter
---


title: Sliding collision response

text:
# Question
Title: Sliding collision response
I have been reading plenty of tutorials about sliding collision responses yet I am not able to implement it properly in my project. What I want to do is make a puck slide along the rounded corner boards of a hockey rink. In my latest attempt the puck does slide along the boards but there are some strange velocity behaviors. First of all the puck slows down a lot pretty much right away and then it slides for awhile and stops before exiting the corner. Even if I double the speed I get a similar behavior and the puck does not make it out of the corner. I used some ideas from this document http://www.peroxide.dk/papers/collision/collision.pdf.

This is what I have:

Update method called from the game loop when it is time to update the puck (I removed some irrelevant parts). I use two states (current, previous) which are used to interpolate the position during rendering.

```
public override void Update(double fixedTimeStep)
{
    /* Acceleration is set to 0 for now. */
    Acceleration.Zero();

    PreviousState = CurrentState;

    _collisionRecursionDepth = 0;

    CurrentState.Position = SlidingCollision(CurrentState.Position, CurrentState.Velocity * fixedTimeStep + 0.5 * Acceleration * fixedTimeStep * fixedTimeStep);

    /* Should not this be affected by a sliding collision? and not only the position. */
    CurrentState.Velocity = CurrentState.Velocity + Acceleration * fixedTimeStep;

    Heading = Vector2.NormalizeRet(CurrentState.Velocity);
}

private Vector2 SlidingCollision(Vector2 position, Vector2 velocity)
{
    if(_collisionRecursionDepth > 5)
        return position;

    bool collisionFound = false;

    Vector2 futurePosition = position + velocity;

    Vector2 intersectionPoint = new Vector2();

    Vector2 intersectionPointNormal = new Vector2();

    /* I did not include the collision detection code, if a collision is detected the intersection point and normal in that point is returned. */

    if(!collisionFound)
        return futurePosition; /* If no collision was detected it is safe to move to the future position. */

    /* It is not exactly the intersection point, but slightly before. */
    Vector2 newPosition = intersectionPoint;

    /* oldVelocity is set to the distance from the newPosition(intersection point) to the position it had moved to had it not collided. */
    Vector2 oldVelocity = futurePosition - newPosition;

    /* Project the distance left to move along the intersection normal. */
    Vector2 newVelocity = oldVelocity - intersectionPointNormal * oldVelocity.DotProduct(intersectionPointNormal);

    if(newVelocity.LengthSq() < 0.001)
        return newPosition; /* If almost no speed, no need to continue. */

    _collisionRecursionDepth++;

    return SlidingCollision(newPosition, newVelocity);
}

```

What am I doing wrong with the velocity? I have been staring at this for very long so I have gone blind. I have tried different values of recursion depth but it does not seem to make it better. Let me know if you need more information. I appreciate any help.

**EDIT:** A combination of Patrick Hughes' and teodron's answers solved the velocity problem (I think), thanks a lot! This is the new code:

I decided to use a separate recursion method now too since I don't want to recalculate the acceleration in each recursion.

```
public override void Update(double fixedTimeStep)
{
    Acceleration.Zero();// = CalculateAcceleration(fixedTimeStep);

    PreviousState = new MovingEntityState(CurrentState.Position, CurrentState.Velocity);

    CurrentState = SlidingCollision(CurrentState, fixedTimeStep);

    Heading = Vector2.NormalizeRet(CurrentState.Velocity);
}

private MovingEntityState SlidingCollision(MovingEntityState state, double timeStep)
{
    bool collisionFound = false;

    /* Calculate the next position given no detected collision. */
    Vector2 futurePosition = state.Position + state.Velocity * timeStep;

    Vector2 intersectionPoint = new Vector2();

    Vector2 intersectionPointNormal = new Vector2();

    /* I did not include the collision detection code, if a collision is detected the intersection point and normal in that point is returned. */

    /* If no collision was detected it is safe to move to the future position. */
    if (!collisionFound)
        return new MovingEntityState(futurePosition, state.Velocity);

    /* Set new position to the intersection point (slightly before). */
    Vector2 newPosition = intersectionPoint;

    /* Project the new velocity along the intersection normal. */
    Vector2 newVelocity = state.Velocity - 1.90 * intersectionPointNormal * state.Velocity.DotProduct(intersectionPointNormal);

    /* Calculate the time of collision. */
    double timeOfCollision = Math.Sqrt((newPosition - state.Position).LengthSq() / (futurePosition - state.Position).LengthSq());

    /* Calculate new time step, remaining time of full step after the collision * current time step. */
    double newTimeStep = timeStep * (1 - timeOfCollision);

    return SlidingCollision(new MovingEntityState(newPosition, newVelocity), newTimeStep);
}

```

Even though the code above seems to slide the puck correctly please have a look at it.

I have a few questions, if I don't multiply by 1.90 in the newVelocity calculation it doesn't work (I get a stack overflow when the puck enters the corner because the timeStep decreases very slowly -\> a collision is found early in every recursion), why is that? what does 1.90 really do and why 1.90?

Also I have a new problem, the puck does not move parallell to the short side after exiting the curve; to be more exact it moves outside the rink (I am not checking for any collisions with the short side at the moment). When I perform the collision detection I first check that the puck is in the correct quadrant. For example bottom-right corner is quadrant four i.e. circleCenter.X \< puck.X && circleCenter.Y \> puck.Y is this a problem? or should the short side of the rink be the one to make the puck go parallell to it and not the last collision in the corner?

**EDIT2:**

This is the code I use for collision detection, maybe it has something to do with the fact that I can't make the puck slide (-1.0) but only reflect (-2.0):

```
/* Point is the current position (not the predicted one) and quadrant is 4 for the bottom-right corner for example. */
if (GeometryHelper.PointInCircleQuadrant(circleCenter, circleRadius, state.Position, quadrant))
{
    /* The line is: from = state.Position, to = futurePosition. So a collision is detected when from is inside the circle and to is outside. */
    if (GeometryHelper.LineCircleIntersection2d(state.Position, futurePosition, circleCenter, circleRadius, intersectionPoint, quadrant))
    {
        collisionFound = true;

        /* Set the intersection point to slightly before the real intersection point (I read somewhere this was good to do because of floting point precision, not sure exactly how much though). */
        intersectionPoint = intersectionPoint - Vector2.NormalizeRet(state.Velocity) * 0.001;

        /* Normal at the intersection point. */
        intersectionPointNormal = Vector2.NormalizeRet(circleCenter - intersectionPoint)
    }
}

```

When I set the intersection point, if I for example use 0.1 instead of 0.001 the puck travels further before it gets stuck, but for all values I have tried (including 0 -\> the real intersection point) it gets stuck somewhere (but I necessarily not get a stack overflow). Can something in this part be the cause of my problem?

I can see why I get the stack overflow when using -1.0 when calculating the new velocity vector; but not how to solve it. I traced the time steps used in the recursion (initial time step is always 1/60 ~ 0.01666):

```
Recursion depth   Time step next recursive call
[Start recursion, time step ~ 0.016666]
0                 0,000985806527246773
[No collision, stop recursion]
[Start recursion, time step ~ 0.016666]
0                 0,0149596704364629
1                 0,0144883449376379
2                 0,0143155612984837
3                 0,014224925727213
4                 0,0141673917461608
5                 0,0141265435314026
6                 0,0140953966184117
7                 0,0140704653746625
...and so on.

```

As you can see the collision is detected early in every recursive call which means the next time step decreases very slowly thus the recursion depth gets very big -\> stack overflow.

# Answer
> 4 votes
Refer to the following picture:

Say we are at instance *t* and we want to get the velocity and position of the entity at time *t+Dt*. The simplest and crudest pseudocode comprising collision detection, handling and naive Euler integration would then be:

```
     predictedPos = oldPos + oldVelocity * Dt;
     if ( insideSurface(predictedPos) )
     {
        intersectionPoint = intersect(Plane, oldPos, predictedPos);
        normalVel = dot(planeNormal, oldVelocity) * planeNormal; // yellow arrow
        intersectionTime = length(oldPos, intersectionPoint) / length(oldPos, predictedPos) * Dt;
        timeLeft = Dt - intersectionTime; // the time left for the ball to travel from the intersection point to the corrected position
        newVelocity = oldVelocity - 1.9 * normalVelocity; // geometrically reflect the velocity using the plane's normal
        correctedPos = intersectionPoint + timeLeft * newVelocity;
     }
     else
     {
        correctedPos =  oldPos + oldVelocity * Dt;
        newVelocity = oldVelocity;
     }
     oldVelocity = newVelocity + acceleration * Dt;
     oldPos= correctedPos;

```

`Acceleration` can be anything: gravity, `-b* oldVelocity` \- a drag force or even a constant if you plan on having a rocket boosted hockey puck. Note that `-1.90 * normalVelocity` is used to geometrically reflect the velocity, but also to "dampen" it as an effect of an imperfect elastic collision. If you don't want to lose energy, just use `2.0 * normalVelocity` instead for perfect reflections.

*For a sliding behaviour* use this trick:

```
     predictedPos = oldPos + oldVelocity * Dt;
     if ( insideSurface(predictedPos) )
     {
        intersectionPoint = intersect(Plane, oldPos, predictedPos);
        normalVel = dot(planeNormal, oldVelocity) * planeNormal; // yellow arrow
        intersectionTime = length(oldPos, intersectionPoint) / length(oldPos, predictedPos) * Dt;
        timeLeft = Dt - intersectionTime; // the time left for the ball to travel from the intersection point to the corrected position
          // cancel out the normal component
          newVelocity = oldVelocity - 1.0 * normalVelocity;
          // correct the magnitude
          newVelocity = length(oldVelocity) / length(newVelocity) * newVelocity;
        correctedPos = intersectionPoint + timeLeft * newVelocity;
     }
     else
     {
        correctedPos =  oldPos + oldVelocity * Dt;
        newVelocity = oldVelocity;
     }
     oldVelocity = newVelocity + acceleration * Dt;
     oldPos= correctedPos;

```

This way, you make sure the newVelocity has the same magnitude as the oldVelocity, hence no energy loss, hence no "slowing down".

**Collision with a circular rink/wall** Refer to the picture below: Say your collision handling method looks like:

```
  HandleCollision( currPos, currVel, timeSlice, outPos, outVel)

```

Then you should compute a possible collision between your object and the rink, then from the intersecion point, with a new (reflected) velocity, call again this method until the time left to travel is zero or either the puck is completely inside the circle. In naive pseudocode:

```
  HandleCollision( currPos, currVel, timeSlice, outPos, outVel)
  {
       bool intersects = IntersectWall(currPos, currVel, timeSlice, intPos);
       if (intersects)
       {
           // time left to travel after collision
           timeLeft = timeSlice - length(currPos - intPos) / length(currVel);
           newPos = intPos;
           normal = normalize(intPos - circleCenter);
           // reflection with losses (energy)
           newVel = currVel - 1.90 * dot(currVel, normal) * normal;
           // check for collisions
           HandleCollision(newPos, newVel, timeLeft, outPos, outVel);
       }
       else
       {
           outPos = timeSlice * currVel + currPos;
           outVel = currVel;
       }
  }

```

Checking with the picture: the initial time step is *t0*, but when the puck still has *t1* units to go, it hits the wall at *P1*. Now, the procedure is called again, this time *t2=t1* is the time left to travel. When it hits the wall again, at *P2*, is still got some *t3* units left to go. Again, we set the current position to *P2* and reflect the velocity. Using *t3* and the reflected velocity, we end up with the final position, *P3*. This is just one example depicting how the method should work, conceptually.

**Working sample**

Using Ogre as a render engine, I've written this terribly simplified update function:

```
 void BaseApplication::PerformCollision(Ogre::Vector2 currPos, Ogre::Vector2 currVel, double timeSlice, Ogre::Vector2 &outPos, Ogre::Vector2 & outVel)
 {
Ogre::Vector2 newPos, newVel = currPos;
newPos = currPos + currVel * timeSlice;

if (newPos.length() > mRadius)
{
    //collision
    Ogre::Vector2 intPos = currPos;
    double timeLeft = timeSlice;
    Ogre::Vector2 normalVec = newPos;
    normalVec = normalVec / normalVec.length();
    Ogre::Vector2 reflVel = currVel - 1.9f * normalVec * normalVec.dotProduct(currVel);
    PerformCollision(intPos, reflVel, timeLeft, outPos, outVel);
}
else
{
    outPos = newPos;
    outVel = currVel;
}
 }

```

this is how it should work..

# Answer
> 1 votes
Your recursion isn't handling time, and without knowing how much time was used out of the fixed step in the calling function you can't move your position in any real way.

Because new position = old position + velocity * time.

If you recurse on the Update() function instead of SlidingCollision() and figur out how much time had been used before the collision and used that value to pass back into Update() then this might work like you expect.

Example:

```
Update( 1.0 )
  hit something at 0.75 of my full possible move
  Update( 0.25 )
    hit something at 0.5 of my full possible move
    Update( 0.125 )
      nothing hit
    pop
  pop
returns

```

At least I think that's it.

---
Tags: collision-detection
---


title: Drawing hexagonal grid on Android

text:
# Question
Title: Drawing hexagonal grid on Android
I'm trying to draw a hexagon grid in my Android application. I don't want to reinvent the wheel here, so I'm looking for some frameworks/libraries or just some basic ideas about how should one do this. Do you have some ideas?

What I found so far:

# Answer
The math applies to any platform, of course. Since you asked for basic ideas on how to do this: **just use the code from the first link you provided**. The java code for implementing all the required formulas is present and could be used as-is. Then you have an excellent example of how to tie that class into your existing code. Use the source from the simple java test applet as a guide to help you integrate this into your code.
> 6 votes

---
Tags: java, android, tiles, hexagonal-grid
---


# Question
Title: HTML5 Canvas fillStyle as numbers not text
When drawing vector graphics in the canvas you set the fillStyle using an rgba string like this...

```
context.fillStyle = "rgba(255, 223, 191, 1)";

```

Is it possible to feed in a javascript object instead (or just numbers). Seems silly that I would need to construct a string to feed to this value if I wanted the color dynamic.

```
context.fillStyle = "rgba(255, 223, 191, " + alpha + ")";

```

The specification clearly says "a CSS Color string" but it seems crazy. Am I missing something?

http://www.w3.org/TR/2dcontext/#fill-and-stroke-styles

update: I switched to using globalAlpha for this specific example. But still seems crazy.

# Answer
Nope, you're not missing anything. This has to be a string, containing a valid CSS color value.

To reassure you, you're not the first one wondering why so much hate.
> 2 votes

---
Tags: html5, html-canvas, browser-based-games
---


# Question
Title: How to display bitmap using Texture api in android opengl
I want to display a bitmap image at screen using texture api in android opengl. Some code which I have used in our code as below.

```
public void onSurfaceChanged(GL10 gl, int width, int height) {
    gl.glGenTextures(1, texture, 0);
    gl.glBindTexture(GL10.GL_TEXTURE_2D, texture[0]);
    gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_NEAREST);
    gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_NEAREST);
    Bitmap bmp = BitmapFactory.decodeResource(ContextController.getContext().getResources(), R.drawable.ic_launcher);
    GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bmp, 0);
    bmp.recycle();
}

```

I have use this code But image is not display, screen is display as blank.

# Answer
> 1 votes
You are omitting important opengl calls. http://www.opengl.org/wiki/Common\_Mistakes#Creating\_a\_Texture

---
Tags: android, opengl-es
---


title: Deactivate keyboard input on collision

text:
# Question
Title: Deactivate keyboard input on collision
I'm creating an online-canvas-game with a tank as player object.

Now I have several structures in my canvas, that shouldn't be able to be overdriven by the tank...
My solution is to detect the collision like that:

```
if(hero.x > reactor[i]['x'] - 32 && hero.x <= reactor[i]['x'] + 32
   && hero.y > reactor[i]['y'] - 32 && hero.y <= reactor[i]['y']){
    collidetop = true;
}

if(hero.x > reactor[i]['x'] - 32 && hero.x <= reactor[i]['x'] + 32
   && hero.y >= reactor[i]['y'] && hero.y < reactor[i]['y'] + 32){
    collidebottom = true;
}

if(hero.x > reactor[i]['x'] - 32 && hero.x <= reactor[i]['x']
   && hero.y > reactor[i]['y'] - 32 && hero.y <= reactor[i]['y'] + 32){
    collideleft = true;
}

if(hero.x > reactor[i]['x'] && hero.x <= reactor[i]['x'] + 32
   && hero.y > reactor[i]['y'] - 32 && hero.y <= reactor[i]['y'] + 32){
    collideright = true;
}

```

The `hero` object is the tank, `hero.x` the x-coordinate, and so on...
Now I'd like to deactivate the keyboard input for the direction key, if the objects collide...
For this reason I have the variables `wok`, `aok`, `sok` and `dok` \- they all contain booleans.
If `wok = false`, then the key "w" is deactivated...
I've connected the collide variables to the keyboard inputs:

```
if(collidetop == true){
    sok = false;
}
if(collidetop == false){
    sok = true;
}
if(collidebottom == true){
    wok = false;
}
if(collidebottom == false){
    wok = true;
}
if(collideright == true){
    aok = false;
}
if(collideright == false){
    aok = true;
}
if(collideleft == true){
    dok = false;
}
if(collideleft == false){
    dok = true;
}

```

My problem is: if the tank doesn't collide the other object any more, the keys stay blocked... Could you help me with that?

# Answer
Say your tanks has driven into a wall. It shouldn't be able to move forward anymore. In this case you disable the key that gives the 'move forward' command however I think this is the wrong way of looking at it. You can still give the tank the move forward command, that shouldn't be a problem, what really is stopping it from moving forward is the wall.

I would take the following approach:

A tank/users should always be able to request to move however the physics system should decided if the tank moves. This means that you would have the following setup:

```
1: Tank wants to move forward
2: The physics system stores the old position of the tank
3: The physics system moves the tank forward
4: The physics system checks if the tank now collides with something
5: If the tank collides with something move it back to old position, if it didn't collide with something everything is good, keep it where it is.

```

Having the physics system do all the movements also has the added benefit that other things than user input can move the tank, for example explosions, as long as they request the physics system to move it everything should be OK and you only have to write the code once.
> 2 votes

# Answer
Deactivating input isn't the usual way to react to environment collisions. In a nutshell, it's probably a better idea to affect your tank position when a collision is detected. Roy T. just gave you one proper solution.

You could also do as follows without modifying too much code, just stick the tank to one of the reactor's edges when a collision is detected:

```
if(hero.x > reactor[i]['x'] - 32 && hero.x <= reactor[i]['x'] + 32 &&
   hero.y > reactor[i]['y'] - 32 && hero.y <= reactor[i]['y'] - 28){
    hero.y = reactor[i]['y'] -33;
}

if(hero.x > reactor[i]['x'] - 32 && hero.x <= reactor[i]['x'] + 32 &&
   hero.y >= reactor[i]['y'] + 28 && hero.y < reactor[i]['y'] + 32){
    hero.y = reactor[i]['y'] +33;
}

if(hero.x > reactor[i]['x'] - 32 && hero.x <= reactor[i]['x'] - 28 &&
   hero.y > reactor[i]['y'] - 32 && hero.y <= reactor[i]['y'] + 32){
    hero.x = reactor[i]['x'] -33;
}

if(hero.x > reactor[i]['x'] + 28 && hero.x <= reactor[i]['x'] + 32 &&
   hero.y > reactor[i]['y'] - 32 && hero.y <= reactor[i]['y'] + 32){
    hero.x = reactor[i]['x'] +33;
}

```

This glitches easily if your tank moves fast compared to the reactor's size, but it should at least give you the satisfaction of quickly seeing something that works.

The topic of game collisions and physics in general is huge, so I recommend you find a good resource to learn the basics. Or if you just want collisions but don't want to learn the details, you could try out an existing library, such as Box3DJS (I've not tested it personally so I don't know if it's a good one).
> 2 votes

---
Tags: collision-detection, javascript, html-canvas, keyboard
---


# Question
Title: What are the maths behind 'Raiden 2' purple laser?
The path of the laser is affected by user input and enemies present on the screen. Here is a video, at 5:00 minutes the laser in question is shown : Raiden II (PS) - 1 Loop Clear - Part 2

**UPDATE**

Here is a test using Inkscape, ship is at bottom, the first 4 enemies are targeted by the plasma. There seems to be a sort of pattern. I moved the ship first, then the handle from it to form a 45° angle, then while trying to fit the curve I found a pattern of parallel handles and continued so until I reached the last enemy.

**Update, 5/26/2012** : I started an XNA project using beziers, there is still some work needed, will update the question next week. Stay tuned !

**Update : 5/30/2012** : It really seems that they are using Bézier curves, I think I will be able to replicate/imitate a plasma of such grade. There are two new topics I discovered since last time : Arc length, Runge's phenomenon, first one should help in having a linear movement possible over a Bézier curve, second should help in optimizing the number of vertices. Next time I will put a video so you can see the progress 8-)

# Answer
I just created something that may help you. It was in response to help somebody on the GLBasic forums.

Here is the forum link with my suggestion: Random Textured Rolling Hills

This is written in GLBasic, but I tried to keep it easy to read, so it should be easily converted to any language.

To use it for your needs, you would need to generate your spline data / points. Replace the 'hill' points in my example with your spline points. You would only need to add an animation / flickering effect somehow. Maybe a random texture shift.

The real 'magic' happens in my 'AddPoint' function:

```
FUNCTION AddPoint: h AS THillPoint
    DIMPUSH self.points[], h

    // Is this the very first data point?
    IF LEN(self.points[]) = 1
        self.points[0].pu.Set(0, self.points[0].pm.y - self.texture_ht_up)
        self.points[0].pd.Set(0, self.points[0].pm.y + self.texture_ht_dn)
        RETURN
    ENDIF

    ALIAS h0 AS self.points[-2]  // Reference to the 2nd last point
    ALIAS h1 AS self.points[-1]  // Reference to the last point
    LOCAL angle#
    LOCAL v1 AS TVector
    LOCAL v0 AS TVector

    // Calculate 'p2' of HillPoint - form rectangle with previous point
    angle = ATAN(h1.pm.y - h0.pm.y, h1.pm.x - h0.pm.x)  -90// Angle of the two points

    v1.x = COS(angle) * self.texture_ht_up + h1.pm.x
    v1.y = SIN(angle) * self.texture_ht_up + h1.pm.y
    v0.x = COS(angle) * self.texture_ht_up + h0.pm.x
    v0.y = SIN(angle) * self.texture_ht_up + h0.pm.y
    h0.pu = h0.pu.AverageWith(v0)
    h1.pu.Copy(v1)

    v1.x = COS(angle) * -self.texture_ht_dn + h1.pm.x
    v1.y = SIN(angle) * -self.texture_ht_dn + h1.pm.y
    v0.x = COS(angle) * -self.texture_ht_dn + h0.pm.x
    v0.y = SIN(angle) * -self.texture_ht_dn + h0.pm.y
    h0.pd = h0.pd.AverageWith(v0)
    h1.pd.Copy(v1)
ENDFUNCTION

```

This is where I calculate the final quads / polygons that plots the sprite along the line.

Here's the final results:

And with the polygons' wireframe turned on:
> 6 votes

---
Tags: mathematics, shoot-em-up
---


title: Undeviating bullet in AndEngine

text:
# Question
Title: Undeviating bullet in AndEngine
I'm looking for a bullet that can collide with other bodies of the world but doesn't change direction according to collisions. I want the bullet to perform the collisions but without changing its own direction of moving. Basically I want to create a super bullet that can kill multiple bodies available in sequence. Would you have an advice?

If `RayCastCallback` is part of the solution, then could you tell me how to use it in this case?

# Answer
> 1 votes
AndEngine's physics is based on Box2D. In Box2D , you can create the Body of your bullet with a sensor Fixture. There is a flag you can set on the FixtureDef to make it a sensor. A sensor in Box2D is basically a Fixture that will participate in collisions but not react to collisions on its own which is what you want. You can then provide custom responses to collisions by registering for some callbacks...

From Box2D User Manual:

> Sensors do not generate contact points. There are two ways to get the state of a sensor:
>
> 1. b2Contact::IsTouching
> 2. b2ContactListener::BeginContact and EndContact

I'm sure those callbacks/flags are exposed in AndEngine somehow.

# Answer
> 0 votes
The usual way of creating bullets in video games is to perform raycasts, see this question for details. What you want is just a raycast that *doesn't stop on the first intersection*: there you go, undeviating bullets.

I've no experience with AndEngine so I can't tell you if `RayCastCallback` will do the trick, but that's possible.

---
Tags: andengine, projectile-physics
---


title: Basic post-processing shader problem

text:
# Question
Title: Basic post-processing shader problem
I'm trying to create a basic post-processing shader, like I did many times before but somehow today it's just not working, I guess it's something basic that I missed.

Anyway my setup:

I have 3 render targets rts\[0\], rts, and rts\[2\], I draw a simple model in each one of them. I then draw the render targets to the screen using the following code:

```
GraphicsDevice.SetRenderTarget(null);
GraphicsDevice.Clear(Color.CornflowerBlue);
spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, null, null, null);

spriteBatch.Draw(rts[0], new Rectangle(0, 0, GraphicsDevice.Viewport.Width / 2, GraphicsDevice.Viewport.Height / 2), Color.White);
spriteBatch.Draw(rts[1], new Rectangle(GraphicsDevice.Viewport.Width / 2, 0, GraphicsDevice.Viewport.Width / 2, GraphicsDevice.Viewport.Height / 2), Color.White);
spriteBatch.Draw(rts[2], new Rectangle(0, GraphicsDevice.Viewport.Height / 2, GraphicsDevice.Viewport.Width / 2, GraphicsDevice.Viewport.Height / 2), Color.White);

spriteBatch.End();

```

This gives me the following picture: Which is exactly what I expect it to be :)

Now I feed these 3 render targets as textures to my shader like this: (shaderTexture is a black 1x1 texture)

```
cutAwayEffect.Parameters["lowTexture"].SetValue(rts[0]);
cutAwayEffect.Parameters["highTexture"].SetValue(rts[1]);
cutAwayEffect.Parameters["cutTexture"].SetValue(rts[2]);

spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.Opaque, null, null, null, cutAwayEffect);

spriteBatch.Draw(shaderTexture, new Rectangle(GraphicsDevice.Viewport.Width / 2, GraphicsDevice.Viewport.Height / 2, GraphicsDevice.Viewport.Width / 2, GraphicsDevice.Viewport.Height / 2), Color.White);

spriteBatch.End();

```

And the shader:

```
texture lowTexture;
sampler lowSampler = sampler_state
{
    Texture = (lowTexture);
};

texture highTexture;
sampler highSampler = sampler_state
{
    Texture = (highTexture);
};

texture cutTexture;
sampler cutSampler = sampler_state
{
    Texture = (cutTexture);
};

float4 PixelShaderFunction(float2 texCoord: TEXCOORD0) : COLOR0
{
    float4 baseColour = tex2D(lowSampler, texCoord).rgba;
    float4 highColour = tex2D(highSampler, texCoord).rgba;
    float4 cutColour = tex2D(cutSampler, texCoord).rgba;
    float4 finalColour = baseColour + highColour * cutColour;

    return finalColour;
}

technique CutAway
{
    pass Pass1
    {
        PixelShader = compile ps_2_0 PixelShaderFunction();
    }
}

```

Now I would expect to see a combination of all 3 render targets in the bottom right corner, however I don't see any data from baseColour. When I change finalColour to just baseColour I only see black, same goes for just highColour and just cutColour. Even finalColour = highColour*cutColour only gives me black while finalColour = baseColour + highColour*cutColour; does give me something.

The shader does seem to be working, changing final Colour to float4(1,0,1,1) gives me the expected pink square. There seems to be a problem reading the data from the textures, but I've got no clue why.

# Answer
> 0 votes
In the end I've made the following changes and it now works

In the shader I replaced the lowTexture + lowSampler by this

```
sampler lowSampler : register(s0);

```

The draw code is now:

```
 cutAwayEffect.Parameters["highTexture"].SetValue(rts[1]);
            cutAwayEffect.Parameters["cutTexture"].SetValue(rts[2]);
            cutAwayEffect.Parameters["blurWidth"].SetValue(0.07f);

            spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, null, null, null, cutAwayEffect);
            spriteBatch.Draw(rts[0], new Rectangle(GraphicsDevice.Viewport.Width / 2, GraphicsDevice.Viewport.Height / 2, GraphicsDevice.Viewport.Width / 2, GraphicsDevice.Viewport.Height / 2), Color.White);
            spriteBatch.End();

```

Why this solves the problem? I'm not 100% sure. The spritebatch now automatically puts rts\[0\] in to register(s0) and I don't have to use the dummy texture anymore. Maybe that was giving problems but I'm still not sure. So if someone has a suggestion why this works, or better: why the original code didn't, feel free to post your answer.

---
Tags: xna, c#
---


title: TF2 plugin signature (Source SDK)

text:
# Question
Title: TF2 plugin signature (Source SDK)
I am working on the server plugin for TF2. I need it for getting some stats from game (no hacking and cheating). My problem: I got message "No valid signature found..." while testing my plugin. But I want to make my plugin public in future (maybe).

Please tell me about signing procedure. How can I get valid signature for my plugin? What I must to do (send my plugin to Valve or what else)?

# Answer
> 3 votes
Two types of plugins:

**Server Plugins:** are C++ code libraries that modify the behaviour of dedicated servers.

**Client plugins:** are server plugins running in a client (rather than a dedicated server). They have access to client interfaces that dedicated servers cannot provide.

From the Source documentation:

> Client plugins must be signed by Valve before they can be loaded - you'll have to email and ask. During development, run the game in -insecure mode to bypass the signature check.

I imagine the process is the same for server plugins, the documentation is mute on that. That's my best guess. Probably your best bet is to email Robin Walker and ask.

---
Tags: server, plugin, valve
---


# Question
Title: How do I compile Half Life 1 for Windows?
I want to compile the *"Half Life 1"* source code, but I don't have Visual Studio 6 or 2002 or 2003. There are a few projects which have ported the code to Visual Studio 2008, but they don't work. How do I compile it for Windows?

I am new to the game development scene; I know I probably shouldn't be jumping into something so advanced, but I want a fun project. If any one could point me in the right direction, that would be great!

# Answer
Yes, that's a good question - why exactly are you trying to recompile Half-Life?

If you intend to mod it, you may be able to find a modder community that has a cleaner base code that will compile easier. Think something like ioquake3, just for Half-Life instead.

If you're trying to just tinker with the source code and teach yourself how to program, then a much better bet would be to find a cleaner base code that's more updated. Excellent examples would be Half-Life 2, pulled directly from Valve through Steam, or, again, something like ioquake3. I was able to compile ioquake3 with absolutely zero work - I just downloaded it, opened it, and compiled it.

Really, I don't know how beneficial it is to try and clean up crusty old code. Beginners will learn much more by getting involved in the mod community. Experts would probably pull out their old Windows 98 machine, boot up VS6 and go from there ;-)
> 3 votes

---
Tags: visual-studio
---


# Question
Title: Silly question about perspective correct texture mapping
OK, I'll admit, the math on a perspective projection matrix is quite hairy for me, but I get the general gist of it: morph the object so that it looks... perspective-ish.

But there is one thing which I really don't get it: if I send the textcoord for a vertex to a "smooth out fTexCoord" varying variable, how is that interpolation affected by either the clip space coordinates (x,y,z,w), where w actually has a value !=1 or a naive implementation without the w component? Is the interpolation happening in clip space?

I mean, I understand WHY half a quad texture looks squished at the diagonal if looked from a perspective type of camera, because one triangle is morphed and it's texture coordinates just fill a smaller area than the triangle which is closer to the camera.

What I don't understand is how clip space avoids thats. I mean, isn't the fTexCoord just interpolated based on the distance against the tree verts? And if I can give naive gl\_Position values, and OK clip space gl\_Position values, and they occupy the same space in... space, how can the perspective correct texture mapping help that?

# Answer
> 3 votes
Perspective-correct interpolation doesn't affect the vertices; it pushes around the stuff *between* the vertices. Ordinary interpolation is linear in screen space: it treats the triangle as being squashed flat onto the screen, so every pixel represents the same size of UV area, and the UVs for each pixel advance at a constant rate as you move along the triangle from one vertex to another.

This is not what you want because if the triangle is projected from 3D, then pixels on the farther-away parts of the triangle represent a larger UV area than closer pixels, and as you move from one vertex to another the UVs should advance at a nonlinear rate, changing quickly for the closer pixels and more slowly for the farther pixels. See this image:

Note how the vertical grid lines are evenly spaced on the left (the original texture) but not evenly spaced on the right (perspective warp) - their spacing changes from wide to narrow as you move horizontally across the image.

Perspective-correct interpolation takes into account the 3D depth of each vertex of the triangle in order to accomplish this nonlinear interpolation. You might think of it conceptually as interpolating linearly in world space or in clip space (the two are linearly related via the projection matrix, so linear in one is linear in the other). In actual fact, the interpolation is being done by calculating u/w, v/w, and 1/w at each vertex (w being from the vertex's clip-space position), then interpolating those three values linearly in screen space, then calculating u = (u/w) / (1/w) and v = (v/w) / (1/w) at each pixel. If you work out the math, it turns out this is equivalent to interpolating linearly in world space / clip space.

---
Tags: mathematics, textures, projection
---


# Question
Title: 3D Game Engine comparable to UDK that's not GPL'd
Are there any good, free 3D game engines similar to UDK that are under open-source licenses without copyleft provisions?

# Answer
> 3 votes
Panda3D is relatively nice (note: relative to most FOSS game engines, not things like UDK) and free/unencumbered, though you would need a commercial license for FMOD if you use that I think (FFTW and ARToolkit also need commercial licences if you use them, but those are more special case tools). FMOD is dirt cheap as middleware goes though. Unity isn't open really, but I don't think there are any royalty requirements on it.

# Answer
> 1 votes
Cube 2 is an engine similar to quake engines that is under zlib (soon CubeCreate will be released with lua scripting based on Cube2)

There is also the more general Panda3d, Ardor3D, jMonkeyEngine. As well as a handful of 2d engines you can use without a problem

However there is nothing close yet to Unity, UDK or Source yet

# Answer
> 1 votes
jMonkeyEngine is pretty full featured and available under the BSD license.

It's my personal favourite if you want an open source, cross-platform engine with modern OpenGL features a good community.

---
Tags: udk
---


# Question
Title: Tactics for moving the render logic out of the GameObject class
When making games you often create the following game object from which all entities inherit:

```
public class GameObject{
    abstract void Update(...);
    abstract void Draw(...);
}

```

So in you update loop you iterate over all the game objects and give them a chance to change state, then in the next draw loop you iterate again over all the game objects and give them a chance to draw themselves.

Although this works fairly well in a simple game with a simple forward renderer it often leads to a few gigantic game objects that need to store their models, multiple textures and worst of all a fat draw method that creates a tight coupling between the game object, the current render strategy and any rendering related classes.

If I were to change the render strategy from forward to deferred I would have to update a lot of game objects. And the game objects I make are not as reusable as they could be. Of course inheritance and/or composition can help me fight code duplication and make it a bit easier to change implementation but it still feels lacking.

A better way, perhaps, would be to remove the Draw method from the GameObject class altogether and create a Renderer class. The GameObject would still need to contain some data about it's visuals, like what model to represent it with and what textures should be painted on the model, but how this is done would be left to the renderer. However there are often a lot of border cases in rendering so although this would remove the tight-coupling from the GameObject to the Renderer, the Renderer would still have to be all knowing about all the game objects which would make it fat, all knowing and tightly-coupled. This would violate quite a few good practices. Maybe Data-Oriented-Design could do the trick. Game objects would certainly be data, but how would the renderer be driven by this? I'm not sure.

So I'm at a loss and can't think of a good solution. I've tried to use the principles of MVC and in the past I had some ideas about how to use that in games, but recently it doesn't seem as applicable as I thought. I would love to know how you all tackle this problem.

Anyway let's recap, I'm interested in how the following design goals can be achieved.

* No rendering logic in the game object
* Loose coupling between game objects and render engine
* No all knowing renderer
* Preferably runtime switching between render engines

The ideal project setup would be a separate 'game logic' and render logic project that don't need to reference each other.

*This thought train all started when I heard John Carmack say on twitter that he has a system so flexible he can swap out render engines at run time and can even tell his system to use both renderers (a software renderer and a hardware-accelerated renderer) at the same time so he can inspect differences. The systems I've programmed so far aren't even near that flexible*

# Answer
> 7 votes
A quick first step to uncoupling:

Game objects reference an identifier of what their visuals are but not the data, let's say something simple like a string. Example: "human\_male"

Renderer is responsible for loading and maintaining "human\_male" references and passing back to objects a handle to use.

Example in horrible pseudocode:

```
GameObject( initialization parameters )
  me.render_handle = Renderer_Create( parameters.render_string )

- elsewhere
Renderer_Create( string )

  new data handle = Resources_Load( string );
  return new data handle

- some time later
GameObject( something happens to me parameters )
  me.state = something.what_happens
  Renderer_ApplyState( me.render_handle, me.state.effect_type )

- some time later
Renderer_Render()
  for each renderable thing
    for each rendering back end
        setup graphics for thing.effect
        render it

- finally
GameObject_Destroy()
  Renderer_Destroy( me.render_handle )

```

Sorry for that mess, anyways your conditions are met by that simple change away from pure OOP based on looking at things like real world objects and into OOP based on responsibilities.

* No rendering logic in the game object (done, all the object knows is a handle so it can apply effects to itself)
* Loose coupling between game objects and render engine (done, all contact is via an abstract handle, states that can be applied and not what to do with those states)
* No all knowing renderer (done, only knows about itself)
* Preferably runtime switching between render engines (this is done at the Renderer\_Render() stage, you do have to write both back ends though)

Keywords you can search on to go beyond a simple refactoring of classes would be "entity/component system" and "dependency injection" and potentially "MVC" GUI patterns just to get the old brain gears spinning.

# Answer
> 2 votes
What I've done for my own engine is to group everything into modules. So I have my `GameObject` class and it holds a handle to:

* ModuleSprite - drawing sprites
* ModuleWeapon - firing guns
* ModuleScriptingBase - scripting
* ModuleParticles - particle effects
* ModuleCollision - collision detection and response

So I have a `Player` class and a `Bullet` class. Both derive from `GameObject` and are added to the `Scene`. But `Player` has the following modules:

* ModuleSprite
* ModuleWeapon
* ModuleParticles
* ModuleCollision

And `Bullet` has these modules:

* ModuleSprite
* ModuleCollision

This way of organizing things avoids the "Diamond of Death" where you have a `Vehicle`, a `VehicleLand` and a `VehicleWater` and now you want a `VehicleAmphibious`. Instead you have a `Vehicle` and it can have a `ModuleWater` and a `ModuleLand`.

Added bonus: you can create objects using a set of properties. All you have to know is the basetype (Player, Enemy, Bullet, etc.) and then create handles to modules you need for that type.

In my Scene, I do the following:

* Call the `Update` for all `GameObject` handles.
* Do collision checking and collision response for those that have a `ModuleCollision` handle.
* Call the `UpdatePost` for all `GameObject` handles to let know about their final position after physics.
* Destroy objects that have their flag set.
* Add new objects from the `m_ObjectsCreated` list to the `m_Objects` list.

And I could organize it further: by modules instead of by object. Then I would render a list of `ModuleSprite`, update a bunch of `ModuleScriptingBase` and do collisions with a list of `ModuleCollision`.

---
Tags: architecture
---


# Question
Title: For the handling of buildings on a tile-based strategy game, what aproach should I use?
On a tile-based game of the strategy genre, which allows the player to place buildings over the terrain tiles, there are multiple approaches that can be taken for handling such situation.

The ones that I immediately think about regarding that are:

1. Create two layers. One for the base tiles (terrain), and a second for buildings. And, for handling (operations before rendering), iterate them.
2. Create a single layer, with the `tile class` having both the reference to the base (terrain) and the building reference (`null` if no building at that tile). And for handling, iterate just one tile-map, but each iteration will then have to have an `if(building!=null){...}` added to it.

*EDIT:*

As further specification, the situation is that the game will be more focused on management and sandbox (tough combat will still be present), and every building will have many variables that are independent from the other buildings (even of the same type of building). *NOTE: You can use the game "Caesar 3" as an example of what I'm going for.*

For example, for "housing" buildings, they will have leveling, with a growth (level-up) based on the meeting of the required resources needed for the next level (from "materials", like wheat and wine, to access to specific "infrastructure", like public bathhouses or religious buildings), as well as the handling of such resources (current amount of "material X" stored, max amount of "material X" to be stored, consumption-ratio of "material X").

Another thing is, I don't need to literally render buildings on top of terrain (render both), and actually, I think it's probably a bad thing...So instead, I'm trying to do the handling in a way that will also not do unnecessary rendering. On the rendering loop, the building is rendered when its present, or the terrain otherwise. *(This might be a worse approach instead of a better one, tough. Please tell me if so!)*

*EDIT 2: Please regard the part above as a **note**. This question is **not** as related to rendering as it is to handling! I'm beginning to think about removing it.*

For my exemple aproaches, both would have a separated logical layer for buildings, as a single building can occupy more than a single tile (a building can be 2x2, 3x3 or 4x8 terrain-tiles, for example).

So, regarding terrain-to-building relation, approach-1 would would go:

> 2 iterating loops...
>
> BUILDINGS-loop: "You are currently iterating me; I am above the following terrain-tiles: 1,2,3 and 4; My current resources are: \[...\]"
>
> TERRAIN-loop: "(My coords are under a building, **render that building instead!**) || (I'm not under any buildings! **Render me!**)"

While approach-2 would go:

> 1 iterating loop...
>
> TERRAIN-loop: "If you are searching for the building that was built over me, (it's null, **render me!**) || (its not null, **proceed to the building's door, over there!**)"
>
> BUILDING: "Terrain x-y sent you to my door? (Sorry, i have already been iterated, skip me) || (Hmm, and it seems I have not been iterated yet! Alright then! My current resources are: \[...\]; **Render me!**)"

*Note: The "render" parts are to be considered as just flags to be used by the rendering loop that comes after all handling is done, thus, not as the actual time the rendering happens.*

*END OF EDIT.*

The questions are...

* Which is best overall? (why?)
* Is either best for a specific matter? (EX: *"`This` uses more processing, but is less memory-heavy, because..."*)
* And, are there other (better?) approaches?

# Answer
> 3 votes
I prefer the first strategy because it allows a lot of liberty for rendering process. I use it for my 2D games since the day I had to make a building transparent... it avoids the massive use of conditions.

But the second method you suggest is pretty fine too. In fact it will depend of your needs and, except for specific features, both will allow you to do the same for different cost.

The important thing here is to know the important features you will have to deal with. But only the important ones. Make your choice on those features... then, when specifics will come, you will have to find a way to adapt your initial choice (and everything is possible, don't worry).

# Answer
> 5 votes
There is no "best overall". This is where the prohibition about premature optimization comes from; neither method is likely going to impact your performance in any *measurable* way.

Personally, I wouldn't make buildings tiles at all; they should be sprites. Technically, they are a modified form of unit. This allows them to act like units in meaningful ways. You can give them attacks for defensive buildings. They can die. They have a collision area. And most importantly, you can make the buildings *move* if you so desire (see Terran in StarCraft).

# Answer
> 1 votes
Assuming your buildings don't always occupy an entire tile, building over terrain is better. If the building occupies 100% of a tile and always 100% of a tile, then the building is just yet another terrain tile so that's a very simple problem.

Doing building drawn over terrain allows you to use transparency in your building tiles. That lets you do things like have buildings that don't occupy 100% of a tile. That might mean less than a single terrain, but it might mean MORE than a tile too. For example, you might want a building to cast a shadow, and that shadow extend into an adjacent tile. You can do this with semi-transparent textures.

Also, consider how you want to show tentative building placement. It's not an uncommon design to show a semi-transparent version of the building overlaid on the terrain as the user drags it around with a mouse. Letting go of the mouse (or clicking) places the building.

Depending on your game needs, you might even draw your buildings with multiple layers. Consider if you wanted to show inside of a building. You could have a graphic of the building without a roof, and then a roof graphic you draw on top of that. If you want to look inside the building, remove (or draw semi-transparent) the roof graphic. This is useful if you want the player to walk inside of a building.

Overall, the complexity of rendering terrain then tile on top is trivial compared to having to maintain a complex data/logic structure.

---
Tags: java, tiles, performance, tilemap, slick
---


title: Calculate Costs for Buildings

text:
# Question
Title: Calculate Costs for Buildings
I have the following arrays:

```
[costs] => Array (
   [0] => Array (
       [value] => 600
       [name] => Wood
   )
   [1] => Array (
       [value] => 200
       [name] => Stone
   )
   [2] => Array (
       [value] => 800
       [name] => Iron
   )
   [3] => Array (
       [value] => 300
       [name] => Gold
   )
)

Array (
    [0] => Array (
        [balance] => 70636.86
    )
    [1] => Array (
        [balance] => 70636.86
    )
    [2] => Array (
        [balance] => 70636.38
    )
    [3] => Array (
        [balance] => 141072.77
    )
)

```

I want to check if the second array enough resources to spend from the first array and if one of the values from the first array is not = or less. Can someone help me out?

What I've tried so far:

```
for($i = 0; $i < 4; $i++)
{
    $balance = $this->listResources[$i]['balance'];
    if($balance >= $this->buildingCosts[$i]['value'])
        $this->listBuildings[$i][$this->listKey]['status'][$balance] = '1';
    else
        $this->listBuildings[$i][$this->listKey]['status'] = '0';
}

```

What I'm trying to find out is to see if I have enough resources in array to spend ( values that I need are found in costs )

# Answer
Your question is extremely cryptic (we can only vaguely guess, for example, that `$this->listKey` in some way refers to the building type you're trying to create, and some of your sentences are unintelligible), but I suspect you mean something like:

```
for($i = 0; $i < 4; $i++) {
    $balance = $this->listResources[$i]['balance'];
    $this->listBuildings[$this->listKey]['status'][$i] = ($balance >= $this->buildingCosts[$i]['value']);
}

```

That populates `$this->listBuildings` with status arrays that map resource index numbers to booleans indicating whether or not the available quantity of that resource is sufficient.
> 2 votes

---
Tags: php, sql
---


# Question
Title: Determining and culling non-visible vertices
Ahoy!

After posting my previous question on tile maps, i've been tinkering with an implementation i'm rather pleased with so far but would like to gather some more information about submitting geometry to be rendered by OpenGL.

A little background information:

I've set up a tile map which renders "volumes" in a layered manner very much like Minecraft's implementation using voxels (note; i'm not creating another bloody minecraft clone!) but with a twist in that any "volume" can be extruded along the Y-axis to create variably sized tiles. This all works fine and for the purposes of my tile map, is exactly what I set out to achieve.

My question:

My current confusion lies within the realms of how the vertex data is submitted to be rendered. I'm conscious that when two volumes are rendered in a single tile (think of them as layers; rock on the bottom, mud or water on top), the bottom volume is not actually visible unless there are no neighbouring tiles. To this end, is there any point in submitting the vertices for an object that may not be visible?

Consider two cuboids side by side. From any angle, you can only ever see 5 faces of each cuboid as the other faces are adjacent. Does OpenGL recognise this and discard them (if glCullFace or another appropriate method is used/enabled?) or do I need to actually determine what is visible and remove redundant vertices myself? Is there any harm in not removing them?

For the purposes of my tile map, I don't imagine that my "world" will ever be large enough to cause issues with rendering speed but I'd would like to optimise this so non-visible volumes are simply not rendered. I've been toying with a few ideas for determining which volumes are visible before adding them to the VBO but was wondering how much leg work OpenGL would do for me. There's no point me trying to solve a problem that doesn't exist and also, would OpenGL be able to calculate this much quicker that my own implementation?

I'd like the tile map to be deformable whereby the top-most volumes can be removed or resized to reveal the volumes below (also, some tiles may be transparent, such as water) so rendering the whole tile map (or at least what is visible on screen) would seem necessary.

I have the implementation down and working so far and it's running at a reasonable speed without any issues. I'm just not sure how much work OpenGL does in the background with regards to rendering and culling vertex data that isn't actually visible due to it being obscured by other objects. Can anyone provide insight into this, or at least point me in the direction of where I can read up on such matters?

Any help and information would be greatly appreciated :)

# Answer
> 7 votes
1. **Vertices**: Every triangle you submit to OpenGL must be checked against the view frustum. If you send geometry which is out of view, it still must be transformed (by your vertex shader) to find out that it is out of view. The more vertices in your scene, the more useful it is to cull vertices in your code before sending them to the GPU.

If this is a bottleneck for you, then (since you are using a tiled scene) you should break up your scene into chunks of several tiles, each of which is a separate VBO, and skip `glDraw...`ing them if they are outside the view frustum.

You asked: “is there any point in submitting the vertices for an object that may not be visible?” You should only do so if you find it is more expensive to do a test for whether they are visible than it is for the GPU to do so, or if they are (usefully) bundled together in a VBO that it would be inefficient to be adjusting all the time for new visibility.
2. **Faces**: You should remove the redundant faces that face toward each other; OpenGL doesn't know you're not going to be doing transparency in your shader, for example, and will fully process all of them. Keeping these redundant faces will waste both vertex and fragment processing capacity.

`glCullFace` is only relevant to removing the back-sides of triangles; it does nothing for obscured front sides and still requires the vertices to be checked, but it does allow skipping the fragment stage for that face.
3. **Fragments**: After the GPU has decided a triangle needs to be drawn, every pixel (fragment) in it needs to be processed individually (for texturing and other effects). At this point, the best you can do is order your data so that nearer-to-the-camera geometry is rendered *first* (e.g. render the mud before the rock), allowing the depth buffer test to skip full fragment processing.

It is worth noting that one of the easiest ways to bog down a GPU (due to insufficient *fill rate*) is to have many large triangles covering large areas of the screen; this could happen, for example, if the player zooms in on a complex multi-layered tile and you're either doing transparency or unnecessarily rendering obscured layers.

---
Tags: opengl-es, vector, geometry
---


title: OpenGL ES 2.0 gluUnProject

text:
# Question
Title: OpenGL ES 2.0 gluUnProject
I've spent more time than I should trying to get my ray picking program working. I'm pretty convinced my math is solid with respect to line plane intersection, but I believe the problem lies with the changing of the mouse screen touch into 3D world space.

Heres my code:

```
    public void passTouchEvents(MotionEvent e){

        int[] viewport = {0,0,viewportWidth,viewportHeight};
        float x = e.getX(), y = viewportHeight - e.getY();

        float[] pos1 = new float[4];
        float[] pos2 = new float[4];
        GLU.gluUnProject(   x, y, 0.0f,
                            mViewMatrix, 0,
                            mProjectionMatrix, 0,
                            viewport, 0,
                            pos1, 0);

        GLU.gluUnProject(   x, y, 1.0f,
                            mViewMatrix, 0,
                            mProjectionMatrix, 0,
                            viewport, 0,
                            pos2, 0);
    }

```

Just as a reference I've tried transforming the coordinates `0,0,0` and got an offset. It would be appreciated if you would answer using OpenGL ES 2.0 code.

# Answer
The GLU library was made with 1.1, but the gluUnProject can still be used in 2.0 as long as you have the correct values. The 4th parameter should be the multiplied model view matrix, not just the model matrix or just the view matrix. Also, the calculated pos1 and pos2 values have to be converted from 4D vectors to 3D vectors by dividing them by their w component. According to this: http://forums.create.msdn.com/forums/p/10940/70238.aspx.
Here's how I did it for Android:

```
public void singleTouch(float x, float y)
{
    float[] nearPos = new float[4];
    float[] farPos = new float[4];
    PointF touchPoint;

    boolean unprojectedNear = (GLU.gluUnProject(x, y, 0,
        floorViewDrawable.getMvMatrix(), 0, projectionMatrix, 0,
        viewport, 0, nearPos, 0) == GLES10.GL_TRUE);
    boolean unprojectedFar = (GLU.gluUnProject(x, y, 1,
        floorViewDrawable.getMvMatrix(), 0, projectionMatrix, 0,
        viewport, 0, farPos, 0) == GLES10.GL_TRUE);

    if (unprojectedNear && unprojectedFar)
    {
        // To convert the transformed 4D vector to 3D, you must divide
        // it by the W component
        nearPos = convertTo3d(nearPos);
        farPos = convertTo3d(farPos);

        // Use the near and far instead of the assumed camera position
        float floorViewX = (((farPos[0] - nearPos[0]) / (perspectiveFar - perspectiveNear)) * nearPos[2]) + nearPos[0];
        float floorViewY = ((((farPos[1] - nearPos[1]) / (perspectiveFar - perspectiveNear)) * nearPos[2])  + nearPos[1]) + (2f * positionY);

        touchPoint = new PointF(floorViewX, floorViewY);

        if (floorViewDrawable.getArea()
            .contains(touchPoint.x, touchPoint.y))
        {
            floorViewPoint = new PointF(nearPos[0], nearPos[1]);
            Log.e(HostessMobileApp.TAG, "floorViewTouched");
        }
    }
}

private float[] convertTo3d(float[] vector) {
    float[] result = new float[4];

    for (int index = 0; index < vector.length; index++) {
        result[index] = vector[index] / vector[3];
    }

    return result;
}

```

Here's a resource for explaining gluUnproject if anybody needs it. http://myweb.lmu.edu/dondi/share/cg/unproject-explained.pdf
> 3 votes

---
Tags: 3d, android, opengl-es2, raycasting
---


title: GLSL mesh discard command?

text:
# Question
Title: GLSL mesh discard command?
Is there a GLSL command similar to the `discard`, but it discards the whole mesh and not just a fragment?

# Answer
> 2 votes
I also think there is no way how to "discard" whole mesh, but you can transform every vertex of the mesh to the same output vertex, so whole mesh will "implode" into one point in space. If you place it behind camera, it will be clipped and not processed.

# Answer
> 1 votes
Well, I'm pretty sure, the fragment shader doesn't have a concept of a mesh. I'm mostly sure the vertex shader doesn't either. You could update the vertex shader to let it know which mesh it's processing via a `uniform` variable, but I assume you want something all GPU side.

So I believe the answer is, no, it does not. However, I'd love to be wrong, I think that would be pretty useful.

# Answer
> 1 votes
No. Object culling (discarding a whole mesh) must be done before submitting your drawing commands to the GPU.

Remember that the shaders are running at various stages of the pipeline. The vertex shader is run after submitting objects to the GPU. And operates on the vertex level only - it has no cinder of any other vertices, primitives, or the rendered object at all.

The fragment shader runs on fragments only, and has no concept of other fragments, the primitive that created the fragment, the vertices that made the primitive, or the original object.

If you want to selectively disable a mesh based on some kind of GPU processing, you will need to do multiple passes. Things like occlusion queries can be used, or transform feedback.

---
Tags: glsl, fragment-shader
---


title: Minecraft Mod portable torch/lantern

text:
# Question
Title: Minecraft Mod portable torch/lantern
I have just started making a mod for minecraft, I learned how to make items and import custom png's and have gotten all of that to work. I have been searching around the code trying to find a way to make an item being held or in the inventory give off light around the player. I do have experience coding in java, but I am not well acquainted with the minecraft code.

(This is using mcp 5.6 with modloader in minecraft 1.1 with eclipse)

# Answer
> 4 votes
The simplest way would be to maintain an invisible "torch block" that follows the player.

Otherwise, your are going to have to get into the FX coding.

As far as I know, only blocks can generate light.

However here is a thought, have a look into how fire works when entity's are on fire. I'm not sure if they give off light or not.

---
Tags: java, minecraft-modding, modding
---


# Question
Title: Store data on server or only in database?
I have been working on programming an online RPG in Java for a while now. It's a huge project and way too hard for me, but I'm having fun learning.

server and client: Java
database: MySQL

I have mainly been working on the GUI but now have started to draw a map based on the tileset returned from my server. I am now ready to grab my users coordinates from the db, but I am wondering if I should have them sitting in a temp variable on my server or just access/change the coordinates in the database.

Long story short: hit db always for lookups and changes or have a LinkedList or something on the server?

# Answer
> 4 votes
Assuming that you're going for persistence between runs, using the server to maintain the save state of your users for the RPG and as the authoritative source to restore from...

Storing the positions **in the DB is fine for a turn based** design and guarantees your players won't lose any steps if they crash. This makes players happy.

For a **realtime game you'll want to cache** and work on positions in memory, any structure like a list or array is fine for your scale, and occasionally store that to the DB. Here you have to balance how often you save to DB between making players happy by not losing too many steps if you crash, and slowing your server down with too many DB writes.

That's it, no need to get more complex until you approach MMO server loads.

---
Tags: java, game-design
---


# Question
Title: Changing the size of shuriken particle effects to simulate a torch flame Unity3D
Basically I'm trying to use the "Flame" particle effect to simulate the flame on a torch. My problem is the flame is far too big. I've been trying too figure out how to resize the flame to fit the torch, but nothing seems to work. I've adjusted all the properties, and the scale itself. But no matter what it's too big. Anybody know how I could accomplish this?

# Answer
> 1 votes
Changing the scale of the object won't do anything. What you have to do is change the "Start Size" property of the particle system.

---
Tags: unity, particles
---