# Question
Title: I am looking to make a spaceship tilt as it corners but I cant get it to return
I am using the TL game engine I am not allowed to use a physics engine but I need to make the spaceship lean as it corners, I can make it lean but cannot make it return to its starting position. I have looked at implementing some kind of spring physics but I don't understand it.

Here is my code so far

```
if(myEngine->KeyHeld(Key_A))
    {
        car->RotateY(carSteer * frameTime);
        if(carSteer >= -carMaxSteer)
        {
            carSteer -= carSteerIncrement;
            car->RotateLocalZ(-(carSteer * frameTime));
        }
    }
    if(!myEngine->KeyHeld(Key_A))
    {
        if(carSteer < 0)
        {
            carSteer = 0;
        }
    }
    if(myEngine->KeyHeld(Key_D))
    {
        car->RotateY(carSteer * frameTime);
        if(carSteer <= carMaxSteer)
        {
            carSteer += carSteerIncrement;
            car->RotateLocalZ(-(carSteer * frameTime));
        }
    }
    if(!myEngine->KeyHeld(Key_D))
    {
        if(carSteer > 0)
        {
            carSteer = 0;
        }
    }

```

All the functions I am calling are built into the engine and I did not write them. Any Help Would Be Appreciated Thanks.

# Answer
> 1 votes
This may not be the case but I see you are only doing the rotations when holding down a key. In your checks for if you are Not holding the key down, you reset carSteer to 0, but you do not do anything with the rotations to put the spaceship back to a 0 rotation as well.

Based on your comment this does seem to be the issue but you want a way to ease the ship back to its flat orientation as opposed to a quick snap back. You basically want to do the same thing you are doing to get it to tilt but in reverse and based off of a secondary variable so it does not affect your steering as well. NOTE: I only show the changes to one of the key presses. You would want to do the same for the other one as well. (It can use the same tracking variable though)

```
var carTilt; //assumed to be the same type as carSteer.
if(myEngine->KeyHeld(Key_A))
{
    car->RotateY(carSteer * frameTime);
    if(carSteer >= -carMaxSteer)
    {
        carSteer -= carSteerIncrement;
        carTilt = carSteer;
        car->RotateLocalZ(-(carTilt * frameTime));
    }
}
else // This is a good thing to change as you will not do the logic check twice
{
    if(carSteer < 0)
    {
        carSteer = 0;
    }
    if(carTilt < 0)
    {
        carTilt += carSteerIncrement * 1.5; // Tilt back a little faster
        car->RotateLocalZ((carTilt * frameTime));
    }
}

```

Now some caveats to this.. I do not have the code and have not tested it. What I do hope I am showing however is that you separate out a measurement of the tilt that is not going to be used for motion. I called it carTilt in this case. You can then decrease this over time instead of instantly and use it to return the car to its 0 orientation smoothly.

Hope this helps.

---
Tags: c++, physics, movement
---


title: Fast pixelshader 2D raytracing

text:
# Question
Title: Fast pixelshader 2D raytracing
I'd like to do a simple 2D shadow calculation algorithm by rendering my environment into a texture, and then use raytracing to determine what pixels of the texture are not visible to the point light (simply handed to the shader as a vec2 position) .

A simple brute force algorithm per pixel would looks like this:

```
line_segment = line segment between current pixel of texture and light source

For each pixel in the texture:
{
  if pixel is not just empty space && pixel is on line_segment
       output = black
  else
       output = normal color of the pixel

}

```

This is, of course, probably not the fastest way to do it. Question is: What are faster ways to do it or what are some optimizations that can be applied to this technique?

# Answer
Assuming you don't want to use standard shadow mapping, you could use a signed distance field to do it. This involves building a texture that tells you, for each pixel, the distance to the nearest opaque surface in any direction. The distances are negative when you're inside an opaque object and positive when outside (this allows the surfaces to be positioned with sub-pixel precision; the distance field texture can be substantially lower resolution than your world).

You can then trace through this texture at runtime: starting from a pixel, look up the distance field at that pixel, and then move by that distance along a vector toward the light source. Look up the distance field at the new point and repeat.

If you make it to the light source, the original point is unoccluded; if you go too many iterations or the distance value falls below some small threshold, the original point is in shadow. This algorithm is called "sphere tracing" in 3D; I guess in your case it'd be "circle tracing". :)

There are a few articles out on the Web about signed distance fields and sphere tracing, mostly in a 3D context (for tracing against voxel fields and such), but the same concepts should work in 2D.

Also, note that the distance field textures can be precomputed for the environment and for any moving objects you want to cast shadows, and combined in real time by using min blending (that is, a blending mode that takes the minimum of the two pixels being blended - `glBlendEquation(GL_MIN)` in OpenGL, or `D3D11_BLEND_OP_MIN` in D3D11).
> 11 votes

---
Tags: 2d, lighting, raytracing
---


title: Animated dice framework for XNA?

text:
# Question
Title: Animated dice framework for XNA?
I'm looking for a reusable 3d animated dice component I can reuse in my XNA board game.

I know it might be wishful thinking in hoping such a component exists, but at the same time worthwhile checking.

I'm looking for something that can give a realistic dice animation and return the dice result that matches the animation.

Does such a thing exist?

# Answer
There is one that exists for Silverlight here. It'll likely be fairly simple to convert that to full XNA. The source code is available and from what I can tell the creator's intention is to have it easily "plug-able" into existing projects.
> 2 votes

---
Tags: xna, animation
---


# Question
Title: Which optional features would you recommend for a raytracer?
I'm developing a basic triangle mesh raytracer on a short deadline.
This means I can't implement every feature I come across, so I'm looking for some feedback about which features you think are most important, taking into consideration the performance of the feature and how much punch it packs.

I'm especially looking for optimization techniques that allow for a faster rendering and simple techniques that make a big impact on the final scene quality.
Is there any chance of making it fast enough to run in realtime?

Here are some example of features I've read about:

* Anti-aliasing
* Bounding box
* Sky box

# Answer
> 2 votes
The biggest problem you're going to run into is that every technique you add to improve image quality will increase the computational cost of the program by a lot more than you'd initially expect. I'll run down a list of techniques you might want to consider by also point out their complexity and cost. All of these techniques fall under the category of Distributed Ray Tracing, which is covered in this research paper.

**Soft Shadows** \- The idea behind soft shadows is to capture the umbra and penumbra cast by an object being illuminated by an area light source. The umbra is the portion of geometry that is completely occluded from light, and the penumbra is the area that some of the light reaches, but not all. The usual shadow technique for ray tracing is to just cast one ray towards the light source, and, if it is occluded, then the origin of that ray can be darkened appropriately. For soft shadows, instead of firing one ray, we fire multiple rays, but each to a random point on the light source. Some of them may hit, and some may be occluded. The final blended result will give either a fully-darkened or partially-lit result. Unfortunately, to get smooth results, I've found that 50 or more shadow rays have to be cast.

**Glossy Surfaces** \- Many basic ray tracers render either completely diffuse or completely reflective surfaces. Glossy surfaces are those which are mostly diffuse by somewhat reflective. The appearance is generated by tracing multiple random rays in the cone of the reflected ray, and blending the results. The angle of the cone is determined by the roughness of the surface. Like soft shadows, many rays have to be traced in order to get smooth results, and there is a great increase in complexity here, because these rays are being traced rather than just cast.

**Anti-Aliasing** \- In order to smooth the hard pixel edges on the final visualization of your scene, you can trace multiple rays through each pixel. Determining the points on the pixel through which the rays will be traced is an area to explore for optimizing how many rays you must trace to get a good image. You could look into something called stratified sampling.

**Participating Media** \- This encompasses fog and dust in the scene that you're ray tracing. It can yield results like a beam of light shining in through a window. To render participating media, you have to use a technique called ray marching. You sample your ray at increments as it's sent into the scene (this sampling is saying "if I just happened to hit a spec of dust, what color would I be?"). At each sample, you cast a shadow ray to the light source. If the point is lit, then you can add the light color to that pixel. The trick is in blending the result so that it's faint enough to still see the image behind the media. Following a common theme, this technique can get expensive because you'll end up casting many shadow rays.

There are some other techniques described in the paper I listed earlier including depth of field and motion blur.

Now, as far as acceleration structures for your ray-tracer are concerned, the best that I can recommend are spatial structure like octrees or kd-trees. You only have to test your rays against geometry which is contained in the spatial partitions it intersects as it travels through the scene. Along those lines, you could also include primitive bounding boxes around your triangle meshes, to further cut down on the number of times you must check your ray against all the triangles of a mesh (because this is the most expensive part of the whole program!).

Also, if you haven't done so already, I highly recommend including a visualization for your rays which can be viewed in a rasterized version of your scene. For example, you press 't' with your mouse hovering over a pixel, and then you can draw lines to represent each type of ray that is cast as the original one makes its way through the scene.

Finally, unless you're developing your ray tracer on the GPU and including every optimization and spatial acceleration data structure in the book, you're unfortunately not going to get it running close to real time.

Good luck :)

# Answer
> 2 votes
Ktodisco already mentioned most of what there is to know, but to add to what has already been mentioned I'd like to mention a few more *ideas*. I've also found this resource to be of great help to me on this subject.

**Environment Mapping**

Add an environment map to your scene, such as a cube map. A cube map is basically just a collection made up by six textures. Each of the textures represents one of the faces of a cube that describes the "environment". The most common example is a sky box. Given a direction vector from the center of the cube, your CubeMap class should be able to to tell you the color of the pixel that the vector is "pointing to".

Once you have that class, it's pretty trivial to add it to your raytracer. Just redirect any rays that don't intersect anything in the scene, to your cube map, and use the color it returns. From experience this will improve the look of your scene by a large margin. Also, since it doesn't involve casting any additional rays, it won't slow your performance down by much.

**Bump Mapping**

If you want to add a bit of roughness to your surfaces, one hack I've found was pretty easy to implement was to add a little bit of displacement or randomization to the normals of your surface before calculating your lighting. Using some sort of noise texture (e.g. perlin noise) as a basis for that displacement will also allow you more control over the frequency and depth of the bumps.

**Chromatic Dispersion**

Haven't tried this on a raytracer yet, but it worked nicely on a glass shader I've created before. Basically the idea is that different light wavelenghts are refracted by different amounts, so whenever you're calculating a refraction, instead of casting one ray, you cast three separate rays with different indices of refraction, and in the end combine the results with a tint of R, G and B for each of the rays. You can also combine this with the fresnel effect which varies the reflectiveness of the surface based on the angle at which you're seeing it. More information here.

---
Tags: 3d, graphics, raytracing
---


# Question
Title: How do I generate a random curve for landscape (like Worms)?
> **Possible Duplicate:**
> How do I generate terrain like that of Scorched Earth?
> How can I generate Worms-style terrain?

I must build random curve line for the 2D Game on the BitMap (like in Worms, from the side).

Teacher said that I should do it using Terrain Generation through recourcy (I work in Delphi 7). I understand the main principle, but I don't know how to introduce it as code.

All measurements according to the screen resolution.

# Answer
> 1 votes
That depends on how the curve should look like.

The easiest solution that come to mind is to generate a few sine or cosine curves (I am sure delphi provides the required methods) and add them to each other. Then take a part of the resulting curve and you got your random line.

Another approach would be to randomly select a few points on the screen and calculate a spline that fits those points. How ever this is more difficult to do. For starters I'd go with the sine or cosine lines. This should be fairly simple to do.

# Answer
> 0 votes
I don't know how worms did their terrain generation but there are many ways to generate terrain.

Midpoint works by taking a straight line, and pulling the center up or or down a random height. Then split the line into 2 and pull the centers up or down a smaller random number. Then split the line into 4, 8, etc etc.

Perlin Noise is a bit tricky to explain, but in essence makes black and white clouds which you can use as a height map. However recommend reading it, it serves well in all things procedural.

Faulting is similar to midpoint, you pick a random point on your terrain, raise one side, lower the other side, keep doing this until happy :)

I think L-Systems would be the best for this, abit trick again to explain but I'll give it a shot. L-Systems work with Strings and Rules. So if 'A' represented a flat line. I could have a rule that said make every 'A' 'AABB', so our string becomes 'AABB', then the next rule might be make every 'AB' 'BCB' in which case our string would become 'ABCBA'. Each letter would represent something in you landscape, which would generate the overall picture. (Bad explanation sorry.)

---
Tags: graphics, software-engineering, delphi
---


title: Frustum culling code architecture

text:
# Question
Title: Frustum culling code architecture
I'm adding frustum culling into my game engine, but I have some design issues regarding the frustum and the cameras. Should the frustum be a member of the camera, or vice versa ? Should a camera be built from a frustum or should the camera build and maintain it's own frustum ?

# Answer
**Short Answer**

Make your frustum class independent from any camera implementation - it only requires a combined view-projection matrix to be created. Then, add a frustum instance to your camera class. Think about it - it makes sense to think that a `camera has a frustum` but not the other way around.

---

**Long Answer**

A `Camera` class will typically manage a view and projection matrix. But you usually rely on helper methods from your API to create these matrices, such as `CreateLookAt` or `CreatePerspective`. While it might be possible, I don't think it would be very practical to deduce the view and projection matrices from the frustum. **So I'd forget about building the camera from the frustum**.

As for *how* to build the `Frustum`, I like the way that XNA handles it, which is basically by providing a **constructor that takes a combined view-projection matrix and deduces everything else from there**. This way there's no direct dependency between the frustum and your camera implementation. All it cares about it receiving *some* view-projection matrix from *somewhere*.

Finally, as for whether one class should *contain* the other, my opinion is that, if anything, **your camera class could manage a frustum object and keep it in sync**. I think doing it the other way around would be a bad design choice, because the frustum is a lower level concept than the camera, and the frustum shouldn't have to rely on a specific camera implementation. Or the simple argument that composition should be used to implement `has-a` type of relationships, and it doesn't make sense to say that a `frustum has a camera`.

---

**Example**

In sum, something like this for the frustum class (just to give you an idea, it might have other members and features too):

```
class Frustum
{
public:
    Frustum(Matrix viewProjection);
    void SetMatrix(Matrix viewProjection);

    bool Intersects(BoundingBox box);
    bool Intersects(BoundingSphere sphere);
    bool Intersects(Point point);

private:
    Plane[6] planes;
}

```

With your camera class being something like (once again not a complete example):

```
class Camera
{
public:
    void SetPosition();
    void SetPitch();
    void SetYaw();

    Matrix GetViewMatrix();
    Matrix GetProjectionMatrix();
    Frustum& GetFrustum(); // Or expose the Intersects methods directly

private:
    Matrix viewMatrix;
    Matrix projectionMatrix;
    Frustum frustum;
}

```
> 4 votes

---
Tags: c++, architecture, frustum
---


# Question
Title: How do I avoid 3D AABB collision response getting stuck at block edges?
I want the player to be able to slide along cubes, but without getting caught at the seam between 2 adjacent cubes. I've gotten it so that I can do x collision, with sliding, and y, and z, but I can't do them *together*, probably because I don't know how to resolve it correctly.

Here's an example:

```
[]
[]
[]
[]O
[]

```

Pretend all the tiles are touching. `O` is the player (moving upward). The methods I was trying would get the player stuck between the cubes because the z axis was responding and kicking me out.

I don't know how to resolve this in all 3 directions, like how would I go about telling which direction I have to resolve in. My previous methods involved me checking 4 points in a axis aligned square around the player, I was checking if these points where inside the cubes and if they where fixing my position, but I couldn't get it working correctly.

# Answer
I am working on a cube engine and solved this problem by treating each movement step as three separate axis-aligned movements, each having its own collision test and response. Thus, the upward motion never sees the blocks on the left, because it's either before the leftward motion (free to move) or after (in which case the leftward motion was stopped at the appropriate position), but in either case the upward motion does its collision test directly upward and so does not see the blocks of the wall.

The disadvantage I see is that fast diagonal motions may "stick out to the side" and hit things they shouldn't, but I haven't seen that in practice yet.
> 1 votes

# Answer
its always a good idea to make the objects to move around in your world be smaller then the world they are to move around in.

In a non-oriented collision system (things can not rotate) you would just pass the contact pair to the collision resolution system then determine from the velocity vector if it was moving toward that block. if not do nothing and clear the collision. otherwise resolve as normal. this works best on non-oriented collisions because the resolutions can be handled quite easily.

for oriented collision systems you just need to calculate the contact normal, but realistically if the object is able to rotate should make the movable object be smaller then the space to be traversed even while rotated.

though if it is a move by move system then you could also accomplish it with a move by move bool system
> 0 votes

---
Tags: 3d, collision-resolution, aabb, block-world
---


title: Nifty popup fails to register

text:
# Question
Title: Nifty popup fails to register
I'm new to Nifty GUI, so I'm following a tutorial here for making popups. For now, I'm just trying to get a very basic "test" popup to show, but I get multiple errors and none of them make much sense. To show a popup, I believe it is necessary to first have a Nifty Screen already showing, which I do. So here is the `ScreenController` for the working Nifty Screen:

```
public class WorkingScreen extends AbstractAppState implements ScreenController {

//Main is my jme SimpleApplication
private Main app;
private Nifty nifty;
private Screen screen;

public WorkingScreen() {}

public void equip(String slotstr) {
    int slot = Integer.valueOf(slotstr);
    System.out.println("Equipping item in slot "+slot);
    //Here's where it STOPS working.
    app.getPlayer().registerPopupScreen(nifty);
    System.out.println("Registered new popup");
    Element ele = nifty.createPopup(app.getPlayer().POPUP);
    System.out.println("popup is " +ele);
    nifty.showPopup(nifty.getCurrentScreen(), ele.getId(), null);
}

@Override
public void initialize(AppStateManager stateManager, Application app) {
    super.initialize(stateManager, app);
    this.app = (Main)app;
}

@Override
public void update(float tpf) {
    /** jME update loop! */
}

public void bind(Nifty nifty, Screen screen) {
    this.nifty = nifty;
    this.screen = screen;
}

```

When I call `equip(0)` the system prints `Equipping item in slot 0`, then a lot of errors and none of the subsequent `println()`'s. Clearly it botches somewhere in `Player.registerPopupScreen(Nifty nifty)`. Here's the method:

```
public final String POPUP = "Test Popup";
public void registerPopupScreen(Nifty nifty) {
    System.out.println("Attempting new popup");
    PopupBuilder b = new PopupBuilder(POPUP) {{
            childLayoutCenter();
            backgroundColor("#000a");

            panel(new PanelBuilder() {{
                id("List");
                childLayoutCenter();
                height(percentage(75));
                width(percentage(50));
                control(new ButtonBuilder("TestButton") {{
                    label("TestButton");
                    width("120px");
                    height("40px");
                    align(Align.Center);
                }});
            }});
    }};
    System.out.println("PopupBuilder success.");
    b.registerPopup(nifty);
    System.out.println("Registerpopup success.");
 }

```

Because that first `println()` doesn't show, it looks like this method isn't even called at all!

# Edit

After removing all calls on the `Player` object, the popup works. It seems I'm not "allowed" to access the player from the `ScreenController`. Unfortunate, since I need information on the player for the popup. Is there a workaround?

# Answer
A old question but anyway, I suspect that I know what the problem is.

Depending on how your implement the reference to the `ScreenController` Nifty will create a new instance of the referred class. I guess this is the problem that is pestering you. It results in two instances of this class, one that is maintained by JME and that contains the proper references to the player and so on, and one newly created that contains no references but is used and referred to by Nifty.

To solve this you have to use the `registerScreenController()` funktion auf the `Nifty` class to register the correct instance of the screen controller **before** the actual GUI is load from the XML file or build using Java.
> 2 votes

---
Tags: gui, jmonkeyengine
---


title: Programming real time combat

text:
# Question
Title: Programming real time combat
I am programming a lot of turn based game, all text, but how do you program real time combat in games, like an rts, or a shooter, where everything is not input based

# Answer
Real Time games are just Turn Based games where the turns go by really fast. Also a "turn" doesn't pause to wait for input, instead either polling keyboard/gamepad/mouse states or getting the information via events.

The game loop is your friend. Here is a more detailed explanation of some of the basic concepts and techniques involved.

As a side note, making a real time text based game is going to be difficult due to the nature of the console window. I'd recommend reading up on some basic graphics/input handling so you have a good platform to work from. SDL is a good choice if you want to dive in and Lazy Foo' has some excellent tutorials on the matter. As a bonus, the game loop structure is used in a number of the tutorials so you'll have some actual implementation to experiment with.
> 3 votes

# Answer
Event handling in OOP or a loop if you're using a more traditional language.
> 0 votes

---
Tags: c++, game-mechanics
---


title: Photon alongside LibGDX

text:
# Question
Title: Photon alongside LibGDX
Can anyone point me to a possible implementation of the Photon network engine along with LibGDX for Android? Or any multiplayer networking SDK for all that matters.

From reading source code it seems that Photon uses the native Android SDK heavily, like Intents and such, which are not provided through LibGDX.

# Answer
> 2 votes
You call out of libgdx into custom java methods. It would take some work but i'm sure it's possible. Take a look in the Android SDK in the demos folder for **demo-realtime** and hook up a way to call out of libgdx into the hosting android Activity. I posted some code here that you can use or any way you prefer. It looks like the Intents they are launching are just to show other views (Help, Options, etc) that you can definitely do if you want to jump to different Activities in your game.

If you need to call back into libgdx, use the Application.postRunnable method.

**Edit:** Yep, that's what I would do because every time you leave the gdx hosted Activity and return, it will cause the gl context to spin back up which may lead to a poor user experience. If you want to have different views/menus hosted in your Android app, use something that doesn't leave the current Activity like this:

BetterPopupWindow.java

This window can be launched from a method in your Activity class which you could call from libgdx and you won't lose the gl context in libgdx.

---
Tags: java, android, libgdx, networking, photon
---


# Question
Title: This for array colllision function doesn't work with anything but first object in array
For some reason, this simple simple loop is totally broken. (characterSheet is my character Class, it's just a movieClip with some extra functionality) (hitBox, is basically a square movieclip)

Anyway: every time hitBox make contact with a characterSheet in a different order than they were created: Nothing happens. The program only seems to be listening to collisions that are made with o2\[0\]. As soon as another hitBox is created, it pushes the last one out of o2\[0\] and the last one becomes totally useless. What's super weird is that I can hit characterSheets in any order I like....

```
    public function collisions(o1:Array, o2:Array)
    {
        if((o1.lenght>=0)&&(o2.length>=0)){
            for (var i = 0; i < o1.length; i++)
            {
                var ob1 = o1[i];
                for (var f = 0; f < o1.length; f++)
                {
                    var ob2 = o2[f];

                    if (ob1 is characterSheet)
                    {   if (ob2.hitTestObject(ob1))
                            {
                                var right:Boolean = true;
                                if (ob1.x < hitBox(ob2).origin.x)
                                    right = false;
                                characterSheet(ob1).specialDamage(hitBox(ob2).damageType, hitBox(ob2).damage, right);
                                }}}}}}

```

Also it might be somewhat helpful to see the function for creating a new hitBox

```
    public function SpawnHitBox(targeted, following, atype, xoff, yoff, ... args)
    {
        var newHitBox = new hitBox(targeted, following, atype, xoff, yoff, args);
        badCollisionObjects.push(newHitBox);
        arraydictionary[newHitBox] = badCollisionObjects;
        addChild(newHitBox);

    }

```

# Answer
I think it should be: `for (var f = 0; f < o2.length; f++)`... just skimmed the code, that seemed to stand out. If there is only one object in o1 array, then you will get a single collision only
> 1 votes

---
Tags: actionscript-3
---


# Question
Title: How do I save data to the iPhone properly and securely?
I'm creating a game using Cocos2D (objective-c) and it has come to the point where I have to save data to local storage, like high scores and similar stuff.

I know that `NSUserDefaults` is not a good option because it isn't encrypted. I would like to know what is or what are the best/simple methods of saving data with security to the iPhone to avoid a casual hacker from changing the score.

# Answer
Personally, I wouldn't try to encrypt the file. It makes writing and parsing more complicated (eg. you'll have to work around the built-in mechanisms) and it's also much harder to debug, because you can't have a look what your app just wrote there.

Instead just write to the application directory or use `NSUserDefaults`.

Now this doesn't address your issue about hacking of these files. To add some protection I'd suggest that you create a hash (checksum) of that data and store it in the Keychain. Then every time you read the data back in, you compare the stored hash to the one that you'll get from the read data. If it's the same, everything is fine. If the data has been altered, your checksums won't match and you can do any counter-measure you'd like...
> 1 votes

# Answer
Well if you're worried about secure data, I would encrypt it yourself regardless of where it's stored. Since I don't do iOS programming I don't really know where you can store it but I would suggest also storing it online if possible. That way, you always have control over the data. But, if that's not an option, (if it lets you) store it in the app folder encrypted. Hope this helps.
> 0 votes

# Answer
If you want to store the players score than NSUserDefaults is the best option to store it as no one can change it except your application itself.

There are other options available in iOS devices, like in a file in the documents folder of your application in the form of plist, sqlite3 or normal text file, which can be modified by iExplorer application for mac and windows. But you don't have to worry about that as most of the iPhone users won't go to that much level to just change their score. They are gonna play ur game instead, if they like it.

So you don't need to worry about the where to store your application data. But even if you are worried than there are some encryption classes available in iOS framework that you can use to store your data.
> 0 votes

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


title: How far do I take Composition?

text:
# Question
Title: How far do I take Composition?
(Although I'm sure this is a common problem I really don't know what to search for. Composition is the only thing I could come up with.)

I've read over and over that multiple inheritance and subclassing is really, really bad, especially for game entities. If I have three types of motions, five types of guns, and three types of armoring, I don't want to have to make 45 different classes to get all the possible combinations; I'm going to add a motion behavior, gun behavior, and armor behavior to a single generic object. That makes sense.

But how far do I take this?

I can have as many different types of behaviors as I can imagine: DamageBehavior, MotionBehavior, TargetableBehavior, etc. If I add a new class of behaviors then I need to update all the other classes that use them. But what happens when I have functionality that doesn't really fit into one class of behaviors? For example, my armor needs to be damageable but also updateable. And should I be able to have use more than one type of behavior on an entity at a time, such as two motion behaviors?

Can anyone offer any wisdom or point me in the direction of some useful articles?

Thanks!

# Answer
Inheritance isn't a bad thing per-se, you just shouldn't start using it too far up the hierarchy. I usually mix them.

```
class Weapon{
    void Attack() = 0;
}
class Sword : public Weapon{
    void Attack(){...}
}
class Gun : public Weapon{
    void Attack(){...}
}

class Player{
Weapon* m_weapon;
Mover* m_mover;
Armor* m_armor;
...

void Update(){
    if(UserHasPressedAttackKey)
        m_weapon->Attack();
    ...
}
}

```

From there on I think about what else I need. For example, if I need my "behaviors" to be very generic (e.g. an armor that doesn't only mitigate damage but also sends lighning bolts to all nearby enemies every 2 seconds) I think about implementing a messaging system instead.

```
class LightningArmor : public Armor{
    void OnMessageReceive( Message message ){
         if(message.type == EVERY_2_SECONDS)
              useMassiveLightningAttack();
         else if(message.type == ATTACKED)
              mitigateDamage();
    }
    LightningArmor(){
         ListenToMessage(EVERY_2_SECONDS);
         ListenToMessage(ATTACKED);
    }
}

```

An event-messaging system allows you to be very generic. As long as you have the events your stuff can basically do everything. But of course it's much more work implementing that than keeping a rather static system like above.

If you need even more power (e.g. having 2 Movers/Weapons) at the same time you can use a container instead

```
class Player{
    std::vector<Behavior*> m_behaviors;

   ....
}

```

Instead of specifically calling m\_weapon-\>Attack() you can now let it run solely through event messages. Regarding your question whether it's useful to have 2 Motion behaviors - it might be. For example, a second one could be used to simulate gravity (or any other directional force) by constantly trying to move you down the Y axis.

But the question is whether you really need that. If you're not sure you can always come back later and implement what other things you need.

If you own StarCraft 2 (or a friend does) you might want to look into their Map Editor. Their data portion basically handles everything with behaviors. It nicely shows the advantages and disadvantages - you can do everything with it, it just becomes a lot more complicated than other approaches.
> 1 votes

---
Tags: architecture, component-based
---


title: Loading files during run time

text:
# Question
Title: Loading files during run time
I made a content pipeline extension (using this tutorial) in XNA 4.0 game.

I altered some aspects, so it serves my need better, but the basic idea still applies. Now I want to go a step further and enable my game to be changed during run time. The file I am loading trough my content pipeline extension is very simple, it only contains decimal numbers, so I want to enable the user to change that file at will and reload it while the game is running (without recompiling as I had to do so far). This file is a very simplified version of level editor, meaning that it contains rows like:
`1 1,5 1,78 -3,6`

Here, the first number determines the object that will be drawn to the scene, and the other 3 numbers are coordinates where that object will be placed.

So, how can I change the file that contains these numbers so that the game loads it and redraws the scene accordingly?

Thanks

# Answer
The content pipeline cannot do that (without a bit of hacking about), it processes content as part of the project's build process.

Just use regular .net functions for monitoring file changes, `FileSystemWatcher` maybe and reading files `File.ReadAllText()`.
> 1 votes

---
Tags: xna-4.0, loading, xna-content-pipeline, hot-reload
---


# Question
Title: Rending 2D Tile World (With Player In The Middle)
What I have at the moment is a series of data structures I'm using, and I would like to render the world onto the screen (just the visible parts).

I've actually already done this several times (lots of rewrites), but it's a bit buggy (rounding seems to make the screen jump ever so slightly every x tiles the player walks past).

Basically I've been confusing myself heavily on what I feel should be a pretty simple problem... so here I am asking for some help!

OK! So I have a 50x50 array holding the tiles of the world. I have the player position as 2 floats, x (\[0, 49\]) and y (\[0, 49\]) in that array. I have the application size exactly in pixels (x and y). I have an arbitrary TILE\_SIZE static int (based on screen pixels).

What I think is heavily confusing me is using a 2d orthogonal projection in opengl which maps (0,0) to the top left of the screen and (SCREEN\_SIZE\_X, SCREEN\_SIZE\_Y) to the bottom right of the screen.

```
    gl.glMatrixMode(GL.GL_PROJECTION);
    gl.glLoadIdentity();

    glu.gluOrtho2D(0, getActualWidth(), getActualHeight(), 0);

    gl.glMatrixMode(GL.GL_MODELVIEW);
    gl.glLoadIdentity();

```

The map tiles are set so that the (0,0) in the array is the bottom left.

And the player has to be in the middle on the screen (SCREEN\_SIZE\_X/2, SCREEN\_SIZE\_Y/2).

What I've been doing so far is trying to render 1-2 tiles more all around what would be displayed on the screen so that I don't have to worry about figuring out rendering half a tile from the top left, depending where the player is.

It seems like such an easy problem but after spending about 40+hours on it rewriting it many times I think I'm at a point where I just can't think clearly anymore...

Any help would be appreciated. It would be great if someone can provide some very basic pseudo code on keeping the player in the middle when your projection is mapped to screen coordinates and only rendering basically the tiles that you would be any be see.

Thanks!

# Answer
If I understand you correctly then I think the easiest way to solve this is to render the map always at the same coordinates.

So the render coordinates for the tiles would be something like: `(x * TileWidth ; y * TileHeight)`. The location of the character is calculated just the same way. Now for the moving part you should translate of the OpenGL coordinates using `glTranslatef`. Using this function is you shift the origin location out of your screen. The values for the translate function would be something like: `(playerPos.x * TileWidth - SCREEN_WIDTH/2; (playerPos.y * TileHeight - SCREEN_HEIGHT/2)`. You might have to alter the calculate by inverting the height by adding `SCREEN_HEIGHT - (...)`. But I hope you get the general idea.

Now as for the problem that the screen coordinate are inverted compared to what you expected. You can fix this problem simply by using `glScale`. Using `-1` as second parameter will invert the Y coordinate of all subsequent OpenGL calls. That should help you turning the coordinates as you need it.

And finally in detect if the tiles are on the screen and need to be rendered or not you can get use your render coordinates of your player character (`playerPos.x * TileWidth; playerPos.y - TileHeight`) and check if the location of the tile is within `SCREEN_WIDTH/2 + TileWidth` and `SCREEN_HEIGHT/2 + TileHeight` around your player location. If not you don't need to render the tile.
> 1 votes

---
Tags: opengl, java, tilemap
---


# Question
Title: Android: how do I switch between game scenes in a game? Any tutorials?
I am trying to create a simple game using the Android SDK *without* using AndEngine (or any other game engine). I have plenty of experience designing games from the past, but I'm having lots of trouble trying to use the Android SDK to make my game. By far my biggest hurdle right now is switching between views. That is, for example, going from the menu to the first level, etc.

I am using a traditional model I learned (I think it's called a scene stack or something?) in which you push the current scene onto a stack and the game's main loop runs the top item of the stack. This model seems non-trivial to implement in the Android SDK, mostly because Android seems to be picky about which thread instantiates which view. My issue is that I want the first level to show up when you press a button on the main menu, but when I instantiate the first level (the level class extends `SurfaceView` and implements `SurfaceHolder.Callback`) I get a runtime error complaining that the thread that runs the main menu can't instantiate this class. Something about calling `Looper.prepare()`. I figured at this point I was probably doing things wrong.

I'm not sure how to specifically phrase my issue into a question, so maybe I should leave it as either

1) Does anybody know a good way (or the 'proper' way) to switch between scenes in an Android game?

or

2) Are there any tutorials out there which show how to create a game that doesn't take place entirely in one scene? (I have googled for a while to no avail... maybe someone else knows of one?)

Thanks!

# Answer
If you are using `Android` SDK, then you can use `Activity`, to switch between Scenes. Every `Activity` is a different Scene on screen and when one gets launched any previous Activity are sent to Pause status.
Activities can be launched using the following method.

```
 startActivity(new Intent(this,MyActivity.class));

```

Learn more about Activity LifeCycle here
> 2 votes

# Answer
I'm not familiar with the Android SDK, but seeing the error you have it seems that you're somehow not "freeing" you menu when you switch to your level. As Android can't display two of those `SurfaceView`s at the same time, it squeaks and halts your program. Maybe there's something you have to do on your menu view, some method to call to detach it from the screen, before you create and attach another view? Maybe you should completely destroy your menu before instantiating your level? Maybe you can have only one view for your whole app, so there's no way to switch between views?

I don't know any tutorial either, but my bet is that you'll find some demo in the SDK.

Oh, and if your game has only a few game states, using a scene stack for this might be overkill. A simple FSM is way enough if you just have say a menu, a gameplay state and a credits screen.
> -2 votes

---
Tags: android, state
---


# Question
Title: Problem with scrolling background in one OpenGL loop
I have 960x3000 map image in png and I'm scrolling it in a loop like this (it's called in 60 FPS loop):

```
glPushMatrix();
    glBindTexture( GL_TEXTURE_2D, mapTex[iBgImg]);
    glBegin(GL_QUADS);
    double mtstart = 0.0f - fBgVPos/(double)BgSize;
    double mtend = mtstart + mtsize;
    glTexCoord2d(0.0, mtstart); glVertex2f(fBgX, TOP_MARGIN);
    glTexCoord2d(1.0, mtstart); glVertex2f(fBgX + MAP_WIDTH, TOP_MARGIN);
    glTexCoord2d(1.0, mtend); glVertex2f(fBgX + MAP_WIDTH, BOTTOM_MARGIN);
    glTexCoord2d(0.0, mtend); glVertex2f(fBgX, BOTTOM_MARGIN);
    glEnd();
glPopMatrix();

```

unfortunately it isn't smooth when the game is in windowed mode. However, it is smooth in full screen mode. I'm using GLFW for windows. Maybe there is something wrong with my method? Is there anything better? Or could this be hardware problem?

Edit: Window is created using

```
 glfwOpenWindowHint(GLFW_WINDOW_NO_RESIZE, GL_TRUE);
 glfwOpenWindowHint(GLFW_REFRESH_RATE, 60);

```

and main loop is using glfwSwapInterval(1) to ensure 60 FPS;

# Answer
*copied from my comment*

You need to add `glFinish;` before `SwapBuffers` command. This will force OpenGL to display rendering ASAP, instead of waiting for more data you may pass to it or relying on OpenGL sense of "right time" to finish. It may make the animation look smoother, because in current code if OpenGL waited just 1ms more the whole frame according to refresh rate will be delayed by 1/60s and next frame after it will probably get skipped - hence the jaggy motion.
> 1 votes

---
Tags: opengl, 2d, side-scroller
---


# Question
Title: How to achieve this particular screen filter with GLSL?
I know this may be a "short" question, but still here it goes.

I would like to know how to achieve a post rendering effect, that looks like the following image from walking dead series:

I will make the art already fitting the style, but what if I want to make the colors more coherent by adding a color filter such as the one in the picture?

Thanks

# Answer
What you could do to match this scene:

* **Grunge**. Multiply dirt textures into the meshes' textures to make it look rustic.
* **Fog and clouds**. If you notice, the brown clouds and dusty fog really pull this scene together.
* **Sepia**. As Johnathan Dickinson mentioned, you could use a sepia shader to finish it off.
> 3 votes

# Answer
Easiest approach to sepia would be to mix every resulting pixel with sepia color at specified proportion. Pseudocode: `Result.rgb = lerp(Color.rgb, Sepia.rgb, Factor);` Where Sepia tone may need some tweaking as well (check these variants for example: http://en.wikipedia.org/wiki/Sepia\_(color))
> 2 votes

---
Tags: 2d, shaders, glsl
---


# Question
Title: Why did the old 3D games have "jittery" graphics?
I've been playing *"MediEvil"*, lately, and it got me wondering: what causes some of the old 3D games to have "flowing" graphics, when moving? It's present in games like *"Final Fantasy VII"*, *"MediEvil"*, and I remember *"Dungeon Keeper 2"* having the same thing in zoom mode. However, examples like *"Quake 2"* didn't have this "issue", and it's just as old. The resolution doesn't seem to be the problem, everything is rendered perfectly fine when you stand still. Is the game refreshing slowly, or is it something to do with buffering?

# Answer
I have only the most bizarre of citations for this, but it appears on the original PlayStation, the vector unit (which was usually used to transform vertices) was capable of fixed-point operations, and the rasterizer also used fixed-point math, but only integers could be passed between the two. So you're seeing quantization artifacts: polygon corners are getting snapped to the nearest grid point. Perfectly stable for a still scene, but fairly disconcerting in motion.

From a little bit of additional research, it appears that the original PlayStation had different resolutions at which the rasterizer could work, from 256x224 to 740x480. So you could pick lower resolutions to get better fill rate, but you'd see these sorts of artifacts, as the grid at low resolutions is coarse enough to easily detect with the naked eye.
> 27 votes

# Answer
If you play Quake 2 in software mode, it actually does have some of the issues you mention. If you look at certian models at sharp angles in Quake 2, you'll see "swimming" textures. This is because many early 3D engines used affine texture mapping. This saves you the expensive per-pixel divide that gives you perspective correct texture mapping, but it means your textures will warp when viewed at sharp angles.

Also, many early 3D games (including Quake 2) used simple vertex morphing to animate their models as opposed to skeletal animation. The vertices are tweened between keyframes with linear interpolation. Naturally, this doesn't preserve the distances between vertices very well, so you end up with jelly vertex syndrome—the models jiggle a little bit as they animate!
> 10 votes

---
Tags: 3d
---


title: Custom Music in Skyrim's Creation Kit?

text:
# Question
Title: Custom Music in Skyrim's Creation Kit?
Can you bring in external music such as mp3s? If so, how? I didn't see anything about this in the wiki Bethesda released.

Also how does this work with regards to the Steam Workshop? Don't imagine they would appreciate uploading copyrighted content. I don't particularly care about making a public mod, I just want to screw around privately and create dungeons/towns using music from some of my favorite games.

Thanks.

# Answer
I'm currently having trouble getting my custom music to play, but it worked for someone else so...

1. Convert your MP3s to WAV format and create a folder named "Music" in Skyrim's Data folder. Put your WAVs in there or in any subfolders.
2. Open up the CK and go to Audio \> Music Tracks. Right click any entry and click "New". Enter a name in the ID field and select "Single Track" from the dropdown list. Now click "Choose File" and you'll be in the Music folder you just created. Select the desired WAV. If your music will play in battles, make sure you also choose a file that plays when combat ends, and choose some points in the combat music for it to play (in \[minute\]:\[second\] format). There should already be some files for finishing music, but you might want to add some that fits your track. I'm not sure what happens if you don't do this. Also, if you want just your custom made locations to have the music, you can click the "Has Conditions" checkbox and set conditions on the Conditions tab.
3. Go to Audio \> Audio Types, right-click the category you want to add the new music to, and click Edit. Right click the list of tracks the audio type is using, click Add, and find the track you just added. Save the mod and make sure it's activated.

As I said before, I'm still trying to get my custom music to work. I used Switch Sound File Converter to convert my MP3s, so if you use something else and it works for you, then by all means report back.
> 4 votes

# Answer
As far as I know, Skyrim doesn't want to read anything other than 16Bit Mono .Wav files. I save everything at 44.100Khz.

Does having an Xwm file in your music folder make a difference?
> 1 votes

# Answer
I just copied the papyrus script of a Dragon fight music, inserted my new song in there (replacing the old one by renaming it exactly the same) and pasted the papyrus script.

All done in the CK :)
> 0 votes

---
Tags: music, modding, skyrim-modding
---


# Question
Title: How do I find the angle required to point to another object?
I am making an air combat game, where you can fly a ship in a 3D space. There is an opponent that flies around as well. When the opponent is not on screen, I want to display an arrow pointing in the direction the user should turn, as such:

The arrow will be on the HUD. It will not actually turn to the opponent. I want it to indicate which direction a user should turn to see the enemy ship. This arrow will circle around the cross-hairs (radius 60 pixels).

So, I took the camera location and the opponent location and did this:

```
double newDirection =
   atan2(activeCamera.location.y-ship_wrap.location.y,
   activeCamera.location.x-ship_wrap.location.x);

```

After which, I get the position on the circumferance of a circle which surrounds my crosshairs, like such:

```
trackingArrow.position = point((60*sin(angle)+240),60*cos(angle)+160);

```

It all works fine, except it's the wrong angle! I assume my calculation for the new direction is incorrect. Can anyone help?

# Answer
The big problem that I see is that you don't subtract the camera's angle from the calculated angle. You should have:

`double newDirection =
 atan2(activeCamera.location.y-ship_wrap.location.y,
 activeCamera.location.x-ship_wrap.location.x)-cameraAngle;`

If you don't then when the camera rotates, the direction will remain the same!

I also think you've got the coordinate system wrong somewhere. Here are some diagnostic questions:

1. Is your Z axis the vertical axis? If it is you're fine. If not, replace .x and .y with the axes forming a flat plane (eg axes parallel to the ground).
2. Does the coordinate system of the point(x,y) function have (0,0) as the top left pixel?

If it does then I see a problem with this line of code:

`point(60*sin(angle)+240,60*cos(angle)+160);`

The idea with that line is that when angle=0 you should have the topmost pixel, when angle=90 degrees it should be the leftmost pixel, and when angle=-90 it should be the rightmost pixel. Here, if angle=0 the coordinates are point(240,220) when - if (0,0) is the top left pixel - the value should be (240,100). (the topmost pixel).

Also, when angle=90 the pixel is point(300,160) when it should be (180,160). So you need to negate both:

`point(-60*sin(angle)+240,-60*cos(angle)+160);`

A similar line of reasoning could be used for other coordinate systems.
> 3 votes

# Answer
I've seen the comment of Byte56, but the links there don't provide the exact answer, or aren't graphically detailed for this specific task, so if it's an answer the user wants, why not let him have one. Here goes.

Imagine you're flying over the ground (the xy plane) and your ship's orientation is known (the green camDir vector). You want your camDir to coincide with the red vector (from your positions to your opponent's position,i.e. **normalize(targetPos - camPos) = targetDir** )

To turn in a relevant way for your picture description, you could rotate against the Z axis. To find the amount of rotation, you need to compute the cross product of camDir and targetDir. The cross product tells you the shortest turning orientation because **|cross(a,b)| = |a| |b| sin(angle(a,b))** . Note that the angle between the two vectors is less than 180 degrees, in absolute value. Now, you can compute the dot product to find the cosine of the turning angle since **dot(a,b) = |a| |b| cos(angle(a,b))**.

The nice part is that both *camDir* and *targetDir* are unit/normalized vectors, so their cross and dot products provide you with the sine and cosine of the angle you want. Now just apply atan2 on the sine and cosine and retrieve the value of your angle (the dark-red arc in the image, for example). The blue circle around the plane is the same as your "radar" circle. That should be about it. So you need the camera direction, just the position of your ship is not enough - you have to "fire" in a direction, right?
> 4 votes

# Answer
There's a pretty easy way to do it using the model and viewing matrices, assuming you're in first person.

Just run the opponent's position through the model and viewing matrices, and you'll get his position in view space. Disregard the Z component and normalize 2D vector made from the X and Y components, and presto, you've got a vector on the screen that points to your object. Note that this is *already* the coordinate of your arrow on-screen. If you also need the angle, it's `atan2(y, x)`.
> 2 votes

---
Tags: c++, mathematics, objective-c
---


title: How to create Executable Jar

text:
# Question
Title: How to create Executable Jar
When I run a jar file I created, I get the following error, so please someone help me out of this:

> Exception in thread "LWJGL Application" com.badlogic.gdx.utils.GdxRuntimeException: Couldn't load file: img/black\_ring.png at com.badlogic.gdx.graphics.Pixmap.(Pixmap.java:137) at com.badlogic.gdx.graphics.glutils.FileTextureData.prepare(FileTextureData.java:55) at com.badlogic.gdx.graphics.Texture.load(Texture.java:175) at com.badlogic.gdx.graphics.Texture.create(Texture.java:159) at com.badlogic.gdx.graphics.Texture.(Texture.java:133) at com.badlogic.gdx.graphics.Texture.(Texture.java:122) at com.badlogic.runningball.UserBall.(UserBall.java:19) at com.badlogic.runningball.GameScreen.(GameScreen.java:25) at com.badlogic.runningball.RunningBall.create(RunningBall.java:12) at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:126) at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:113) Caused by: com.badlogic.gdx.utils.GdxRuntimeException: File not found: img/black\_ring.png (Internal) at com.badlogic.gdx.files.FileHandle.read(FileHandle.java:108) at com.badlogic.gdx.files.FileHandle.length(FileHandle.java:364) at com.badlogic.gdx.files.FileHandle.readBytes(FileHandle.java:156) at com.badlogic.gdx.graphics.Pixmap.(Pixmap.java:134) ... 10 more

# Answer
> 5 votes
The problem in this case is that the file `img/black_ring.png` is missing from the JAR-file. You need to add it, else the application can't start. Any application able to handle a JAR file as ZIP archive enables you to do so.

For a description on how you create a fitting file directly your question contains far to less information. Information like how you created this JAR file in the first place and the IDE and/or buildsystem you used are essential to get a good answer.

# Answer
> 0 votes
Use the program 7zip, or, on if you are on a Unix system it should have tar installed, which is what a Jar is: a Java tar.

I'm not sure what your development environment is, but you seem to be lacking the fundamental knowledge of how an executable jar works.

For a jar to be executable, it needs a manifest file. This file tells java what your main class file is, i.e:

```
Manifest-Version: 1.0
Main-Class: package.names.MainClass

```

I see you are also using LWJGL. To use that, you will also need to specify the classpath variable in the manifest, so it will now look like this:

```
Manifest-Version: 1.0
Main-Class: package.names.MainClass
Class-Path: lwjgl.jar

```

This assumes that lwjgl.jar will be in the same folder as your executable jar. IIRC lwjgl also requires native libraries, so you will have to set that as an argument to the Java VM, try this: http://lmgtfy.com/?q=lwjgl+manifest

Edit: Just realized I forgot to say how to actually create the jar!

To create the jar file, you use the jar command:

```
jar cvfm output.jar manifest *.class

```

For finding all the class files, on Linux I use this handy command

```
find . -iname '*.class' | sed 's:\./::' > filelist

```

to get all the class files in all the subdirectories of your current location and output them into the file 'filelist'.

(I'm sure there is an easier way, but that's how I do it)

then you can use the command

```
jar cvfm output.jar manifest @filelist

```

without worrying about having to recurse into subdirectories looking for classes

---
Tags: java, libgdx
---


title: Game Object Design

text:
# Question
Title: Game Object Design
I'm having a problem with the way I designed my first simple game in C++.

I have GameObject (abstract class) and ObjectA which inherits the update() and draw() methods from GameObject.

My main loop contains a linked list of GameObject\*, and while that list is not empty it cycles through it, calling update on each one.

Up until this point, I thought the design was standard(?) and would work.

However, when I call update on ObjectA() I run into two problems:

* ObjectA can die which messes up the list, which in turn throws off the loop in main.
* ObjectA can spawn more ObjectA's but these are local scope and the update() goes out of scope, creating problems in main's list of GameObjects.

I think my design if alright, but I'm having such problems with segmentation faults that there must be something seriously wrong with at least one part of my implementation. If anyone could point out any serious mistakes or simple examples of this being done (or even alternative designs) then I would greatly appreciate it!

# Answer
First off, don't use linked lists.

Second, your design should work, in theory. For the dying problem, an easy solution is to just have some kind of flag on your GameObject class that says whether or not the object is dead. Just set it in your concrete classes' `update` method when appropriate. Then after all of your updates are complete, remove the dead objects from the object list.

So in theory something like this (excuse my C++ it's been a while):

```
for_each( m_allEntites.begin(), m_allEntites.end(), mem_fun( &GameObject::update ) );
remove_if( m_allEntites.begin(), m_allEntites.end(), mem_fun( &GameObject::isDead ) );
for_each( m_allEntites.begin(), m_allEntites.end(), mem_fun( &GameObject::draw ) );

```

Third, for your "new game objects" problem. What you want to do is use `new` on the ObjectA objects you create. If you can't modify the list while you're iterating over it, an easy solution is to create a temporary list (or vector, whatever) with the new objects you've created. Then when you're done with `update`, add the new objects to the list of all objects. A naive solution would just be that all GameObjects know about the class that contains them, but I wouldn't worry about the coupling that imposes at this point in time until you figure out the basics. So in your class that contains the list of all objects, and modifying the above structure, you can do something like this:

```
for_each( m_allEntites.begin(), m_allEntites.end(), mem_fun( &GameObject::update ) );
m_allEntites.insert( m_allEntities.end(), m_newEntities.begin(), m_newEntites.end() );
m_newEntites.clear();
remove_if( m_allEntites.begin(), m_allEntites.end(), mem_fun( &GameObject::isDead ) );
for_each( m_allEntites.begin(), m_allEntites.end(), mem_fun( &GameObject::draw ) );

```

*Edit:* Just realized previous code would leak dead objects. I'm used to using `ptr_vector` instead of standard `vector` to maintain strict ownership rules. Using a standard vector you'd want to iterate over the list and `delete` dead objects. A common pattern I've used in the past was to also set their pointer to `null` then do a `remove_if` on `null` objects. Or you could do something fancy and keep GameObjects around in a bucket pattern to avoid allocations if that's the route you wanted to go down.
> 4 votes

# Answer
The solution is to iterate in reverse from back to front. That way, if you: 1. Add things to the end of the list, it won't get iterated upon 2. The currently-iterated thing dies, the loop can still continue as normal

If I were you, I'd use a vector class and iterate backwards using numeric indices. (e.g. for int i = things.size() - 1; i \>= 0; -- i)
> 2 votes

# Answer
Actually why not use a vectors standard methods to add and remove objects? Basically its just an array of pointers to objects and when an object needs to die you simply remove it and the vector will decrease its size automatically. The nice thing is that you have a base class "Object" lets say and it doesnt matter to the vector what the derived types are as long as they are inherited from Object. This allows you to call update() draw() regardless of the objects type.

```
std::vector<Object *> objects;  // Your list of pointers to objects

```

When one needs to die:

```
void ObjectManager::destroy(Object *o)
{
    for(int i=0; i<objects.size(); i++)
          {
             if(objects[i] == o)
                {
                   objects[i]->destroy();  // Define virtual method destroy
                   delete objects[i];      // Delete the pointer (create with new)
                   objects.erase(objects.begin() + i);  // Erase from vector!
                   return;
                }

          }
}

```

I hope this helps (albeit a year late lol). The destroy method is a good idea because derived classes wont have their destructors called when called through a base class pointer like this unless you define the destructors as virtual. Having default constructors should be fine depending on how you designed your objects but you could use an init() function as well that is virtual.
> 1 votes

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


title: D3D9 Alpha Blending on the surfaces

text:
# Question
Title: D3D9 Alpha Blending on the surfaces
I have a surface (OffScreenPlain or RenderTarget with D3DFMT\_A8R8G8B8) which I copy pixels (ARGB) to, from a third party function. Before pixel copying, Bits are accessed by LockRect.

This surface is then StretchRect to the Backbuffer which is (D3DFMT\_A8R8G8B8). Surface and Backbuffer are different dimensions. Filtering is set to D3DTEXF\_NONE.

Just after creating the d3d device I've set following RenderState settings

```
D3DRS_ALPHABLENDENABLE -> TRUE
D3DRS_BLENDOP          -> D3DBLENDOP_ADD
D3DRS_SRCBLEND         -> D3DBLEND_SRCALPHA
D3DRS_DESTBLEND        -> D3DBLEND_INVSRCALPHA

```

But I see no alpha blending happening. I've verified that alpha is specified in pixels.

I've done a simple test by creating a vertex buffer and drawing a triangle (DrawPrimitive) which displays with alpha blending.

In this test surface was StretchRect first and then DrawPrimitive, and the surface content displays without alpha blending and the triangle displays with alpha blending.

What am I missing here? Thanks

EDIT: I must add this is on x64 Win7

# Answer
`StretchRect` doesn't perform blending. You'd need to actually render a quad that's mapped with your surface texture in order to get blending to happen.
> 1 votes

# Answer
It seems the alpha information is being lost at some point. Try inspecting the surface pixels between each operation to find out where.
> 0 votes

---
Tags: directx9
---


# Question
Title: What's the purpose of OpenGL's Vertex Array Objects?
I've just started out with OpenGL I still haven't really understood what Vertex Array Objects are and how they can be employed.

If Vertex Buffer Object are used to store vertex data (such as their positions and texture coordinates) and the VAOs only contain status flags, where can they be used? What's their purpose?

As far as I understood from the (very incomplete and unclear) GL Wiki, VAOs are used to set the flags/statūs for every vertex, following the order described in the Element Array Buffer, but the wiki was really ambiguous about it and I'm not really sure about what VAOs really do and how I could employ them.

# Answer
> 52 votes
I think you will understand their purpose better with a sample. By reading the comments you will understand how VAOs are used.

```
// BEGIN INITIALIZATION
// Define some vertex data
struct Vertex {
  GLfloat position[3];
  GLfloat texcoord[2];
};
Vertex vertexdata[NUM_VERTS] = { ... };
GLubyte indexdata[NUM_INDICES] = { 0, 1, 2, ... };

// Create and bind a VAO
GLuint vao;
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);

// Create and bind a BO for vertex data
GLuint vbuffer;
glGenBuffers(1, &vbuffer);
glBindBuffer(GL_ARRAY_BUFFER, vbuffer);

// copy data into the buffer object
glBufferData(GL_ARRAY_BUFFER, NUM_VERTS * sizeof(Vertex), vertexdata, GL_STATIC_DRAW);

// set up vertex attributes
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, position));
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, texcoord));

// Create and bind a BO for index data
GLuint ibuffer;
glGenBuffers(1, &ibuffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibuffer);

// copy data into the buffer object
glBufferData(GL_ELEMENT_ARRAY_BUFFER, NUM_INDICES * sizeof(GLubyte), indexdata, GL_STATIC_DRAW);

// At this point the VAO is set up with two vertex attributes
// referencing the same buffer object, and another buffer object
// as source for index data. We can now unbind the VAO, go do
// something else, and bind it again later when we want to render
// with it.

glBindVertexArray(0);

// END INITIALIZATION

// BEGIN RENDER LOOP

// This is it. Binding the VAO again restores all buffer
// bindings and attribute settings that were previously set up
glBindVertexArray(vao);
glDrawElements(GL_TRIANGLES, NUM_INDICES, GL_UNSIGNED_BYTE, (void*)0);

// END RENDER LOOP

```

# Answer
> 2 votes
VAOs are useful, because you don't have to set up everytime all attributes. It should also be faster just bind one VAO rather then setting all attributes.

# Answer
> 1 votes
This is my favorite link: http://www.songho.ca/opengl/gl\_vertexarray.html

It should help you get a better understanding of the differences between VAO and VBOs. Also, Id recommend reading a chapter in OpenGL superbible on this topic. It does a good job at explaining these basics at length and with examples.

# Answer
> 0 votes
Lecture 9 Here http://nccastaff.bournemouth.ac.uk/jmacey/CA1/index.html has some stuff about it (as do the rest of my notes) and If you look at the NGL library on the same site I have a class that wraps up the behaviour of a VAO

---
Tags: opengl
---


title: Kinect: interaction pattern

text:
# Question
Title: Kinect: interaction pattern
I'm on kinect coding with OpenNI, and i'm really enthusiastic of this new device!

I'm looking for some interaction pattern, like how to control movement of an actor in a 3d space.

anyone have some advice?

# Answer
> 1 votes
I know this post is old, but as technology has caught up to this question, OpenNI has since developed a wrapper that you can use for Unity to basically drag and drop onto a biped and control with the Kinect. Also on coding for fun they have wrappers for the UDK as well. So yes, now you can, the information is out there.

---
Tags: interface, kinect
---


title: CUDA 4.1 Particle Update

text:
# Question
Title: CUDA 4.1 Particle Update
I'm using CUDA 4.1 to parse in the update of my Particle system that I've made with DirectX 10. So far, my update method for the particle systems is 1 line of code within a for loop that makes each particle fall down the y axis to simulate a waterfall:

```
m_particleList[i].positionY = m_particleList[i].positionY - (m_particleList[i].velocity * frameTime * 0.001f);

```

In my .cu class I've created a struct which I copied from my particle class and is as follows:

```
struct ParticleType
{
    float positionX, positionY, positionZ;
    float red, green, blue;
    float velocity;
    bool active;
};

```

Then I have an UpdateParticle method in the .cu as well. This encompass the 3 main parameters my particles need to update themselves based off the initial line of code. :

```
   __global__ void UpdateParticle(float* position, float* velocity, float frameTime)
{

}

```

This is my first CUDA program and I'm at a loss to what to do next. I've tried to simply put the particleList line in the UpdateParticle method, but then the particles don't fall down as they should.

I believe it is because I am not calling something that I need to in the class where the particle fall code use to be. Could someone please tell me what it is I am missing to get it working as it should?

If I am doing this completely wrong in general, the please inform me as well.

# Answer
> 3 votes
You're thinking is slightly off, but you're on the right track. When you use CUDA, and update your particles on the GPU, depending on how many particles you have, you will roughly be dedicating one processor on the GPU to each particle. So your line of code in `UpdateParticle` will look very similar to your CPU call listed at the top of your question. The key is how to get the data to GPU, and how to access it in the device function.

I'll do my best to give an overview of all the parts you'll need, but for a more detailed reference, I recommend this book. If you happen to be a student somewhere, or have an account with Safari Books online, then you could start reading online for free.

So, the first thing you need to do, after you've created your particles on the CPU (host), is allocate memory for them on the GPU (device), and copy over the data. CUDA makes this very easy:

```
ParticleType* dev_particles; // The array of particles on the GPU.
// Assume that 'particles' is the pointer to your array of CPU particles
cudaMalloc((void**)&dev_particles, num_particles*sizeof(ParticleType));
cudaMemcpy(dev_particles, particles, num_particles*sizeof(ParticleType), cudaMemcpyHostToDevice);

```

So `dev_particles` is your pointer to memory on the GPU. It's important that you DO NOT try to access data from this via host code (code that runs on the CPU). Now you can write `UpdateParticle` as something like this:

```
__global__ void UpdateParticle(ParticleType* particles) {
    int index = blockIdx.x;
    particles[index].positionY = // Update the position here;
}

```

`blockIdx` is a CUDA built-in variable that stores the information about which block of the device is currently executing. What's happening, conceptually, is you will be launching N blocks on the GPU, where N is your number of particles, and each block will update only one particle. The 'x' value of the block determines which particle in the list that block will update. Note that you could mix this up however you want, so long as every particle is addressed, but this assignment makes the most sense.

Finally, to launch the GPU simulation of your particles, you would make a call like this:

```
UpdateParticles<<<num_particles,1>>>(dev_particles);

```

This launches `num_particles` blocks, and one thread per block. More information about threads can be found in that book I mentioned. Just note that the number of blocks you can launch is limited, and using threads can significantly increase the amount of particles you can operate on. For starters, I suggest just getting familiar with blocks.

If you want to operate on the particles in host code, after you've updated them on the device, you'll need to copy the data back over:

```
cudaMemcpy(particles, dev_particles, num_particles*sizeof(ParticleType), cudaMemcpyDeviceToHost);

```

and then `particles` will contain the updated data. Note that you can set up graphics interoperability with DirectX, allowing you not to have to copy data back and forth from the GPU each frame. However, that's beyond the scope of your question.

Also, if you need to send additional information to the device function, like frameTime, you might need to allocate space for that as well on the GPU, using a similar process as I used with the particles. It might be possible to just pass a single variable by value, but a pointer will not work, as a device cannot access host memory, and a host cannot access device memory.

If you have any questions, feel free to ask in comments.

Hope this helps :)

# Answer
> 6 votes
Wow, this ended up being a pretty long answer but I've explained it as thoroughly as I could, so it might be worth the read (or at least I hope so :D) I explain as much as I can about the theory, the practice and little optimizations you can make. Enjoy!

## The theory

A kernel in CUDA is actually what gives you extreme parallel processing. CUDA follows a SPMD (**Single Program-Multiple Data**) approach: a single program (your kernel) is executed along several threads, manipulating multiple data in parallel. Bear in mind it's SPMD and not SIMD since your program code can branch (e.g. in `if` clauses, which you should avoid, since branching is heavy for GPUs) so it's not just a single instruction executed in multiple data (which would be a vector-processor, which GPUs are not! I hope I made this clear.)

Inside your kernel you should update your particles. Each thread executing your kernel would correspond to a particle (or a set of particles if you wish, which may help coalescing memory accesses.) That way you should IMMEDIATELY **get rid of the for loop**, wherever it's right now. Your kernel is practically your new loop (although it's not a loop per se.)

Since your particles don't affect each other you can safely update themselves inside the kernel, not needing a double buffer (which you would need to avoid race conditions.) This means you can safely overwrite each particle data because it doesn't matter to other particles' simulation.

I can see you barely got it, but it's weird how, although you do have a `struct ParticleType`, you're passing pointers to position and velocity to your kernel. Why are you not passing the struct array in the first place?

I'm going to continue this answer **without using the struct**, but if your data is laid as an array of `ParticleType` in GPU memory you should pass this array to the kernel, because if you didn't, you'd have to separate the data in different arrays (which would defeat all purposes of paralellization, since it would take a LONG time of memory accesses for each frame.)

## Some more theory on kernels

Kernels are executed in **batches of blocks** (actually in batches of *warps*, which are 32 threads, but you don't need to know this right now since it's hardware-stuff.) These blocks contain up to 768 threads (in G80... the limit is higher in newer architectures) which can communicate with each other, either by shared memory (with the `__shared__` qualifier) or by syncing (calling `__synchthreads();`.) Threads inside blocks are guaranteed to be able to do these tasks, but outside blocks, threads are oblivious to other threads (although not to the non-shared data they change.) Even blocks are oblivious to each other.

Once your kernel is executing you need to address your different data indices. But you're not passing any index as an argument! To address your particles, you have some convenient **built-in variables**:

1. `blockIdx` \- Your current global block id.
2. `blockDim` \- The global block dimension (threads per block.) Thus `blockIdx.x * blockDim.x` is the index of the first thread in your block.
3. `threadIdx` \- The current thread id (inside the block.) `blockIdx.x * blockDim.x + threadIdx.x` would be your current thread index (easy if you think about it, firstThreadInBlockIndex + currentThreadInsideBlockIndex.)

This way you can address different indices using the following statement:

`int idx = blockIdx.x * blockDim.x + threadIdx.x;`

See the `.x` after each variable? These built-ins are actually `dim3` (can have up to **three dimensions**) but you don't need this, since you're working on a 1d array so you just need the x dimension (just so you knew it.)

## Allocating data in GPU

You first need to **allocate and feed your buffers in GPU**. If you're not modifying your data in your host code (which you shouldn't) you should just allocate the data once and then re-use the buffer in subsequent calls.

To allocate (and copy from host) a single buffer (if you don't use the `ParticleType`, you'll need one allocation for the `position`, one for the `velocity` buffer, etc.) you have to use these CUDA calls:

```
float* h_position; // Your host pointer. This holds the data (I assume it's already filled with the data.)
float* d_position; // Your device pointer, we will allocate and fill this
cudaMalloc( (void**)&d_position, numParticles * sizeof(float) );
cudaMemcpy( d_position, h_position, numParticles * sizeof(float), cudaMemcpyHostToDevice);

```

Pretty easy to understand.

## First approach: naive implementation

Summing up, you should call your UpdateParticle kernel like this:

```
int threads_per_block = 128; // You should play with this value
int blocks = numParticles/threads_per_block + ( (numParticles%threads_per_block)1:0 );

```

I'm making a stop here to clarify the modulo (%) thing. You need it because if `numParticles%threads_per_block` is not zero you need **one extra block for the remaining threads**. E.g. `129 particles/128 part_per_blk = 1 blk`, while you actually need two blocks (one for the first 128 threads, and one block for the remaining one.)

**There is a problem with this approach.** Think of the aforementioned example: since you're allocating 2 blocks with 128 threads per block, your actually spawning 256 threads... but your array has 129 elements! Not only some threads are going to repeat work but they're also going to do the work twice (which would lead to some particles moving twice as fast) or even worse (this is the case here) **unintendedly writing to illegal indices**.

You can safely overcome that problem **checking for the correct indices**. This is your complete kernel call:

```
UpdateParticle <<< blocks, threads_per_block >>> ( d_position, d_velocity, frameTime, numParticles );

```

Your kernel should look like this:

```
__global__ void UpdateParticle(float* position, float* velocity, float frameTime, int numParticles)
{
    int idx = blockIdx.x * blockDim.x + threadIdx.x; // Compute the index

    if (idx < numParticles) { // Is this index valid?
        position[idx] = position[idx] - velocity[idx] * frameTime * 0.001f;
        ... // some more updates
    }
}

```

## Second approach: re-tessellating

As I said earlier, it might be wise to tessellate further inside your kernel. Your GPU bus is 128 bits, so **reading 4 floats** (`4*32 bits = 128 bits`) per thread **is just as cheap as reading just one float**. You might have to adjust this further if you end up using the `ParticleType` array. Just to try keep your data **128-bit aligned**.

You have to pass a new argument to your kernel:

```
UpdateParticle <<< blocks, threads_per_block >>> ( d_position, d_velocity, frameTime, numParticles, particlesPerThread );

```

Bear in mind **this would change your number of blocks**, so change it accordingly.

Your kernel would almost be the same.

```
__global__ void UpdateParticle(float* position, float* velocity, float frameTime, int numParticles, int particlesPerThread)
{
    int idx = blockIdx.x * blockDim.x + threadIdx.x;

    if (idx < numParticles/particlesPerThread) {
        for ( int i = 0; i < particlesPerThread; i++ ) {
            position[idx+i] = position[idx+i] - velocity[idx+i] * frameTime * 0.001f;
           ... // some more updates
       }
    }
}

```

Also bear in mind your `particlesPerThread` **should be a divisor of your total number of particles** (or the for loop is going to access indices outside your array size in the very last thread.)

It might also be wise to **unroll the loop** (as I said earliear, braching is no good to GPUs) thus you wouldn't need the `particlesPerThread` parameter (although you still need to adjust `blocks` accordingly.) I know this might be hell to maintain but hey, **if it's worth the performance**... why not do it? This would be your new unrolled kernel:

```
__global__ void UpdateParticle(float* position, float* velocity, float frameTime)
{
    int idx = blockIdx.x * blockDim.x + threadIdx.x;

    if (idx < numParticles/4) { // the unrolled loop is 4 iterations
        position[idx] = position[idx] - velocity[idx] * frameTime * 0.001f;
        position[idx+1] = position[idx+1] - velocity[idx+1] * frameTime * 0.001f;
        position[idx+2] = position[idx+2] - velocity[idx+2] * frameTime * 0.001f;
        position[idx+3] = position[idx+3] - velocity[idx+3] * frameTime * 0.001f;
        ... // some more updates
    }
}

```

## Conclusion

Unfortunately performace in CUDA involves a lot of tweaking, but I hope with all this background you'll be able to tweak it to fit your needs.

There could be further optimizations such as using `__shared__` qualified memory (which is A LOT faster than reading from global-memory) but since you're executing so little operations on your data it would probably not be worth the hassle.

You might also want to **precompute** the `frameTime * 0.001f` bit in a register before anything else (just do `float realTime = frameTime * 0.001f` and use it instead) or **even better: pass it already transformed from host code**. It won't be a problem for such a small number of operations, but registers are also shared between blocks, so registers (any non-qualified variable inside your kernel, like `idx` in my examples) can be a bottleneck too. Bear it in mind!

# Answer
> 1 votes
Thank you so much for you in depth answers. These have provided a lot of useful information and I'm currently in the process of implementing the information you gave into my project. Though I currently have one issue I was wondering you could help me with.

Please note, I know that I haven't really modified the code you have given me, I am just trying to get the build first, then modify it proper. If I can get at least a single particle to fall down with this, I'll know I'm on the right track.

Right now, in my kernal class I have the following code:

```
    __global__ void UpdateParticle(float* position, float* velocity, float frameTime, int numParticles)
{
    int idx = blockIdx.x * blockDim.x + threadIdx.x; // Compute the index

    if (idx < numParticles) { // Is this index valid?
        position[idx] = position[idx] - velocity[idx] * frameTime * 0.001f;
      //  ... // some more updates
    }
}

```

Following that, in the .cpp file I have amended the particle update method as follows:

```
void ParticleSystemClass::UpdateParticles(float frameTime)
{
    int i;
    float* h_position; // Your host pointer. This holds the data (I assume it's already filled with the data.)
    float* d_position; // Your device pointer, we will allocate and fill this
    float* d_velocity;
    float* d_time;
    int threads_per_block = 128; // You should play with this value
    int blocks = m_maxParticles/threads_per_block + ( (m_maxParticles%threads_per_block)1:0 );
    const int N = 10;
    size_t size = N * sizeof(float);
    cudaMalloc( (void**)&d_position, m_maxParticles * sizeof(float) );
    cudaMemcpy( d_position, h_position, m_maxParticles * sizeof(float), cudaMemcpyHostToDevice);

    UpdateParticle_cuda(d_position, d_velocity,frameTime, m_maxParticles,blocks,  threads_per_block);

    return;
}

```

When I build the program, the only error I get comes from the following line:

```
    int blocks = m_maxParticles/threads_per_block + ( (m_maxParticles%threads_per_block)1:0 );

```

The error behind is being:

> error C2059: syntax error: ')'
>
> error C2143: syntax error: missing a ')' before 'constant'

From what I can see, there is no missing bracket in that statement, and no google search I do seems to yield any result for find a solution.

Is there something wrong with my what I have put so far, or I have got it totally wrong?

Please help me fix this bug.

Thanks.

---
Tags: directx, gpgpu, cuda
---


# Question
Title: Why is my primitive xna square not drawn/shown?
I have made this class to draw a rectangle, but I cant get it to be drawn, I have no issues displaying a 3d model created in 3dmax, but shown these primitives seems much harder

I use this to create it

```
board = new Board(Vector3.Zero, 1000, 1000, Color.Yellow);

```

And here is the implementation

```
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Shapes;
using Quadro.Models;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace Quadro
{
    public class Board : IGraphicObject
    {
        //Private Fields
        private Vector3 modelPosition;
        private BasicEffect effect;
        private VertexPositionColor[] vertices;
        private Matrix rotationMatrix;
        private GraphicsDevice graphicsDevice;
        private Matrix cameraProjection;

        //Constructor
        public Board(Vector3 position, float length, float width, Color color)
        {
            var _color = color;

            vertices = new VertexPositionColor[6];
            vertices[0].Position = new Vector3(position.X, position.Y, position.Z);
            vertices[1].Position = new Vector3(position.X, position.Y + width, position.Z);
            vertices[2].Position = new Vector3(position.X + length, position.Y, position.Z);
            vertices[3].Position = new Vector3(position.X + length, position.Y, position.Z);
            vertices[4].Position = new Vector3(position.X, position.Y + width, position.Z);
            vertices[5].Position = new Vector3(position.X + length, position.Y + width, position.Z);

            for(int i = 0; i < vertices.Length; i++)
            {
                vertices[i].Color = color;
            }

            initFields();
        }

        private void initFields()
        {
            graphicsDevice = SharedGraphicsDeviceManager.Current.GraphicsDevice;
            effect = new BasicEffect(graphicsDevice);
            modelPosition = Vector3.Zero;

            float screenWidth = (float)graphicsDevice.Viewport.Width;
            float screenHeight = (float)graphicsDevice.Viewport.Height;
            float aspectRatio = screenWidth / screenHeight;
            this.cameraProjection = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45.0f), aspectRatio, 1.0f, 10000.0f);
            this.rotationMatrix = Matrix.Identity;
        }

        //Public Methods
        public void Update(GameTimerEventArgs e)
        {

        }

        public void Draw(Vector3 cameraPosition, GameTimerEventArgs e)
        {
            Matrix cameraView = Matrix.CreateLookAt(cameraPosition, Vector3.Zero, Vector3.Up);

            foreach (EffectPass pass in effect.CurrentTechnique.Passes)
            {
                pass.Apply();

                effect.World = rotationMatrix * Matrix.CreateTranslation(modelPosition);
                effect.View = cameraView;
                effect.Projection = cameraProjection;
                graphicsDevice.DrawUserPrimitives(PrimitiveType.TriangleList, vertices, 0, 2, VertexPositionColor.VertexDeclaration);
            }
        }

        public void Rotate(Matrix rotationMatrix)
        {
            this.rotationMatrix = rotationMatrix;
        }

        public void Move(Vector3 moveVector)
        {
            this.modelPosition += moveVector;
        }
    }
}

```

# Answer
I've tried your code and it appears to be working on an empty project for the most part. But there are a few things that could make it fail:

1. You need to enable `VertexColorEnabled` on your effect otherwise it will be rendered white:

```
effect.VertexColorEnabled = true;

```
2. If you don't see the board being rendered you're probably looking at it *from behind*. By default, backfacing polygons are culled so they won't be drawn. Either position your camera so that you're seeing the board from the correct angle, or disable backface culling before rendering with:

```
graphicsDevice.RasterizerState = RasterizerState.CullNone;

```
3. You should be setting your effect properties *before* applying the pass, not after! That could also be the source of the problem if you're rendering other objects before and after the board. And move all the `effect.Property` assignments that you're currently doing *outside* the loop. There's no meaning in them being inside the loop if the values are the same in every pass.
4. This one is optional. Since the `BasicEffect` only uses one pass you can also simplify your rendering code by replacing the loop with a simple:

```
effect.CurrentTechnique.Passes[0].Apply();

```
> 2 votes

---
Tags: xna, 3d, windows-phone-7
---


# Question
Title: How do you cope mentally with one very long piece of work
This is my first games industry job and my task is to take out one major game component and put in a newer one.

So far it's been 5 weeks, and I'm still just staring at errors. I think it could be months before it's at the point that it can compile. It's really getting me down. I'm just changing things over, I'm not really writing anything myself. it's just endless. I fix a thousand errors and nine thousand take their place.

I'm sure this must be a common thing, so I was just wondering, how do you cope with this? It doesn't seem like I can break it down into little chunks at all.

# Answer
Welcome to the game industry :)

So you're doing a massive refactoring. Massive refactoring is Evil, but that's not the topic. You were probably given this task to test your nerves anyway, so don't give up on it.

My answer is: you **have to** break it down into little chunks. It'll be your daily routine in a few months, so you have to learn how to divide and conquer. It's basically your job. A few suggestions:

* Make sure you understand what this component is **supposed to do**. Play with what you have to take out and see what it does, ask your colleagues if your assumptions are right.
* You're rewriting this module for a reason. It might not be obvious to you, but if you were given this task it's most likely because something was so crappy that people feel it's better starting it over. Ask around: what are those **defects**?
* Try finding the **core feature** of the component you're rewriting, its very substance, the reason it exists, and start by getting this one working. It must be really tiny, as small as you can. Ask your colleagues about what they think this feature would be. If it's a GFX system, just make it display one polygon. If it's an animation system, just place one bone properly. If it's an AI system, just make it play an animation. Etc. etc. Just trash everything that gets in the way and gives you all those daunting errors. Don't get disturbed by the details, just get this core feature working as quickly as you can. Your implementation will be ugly, full of bugs and hacks and magic numbers and you wouldn't let anyone glance at your code, but that's not a problem.
* Once you've got this core feature, you'll already start feeling better. It's essential to see the result of your work as early as possible 1) for your morale 2) to be able to test it. So, test it, stress test it, **torture it**. If it crashes or shows some really bad bug, fix this. It's the heart of your module so **rework** it a bit and clean it up until you feel comfortable with it.
* Then show it to your colleagues and ask them if that's what the game needs. **Ask for a code review**: your colleagues will probably tell you about plenty of things that you didn't think of. You'll have to **refactor again** to make sure your implementation fits with what the rest of the team wants.
* Then when you feel ready for it, pick one of the other features you trashed earlier on, rinse, repeat. Make it work as fast as you can, rework, ask for a review, re-rework.

I have to put the emphasis one last time on this: **communicate**. Ask you colleagues, not only your lead, not only the programmers, everybody that will use or test or evaluate this system. Don't fear about asking stupid questions: when in doubt, it's always better to get the information right now than to wait weeks for a meeting or a review.

The reality of game programming is that you're not going to create brand shiny new systems everyday, it's a job of keeping focus and getting the things done quickly and efficiently. Pull yourself together, get to work, and good luck!

EDIT

There's extra info I find useful in Leo's comment and dhasenan's answer, I'm shamelessly steeling that from them to complete this answer.

I didn't write about how to deal with **inter-dependencies**. The module you're rewriting is probably deeply coupled with the rest of the game, that's why you get so many errors when changing something. So there's two solutions:

* If there are just a **few** dependencies, then you're lucky. The old and the new module can be kept in parallel for a while, you can even have a switch for your users so they can decide to change between the old and the new module whenever they need to. Just put a switch somewhere, in a configuration file or in a debug menu, and use it where-ever your module is plugged to the rest of the game. When your new module is ready for production, put the switch on by default. Later on, when the old module is not used anymore or when production needs to go on, remove the old module and the switch.
* If there are **many** dependencies, you have to unplug and re-plug them one by one. Try to keep both modules in the background, and each time you get a new feature to work, switch to the new module for that feature. I.e. unplug and re-plug what's related to this feature. It'll take you some time because it's probably more work than changing just one function call: some data structures might change, the program flow might change, etc. But it's still better than rewriting everything once and taking weeks to kill the compilation beast. If that's really impossible to keep both the old and the new modules in parallel because you module is so vital to the game, you might consider rewriting in place. But beware that this could mean that if the defects are in the old module's interface, you'll end up with the same defects. Anyway, if this happens, try taking advantage of this refactoring: you might be able to remove a few dependencies or to split the module in sub-modules for the sake of good software design.

If there's something specific to video game development, it's this: we're not doing rocket science, or a complicated research work, we're part of a creative process. When doing something, you have to craft a first version as quickly as possible so it can be tested, played, frown upon, and modified. You can't spend weeks doing "one very long piece of work" without delivering a bit.
> 21 votes

# Answer
You have to split up your task, but nobody's offering advice on how to do that.

* Do the new and old modules work together? That is, can you compile your project with both? This will let you at least compile and probably run automated tests at some milestones.
* Are you writing the new module? Or is the old one code that you own? Rewrite in place (insofar as the external API is remaining the same). If you fix one function at a time, you should be able to continue using the combined mongrel API, to some extent.
* Are there other projects at the company that will be making a similar transition? Write wrappers around these modules to make the process easier next time. It might be worthwhile doing this in the meantime.
* Can you comment out or avoid compiling chunks of your dependency chain? If you have half a million lines of code total, maybe you can split it up into twenty chunks that compile independently, get one working in a couple weeks, and then move on to the next. Maybe not fully independent chunks all the time, but then you can do it in order of dependencies.

Also: ask your manager for advice. I would probably start off describing the problem: it's taking so long to get things compiling properly that it's hard to keep track of changes, which will make it harder to debug once you have something you can test. Then I'd mention a potential solution, and ask: "How do you recommend I implement this solution, or is there a better way of doing this entirely?"
> 1 votes

---
Tags: game-industry, jobs
---