# Question
Title: Should NPC dialog be stored in XML or in a script?
I'm developing an action RPG with some friends. I would like to know the differences and pros/cons of making NPC's dialogue using a file in XMLformat instead of using a script.

I see that script method is often used by game developers for NPC text, but is it better then a XML file? We've thought that a XML file with tags like

```
<FirstText>[text1]<SecondText>[text2]

```

et cetera is perfect for NPC text and also for possible quests to give the player.

So what are the differences between this two methods? Is a script suitable for this aim?

# Answer
> 17 votes
Dialogue could be provided in any form/structure you wish it depends on how you parse the information that makes the difference. I will provide you with a basic XML syntax to get you started without understanding your games structure or language I afraid i cant provide an implementation.

```
<?xml version="1.0" encoding="UTF-8"?>
    <npcs>
      <npc name="Abstract">
        <dialogue>
          <text>Welcome #{PlayerName} to Stack Exchange, What would you like to know? </text>
          <options>
            <option action="dialogue5">Tell me about Stack Exchange?</option>
            <option action="quest1">Give me quest</option>
            <option action="object1">Give me object</option>
          </options>
        </dialogue>
        <dialogue id="5">
          <text>Stack Exchange is a fast-growing network of 87 question and answer sites on diverse topics</text>
          <text>We build libraries of high-quality questions and answers, focused on the most important topics in each area of expertise</text>
        </dialogue>
      </npc>
    </npcs>

```

As you can see its pretty much limitless to how you want to structure the XML.

Here i can provide a list of my npc's, their list of dialogue's, so in this particular example a player could talk to npc it would say "welcome what would you like to know?" and provide options which can be passed onto another dialogue or a quest or give item. So long as you follow the Structure of xml anything goes.

Hope this helps

# Answer
> 5 votes
Although XML is more predictable, kinda have a defined structure and all that. I would go with scripts.

Rolling your own language(if you have the time, but usually this is not the best choice), or even implementing one.

There are LOTS of script languages out there, they're all nice, some examples:
Squirrel, Lua, Angel Script, Python, and many many many others.

The choice of script over XML is not easy. XML is a straight path, easy to follow. Scripts are kind hard to implement, but if well implemented, gives you plenty of freedom.

Scripts are awesome because they gives you an organization that you may be already used to, make it easier for conditional statements, loops, acessing data. And also you can even making npcs execute algorithms made on the script itself. See this Ragnarok Online NPC Example:

```
mes "Hi adventurer, what do you want to drink today?";
switch(Select("Water", "Potions", "Nothing"))
{
    case 0:
        if($money >= 100)
        {
            $money -= 100;
            mes "here is your water.";
            giveitem waterbottle_id, 1;
            next;
        }
        else
        {
            mes "Sorry, you don't have enough money :/";
            next;
        }
        break;
    case 1:
        mes "Sorry, we're out of potions today.";
        next;
        break;
     default:
        break;
}
mes "Thanks for coming have a nice day!";
close;

```

This follows a structured form, XML's are like if you were putting lots of labels and jumping over everywhere.

But of course, only choose script if the project really worth it, you have the time, and you're confident while managing VMs.

# Answer
> 4 votes
You should generally prefer structured data (XML) over scripts at every opportunity.

The biggest reason for this is tool support. You can make a dialog editor for a structured format, which supports internationalization, dialog branching, testing a debugging of dialog trees, deadend and infinite loop detection in trees, etc. For a script, the only thing you can do is give te designer a text editor and make him play through all the dialogs in game to try to find bugs.

There is no single part of your engine work more important than your tools. They will make or break your game content. They will determine of you ship on time and under budget. They will allow you to build richer and larger content or restrict you to simpler and less content. All the pretty shaders and fancy dialog UIs and smart AI are useless if your content people can't make use of them.

You can of course also combine structured data and scripts in various ways. Your dialog system will probably need ways to optionally display some options based on certain game conditions. While you should strive for structured data there too, its entirely feasible to allow designers to add script conditions where the pre built ones aren't capable enough. Your NPCs can also use scripts to decide when to enter dialog or which dialog to enter into.

All that said, the actual choice of XML or not is kind of irrelevant. The point of XML is that it is structured and hence machine parseable into processable data structures. Nobody should need to actually be looking at the XML since the game editor UI should be used for making dialog (building a C# tool for this is trivial, and not doing it would be stupid). If XML is a problem for any reason, use another format. Prefer text or merging and conflict resolution in source control. When you ship, you'll be compiling the text files into efficient binary representations.

# Answer
> 1 votes
While XML would make a great way to store your dialogue text, the most important aspect is the ease with which you can read it in, as well as how easy it is to write.

Keeping all your dialogue in one file (or multiple files in a single folder) will make it easier to add translations later. All you'd have to do to choose between them is decide which file (or folder of files) to read from.

An XML file would be a great choice, as it's a well-documented format, but is flexible enough to specify all sorts of things, including dialogue between NPCs if designed correctly.

---
Tags: rpg, scripting, xml, text, npc
---


# Question
Title: Bubble sorting my array does not sort it
I sort an array of chunks by doing this:

```
    for (int i =0; i<this.getQueue().size();i++) {
        for (int j =0; j<this.getQueue().size()-i-1;j++) {
            Chunk temp1 = this.getQueue().get(i);
            Chunk temp2 = this.getQueue().get(i+1);
                if (temp1 != null &&temp2 != null && temp2.getLocation().getY() < temp1.getLocation().getY()) {
                    this.getQueue().set(i, temp2);
                    this.getQueue().set(i+1, temp1);
                }
            }
        }

```

What I want is the the chunks with the lowest Y coordinate will be at the start of the array and the ones with the bigger Y coordinate will be at the end of the array. And this is my result:

```
1024.0
944.0
1104.0
944.0
1104.0
----BEFORE-----
944.0
1024.0
944.0
1104.0
1104.0
---AFTER---

```

Why is this not working It seams fine. I dont want to use a comparator so dont suggest it.

More info, the Y cords are floats. I got the result by for each looping on this queue and printed the Y locations.

# Answer
> 5 votes
Your inner loop iterates `j` times correctly, but the indexes you compare do not change within that loop. Therefore it's impossible for any value to bubble more than 1 position along. Instead of `.get(i)` and `.get(i+1)`, you probably need `.get(j)` and `.get(j+1)`.

You can usually debug problems like this with a debugger, or with `System.out.println` statements to show the values of `i` at each step.

# Answer
> 1 votes
Probably more efficient to swap once per loop by first making a record of best index to swap. Also start the j loop with i + 1 instead of 0. This makes it easier to understand you are swapping starting 1 above the current index. Untested but should give you an idea of how this could be approached.

```
int qSize = this.getQueue().size();
for (int i = 0; i < qSize; i++) {
        Chunk temp1 = this.getQueue().get(i);
        if (temp1 != null) {
            int bestY = temp1.getLocation().getY();
            int swapWithIndex = -1;
            for (int j =i + 1; j < qSize; j++) {
                  Chunk temp2 = this.getQueue().get(j);
                  if (temp2 != null && temp2.getLocation().getY() < bestY) {
                      bestY = temp2.getLocation().getY();
                      swapWithIndex = j;
                  }
            }

            if (swapWithIndex != -1) {
                 this.getQueue().set(i, this.getQueue().get(swapWithIndex));
                 this.getQueue().set(swapWithIndex, temp1);
            }
        }
    }
}

```

---
Tags: java
---


title: Colored Collision Detection

text:
# Question
Title: Colored Collision Detection
Several years ago, I made a fast collision detection for 2D, it was just checking a bullets front-pixel's color to check if it were to hit something. Let's say the target rgb color is (124,200,255) then it just checks for that color. After the collision detection, it paints the target with appropriate picture. So, collision detection is made in background without drawing but then painted and drawn.

How can I do this in 3D? Because, a vertex does not just exist as a 2D picture's pixel. I looked at some java3D and other programs and understood that 3D world is made of objects. Not just pictures. Is there a program that truly fills the world with vertices? But it could be needing terabytes of ram even more.

Do you know an easy way to interpolate the color of a vertex in java3D or similar program?

Note: for a rgb color-identifier, I can make 255\*255\*255 different 2D objects in background.

# Answer
> 3 votes
You have correctly understood your problem. Your clever trick for 2D collision detection is (usually) impractical in 3D precisely because a sufficiently precise voxel array is generally too much data to be keeping in memory or updating per-frame.

(One exception is explicitly voxel-based games, where you're paying that cost anyway, but I'll assume you're not doing that.)

Here's how 3D collision detection is typically implemented. I'll start with the simplest thing that can work and then refine it.

You have a collection — a data structure — holding all of the ‘physical’ objects in your game. Each frame, for every object in this collection, go through every *other* object in this collection, and call a routine which knows how to check these two objects for collisions. (For example, a slow bullet might be treated as a point — no volume of its own — and simply test whether that point is within the other object.)

This works, but since it iterates over all pairs of objects, it takes O(*n*²) time.

The first thing to do is to avoid wasting time on checking distant objects. To do this, you need some sort of *spatial indexing* in your collection of objects. One such data structure is an *octree*, which recursively partitions space into segments which eventually contain only a few objects. I won't include the details here, but in order to do any sort of spatial indexing, you will generally need to have routines which compute the *axis-aligned bounding boxes* of your objects — this is just a rough approximation of the space your object takes up. Once you have a spatial index structure, you can check only pairs of objects which are known to be in the same vicinity.

This algorithm is going to be (sloppily considering) something like O(*nm*² log *n*), where *n* is the total number of objects and *m* is the maximum number of objects all in one pile in one spot.

The second thing to do is avoid wasteful collision tests. (This is mainly applicable if you have lots of stationary objects that can never collide, but which are not treated as a special unique “this is the level geometry” object.) Instead of having a single collection of all physical objects, have (at least) two: one which stores all the moving objects, and one which stores all the stationary objects. Do the same pair-checking (using the spatially indexed collection) for the moving objects, and then check *the moving objects against the stationary objects*. In this way, you do not waste time checking adjacent stationary objects against each other.

Sound like a lot of work? Sure. The good news is, you don't need to write all that, unless you have a very special use case. Just use a physics library (or “engine”) in your code which will provide all of this for you. (Physics libraries also provide response to collision — bouncing off, falling down, etc. — but you can usually use the collision component without the dynamics component, or vice versa, if it is not suited for your game.)

---
Tags: java, collision-detection
---


# Question
Title: Platforms for sharing content and expertise
Are there any platforms / sites where people can share expertise in game development and where you can share (either payed or free) digital content (like images, sounds, animations but also frameworks or libraries) to be used in games? I'd also like the possibility to contact users and request specific pieces of content.

I'd like to start out as an indie developer and have programming skills but I lack the experience and time to create ingame artwork and sound. Is there any site where I could locate other people (artists mostly) who would want to work on a game for free?

I know I can get most technical questions answered on this site and I have some contacts but I'm affraid this won't be enough.

# Answer
If you're looking for sounds may I recommend freesound.org. It has plenty of free (As you might have guessed) material in a variety of categories and formats, hell even minecraft uses sounds from it.
> 1 votes

---
Tags: game-industry
---


# Question
Title: Correct Rotation and Translation with a 4x4 matrix
I am using a 4x4 matrix to transform verts in a shader. I multiply an identity matrix by a rotation matrix by a translation matrix. I am trying to first rotate the verts and then translate them, however in my result, it appears that the verts are being transformed and then rotated.

My matrix looks something like this:

```
m00 m01 m02 tx
m10 m11 m12 ty
m20 m21 m22 tz
--- --- --- 1

```

I am not using OpenGL's fixed function pipeline, I am multiplying matrices on the client side, and uploading the matrix to a GLSL shader.

If it helps, I am using my own matrix multiplication code, but I have recreated this problem using matrices on my graphing calculator, so I don't believe my matrix code has errors..

I'll include a visual aid if needed.

# Answer
> 0 votes
Mutliply the translation matrix with the rotation matrix, not the other way around. You dont need to multiply with the identity matrix at all, that has no effect, it is like multiplying any number with 1, it wont change the number and the matrix.

---
Tags: opengl, glsl, matrix
---


# Question
Title: What are the steps taken by this GLSL code?
> ```
>  1 void main(void)
>  2 {
>  3     vec2 pos = mod(gl_FragCoord.xy, vec2(50.0)) - vec2(25.0);
>  4     float dist_squared = dot(pos, pos);
>  5
>  6     gl_FragColor = (dist_squared < 400.0)
>  7         ? vec4(.90, .90, .90, 1.0)
>  8         : vec4(.20, .20, .40, 1.0);
>  9 }
>
> ```
>
> taken from http://people.freedesktop.org/~idr/OpenGL\_tutorials/03-fragment-intro.html

Now, this looks really trivial and simple, but my problem is with the **mod** function.

This function is taking 2 vec2 as inputs but is supposed to take just 2 atomic arguments according to the official documentation, also this function makes an implicit use of the **floor** function that only accepts, again, 1 atomic argument.

Can someone explain this to me step by step and point out what I'm not getting here?

It's some kind of OpenGL trick? OpenGL Math trick? in the GLSL docs i always find and explicit reference to the type accepted by the function and *vec2* it's not there.

# Answer
> 5 votes
The first line with "mod" makes sure that coordinates are always in the range \[-25;25), repeating all the time ("mod" is for repeating and without the "-vec2(25)" at the end, coordinates would be in the \[0;50) range).

"mod" is often used in this manner to repeat procedurally generated content at no cost.

The reason you won't see explicitly defined types in GLSL docs is because this function works with genType (float/vec2/vec3/vec4) types. By the way, the tutorial you provided includes that:

> Like many functions in GLSL, step has parameters and return values with the type genType. This is shorthand for float, vec2, vec3, and vec4.

Graph of the function: set "fmod(x#2)" here as the first graph and click on "Draw" to see what it looks like.

Here's a graph that might load slower but requires no input: mod(x,2) on Wolfram Alpha

---
Tags: mathematics, glsl
---


# Question
Title: Algorithm for querying linearly through a non-linear list of questions
For a multiplayers trivia game, I need to supply my users with a new quizz in a desired subject (Science, Maths, Litt. and such) at the start of every game.

I've generated about 5K quizzes for each subject and filled my database with them. So my 'Quizzes' database looks like this:

```
|ID   |Subject     |Question
+-----+------------+----------------------------------
|  23 |Science     | What's water?
|  42 |Maths       | What's 2+2?
|  99 |Litt.       | Who wrote "Pride and Prejudice"?
| 123 |Litt.       | Who wrote "On The Road"?
| 146 |Maths       | What's 2*2?
| 599 |Science     | You know what's cool?
|1042 |Maths       | What's the Fibonacci Sequence?
|1056 |Maths       | What's 42?
And so on... (Much more detailed/complex but I'll keep the exemple simple)

```

As you can see, due to technical constraints (MongoDB), my IDs are not linear but I can use them as an increasing suite.

So far, my algorithm to ensure two users get a new quizz when they play together is the following:

```
// Take the last played quizzes by P1 and P2
var q_one = player_one.getLastPlayedQuizz('Maths');
var q_two = player_two.getLastPlayedQuizz('Maths');

// If both of them never played in the subject, return first quizz in the list
if ((q_one == NULL) && (q_two == NULL))
  return QuizzDB.findOne({subject: 'Maths'});

// If one of them never played, play the next quizz for the other player
// This quizz is found by asking for the first quizz in the desired subject where
// the ID is greater than the last played quizz's ID (if the last played quizz ID
// is 42, this will return 146 following the above example database)
if (q_one == NULL)
   return QuizzDB.findOne({subject: 'Maths', ID > q_two});
if (q_two == NULL)
   return QuizzDB.findOne({subject: 'Maths', ID > q_one});

// And if both of them have a lastPlayedQuizz, we return the next quizz for the
// player whose lastPlayedQuizz got the higher ID
if (q_one > q_two)
   return QuizzDB.findOne({subject: 'Maths', ID > q_one});
else
   return QuizzDB.findOne({subject: 'Maths', ID > q_two});

```

Now here comes the real problem:

Once I get to the end of my database (let's say, P1's last played quizz in 'Maths' is 1056, P2's is 146 and P3 is 1042), following my algorithm, P1's ID is the highest so I ask for the next question in 'Maths' where ID is superior to 1056. There is nothing, so I roll back to the beginning of my quizz list (with a random skipper to avoid having the first question always show up). P1 and P2's last played will then be 42 and they will start fresh from the beginning of the list. However, if P1 (42) plays against P3 (1042), the resulting ID will be 1056...which P1 already played two games ago.

Basically, players who just "rolled back" to the beginning of the list will be brought back to the end of the list by players who still haven't rolled back. The rollback WILL happen in the end, but it'll take time and there'll be a "bottleneck" at the beginning and at the end.

Thus my question: What would be the best algorith to avoid this bottleneck and ensure players don't get stuck endlessly on the same quizzes?

Also bear in mind that I've got some technical constraints:

* I can't get a random question in a subject (ie: no "QuizzDB.findOne({subject: 'Maths'}).skip(random());"). It's cool to skip on one to twenty records, but the MongoDB documentation warns against skipping too many documents.
* I would like to avoid building an array of every quizz played by each player and find the next non-played in the database with a $nin.

Thanks for your help

# Answer
> 1 votes
I see a lot of entropy here; i will try to clear the air:

* Programs = Data structures + Algorithms
* You can write the best linear algorithm in the world but if your data structure it's not linear, you can think about that forever without solving the issue
* Since you have to think about the data structures first, at least in this scenario, you are picking the worst possible storing solution, I do not know about this *MongoDB* but after a brief search turns out that is nothing more than a text file and a text file it's a non linear storage solution, for 5K questions is the horror
* A linear data structure will mantain the time/performance required to access the information linear, that basically means *the same*, no matter how the data structure grows in time if it's big or small, for this reason you should use something like an SQL based database, there is SQLite that is a public domain project and you also do not have to worry about any license at all, completely free and you can do what you want to do with it.
* If you are using an SQL based approach you will get benefits using a different database table for each topic and you can also simplify or template your code doing this, so you can even abstract the topic itself and you do not have to write code for each possible topic.
* With SQLite you also get a series of basic functions for your query, one that can mimic a random access it's included

I hope that things are more clear now.

# Answer
> 1 votes
How about this as a solution:

* Store a flag as to whether or not a player has gone through all the questions for a subject.
* If neither player has the flag set, continue as you suggest above.
* If one player has the flag set, use the next question that the other player was due.
* If both players have the flag set, select a question completely at random.

It won't work that well if player A has recently just finished all the questions, and player B has almost finished them - you could perhaps present choose a random question if one player has the flag set and the other has seen \> 75% of the questions.

---
Tags: algorithm, databases
---


title: Restrict camera movements

text:
# Question
Title: Restrict camera movements
I'm making a game with target (orbit camera). I want to limit camera movements when in room. So that camera don't go through walls when moving around target and along the ground. What are common approaches? Any good links with tutorials? I use Unity3D, nevertheless I'm good with a general solution to the problem

# Answer
Usually you'll associate a collision volume with your camera, so that when it hits a wall (or floor, etc.), it stops moving. Some implementations wrap both the camera and the object it's following in the same collision volume, in order to avoid getting a wall between the camera and the object.

The physics acting on the camera collision volume should probably be different than the physics acting on the object it's following. The camera probably doesn't need to be affected by gravity, e.g.
> 4 votes

# Answer
A simple solution would be to cast a ray from the target to the desired camera position, and cap the camera position if it hits anything.

In Unity, it'd be something like this:

```
Vector3 targetPos = ... // this is the position of your target.
Vector3 cameraPos = ... // calculate your orbital camera position, however you choose to do it.
Vector3 targetToCamera = cameraPos - targetPos; // Vector from target to camera.

RaycastHit hit;
if (Physics.Raycast(targetPos, targetToCamera, out hit, targetToCamera.magnitude))
{
  // If we get this far, something is in the way.
  // Move the camera position to the collision position.
  cameraPos = hit.point;
}

```

(Please note I've not tested the code!)

See http://docs.unity3d.com/Documentation/ScriptReference/Physics.Raycast.html

This might result in some sharp camera motions, but it's a reasonable starting point. I've certainly seen commercial games use the same system!
> 4 votes

---
Tags: camera
---


# Question
Title: Distributed Rendering in the UDK and Unity
At the moment I'm looking at getting a game engine to run in a CAVE environment. So far, during my research I've seen a lot of people being able to get both Unity and the Unreal engine up and running in a CAVE (someone did get CryEngine to work in one, but there is little research data about it).

As of yet, I have not cemented my final choice of engine for use in the next stage of my project. I've experience in both, so the learning curve will be gentle on both. And both of the engines offer stereoscopic rendering, either already inbuilt with ReadD (Unreal) or by doing it yourself (Unity). Both can also make use of other input devices as well, such as the kinect or other devices. So again, both engines are still on the table.

For the last bit of my preliminary research, I was advised to see if either, or both engines could do distributed rendering.

I was advised this, as the final game we make could go into a variety of differently sized CAVEs. The one I have access to is roughly 2.4m x 3m cubed, and have been duly informed that this one is a "baby" compared to others.

So, finally onto my question:

* Can either the Unreal Engine, or Unity Engine make it possible for developers to allow distributed rendering? Either through in built devices, or by creating my own plugin / script?

# Answer
> 1 votes
If you need to have several computers rendering different views for your CAVE, (which I think is what you are suggesting), I think you would have to effectively create a networked game, with the controls on one node being sent and replicated on all the others.

You will have to expend some effort ensuring that all the nodes stay synchronised; I would suggest using a lock-step networking approach; this means that you have to ensure that the simulation on all machines is completely deterministic, but makes the networking fairly straightforward as you only have to send the user input across the network to each node.

---
Tags: unity, rendering, udk, distribution
---


# Question
Title: How to convert Maya shaders and Renderman shaders to GLSL?
I know this 2 products but i have never used them for production, since I have a bunch of cool shaders i would like to use them under OpenGL with GLSL but i don't know where to start.

If it's not possible to convert them directly, where i can learn the Renderman syntax for the shaders?

# Answer
I don't know of any tools that allow you to directly convert complex shaders from Maya or 3Ds Max to GLSL/HLSL (although if you do find it, let me/us know!). For simple shaders (lambert, phong) you can probably write your own parser (tools like Havok Content Tools already parse the shaders \[again, simple shaders\] and can give you a material which you can then use to create a GLSL shader in your program).

Maya's and Renderman's shaders rely on a complete framework with a lot of nodes. Moreover, they are designed to work with rendering engines that raytrace into the scene; so a shader can have many passes and many texture units and effects which can be impossible to translate to a single GLSL shader.

However, the opposite exists. That is, you can have your shaders work in the 3D packages which is one way to streamline your pipeline. For example, 3Ds Max supports MetaSL which in turn can be converted to HLSL/GLSL shaders. Maya supports rendering HLSL/GLSL shaders via a plugin which exposes supported attributes of the shader. Same with VRay. So instead of relying on their respective shader networks, you may want to create shaders in GLSL in the respective 3D programs which then makes it easy to export the shader as it is already in GLSL.
> 1 votes

---
Tags: shaders, glsl, maya
---


# Question
Title: How to create a Raining Effect(Particles) on Android?
I am developing a 2d android strategy game, it runs on SurfaceView, so I can't(or can I?) use LibGdx's particle system. And I would like to make a raining effect, I am aiming for something like this( http://ridingwiththeriver.files.wordpress.com/2010/09/rain-fall-animation.gif ), I don't need the splash effect in the end (although that would be superb, but probably would take up a lot of system resources). How could I achieve that raining effect? Any ideas?

Thank You a lot in advance!

# Answer
Conserve your precious CPU/GPU cycles! You can inexpensively approximate rain (and rain splats) without using particles. The rain drops and splats don't even have to move or be aligned! Basically, randomly draw a bunch of the following sprites onto the screen:

Source: bulletproofoutlaws.com (There's also a video of the final effect)
> 11 votes

# Answer
I made a rain shader for 3D without using any particles at all (Video) but instead using three layers of the same texture scrolling by at different speeds at different scales as described in the article Rendering Falling Rain and Snow.

For 2D you obviously would not want a double cone to project your rain textures on but can use a plane instead. You can however use the effects with twisting a little (I think, haven't tested it) to create a feeling for velocity left or right. For back or forward you could just scale a little along the y-axis.
> 5 votes

# Answer
since it's a 2D game, I don't think you'll need a complete particle system to create beautiful rain. here is an idea : just create a rain animation and tile that all over the screen.
> 2 votes

# Answer
Somehow, very primitive Java example without using shaders.

```
    class ParticleSystem
    {
    int maxParicles=10000;
    float ParticleMaxLifeTimeMS=5000;
    particle[] Particles;
    emitter Emitter;
    billboard BillBoard;
    public void Emitt()
    {//emission code goes here}
    public void Evolve()
    {//explosion code goes here}
    class particle
    {
    float SpawnTime;
    float CurrentLife
    float x,y;
    float Vx,Vy;
    float r,g,b,a;
    float mass;
    float scale;
    }

    class emitter
    {
    float x,y;
    float EmissionRate;
    }

    class billboard
    {
    int materail_handler;
    float height,width;
    }
    }

```
> 2 votes

---
Tags: 2d, android, particles
---


# Question
Title: How is the terrain generated in Commandos and Commandos game clones/look-alikes?
The Commandos series of games and its similar western counterpart, Desperados, use a mix of 2D and 3D elements to achieve a very pleasing and immersive atmosphere. Apart from the concept that alone made the series a best-seller, the graphics eye-candy was also a much appreciated asset of that game.

I was very curious on what was the technique used to model and adorn the realistic terrains in those titles? Below are some screenshots that could be relevant as a reference for whomever has a candidate answer:

The tiny details and patternless distribution of ornamental textures make me think that these terrains were not generated using a standard heightmap-blendmap method.

# Answer
The commandos titles look like they use prerendered backgrounds. This means that one or multiple artists design the whole wort in a 2d or 3d programm. Commandos looks like it was done in 3d and then post processed in like photoshop. The exporter of the 3d programm used a special export method, as the viewing perspective is not physically correct. Objects more to the north should be smaller, but the size doesn't change correctly according to the perspective. If I'm not mistaken this mode is called "Orthogonal Mode".

Parts of the generated map are splitted into different groups. There are some graphics, that only are used as ground texture (this may be the biggest part of the exported map), there are parts that are animated or can change (a door for example can have an opened and a closed state) and there are graphics, that sometimes are drawn behind the soldiers and sometimes in front, depending on the standing position.

The Baldurs Gate and Icewind Dale series used the infinity engine, which uses a similar rendering style (the setting may be fantasy, but the graphics always looked kind of realistic to me, just like commandos). There has been a strong modding community around the infinity engine and a quick look to wikipedia revealed to me, that there is an open source clone / implementation of the engine in the works.

* GemRB (the opensource implementation of the infinity engine)

As the engine is pretty well known and documented by the community I think you can will be able to find a lot of detailed information about that type of map rendering in the GemRB community.
> 3 votes

---
Tags: terrain, terrain-rendering, map-editor, content-generation
---


title: Safe to advertise without a trademark?

text:
# Question
Title: Safe to advertise without a trademark?
Alright, I'm currently thinking about registering my game with Steam's new Greenlight program. Only problem is I don't have a trademarked title yet and I read the government's registration process can take a little while. (and $$ I don't have at the moment) So naturally, this got me wondering if it is a sound idea to proceed without one.

So my question is are there any serious pitfalls I should worry about if I start advertising without a trademarked title? (Assuming it doesn't infringe upon anyone else's property of course)

# Answer
Depending on your jurisdiction, simply using your title (and perhaps marking it with a ™ symbol) may qualify it for protection as an unregistered trade mark.

The Wikipedia article is pretty short, so let me quote it in its entirety:

> An **unregistered trade mark** is a trademark which does not benefit from the protection afforded to trade marks through registration.
>
> They may however benefit from protection due to other features of the law in relation to trademarks, such as protection for unregistered marks in the United Kingdom resulting from Passing off law.
>
> In the United States, neither federal nor state registration is required to obtain rights in a trademark. An unregistered mark may still receive common law trademark rights. Those rights, for example, may extend to its area of influence—usually delineated by geography. As such, multiple parties may simultaneously use a mark throughout the country or even state. An unregistered mark may also be protected under the federal "Lanham Act" (15 USC § 1125) prohibition against commercial misrepresentation of source or origins of goods. Unregistered marks are also protectable in the United States under Lanham Act §43(a).

<sup>(Authors: Wikipedia users 195.157.197.108, Mmmbeer and others; used under the CC-By-SA 3.0 license.) </sup>

Ps. The main trademark article on Wikipedia is significantly more detailed, and well worth a read.
> 4 votes

# Answer
Well, I do know that you get copyright just for coming up with it, so if you put proof (on your website or something), then you shouldn't run into too many issues...

Then again, I'm not a lawyer, so don't trust my advice too much!

By proof I mean things like copyright notices on your website( copyright blah 2012).
> 0 votes

---
Tags: intellectual-property, trademark
---


# Question
Title: How to solve ArrayList outOfBoundsExeption?
I'm getting:

```
    09-02 17:15:39.140: E/AndroidRuntime(533): java.lang.IndexOutOfBoundsException: Invalid index 1, size is 1
    09-02 17:15:39.140: E/AndroidRuntime(533):  at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:251)

```

when I'm killing enemies using this method:

```
    private void checkCollision() {
    Rect h1 = happy.getBounds();
    for (int i = 0; i < enemies.size(); i++) {
        for (int j = 0; j < bullets.size(); j++) {
            Rect b1 = bullets.get(j).getBounds();
            Rect e1 = enemies.get(i).getBounds();
            if (b1.intersect(e1)) {
                enemies.get(i).damageHP(5);
                bullets.remove(j);
                Log.d("TAG", "HERE: LOLTHEYTOUCHED");
            }
            if (h1.intersect(e1)){
                happy.damageHP(5);
            }
            if(enemies.get(i).getHP() <= 0){
                enemies.remove(i);
            }
            if(happy.getHP() <= 0){
                //end-screen                           !!!!!!!
            }
        }
    }
}

```

using this ArrayList:

```
        private ArrayList<Enemy> enemies = new ArrayList<Enemy>();

```

and adding to array like this:

```
   public void createEnemies() {
    Bitmap bmp = BitmapFactory.decodeResource(getResources(),
            R.drawable.female);
    if (enemyCounter < 24) {
        enemies.add(new Enemy(bmp, this, controls));
    }
    enemyCounter++;
}

```

I don't really understand what the problem is, I've been looking around for a while but can't really find anything that helps me. If you know or if you can link me someplace where they have a solution for a similar problem I'll be a very happy camper!

# Answer
The problem is the removal of elements from the `enemies` list. If the condition `enemies.get(i).getHP() <= 0` becomes true for an enemy object it may remove more than the intended object since your inner loop will continue to run. The fix is to break out of the inner loop and start checking the next enemy object:

```
if(enemies.get(i).getHP() <= 0){
    enemies.remove(i);
    break;
}

```
> 3 votes

# Answer
This happens when an "earlier" bullet has killed one or more of your enemies, and they are removed with `enemies.remove(i);` in such a way that now `i >= enemies.size()` (e.g. when it was the last enemy or enemies in the ArrayList). A "later" bullet will now be checked against an enemy index that no longer exists, and `enemies.get(i)` throws an `IndexOutOfBoundsException`.

It is generally a bad idea to thoughtlessly iterate over and remove from the same collection: you'll never know where your references end up (in this case `i` doesn't point anymore where you think it does). One way around this is to have a separate clean-up loop when you know your "dead" objects can no longer be referenced. To know which objects to clean-up, either:

* Use a property (`toBeDeleted`) for the objects that need to be removed, or
* Keep track of the set of indices that have been deprecated

So:

```
for (Enemy enemy : enemies) {

    // Check collisions with bullets.
    for (Bullet bullet : bullets) {
        if ( bullet.collides(enemy) ) {
            enemy.hit();
            bullet.setDelete(true);
        }
    }

    // Clean-up bullets.
    for (Iterator<Bullet> it = bullets.iterator(); it.hasNext(); )
        if ( it.next().isDelete() )
             it.remove();

    // Enemy-Happy collision bonus optimization.
    if ( happy.collides(enemy) ){
        happy.hit();
    }

    // Flag dead enemies.
    if ( enemy.hp() <= 0 ) {
        enemy.setDelete(true);
    }
}

// Clean-up enemies.
for (Iterator<Enemy> it = enemies.iterator(); it.hasNext(); )
    if ( it.next().isDelete() )
        it.remove();

```
> 3 votes

---
Tags: android, collision-detection, html-canvas
---


title: TRON: Game A.I algorithm?

text:
# Question
Title: TRON: Game A.I algorithm?
Lightcycles or whatever it was called like.

---

Given a 2d array representing the game map, where each element can be either 0 or 1 (0 representing blank space and 1 representing filled space), what is the algorithm used for TRON enemy A.I?

# Answer
> 7 votes
I haven't had the chance to dig through their code, but Armagetron Advanced is an open-source relatively mature lightcycle battling game.

You can find the source (and executables) here: http://armagetronad.net/downloads.php

# Answer
> 8 votes
This was the subject of one of the Google Ai competitions

There are some great resources from that page:

# Answer
> 1 votes
i don't know of any algorithms but i can create a simple "algorithm" in java

```
//2D boolean (true/false) array
boolean map[][] = new boolean[20][20];
//this represents the position of the AI on the map
int x = 10, y = 10;
//this int will be 1 - 4 and will represent a direction
//1 - up
//2 - right
//3 - down
//4 - left
int direction = 1;

void init(int startX, int startY){
    //set the x and y to a starting position
    x = startX;
    y = startY;
    //this will set the entire array to false
    int i = 0, j = 0;
    while (i<20){
        while(j<20){
            map[i][j] = false;
            j++;
        }
        j = 0;
        i++;
    }

    //and this will set the starting position to true
    map[x][y] = true;
}

void tick(){
    try{
        //try to go straight and will error if
        //it cannot because it would be out of bounds
        switch(direction){
        case 1: //up
            if(!map[x][y-1]){ //will error out here if the block in front is out of bounds
                map[x][y-1] = true;
                y--;
            }
            return;
        case 2: //right
            if(!map[x+1][y]){ //will error out here if the block in front is out of bounds
                map[x+1][y] = true;
                x++;
            }
            return;
        case 3: //down
            if(!map[x][y+1]){ //will error out here if the block in front is out of bounds
                map[x][y+1] = true;
                y++;
            }
            return;
        case 4: //left
            if(!map[x-1][y]){ //will error out here if the block in front is out of bounds
                map[x-1][y] = true;
                x--;
            }
            return;
        }
    }catch(Exception e){

    }
    //this next bit will only be  triggered if the AI could not go straight

    //define two temporary variables, fairly self explanatory.
    boolean canGoLeft = false, canGoRight = false;

    //defines whether it is safe to go left
    //turn left respectively
    //test if straight is safe
    direction--;
    try{
        //try to go straight and will error if
        //it cannot because it would be out of bounds
        switch(direction){
        case 1: //up
            if(!map[x][y-1]){ //will error out here if the block in front is out of bounds
                canGoLeft = true;
            }else canGoLeft = false;
            break;
        case 2: //right
            if(!map[x+1][y]){ //will error out here if the block in front is out of bounds
                canGoLeft = true;
            }else canGoLeft = false;
            break;
        case 3: //down
            if(!map[x][y+1]){ //will error out here if the block in front is out of bounds
                canGoLeft = true;
            }else canGoLeft = false;
            break;
        case 4: //left
            if(!map[x-1][y]){ //will error out here if the block in front is out of bounds
                canGoLeft = true;
            }else canGoLeft = false;
            break;
        }
    }catch(Exception e){
        canGoLeft = false;
    }
    //return to original direction before test
    direction++;

    //now perform the same test but with turning right
    //turn right respectively
    direction++;
    try{
        //try to go straight and will error if
        //it cannot because it would be out of bounds
        switch(direction){
        case 1: //up
            if(!map[x][y-1]){ //will error out here if the block in front is out of bounds
                canGoRight = true;
            }else canGoRight = false;
            break;
        case 2: //right
            if(!map[x+1][y]){ //will error out here if the block in front is out of bounds
                canGoRight = true;
            }else canGoRight = false;
            break;
        case 3: //down
            if(!map[x][y+1]){ //will error out here if the block in front is out of bounds
                canGoRight = true;
            }else canGoRight = false;
            break;
        case 4: //left
            if(!map[x-1][y]){ //will error out here if the block in front is out of bounds
                canGoRight = true;
            }else canGoRight = false;
            break;
        }
    }catch(Exception e){
        canGoRight = false;
    }
    direction--;

    if(canGoLeft&&!canGoRight){//can only go left
        direction--;
        try{
            //try to go straight and will error if
            //it cannot because it would be out of bounds
            switch(direction){
            case 1: //up
                if(!map[x][y-1]){ //will error out here if the block in front is out of bounds
                    map[x][y-1] = true;
                    y--;
                }
                return;
            case 2: //right
                if(!map[x+1][y]){ //will error out here if the block in front is out of bounds
                    map[x+1][y] = true;
                    x++;
                }
                return;
            case 3: //down
                if(!map[x][y+1]){ //will error out here if the block in front is out of bounds
                    map[x][y+1] = true;
                    y++;
                }
                return;
            case 4: //left
                if(!map[x-1][y]){ //will error out here if the block in front is out of bounds
                    map[x-1][y] = true;
                    x--;
                }
                return;
            }
        }catch(Exception e){

        }
    }else if(!canGoLeft&&canGoRight){//can only go right
        direction++;
        try{
            //try to go straight and will error if
            //it cannot because it would be out of bounds
            switch(direction){
            case 1: //up
                if(!map[x][y-1]){ //will error out here if the block in front is out of bounds
                    map[x][y-1] = true;
                    y--;
                }
                return;
            case 2: //right
                if(!map[x+1][y]){ //will error out here if the block in front is out of bounds
                    map[x+1][y] = true;
                    x++;
                }
                return;
            case 3: //down
                if(!map[x][y+1]){ //will error out here if the block in front is out of bounds
                    map[x][y+1] = true;
                    y++;
                }
                return;
            case 4: //left
                if(!map[x-1][y]){ //will error out here if the block in front is out of bounds
                    map[x-1][y] = true;
                    x--;
                }
                return;
            }
        }catch(Exception e){

        }
    }else if(canGoLeft&&canGoRight){//can go either way so it will pick randomly
        if(System.currentTimeMillis()%2==0){//random, will be true half of the time and false the other half
            //change direction one anticlockwise
            direction--;
            try{
                //try to go straight and will error if
                //it cannot because it would be out of bounds
                switch(direction){
                case 1: //up
                    if(!map[x][y-1]){ //will error out here if the block in front is out of bounds
                        map[x][y-1] = true;
                        y--;
                    }
                    return;
                case 2: //right
                    if(!map[x+1][y]){ //will error out here if the block in front is out of bounds
                        map[x+1][y] = true;
                        x++;
                    }
                    return;
                case 3: //down
                    if(!map[x][y+1]){ //will error out here if the block in front is out of bounds
                        map[x][y+1] = true;
                        y++;
                    }
                    return;
                case 4: //left
                    if(!map[x-1][y]){ //will error out here if the block in front is out of bounds
                        map[x-1][y] = true;
                        x--;
                    }
                    return;
                }
            }catch(Exception e){

            }
        }else{
            //change direction one clockwise
            direction++;
            try{
                //try to go straight and will error if
                //it cannot because it would be out of bounds
                switch(direction){
                case 1: //up
                    if(!map[x][y-1]){ //will error out here if the block in front is out of bounds
                        map[x][y-1] = true;
                        y--;
                    }
                    return;
                case 2: //right
                    if(!map[x+1][y]){ //will error out here if the block in front is out of bounds
                        map[x+1][y] = true;
                        x++;
                    }
                    return;
                case 3: //down
                    if(!map[x][y+1]){ //will error out here if the block in front is out of bounds
                        map[x][y+1] = true;
                        y++;
                    }
                    return;
                case 4: //left
                    if(!map[x-1][y]){ //will error out here if the block in front is out of bounds
                        map[x-1][y] = true;
                        x--;
                    }
                    return;
                }
            }catch(Exception e){

            }
        }
    }
}

```

---
Tags: 2d, ai
---


title: Problem with D3DXMatrixReflect

text:
# Question
Title: Problem with D3DXMatrixReflect
Currently I am trying to reflect a sky sphere into a flat piece of geometry which is acting as water. The sphere is very small, it follows the camera on all 3 axis and the z-buffer is turned off so it appears behind everything else.

Can someone please tell me how I can reflect the world matrix on a xz plane. And should I the plane be the water height or the camera height.

Thank you.

# Answer
Given a general plane with equation `A*x + B*y + C*z + D = 0`, the reflection matrix for this plane is:

```
1 - 2*A*A,    -2*A*B,    -2*A*C, 0,
   -2*B*A, 1 - 2*B*B,    -2*B*C, 0,
   -2*C*A,    -2*C*B, 1 - 2*C*C, 0,
   -2*A*D,    -2*B*D,    -2*C*D, 1

```

This is for OpenGL, so you might need to transpose the matrix for DirectX or something. Unfortunately I can't find any sources for the formula.

For your simpler case with xz-plane, a simpler matrix is enough. The following matrix mirrors in y-direction with y given as the plane height.

```
1,  0, 0, 0,
0, -1, 0, 0,
0,  0, 1, 0,
0,-2y, 0, 1

```

Again you might need to transpose the matrix or switch -2y to 2y.
> 2 votes

---
Tags: directx, matrix, geometry, reflection-rendering
---


# Question
Title: Please help with bounding box/sprite collision in darkBASIC pro
So I just recently learned BASIC and figured I would try making a clone of pong on my own in darkBASIC pro, and I made everything else work just fine except for the part that makes the ball bounce off the paddle. And yes I'm aware that the game is not yet finished. The error is on lines 39-51 EVERYTHING IS 2D. The problem i am having is that when the ball hits the paddle it gets like stuck(itll move away like 3 pixels and the back onto the paddle), and will move up or down until it finally gets to the edge of the paddle, or it gets sucked into the inside of the paddle, or it does the same thing where it gets stuck on the paddle, but it does it from behind.

```
  ///////////////////////////////////////////////////////////
  //
  //     Project: Pong
  //     Created: Friday, August 31, 2012
  //     Code: Brandon Spaulding
  //     Art: Brandon Spaulding
  //     Made in CIS lab at CPAVTS
  //     Pong art and code © Brandon Spaulding 2012-2013
  //
  //////////////////////////////////////////////////////////
y=150
x=0
ay=150
ax=612
ballx=300
bally=200
ballx_DIR=1
bally_DIR=1
hide mouse
set global collision on
//objectnumber=10
//make object box objectnumber,5,150,0
do
load image "media\paddle1.png",1
load image "media\paddle2.png",2
load image "media\ball.png",3
sprite 1,x,y,1
     sprite 2,ax,ay,2
     sprite 3,ballx,bally,3
     if upkey()=1 then y = y - 4
     if downkey()=1 then y = y + 4

    //num_1 = sprite collision(1,0)
    //num_2 = sprite collision(2,0)
      num_3 = sprite collision(3,0)

for t=1 to 2

//ball&paddle collision
if num_3 > 0
    if bally_DIR=1
        bally_DIR=0
    else
        bally_DIR=1
    endif
    if ballx_DIR=0
        ballx_DIR=1
    else
        ballx_DIR=0
    endif
endif

//if bally > 1 and bally < 500 then bally=bally + 2.5
if bally_DIR=1
    bally=bally-2.5
        if bally<-2.5
            bally_DIR=0
        endif
else
    bally=bally+2.5
        if bally>452.5
            bally_DIR=1
        endif

endif
if ballx_DIR=1
    ballx=ballx-2.5
        if ballx<-2.5
            ballx_DIR=0
        endif
else
    ballx=ballx+2.5
        if ballx>612
            ballx_DIR=1
        endif

endif
//bally = bally + t
//if bally < 600 or bally > 1 then bally = bally - 2.5
//if ballx < 400 or ballx > 1 then ballx = ballx + 2.5
//move sprite 3,1

   next t
   if escapekey()=1 then exit
   loop
   end

```

Thank you in advance for the help.

# Answer
> 2 votes
You're reloading your images on every frame. Don't do this. Also, you'll be doing yourself and others who read your code a favor if you clean it up. Make sure it's indented properly and don't use raw numbers for image or sprite or whatever other type of object ID. Also, don't use extremely short variable names such as `x` and `ax`. I was able to work out what these referred to, but I had to put some time and brain power into it, which is less brain power I can give toward helping you with your collision problem.

Improved version of your code, much easier for others to read and help you out with:

```
paddle1y = 150
paddle1x = 0

paddle2y = 150
paddle2x = 612

ballx = 300
bally = 200
ballx_DIR = 1
bally_DIR = 1

hide mouse
set global collision on

paddle1Img = 1
paddle2Img = 2
ballImg = 3

paddle1Sprite = 1
paddle2Sprite = 2
ballSprite = 3

load image "media\paddle1.png", paddle1Image
load image "media\paddle2.png", paddle2Image
load image "media\ball.png", ballImage

do
    sprite paddle1Image, paddle1x, paddle1y, paddle1Sprite
    sprite paddle2Image, paddle2x, paddle2y, paddle2Sprite
    sprite ballImage, ballx, bally, ballSprite

    if upkey()=1 then paddle1y = paddle1y - 4
    if downkey()=1 then paddle1y = paddle1y + 4

    num_paddle1_collisions = sprite collision(paddle1Sprite,0)
    num_paddle2_collisions = sprite collision(paddle2Sprite,0)
    num_ball_collisions = sprite collision(ballSprite,0)

    // etc.

```

You also aren't using that for loop in there, just running your set of if statements twice for no real reason. You need to think more about how to solve this problem. I would avoid using DarkBasic's collision. Keep track of the positions and collision rectangles yourself, you'll learn a lot more.

This site does not respond well to posts that are just making us fix your code. The Game Creators' community site has plenty of resources and of plenty good examples on how to implement a pong game. Use it, and do a little more homework instead of just dumping code here.

---
Tags: 2d, bounding-boxes
---


# Question
Title: Adjusting server-side tickrate dynamically
I know nothing of game development/this site, so I apologise if this is completely foobar.

Today I experimented with building a small game loop for a network game (think MW3, CSGO etc). I was wondering why they do not build in automatic rate adjustment based on server performance? Would it affect the client that much if the client knew this frame is based on this tickrate? Has anyone attempted this before?

Here is what my noobish C++ brain came up with earlier. It will improve the tickrate if it has been stable for x ticks. If it "lags", the tickrate will be reduced down by y amount:

```
// GameEngine.cpp : Defines the entry point for the console application.
//

#ifdef WIN32
#include <Windows.h>
#else
#include <sys/time.h>
#include <ctime>
#endif
#include<iostream>
#include <dos.h>
#include "stdafx.h"

using namespace std;

UINT64 GetTimeInMs()
{
    #ifdef WIN32
     /* Windows */
     FILETIME ft;
     LARGE_INTEGER li;

     /* Get the amount of 100 nano seconds intervals elapsed since January 1, 1601 (UTC) and copy it
      * to a LARGE_INTEGER structure. */
     GetSystemTimeAsFileTime(&ft);
     li.LowPart = ft.dwLowDateTime;
     li.HighPart = ft.dwHighDateTime;

     UINT64 ret = li.QuadPart;
     ret -= 116444736000000000LL; /* Convert from file time to UNIX epoch time. */
     ret /= 10000; /* From 100 nano seconds (10^-7) to 1 millisecond (10^-3) intervals */

     return ret;
    #else
     /* Linux */
     struct timeval tv;

     gettimeofday(&tv, NULL);

     uint64 ret = tv.tv_usec;
     /* Convert from micro seconds (10^-6) to milliseconds (10^-3) */
     ret /= 1000;

     /* Adds the seconds (10^0) after converting them to milliseconds (10^-3) */
     ret += (tv.tv_sec * 1000);

     return ret;
    #endif
}

int _tmain(int argc, _TCHAR* argv[])
{
    int sv_tickrate_max = 1000; // The maximum amount of ticks per second
    int sv_tickrate_min = 100; // The minimum amount of ticks per second
    int sv_tickrate_adjust = 10; // How much to de/increment the tickrate by
    int sv_tickrate_stable_before_increment = 1000; // How many stable ticks before we increase the tickrate again

    int sys_tickrate_current = sv_tickrate_max; // Always start at the highest possible tickrate for the best performance

    int counter_stable_ticks = 0; // How many ticks we have not lagged for

    UINT64 __startTime = GetTimeInMs();
    int ticks = 100000;

    while(ticks > 0)
    {
        int maxTimeInMs = 1000 / sys_tickrate_current;

        UINT64 _startTime = GetTimeInMs();

        // Long code here...

        cout << ".";

        UINT64 _timeTaken = GetTimeInMs() - _startTime;

        if(_timeTaken < maxTimeInMs)
        {
            Sleep(maxTimeInMs - _timeTaken);
            counter_stable_ticks++;

            if(counter_stable_ticks >= sv_tickrate_stable_before_increment)
            {
                // reset the stable # ticks counter
                counter_stable_ticks = 0;

                // make sure that we don't go over the maximum tickrate
                if(sys_tickrate_current + sv_tickrate_adjust <= sv_tickrate_max)
                {
                    sys_tickrate_current += sv_tickrate_adjust;

                    // let me know in console #DEBUG
                    cout << endl << "Improving tickrate. New tickrate: " << sys_tickrate_current << endl;
                }
            }
        }
        else if(_timeTaken > maxTimeInMs)
        {
            cout << endl;
            if((sys_tickrate_current - sv_tickrate_adjust) > sv_tickrate_min)
            {
                sys_tickrate_current -= sv_tickrate_adjust;
            }
            else
            {
                if(sys_tickrate_current == sv_tickrate_min)
                {
                    cout << "Please reduce sv_tickrate_min..." << endl;
                }
                else{
                    sys_tickrate_current = sv_tickrate_min;
                }
            }

            // let me know in console #DEBUG
            cout << "The server has lag. Reduced tickrate to: " << sys_tickrate_current << endl;
        }
        ticks--;
    }

    UINT64 __timeTaken = GetTimeInMs() - __startTime;

    cout << endl << endl << "Total time in ms: " << __timeTaken;

    cout << endl << "Ending tickrate: " << sys_tickrate_current;

    char test;
    cin >> test;

    return 0;
}

```

# Answer
> 1 votes
There are a few reasons. Let's start by thinking about **why** the server has something called tickrate in the first place.

* It allows **scheduling** of events. "send world state to clients every N ticks"
* It allows **iterative processing** of game events
* It makes the whole system **synchronous**, granted that all systems rely on same tick counter

So what happens if the server intentionally alters this depending on it's load:

* Event scheduling gets somewhat messed up - server load can change rapidly and packets may be sent late or out of order. Both cause lag and jitter in multiplayer experience.
* Iterative processing of physics for example lose precision, this can easily cause syncing problems between server and connected clients, which then require the server to send out world updates.
* While the server itself still is within sync(if all the systems rely on the same tick counter), there can arise situations when server and client go out of sync network wise - packets arrive with higher delay and go out of order.

So, we bring in problems and probably some hard to debug bugs. Of course, all problems are easy to circumvent with some thought, but is this really the price to pay for less CPU load during times of low CPU load anyway? Of course something like this **could** be benefiting for server which are being ran on hardware with varying load(a shared server for example) but in the end it's the players online experience which takes a hit anyway. Simply put, players prefer servers which don't have performance issues, and dynamic tickrate adjustment wouldn't bring a cure anyway.

---
Tags: c++, architecture, first-person-shooter
---


title: Keyboard input system handling

text:
# Question
Title: Keyboard input system handling
Note: I have to poll, rather than do callbacks because of API limitations (SFML). I also apologize for the lack of a 'decent' title.

I think I have two questions here; how to register the input I'm receiving, and what to do with it.

## Handling Input

I'm talking about after the fact you've registered that the 'A' key has been pressed, for example, and how to do it from there.

I've seen an array of the whole keyboard, something like:

`bool keyboard[256]; //And each input loop check the state of every key on the keyboard`

But this seems inefficient. Not only are you coupling the key 'A' to 'player moving left', for example, but it checks every key, 30-60 times a second.

I then tried another system which just looked for keys it wanted.

`std::map< unsigned char, Key> keyMap; //Key stores the keycode, and whether it's been pressed. Then, I declare a load of const unsigned char called 'Quit' or 'PlayerLeft'.
input->BindKey(Keys::PlayerLeft, KeyCode::A); //so now you can check if PlayerLeft, rather than if A.`

However, the problem with this is I cannot now type a name, for example, without having to bind every single key.

Then, I have the second problem, which I cannot really think of a good solution for:

## Sending Input

I now know that the A key has been pressed or that playerLeft is true. But how do I go from here?

I thought about just checking  `if(input->IsKeyDown(Key::PlayerLeft) { player.MoveLeft(); }`
This couples the input greatly to the entities, and I find it rather messy. I'd prefer the player to handle its own movement when it gets updated. I thought some kind of event system could work, but I do not know how to go with it. (I heard signals and slots was good for this kind of work, but it's apparently very slow and I cannot see how it'd fit).

Thanks.

# Answer
What I'd do is use the observer pattern and have an input class that maintains a list of callbacks or input handling objects. Other objects can register themselves with the input system to be notified when certain things happen. There are different types of callbacks you could register, based on the type of input events observers would like to be notified about. This could be as low level as 'key x is down/up' or more game-specific like 'a jump/shooting/movement event happened'.

Generally game objects have an input handling component that is responsible for registering itself with the input class and providing methods to handle the events it is interested in. For movement, I have an input mover component that has a move(x, y) method. It registers itself with the input system and gets notified on movement events (where x and y would be -1 and 0 to signify moving left), the mover component then changes its parent game object coordinates based on movement direction and object velocity.

I don't know if this is a good solution but it works for me so far. In particular it allows me to provide different kinds of input system that map to the same logical game events so that gamepad button x and keyboard space both generate a jump event for example (it's a bit more complicated than that, allowing the user to reassign key mappings).
> 7 votes

# Answer
I think that the OP's discussion is lumping a bunch of things together, and that the problem can be simplified substantially by breaking it up a bit.

My suggestion:

Keep your array of keys' states. Isn't there an API call to get the entire keyboard state at once? (Most of my work is on consoles, and even on Windows for a connected controller you get the whole controller state at once.) Your key states are a "hard" map on the keys of the keyboard. Untranslated is best, but however you get it easiest out of the APIs.

Then keep a a few parallel arrays that indicate whether the key went up this frame, another indicating that it went down, and a third to indicate simply that the key is "down". Maybe throw in a timer so you can keep track of how long the key has been in its current state.

Next create a method to create a mapping of keys to actions. You'll want to do this a couple of times. Once for UI stuff (and take care to query the Windows mappings because you can't assume the scancode when you press 'A' is going to give an A on the user's computer). Another for each in-game "mode". These are the mappings of keycodes to actions. You can do this a couple of ways, one would be to keep an enum that is used by the receiving system, another would be a function pointer indicating the function to be called on a state change. Maybe even a hybrid of the two, depending on your goals and needs. With these "modes" you can push and pop them onto a controller mode stack, with flags that allow ignored input to keep going down the stack or whatever. The key though is that it is easy to switch in a new mode for handling the input.

Finally, handle those key actions somehow. For motion you might want to do something tricky, translate 'W' down to mean "move forward," but it doesn't need to be a binary solution; you can have "W is down" mean "increase velocity by X until a maximum of Y," and "W is up" to be "decrease velocity by Z until it hits zero." Generally speaking- you want your "controller handling interface in game systems" to be pretty narrow; do all of the key translation in one place and then use the results of that everywhere else. This is in contrast to directly checking to see if Spacebar is pressed anywhere random in the code, because if it's in some random spot it'll probably get hit at some random time when you don't want it to, and you just don't want to deal with that...

I really detest designing to patterns and I think components bring more development cost than good, so that's why I mentioned neither. Patterns will emerge if they're destined to, as will components, but setting out to do either from the outset will only complicate your life.
> 6 votes

# Answer
In SFML, you have the keys in the order they have been pressed with the KeyPressed event type. You process each key in a while(getNextEvent()).

So if the pressed key is in your Key-\>Action map, run the corresponding action, and if it's not, forward it to any widget/stuff that might need it.

Regarding your second question, I'd recommend you to keep it like this because it makes it easier to tweak your gameplay. If you use signals or such, you will have to make a slot for the "RunKeyDown" and another for the "JumpKeySlot". But what happens if in your game, a special action is performed when both are pressed ?

If you want to decorrelate input and entities, you could make your input a State (RunKey = true, FireKey = false, ...) and send it to the player like you send any other event to your AIs.
> 3 votes

# Answer
The correct solution is often a combination of the two methods you discuss:

For gameplay functionality with a predefined set of keys, polling every frame is completely appropriate and you should only poll for keys that are actually bound to something. This is actually analogous to how you would query controller input in a console game, it's going to be entirely polling especially when it comes to analog input devices. During general gameplay you probably want to ignore keypress events and just use polling.

When it comes to typing input for things like names you should switch the game into a different input handling mode. For instance, as soon as a "enter your name" prompt comes up, you can modify what you're input code does. It can either listen for key press events via some callback interface, or you can start polling for each key if required. It turns out that typically during typing events you don't care as much about performance anyway, so polling won't be that bad.

So, you want to use selective polling for gameplay input, and event handling for name typing inputs (or all keyboard polling if event handling is not available).
> 3 votes

# Answer
I like the answer of dash-tom-bang very much, it really highlights some aspects that you should keep in mind when designing an input system.

I'd like to add a little tutorial I stumbled upon which goes in the same direction (including input contexts, 3 layers,...):

http://www.gamedev.net/blog/355/entry-2250186-designing-a-robust-input-handling-system-for-games/
> 1 votes

---
Tags: architecture, input, keyboard, events
---


# Question
Title: Crafty.js multiplayer platform game, keeping players in sync
I'm using crafty.js to create a very simple platform game. It doesn't need to stop cheating, it's actually just seeing other players move around, and it doesn't need to have collision detection between players. They are "shadows".

How I've gone about it so far is to use http://pubnub.com to send messages between clients. These messages are simple. The first if a new player arrival, the second is a key down and the third is a key up.

The code is here: https://github.com/whiteoctober/craftyconcept

However I've hit against the old chestnut of keeping everything in sync.

At the moment I'm letting the each of the clients decide where to place the other players based on the received key events, I also only move "you" until I get a key press event back from pubsub. My thinking here is to try and keep things in sync!

However it isn't perfect, http://www.whiteoctober.co.uk/john/gametest/, things can get out of sync very easily. Key presses arrive in the wrong order etc.

Is there any simple solutions to this, I would like to keep it all client side (with pubnub) and not have a central server with positions etc if possible.

# Answer
> 1 votes
Your problem is that you are making the clients decide where to put the chars. And that will invitable make them out of sync, when you only send keyboard presses, that would only work with a central server, which would keep all they correct data.

If you really want to avoid a centreal server, the way you can do it is by sending the coordinates instead of keypresses, like saying \[player 1, x: 20, y: 500\]

That way you can make each client broadcast theirs OWN player position.

I would that would work for a start.

---
Tags: javascript, html5, client-server, crafty
---


title: Confusing box2d forces

text:
# Question
Title: Confusing box2d forces
Hello Friends. This is my demo game screen-shoot. Here i am using three buttons. Right-bottom button is used for jump and left-bottom buttons used for move left and right.

I have some questions 1) should i use linearImpuls for jump body?? 2) For move right and left which types of force i applied???

PLease tell me i am confusing to use linearImpuls, applyforce and linearVelocity.

Thanks in advance

# Answer
To jump you should use linear impulse upwards. To run you have a couple of options. You could apply a force which wil over time increase velocity. You would then need to limit the maximum velocity. This is done by applying damping. You also want the player to come to a complete stop when not pressing left or right. This is done by applying friction. Set friction and damping quite high to make the controls feel responsive.

You could also instead make a velocity check to see if you are moving to the right or left and apply an impulse if not. This will lead to a bit more jerky behaviour though (which might on the other hand be what you want)
> 0 votes

# Answer
How can i set maximum speed?? Because i am set one force when i press move button

```
if (moveRight.active==YES)
    {
            ballBody->SetActive(true);
        b2Vec2 locationworld=b2Vec2(10,0);
            //b2Vec2 force=b2Vec2(1.0,0);
        double mass=ballBody->GetMass();

        ballBody->ApplyForce(mass*locationworld, ballBody->GetWorldCenter());
  //      ballBody->SetLinearDamping(1.2f);

        NSLog(@"Speed Of Velocity Right: %f",ballBody->GetLinearVelocity().x);
    }

```

This condition is in update method. So where i set maximum speed??
> 0 votes

---
Tags: physics, cocos2d-iphone, box2d
---


title: Heightmap in Shader not working

text:
# Question
Title: Heightmap in Shader not working
I'm trying to implement GPU-based geometry clipmapping and have problems to apply a simple heightmap to my terrain. For the heightmap I use a simple texture with the surface format "single". I've taken the texture from Catalinz's XNA blog.

What I'm trying to do is just getting the single float value from the texture at the vertex world coordinate and apply the value to the Y-Value of the Vertex. I'm applying the heightmap through the shader, because there is no fixed grid in-code it could be applied on. What I've tried so far was using the `tex2Dlod` function, but there seems to be no output or an output of 0. The Direct X vertex shader's code looks like this:

```
float4 worldPos = mul(float4(pos.x,0.0f,pos.y, 1.0f), worldMatrix);
float elevation = tex2Dlod(HeightmapSampler, float4(worldPos.x, worldPos.z,0,0));
worldPos.y = elevation * 128;

```

Where `HeightmapSampler` is a point-mirror sampler of the heightmap texture. Here is the output, I actually get no elevation:

And here's the heightmap I'm using:

# Answer
> 2 votes
What's the resolution of your terrain mesh? You're sampling the texture directly with the worldPos x & z vals: if you have a vertex every 1 unit, you'd get the same texture value each time as it's only the fractional part that's used. See if dividing the vals has any difference, e.g.:

```
float elevation = tex2Dlod(HeightmapSampler, float4(worldPos.x*0.001, worldPos.z*0.001,0,0));

```

---
Tags: hlsl, heightmap
---


# Question
Title: How are certain objects named in OpenGL?
I am a beginner in OpenGL, and I would like to know how to distinguish specific objects in an OpenGL game. For instance, the game world contains 3 gems of different colors, how can I know which one the user collides with exactly? P.S. At first I thought it could be picking, but no, picking is for mouse pointing

# Answer
> 1 votes
It sounds like you just want a general games development glossary like this one:

http://www.gameprogrammer.com/glossary.html

If you want to know the correct terminology for something, you'll just have to look it up. There's no 'central guide'.

Generally by the point at which you're ready to implement something in your game you'll have done enough research on it to not only know that the relevant term is but give a full etymology lesson on how that term came about :)

---
Tags: c++, opengl, objects
---


# Question
Title: How do I prevent my platformer's character from clipping on wall tiles?
Currently, I have a platformer with tiles for terrain (graphics borrowed from Cave Story). The game is written from scratch using XNA, so I'm not using an existing engine or physics engine.

The tile collisions are described pretty much exactly as described in this answer (with simple SAT for rectangles and circles), and everything works fine.

Except when the player runs into a wall whilst falling/jumping. In that case, they'll catch on a tile and begin thinking they've hit a floor or ceiling that isn't actually there.

In this screenshot, the player is moving right and falling downwards. So after movement, collisions are checked - and first, it turns out the player character is colliding with the tile 3rd from the floor, and pushed upwards. Second, he's found to be colliding with the tile beside him, and pushed sideways - the end result being the player character thinks he's on the ground and isn't falling, and 'catches' on the tile for as long as he's running into it.

I could solve this by defining the tiles from top to bottom instead, which makes him fall smoothly, but then the inverse case happens and he'll hit a ceiling that isn't there when jumping upwards against the wall.

**How should I approach resolving this, so that the player character can just fall along the wall as it should?**

# Answer
The simplest, more fail-proof approach is to simply not check for collisions on hidden edges. If you have two wall tiles, one directly above the other, then the bottom edge of the upper tile and the top edge of the lower tile should not be checked for collision against the player.

You can determine which edges are valid during a simple pass over the tile map, storing outward edges as flags on each tile location. You can also just do this at runtime by checking adjacent tiles during collision detection.

There are more advanced versions of this same technique that make it easier and faster to support non-square tiles as well.

I recommend that you read the articles below. They're decent simple introductions to doing basic physics and collision detection in modern platformers (like Cave Story). If you're going for a more old-school Mario feel, there's a few more tricks to worry about, but most of them involve handling jumping and animations rather than collision.

http://www.metanetsoftware.com/technique/tutorialA.html http://www.metanetsoftware.com/technique/tutorialB.html
> 9 votes

# Answer
Here the order I would do things....

1) Save current X,Y of character

2) Move the X direction

3) Check all corner of character by getting the tile data and check if it is solid by doing the following: (X and Y is the character position)

* for top left: floor(X / tileWidth), floor(Y / tileHeight);
* for top right: floor((X + characterWidth) / tileWidth), floor(Y / tileHeight);
* for bottom left: floor(X + / tileWidth), floor((Y + characterHeight) / tileHeight);
* for bottom right: floor((X + characterWidth) / tileWidth), floor((Y + characterHeight) / tileHeight);

...to obtain correct tile data from map data

4) If any of the tiles are solid, then you need to force X to the best position possible by restoring the saved X and...

* if you where moving left: X = floor(X / tileWidth) * tileWidth;
* if you where moving right: X = ((floor((X + characterWidth) / tileWidth) + 1) * tileWidth) - characterWidth;

5) Repeat 2-4 using Y

If your character is taller than a tile, you need to check more tiles. To do this you need to loop and add tileHeight to the characterY position to obtain tile

```
int characterBlockHeight = 3;

// check all tiles and intermediate tiles down the character body
for (int y = 0; y < characterBlockHeight - 1; y++) {
    tile = getTile(floor(characterX / tileWidth), floor((characterY + (y * tileHeight)) / tileHeight));
    ... check tile OK....
}

// finally check bottom
tile = getTile(floor(characterX / tileWidth), floor((characterY + characterHeight) / tileHeight);
... check tile OK....

```

If the character is wider than 1 block then do the same but replace characterY, characterHeight, tileHeight, e.t.c. with characterX, characterWidth, e.t.c.
> 5 votes

# Answer
What if you checked for the possibility of a collision as part of the player's movement method, and rejected movement which caused the player to slide into another object? This would prevent the player from getting 'inside' a block, and therefore he could not be 'on top' of the block below it.
> 2 votes

# Answer
I ran into almost the exact same problem in a game that I'm working on currently. The way I resolved it was to store the area of the overlapping portion when testing for collisions, and then handling those collisions based on their priority (largest area first), then double checking each collision to see if it had already been resolved by an earlier handling.

In your example, the area of the x-axis collision would be greater than the y-axis, so it would be handled first. Then before attempting to handle the y-axis collision, it would check and see that it is no longer colliding after being moved on the x-axis. :)
> 1 votes

# Answer
A simple, but not perfect, fix is to change the shape of the player collision box so that it is not a square. Cut off the corners to make him octagon-like or something similar. This way, when he collides with a tile like the ones in the wall, he will slide off of it and not get caught. This isn't perfect because you can still notice him catching on corners a little bit, but he won't get stuck and it is very easy to implement.
> 1 votes

# Answer
A very similar problem was covered in this tutorial: Introduction to Game Development. The relevant part of the video is at 1:44, explaining with diagrams and code snippets.

Notice 14-tilemap.py exhibits the clipping problem, but it is fixed in 15-blocker-sides.py

I can't exactly explain why the last tutorial example doesn't clip while your code does, but I think it has something to do with:

* Conditional collision response based on the type of tile (which edges are actually active.)
* The player is always 'falling.' Although the player seems to be resting on a tile, the player is actually repeatedly falling through the tile, then being pushed back to the top. (The `self.resting` member in the code is only used to check if the player can jump. Despite this I can't get the player to do a 'double' jump from a wall. Theoretically it might be possible, though)
> 1 votes

# Answer
Another method (which I answered the question Byte56 linked to) would be to check if the collision resolution puts the character in an empty spot or not. So in your problem, you get a collision from the inside rectangle's ceiling to move it up, which would be illegal (as you're still in collision with another tile). Instead you only move it if it you're moved into a free space (such as how the collision from the upper tile would move you to the left), and once you find that collision, you are done.

The answer I gave had code, but it became overly complicated. I'd keep track of all collisions within that timeframe and only take the one which lead to a free space. However if there were none, I think I resorted to resetting the character's position to its last position, however that's really ugly and maybe you would rather try implementing something like the original Mario where he just moves in one direction or something when no free space resolution is possible. Also you could sort that list of collision resolutions and only move to the freespace with the shortest distance (I think that solution would be the most preferable, although I didn't code for that).
> 0 votes

# Answer
I've only done3 SAT in 3D so maybe I'm not getting this right. If I understand your problem it could be due to getting contacts with a contact axis that should not be possible, resulting in player acting like there is a floor. One workaround could maybe be to use a circle shape for your caracter instead, then you will only get contact axes in the x-axis direction when hitting a wall.
> 0 votes

---
Tags: collision-detection, tiles, platformer
---


# Question
Title: How to derive euler angles from matrix or quaternion?
Currently working on steering behavior for my AI and just hit a little mathematical bump.

I'm in the process of writing an align function, which basically tries to match the agent's orientation with a target orientation. I've got a good source material for implementing this behavior but it uses euler angles to calculate the rotational delta, acceleration, and so on. This is nice, however I store orientation as a quaternion and the math library I'm using doesn't provide any functionality for deriving the euler angles. But if it helps I also have rotational matrices at my disposal too.

What would be the best way to decompose the quaternion or rotational matrix to get the euler information?

I found one source for decomposing the matrix, but I'm not quite getting the correct results. I'm thinking it may be a difference of column/row ordering of my matrices but then again, math isn't my strong point. http://nghiaho.com/?page\_id=846

# Answer
> 4 votes
You should really be storing the component vectors (rotation, translation, scale, velocity, etc.) in addition to the matrix and quaternion forms. Not only does that eliminate the problem your having, it reduces compound numerical errors that come up over time from floating point limits.

# Answer
> 0 votes
Here's the code from pyeuclid:

```
class Quaternion:
    def get_euler(self):
        t = self.x * self.y + self.z * self.w
        if t > 0.4999:
            heading = 2 * math.atan2(self.x, self.w)
            attitude = math.pi / 2
            bank = 0
        elif t < -0.4999:
            heading = -2 * math.atan2(self.x, self.w)
            attitude = -math.pi / 2
            bank = 0
        else:
            sqx = self.x ** 2
            sqy = self.y ** 2
            sqz = self.z ** 2
            heading = math.atan2(2 * self.y * self.w - 2 * self.x * self.z,
                                 1 - 2 * sqy - 2 * sqz)
            attitude = math.asin(2 * t)
            bank = math.atan2(2 * self.x * self.w - 2 * self.y * self.z,
                              1 - 2 * sqx - 2 * sqz)
        return heading, attitude, bank

```

---
Tags: mathematics, matrix, rotation, quaternion
---


# Question
Title: Model View Control Issue: Null Pointer Initialization Question
Good morning again. This is David. Please, I need an urgent help regarding control model view where I making a code that uniquely separating into groups:

1. *An Activity Java Class to Display the Interface*
2. *A View and Function Java Class for Drawing Cards and Display it on the Activity Class*

The problem is that the result returns a *Null Pointer Exception*. I have initialize for the ID for *Text View* and *Image View*. Under this class "**draw\_deck.java**". Please help me.

Here's my code for **draw\_deck.java**:

```
package com.bodapps.inbetween.model;

import android.content.Context;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bodapps.inbetween.R;

public class draw_deck extends View
{

public TextView count_label;
public ImageView draw_card;
private int count;

public draw_deck(Context context)
{
    super(context);
    // TODO Auto-generated constructor stub

            //I have initialized two widgets for ID. I still don't get it why I got forced closed by Null Pointer Exception thing.
    draw_card = (ImageView) findViewById(R.id.IV_Draw_Card);
    count_label = (TextView) findViewById(R.id.Text_View_Count_Card);
}

public void draw(int s, int c, String strSuit, String strValue, Pile pile, Context context)
{
    //super(context);

    //Just printing the card drawn from pile
    int suit, value = 1;
    draw_card = (ImageView) findViewById(R.id.IV_Draw_Card);
    count_label = (TextView) findViewById(R.id.Text_View_Count_Card);
    Card card;

    if(!pile.isEmpty()) //Setting it to IF statement displays the card one by one.
    {
        card = pile.drawFromPile();

        //Need to check first if card is null.
        if (card != null)
        {
            //draws an extra
            if (card != null)
            {
                //Get suit of card to print out.
                suit = card.getSuit();
                switch (suit)
                {
                case CardInfo.DIAMOND:
                    strSuit = "DIAMOND";
                    s=0;
                    break;
                case CardInfo.HEART:
                    strSuit = "HEART";
                    s=1;
                    break;
                case CardInfo.SPADE:
                    strSuit = "SPADE";
                    s=2;
                    break;
                case CardInfo.CLUB:
                    strSuit = "CLUB";
                    s=3;
                    break;
                }

                //Get value of card to print out.
                value = card.getValue();
                switch (value)
                {
                case CardInfo.ACE:
                    strValue = "ACE";
                    c=0;
                    break;
                case CardInfo.TWO:
                    c=1;
                    break;
                case CardInfo.THREE:
                    strValue = "THREE";
                    c=2;
                    break;
                case CardInfo.FOUR:
                    strValue = "FOUR";
                    c=3;
                    break;
                case CardInfo.FIVE:
                    strValue = "FIVE";
                    c=4;
                    break;
                case CardInfo.SIX:
                    strValue = "SIX";
                    c=4;
                    break;
                case CardInfo.SEVEN:
                    strValue = "SEVEN";
                    c=4;
                    break;
                case CardInfo.EIGHT:
                    strValue = "EIGHT";
                    c=4;
                    break;
                case CardInfo.NINE:
                    strValue = "NINE";
                    c=4;
                    break;
                case CardInfo.TEN:
                    strValue = "TEN";
                    c=4;
                    break;
                case CardInfo.JACK:
                    strValue = "JACK";
                    c=4;
                    break;
                case CardInfo.QUEEN:
                    strValue = "QUEEN";
                    c=4;
                    break;
                case CardInfo.KING:
                    strValue = "KING";
                    c=4;
                    break;
                }

            }
        }
    }//

            //Below two lines of code, this is where issued the Null Pointer Exception.
    draw_card.setImageResource(deck[s][c]);
    count_label.setText(new StringBuilder(strValue).append(" of ").append(strSuit).append(String.valueOf(" " + count++)).toString());

}

//Choice of Suits in a Deck
    public Integer[][] deck =
    {

        //Array Group 1 is [0][0] (No. of Cards: 4 - DIAMOND)
        {
            R.drawable.card_dummy_1,
            R.drawable.card_dummy_2,
            R.drawable.card_dummy_4,
            R.drawable.card_dummy_5,
            R.drawable.card_dummy_3
        },

        //Array Group 2 is [1][0] (No. of Cards: 4 - HEART)
        {
            R.drawable.card_dummy_1,
            R.drawable.card_dummy_2,
            R.drawable.card_dummy_4,
            R.drawable.card_dummy_5,
            R.drawable.card_dummy_3
        },

        //Array Group 3 is [2][0] (No. of Cards: 4 - SPADE)
        {
            R.drawable.card_dummy_1,
            R.drawable.card_dummy_2,
            R.drawable.card_dummy_4,
            R.drawable.card_dummy_5,
            R.drawable.card_dummy_3
        },

        //Array Group 4 is [3][0] (No. of Cards: 4 - CLUB)
        {
            R.drawable.card_dummy_1,
            R.drawable.card_dummy_2,
            R.drawable.card_dummy_4,
            R.drawable.card_dummy_5,
            R.drawable.card_dummy_3
        },

    };

}

```

And this one of the activity class, **Player\_Mode\_2.java**:

```
package com.bodapps.inbetween;

import java.util.Random;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bodapps.inbetween.model.Card;
import com.bodapps.inbetween.model.Pile;
import com.bodapps.inbetween.model.draw_deck;

/*
 *
 *      Public class for Two-Player mode.
 *
 */

public class Player_Mode_2 extends Activity
{

//Image Views
private ImageView draw_card;
private ImageView player_1;
private ImageView player_2;
private ImageView icon;

//Buttons
private Button set_deck;

//Edit Texts
private EditText enter_no_of_decks;

//text Views
private TextView count_label;

//Integer Data Types
private int no_of_cards, count;
private int card_multiplier;

//Contexts
final Context context = this;

//Pile Model
public Pile pile;

//Card Model
public Card card;

//create View
@Override
public void onCreate(Bundle savedInstanceState)
{

    super.onCreate(savedInstanceState);
    setContentView(R.layout.play_2_player_mode);

    //-----[ Search for Views ]-----

    //Initialize for Image View
    draw_card = (ImageView) findViewById(R.id.IV_Draw_Card);
    player_1 = (ImageView) findViewById(R.id.IV_Player_1_Card);
    player_2 = (ImageView) findViewById(R.id.IV_Player_2_Card);

    //Initialize for Text view or Label
    count_label = (TextView) findViewById(R.id.Text_View_Count_Card);

    //-----[ Adding Values ]-----
    //Integer Values
    count = 0;
    no_of_cards = 0;

    //-----[ Adding Dialog ]-----
    //Initializing Dialog
    final Dialog deck_dialog = new Dialog(context);
    deck_dialog.setContentView(R.layout.dialog);
    deck_dialog.setTitle("Deck Dialog");

    //-----[ Initializing Views for Dialog's Contents ]-----

    //Initialize for Edit Text
    enter_no_of_decks = (EditText) deck_dialog.findViewById(R.id.Edit_Text_Set_Number_of_Decks);

    //Initialize for Button
    set_deck = (Button) deck_dialog.findViewById(R.id.Button_Deck);

    //-----[ Setting onClickListener() ]-----

    //Set Event Listener for Image view
    draw_card.setOnClickListener(new Draw_Card_Model());

    //Set Event Listener for Setting the Deck
    set_deck.setOnClickListener(new OnClickListener()
    {

        public void onClick(View v)
        {

            if(card_multiplier <= 8)
            {
                //Use "Integer.parseInt()" method to instantly convert from String to int value.
                card_multiplier = Integer.parseInt(enter_no_of_decks.getText().toString());

                //Shuffling cards...
                pile = new Pile(card_multiplier); //Multiply no. of decks

                //Dismiss or close the dialog.
                deck_dialog.dismiss();
            }
            else
            {
                Toast.makeText(getApplicationContext(), "Please choose a number from 1 to 8.", Toast.LENGTH_SHORT).show();
            }

        }

    });

    //Show dialog.
    deck_dialog.show();

}

//Shuffling the Array
public void Shuffle_Cards(Integer[][] Shuffle_Deck)
{

    Random random = new Random();

    for(int i = Shuffle_Deck[no_of_cards].length - 1; i >=0; i--)
    {
        int Index = random.nextInt(i + 1);

        //Simple Swapping
        Integer swap = Shuffle_Deck[card_multiplier-1][Index];
        Shuffle_Deck[card_multiplier-1][Index] = Shuffle_Deck[card_multiplier-1][i];
        Shuffle_Deck[card_multiplier-1][i] = swap;
    }

}

//Private Class for Random Card Draw
private class Draw_Card_Model implements OnClickListener
{

    public void onClick(View v)
    {

        //Just printing the card drawn from pile
        int suit = 0, value = 0;
        String strSuit = "", strValue = "";

        draw_deck draw = new draw_deck(context); //This line is where issued the Null Pointer Exception.

        if (count == card_multiplier*52)
        {
            // A message shows up when all cards are draw out.
            Toast.makeText(getApplicationContext(), "All cards have been used up.", Toast.LENGTH_SHORT).show();
            draw_card.setEnabled(false);
        }
        else
        {
            draw.draw(suit, value, strSuit, strValue, pile, context);

            count_label.setText(count); //This is where I got force closed error, although "int count" have initialized the number. This was supposed to accept in the setText() method.
            count++;
        }

    }

}

}

```

Take note that the issues on Null Pointer Exception is the *Image View* and the *Edit Text*. I got to test it. Thanks. If you have any info about my question, let me know it frankly.

# Answer
Truly mysterious null pointer exceptions often arise from the view viewing model code that is being changed under it's nose by a different process. You shouldn't be changing the data structures in "onclick" methods unless everything is carefully synchronized against view access.
> 1 votes

---
Tags: java, android, eclipse
---


# Question
Title: Sharing VBO with multiple objects and fixed size buffer data
I'm just messing around with OpenGL and getting some basic structures in place and my first attempt resulted in each SceneObject class (just contains vertex information right now) having it's own VBO inside it, however I've read that it might be better to share VBOs across multiple objects.

Also, I read that you should avoid resizing a VBO (repeated calls to `glBufferData` with different size parameters), and instead choose a fixed size for a VBO, and just try a range from the buffer. I don't think changing the size of the buffer data would happen too often, but surely it would be better to only allocate the data you need? Choosing an arbitrary value seems risky.

I'm looking for some advice on working with individual objects in a scene and their associated buffer data.

# Answer
> 3 votes
Don't create a new VBO for each SceneObject. Instead create a new VBO for each mesh and have multiple SceneObjects reference the same VBO if they are using the same mesh. If you are using shaders you will never be modifying your data within your VBOs since you will be instead sending a set of matricies to the shader which will transform the 'static' verticies.

Your VBOs should almost always be considered static with the exception being streamed geometry such as terrain.

# Answer
> 0 votes
Sharing a VBO applies for very particular cases, the usual way to go is to have one VBO per mesh. If you have many instances of the same mesh, look at instanced rendering.

It should be noted that `glBufferData()` allocates memory (on the GPU for almost every modern hardware), which is why it shouldn't be called too often.

---
Tags: opengl, architecture
---