# Question
Title: When and why is a Pool class needed to hold objects?
I've been studying opengl es and an example I saw was using a "Pool" class to keep track of touch and keyboard events.

Could someone please explain how and why a pool class is needed. From what I was reading it had something to do with garbage collection and limiting the number of input classes that are made.

This all seems a little abstract to me, so if someone could please explain what is going on, I'd appreciate it, I'll pasted some code here:

```
    public Pool(PoolObjectFactory < T > factory, int maxSize) {
        this.factory = factory;
        this.maxSize = maxSize;
        this.freeObjects = new ArrayList < T > (maxSize);
    }

    public T newObject() {
        T object = null ;
        if (freeObjects.isEmpty())
            object = factory.createObject();
        else
            object = freeObjects.remove(freeObjects.size() - 1);
            return object;
    }

    public void free(T object) {
        if (freeObjects.size() < maxSize)
            freeObjects.add(object);
    }

    PoolObjectFactory <TouchEvent> factory = new PoolObjectFactory <TouchEvent> () {

    @Override
    public TouchEvent createObject() {
         return new TouchEvent();
    }

    Pool <TouchEvent> touchEventPool = new Pool <TouchEvent> (factory, 50);
    TouchEvent touchEvent = touchEventPool.newObject();
    . . . do something here . . .
    touchEventPool.free(touchEvent);

```

Thanks!

# Answer
Pools are used when the number of objects will fluctuate dramatically and are used to reduce the amount of memory allocation and garbage collecting.

Using a pool the standard new Object() which allocates new memory is replaced with pulling an already allocated object from the pool. This is much faster even if you go though and reset every variable in the old object to a default.

If you create a new item each time you have a huge over head as memory must be allocated for each object. Also because you are creating so many objects you must clean them up often which causes the garbage collector to be run very often further hurting performance.

A common example is bullets.

For a FPS there may be 0 bullets on screen then 1000 the next second and then 0 again the second after that. If you were to create a new bullet for every single one fired the constant memory allocation would be extremely performance intensive. In addition the garbage collector has to track all of these instances and clean the up periodically which takes even more time.

If you have a pool of 5000 bullets and only update and interact with the ones not in the freeObjects list you only have 5000 total allocations no matter how long the firefight lasts instead of 1 allocation per bullet. Also the garbage collector only needs to run once any possibility of a firefight has ended. Interacting with the memory is very slow so this makes a huge impact on performance and makes sure the workload is evenly distributed preventing frame rate stutters.
> 17 votes

---
Tags: java, android, object-pools
---


# Question
Title: How can one make multiple movable images in OpenGL ES 2.0?
I was wondering, I've only seen examples of OpenGL ES 2.0 where people have used one or perhaps two images. I didn't see multiple images of where they each had independent movement.

**What if someone needed about 20 independent movable images/objects in their game?**

Would that make for one huge shader, or would one make multiple shaders. And if one makes multiple shaders, how would you use them. I could use some pseudo-code or even better some snippets of real code to see how this would be done in a 2D game.

**I've only seen examples of static arrays that are rendered to a screen. What's an example of multiple movable objects in ES 2.0?**

# Answer
One option is having a vertex buffer describing the positions of the object's vertices, and then using something like `glBufferSubData` to update those positions to move them around. That could be generalized to having a way to update any particular attributes being sent to the vertex shader (color, opacity, transformation data, etc.).

So you'd create a buffer (`glGenBuffers`, `glBindBuffer`, `glBufferData`), write some vertex data into the buffer, and then when that data changes, use `glBufferSubData` to send those changes to the renderer. You'll need to look into setting up your attributes correctly so that your vertex shader knows what to do with that data, though, which is a whole other bit of work and could vary depending on what you want to do, look into `glGetAttribLocation`, `glEnableVertexAttribArray`, `glVertexAttribPointer`, stuff like that. You shouldn't need a separate shader for each new object; the attributes and uniforms you send to the shader would control their individual appearance.
> 2 votes

---
Tags: java, 2d, opengl-es2
---


# Question
Title: Why does this LUA code not render any objects on the screen?
Did I mess up something somewhere? If i put a putsxy in the same box, it renders a string just fine, but for some reason this code hates objects. What this code is supposed to do is render a set of randomly positioned 't's on the screen, and this works fine without objects. However, when I add objects, nothing renders. What am I doing wrong? Help is much appreciated. Code is as follows:

```
-------------------------------
-- Asterix v0.0.3 --
-- Copyright 2013 WilliamTDR. --
-------------------------------

-- prerequestities --
require "actions" -- button input
require "math" -- random numbers

-- Global Variables --
local player = {
    health = 20, -- player health
    foodparts = 12, -- portions of food until the food level depletes by one
    food = 40, -- player food
    x = 50, -- player x position
    y = 50, -- player y position
    roomx = 0, -- x value of room player is in
    roomy = 0 -- y value of room player is in
}

local object = {
    x = 30,
    y = 30,
    roomx = 0,
    roomy = 0,
    name = "Unknown Object",
    touchingplayer = false,
    symbol = "u"
}

local objects = {}

function object:new (o)
    o = o or {}   -- create object if user does not provide one
    setmetatable(o, self)
    self.__index = self
    return o
end

function player.refresh()
    -- reset player values
    player.food = 40
    player.health = 20
    player.foodparts = 12
    player.x = 50
    player.y = 50
    player.roomx = 0
    roomy = 0
end

function player.die()
    rb.lcd_clear_display() -- clear the display
    rb.lcd_putsxy(1, 7, "You have died!")
    rb.lcd_putsxy(1, 45, "Respawning in 3...")
    rb.lcd_update()
    rb.sleep(rb.HZ) -- sleep for one second
    rb.lcd_putsxy(1, 45, "Respawning in 2...")
    rb.lcd_update()
    rb.sleep(rb.HZ)
    rb.lcd_putsxy(1, 45, "Respawning in 1...")
    rb.lcd_update()
    rb.sleep(rb.HZ)
    player.refresh()
    render()
end

function renderobjects()
    for _,object in ipairs(objects) do
        if player.roomx == object.roomx and player.roomy == object.roomy then
            rb.putsxy(object.x, object.y, object.symbol)
        end
    end
    rb.lcd_update()
end

function createnewobjects()
    obj1 = object:new{x = math.random(1,92), y = math.random(1,92), roomx = 0, roomy = 0, symbol = "t", name = "Tree"}
    obj2 = object:new{x = math.random(1,92), y = math.random(1,92), roomx = 0, roomy = 0, symbol = "t", name = "Tree"}
    obj3 = object:new{x = math.random(1,92), y = math.random(1,92), roomx = 0, roomy = 0, symbol = "t", name = "Tree"}
    obj4 = object:new{x = math.random(1,92), y = math.random(1,92), roomx = 0, roomy = 0, symbol = "t", name = "Tree"}
    obj5 = object:new{x = math.random(1,92), y = math.random(1,92), roomx = 0, roomy = 0, symbol = "t", name = "Tree"}
    obj6 = object:new{x = math.random(1,92), y = math.random(1,92), roomx = 0, roomy = 0, symbol = "t", name = "Tree"}
    obj7 = object:new{x = math.random(1,92), y = math.random(1,92), roomx = 0, roomy = 0, symbol = "t", name = "Tree"}
    obj8 = object:new{x = math.random(1,92), y = math.random(1,92), roomx = 0, roomy = 0, symbol = "t", name = "Tree"}
    obj9 = object:new{x = math.random(1,92), y = math.random(1,92), roomx = 0, roomy = 0, symbol = "t", name = "Tree"}
    obj10 = object:new{x = math.random(1,92), y = math.random(1,92), roomx = 0, roomy = 0, symbol = "t", name = "Tree"}
    obj11 = object:new{x = math.random(1,92), y = math.random(1,92), roomx = 0, roomy = 0, symbol = "t", name = "Tree"}
    obj12 = object:new{x = math.random(1,92), y = math.random(1,92), roomx = 0, roomy = 0, symbol = "t", name = "Tree"}
    obj13 = object:new{x = math.random(1,92), y = math.random(1,92), roomx = 0, roomy = 0, symbol = "t", name = "Tree"}
    obj14 = object:new{x = math.random(1,92), y = math.random(1,92), roomx = 0, roomy = 0, symbol = "t", name = "Tree"}
    obj15 = object:new{x = math.random(1,92), y = math.random(1,92), roomx = 0, roomy = 0, symbol = "t", name = "Tree"}
    obj16 = object:new{x = math.random(1,92), y = math.random(1,92), roomx = 0, roomy = 0, symbol = "t", name = "Tree"}
    obj17 = object:new{x = math.random(1,92), y = math.random(1,92), roomx = 0, roomy = 0, symbol = "t", name = "Tree"}
    obj18 = object:new{x = math.random(1,92), y = math.random(1,92), roomx = 0, roomy = 0, symbol = "t", name = "Tree"}
    obj19 = object:new{x = math.random(1,92), y = math.random(1,92), roomx = 0, roomy = 0, symbol = "t", name = "Tree"}
    obj20 = object:new{x = math.random(1,92), y = math.random(1,92), roomx = 0, roomy = 0, symbol = "t", name = "Tree"}
    table.insert(obj1, objects)
    table.insert(obj2, objects)
    table.insert(obj3, objects)
    table.insert(obj4, objects)
    table.insert(obj5, objects)
    table.insert(obj6, objects)
    table.insert(obj7, objects)
    table.insert(obj8, objects)
    table.insert(obj9, objects)
    table.insert(obj10, objects)
    table.insert(obj11, objects)
    table.insert(obj12, objects)
    table.insert(obj13, objects)
    table.insert(obj14, objects)
    table.insert(obj15, objects)
    table.insert(obj16, objects)
    table.insert(obj17, objects)
    table.insert(obj18, objects)
    table.insert(obj19, objects)
    table.insert(obj20, objects)
end

function checks()
    if player.foodparts < 1 then
        player.foodparts = 12
        player.food = player.food - 1
    end

    if player.food < 1 then
        player.health = player.health - 1
    end

    if player.health < 1 then
        player.die()
    end

    if player.x < 1 then
        player.roomx = player.roomx + 1
        createnewobjects()
        player.x = 92
    end

    if player.x > 93 then
        player.roomx = player.roomx - 1
        createnewobjects()
        player.x = 4
    end

    if player.y < 1 then
        player.roomy = player.roomy + 1
        createnewobjects()
        player.y = 92
    end

    if player.y > 93 then
        player.roomy = player.roomy - 1
        renderobjects()
        player.y = 4
    end

    end

function render()
    checks()
    rb.lcd_set_background(0, 255, 0) -- background is black
    rb.lcd_set_foreground(-1, 0, 0) -- foreground is white
    rb.lcd_clear_display()
    rb.lcd_fillrect(5, 3, (player.health * 2), 2)
    rb.lcd_set_foreground(88, 2, 2)
    rb.lcd_fillrect(45, 3, player.food, 2)
    rb.lcd_set_foreground(125, 125, 0)
    rb.lcd_putsxy(player.x, player.y, "*")
    renderobjects()
    rb.lcd_update()
end

function LoadGame()
render()
    while true do
        button = rb.get_plugin_action(0)
        if button == 182 then
            player.x = player.x - 1
            player.foodparts = player.foodparts - 1
            render()
        elseif button == 183 then
            player.x = player.x + 1
            player.foodparts = player.foodparts - 1
            render()
        elseif button == 180 then
            player.y = player.y - 1
            player.foodparts = player.foodparts - 1
            render()
        elseif button == 181 then
            player.y = player.y + 1
            player.foodparts = player.foodparts - 1
            render()
        elseif button == 186 then
            player.x = player.x - 4
            player.foodparts = player.foodparts - 4
            LoadGame()
        elseif button == 187 then
            player.x = player.x + 4
            player.foodparts = player.foodparts - 4
            LoadGame()
        elseif button == 184 then
            player.y = player.y - 4
            player.foodparts = player.foodparts - 4
            LoadGame()
        elseif button == 185 then
            player.y = player.y + 4
            player.foodparts = player.foodparts - 4
            LoadGame()
        elseif button == 191 then
            ShowMainMenu() -- start the program by displaying the main menu of the script.
        end
    end
end

function ShowMainMenu()
    mainmenu = {"New Game", "Load Game", "About MCRE", "Exit"}

    while true do
        s = rb.do_menu("Asterix v0.0.1", mainmenu, nil, false)

        if     s == 0 then LoadGame()
        elseif s == 1 then rb.splash(3 * rb.HZ, "No maps found! Create one first.")
        elseif s == 2 then rb.splash(5 * rb.HZ, "Game ©2013 WilliamTDR. Version 0.0.1, build 4. Minecraft is a registered trademark of Notch Development AB.")
        elseif s == 3 then os.exit()
        elseif s == -2 then os.exit()
        else rb.splash(2 * rb.HZ, "Whoops: Unexpected Button press!" .. s)
        end
    end
end

ShowMainMenu() -- start the program by displaying the main menu of the script.

```

# Answer
> 1 votes
You have these arguments reversed:

```
table.insert(obj1, objects)

```

This should be:

```
table.insert(objects, obj1)

```

Same applies to obj2, obj3 etc.

---
Tags: software-engineering, rendering, lua, objects, gameobject
---


# Question
Title: How scanline rendering finds an intersection with an object
I'm a newbie with graphics and after I read many articles on the web I still don't understand how in rasterizing from a pixel coordinate like (0;0) on the screen the intersection with an object (let's say a sphere) is found before determining its color and how the Z buffer comes into play.

I know something about ray tracing.. is a ray shot from the 0;0 pixel and the intersection point thus determined by the equality between the ray equation with the sphere equation? If it works that way I don't see what the Z buffer is useful to.

I don't know if I explained myself correctly, if not please let me know and I'll try to be as clear as I can on my doubt.

# Answer
> 2 votes
In some ways, rasterisation is the opposite problem to raytracing. In raytracing, you know which pixel you are testing, and you have to find the triangles that are hit by the ray through it. In rasterisation, you have information about a triangle and you need to find which pixels it covers.

Basically, the vertices describing the triangle are projected into screen space through a series of matrix transformations and then interpolation is used to find all the pixels inside the 2D triangle. These are then tested by the depth buffer to see if they are closer than anything else that was written, and if so, then the colour at that pixel can be determined, with lighting, texturing and anything else you want to do.

Here is a good discussion and code regarding software rasterisation. If you are searching for more information, here are a few terms of interest: "scan conversion" "half spaces" and "perspective correct"

# Answer
> 0 votes
Depth Buffer is not as fancy as ray tracing, it's just a simple sort of Z values from objects.

One of many types of information you send to the GPU are postions (x,y,z), after the data is in VRAM (Video Ram) each z value that a pixel intersects is taken in consideration. Something like this:

```
for every polygon in the polygon list in VRAM
  if polygon intersect pixel P
    if not closest Z
     update Z values in buffer

```

Z Buffer is useful because it is done at hardware level and it consists of a comparison between a point and a pixel to say so, ray intersection on the other hand in software development is quite an expensive algorithm.

---
Tags: opengl, 3d, depth-buffer, computational-geometry, software-rendering
---


title: Pac-Man - Public Domain?

text:
# Question
Title: Pac-Man - Public Domain?
I've googled this and haven't come up with anything. Can I create a Pac-Man game and not get in trouble with?

Like can I sell it, and be able to make money without having to pay someone else royalties?

# Answer
> 12 votes
http://en.wikipedia.org/wiki/Pac-Man

> In 2011, Namco sent a DMCA notice to the team that made the programming language Scratch saying that a programmer had infringed copyright by making a Pac-Man game using the language and uploading it to Scratch's official website.\[94\]

Considering they sent a DMCA to someone who wasn't making money off of it I'm going with no.

# Answer
> 9 votes
Pac-Man is still covered by copyright, and has not reverted to the public domain.

Exhaustively sourced proof:

1. Copyright for works created during or after 1978 lasts a bare minimum of 70 years. (section 302.a) (In the case of Pac-Man, 120 years is probably a more likely duration, as it presumably would have been a work for hire performed for Namco by its employees. But we'll assume the minimum of 70 years for the rest of this proof)
2. Pac-Man was created in 1980.
3. At the time of writing, the year is 2013
4. 2013 - 1978 = 35
5. 35 \< 70

Therefore, Pac-Man is still covered by Copyright.

Quod erat demonstrandum

---
Tags: legal
---


title: Screen effects and antialiasing

text:
# Question
Title: Screen effects and antialiasing
I have been working on a game for a while using glut for basic window creation. I was rendering to an offscreen buffer so that I could implement various effects like screen bulging, motion blur, refraction, etc. I also used the screen texture with antialiasing (fxaa).

Now I have changed from glut to sfml. I switched on the in-built antialiasing and it looked much better than my version, but now I don't have the screen in a texture so I can't use the screen effects.

So my question is, how to people normally deal with this issue? Can I take advantage of sfml's antialiasing functionality and retain my effects? I thought about using glReadPixels, but that seems way too slow. Does sfml do offscreen rendering behind the scenes and can I access that texture?

This is not specific to sfml. How do AAA games do it? Do they always implement their own antialiasing techniques?

# Answer
As far as I know, SFML doesn't provide own anti aliasing. Well, when you create a new window, there is an optional parameter for the anti-aliasing level. But this super-sample anti-aliasing is a default handeled by the graphics driver instead of SFML. You can easily get that with GLUT, too.

Internally, SFML doesn't use render to texture, I think. But there is a class to do so on you own. It's named `sf::RenderTarget`. You can render to all classes derived from that, including `sf::RenderTexture`, which might be exactly what you are looking for.

You could either do rendering yourself using raw OpenGL and handle all shaders, render targets and framebuffers yourself. Or you could make use of another SFML class provided for this case. If I remember correctly, it was called `sf::PostFX` and was renamed to `sf::Shader` now. Though I haven't used those classes, it seems rather easy to use them and apply effects. You read the documentation, it is a very good one which many described use cases. But since SFML has only 2D capabilities, I am not sure whether you can use that for a 3D game or not.

Nearly all recent AAA titles make use of deferred rendering, which means to render multiple attributes like depth, view space normals and texture color, to texture. Shading can be applied by reading from those textures, so that the geometry hasn't to be drawn multiple times. This is a step further than what you want to do. Deferred rendering is especially useful for computing a lot of lights.

At least for deferred rendering, anti-aliasing is still a big issue. There are various approaches with their trade-offs. But super sampling is to slow in most cases since you have to super sample all the textures rendered to, which amplified rapidly. What some games do is to detect hard edges using depth and normal information and apply a blur to those pixels. Easier implementations do only read the color texture, for example FXAA. Those are what you want to implement. That is kind of faked anti-aliasing but it has an acceptable low performance trade off.

But before you start altering you whole game think carefully if it makes sense to use those post process anti-aliasing algorithms. If you don't use deferred rendering, it is very likely that you are fine with the default super sampling. It can be used by passing `sf::ContextSettings` to your `sf::Window` instance.
> 1 votes

# Answer
Anti-aliasing is little more than rendering at a higher resolution and scaling it down before putting it on the screen.

Have you considered rendering to a larger off-screen texture?
> -3 votes

---
Tags: shaders, graphics-programming, graphic-effects, sfml, antialiasing
---


title: glBufferSubData and offset alignment?

text:
# Question
Title: glBufferSubData and offset alignment?
I'm having trouble rendering some of my meshes; some display just fine, some are drawn wrong or not at all.

While troubleshooting I was looking at the openGL docs (http://www.opengl.org/sdk/docs/man3/) and on the topic of glBufferSubData the following line caught my eye:

```
Clients must align data elements consistent with the requirements of
the client platform, with an additional base-level requirement that an offset
within a buffer to a datum comprising N bytes be a multiple of N.

```

I am buffering vertex + normal and index data like this:

```
glGenBuffers(1, &mVBO);
glGenBuffers(1, &mIndexBuffer);
glGenVertexArrays(1, &mVAO);

// buffer vertex, normals and index data
glBindVertexArray(mVAO);
glBindBuffer(GL_ARRAY_BUFFER, mVBO);
glBufferData(GL_ARRAY_BUFFER, (vertexData.size() + normalData.size()) * sizeof(float), NULL, GL_STATIC_DRAW);
glBufferSubData(GL_ARRAY_BUFFER, NULL, vertexData.size() * sizeof(float), &vertexData[0]);
glBufferSubData(GL_ARRAY_BUFFER, vertexData.size() * sizeof(float), normalData.size() * sizeof(float), &normalData[0]);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mIndexBuffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indexData.size() * sizeof(uint32_t), &indexData[0], GL_STATIC_DRAW);

glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, (GLvoid*)(vertexData.size() * sizeof(float)));

// unbind array buffer and VAO
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);

```

So for the vertex and normals I first allocate the complete buffer using glBufferData and then fill it in using glBufferSubData. My question then is, according to the docs, do I need to align the offset my normal data, and if so with what? Is this what couldve caused some meshes to draw incorrectly?

# Answer
First of all that quote you give doesn't really apply to `glBufferSubData` itself, but to the actual buffer data at a whole when used (by whatever GL functions that actually work on the buffer object, like drawing from a VBO), since `glBufferSubData` doesn't have any notion of any multi-byte data types yet, it just copies a bunch of bytes around. Only when doing something meaningful with the buffer data (e.g. using it as vertex attribute source) you finally give meaning (and corresponding alignment requirements) to the data.

So in your case you have a buffer that you use as an array of 3-component 32-bit float vectors (as specified by the `glVertexAttribPointer` calls). So both your position and normal data (and the corresponding offsets specified in `glVertexAttribPointer`) have to be properly aligned at `GLfloat` boundaries, which they already are (given that *GL*'s `GL_FLOAT` type has the same size and alignment as *C++*'s `float` type, which is virtually always the case). So you don't have to worry about alignment issues in your example and your errors are caused by something else.
> 4 votes

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


title: Java looking in wrong directory for XML

text:
# Question
Title: Java looking in wrong directory for XML
I found this suggestion on a Stack Exchange site to print out what the current directory is:

```
File file = new File(".");
for(String fileNames : file.list())
    System.out.println(fileNames);

```

Basically, when I run a game in Eclipse, I get this:

But when I compile the game and run it, it prints out this (it prints out the stuff that is in the same directory as the JAR file is). Images, and sound are working fine. It's just the XML file that is causing this.

How do I make Java read XML files from res folder like it does for images and sound in Eclipse?

My particular code that loads the XML is at http://pastebin.com/59Nt7Dtd.

Slick2D documentation is at http://www.slick2d.org/javadoc/.

# Answer
The reason why it works in Eclipse is because you are in the project root when you do this:

```
particleImage = new Image("res/particles/particle.png", false);

```

For consistency, put your XML file there as well or if you don't want to run it from Eclipse, but from a JAR, integrate an absolute data path in your code (do not hardcode it in your source files).
> 4 votes

# Answer
```
 path="/res/particles/file.xml";
 emitter = ParticleIO.loadEmitter(path);

```

This fixed the problem thanks to Cristina
> 0 votes

---
Tags: java, slick
---


# Question
Title: Calling CCRepeaForever on CCLabelTTF Makes Label Not Show Up
I have a CCLabelTTF in the top right hand corner of the view.

```
-(void)scrollScoreLabelAndMonkey{
scoreLabel = [CCLabelTTF labelWithString:@"0000" fontName:@"Marker Felt"
fontSize:30 ];
scoreLabel.position=ccp(420,300);
scoreLabel.color = ccGREEN;
[self addChild:scoreLabel];
}

```

I simply add this code to the bottom of the above method. However as soon as i add this line, the label doesnt show up at all.

```
id moveScore = [CCMoveBy actionWithDuration:.7 position:ccp(scoreLabel.position.x + 10, 0)];
CCRepeatForever *scrollScoreLabel = [CCRepeatForever actionWithAction:moveScore];
[scoreLabel runAction:scrollScoreLabel];

```

Any help is greatly appreciated!

# Answer
> 1 votes
The problem is that you are moving the label to the right (420+10 points). I don't know what do you want to achieve with this action but basically you are continuously moving the label to the right. If you don't understand, change the duration of the animation to something like 2 and you will see the problem.

---
Tags: iphone, ios, cocos2d-iphone
---


# Question
Title: How can I access game instance data in a window procedure callback?
In the window procedure message processing function, I have come across a couple of things where I just have no idea what to do apart from declare a class globally so that my window procedure can see it.

Imagine I have a `Game` class that is created in the window loop function and has a handle to the window passed through into it:

```
class Game
{
    game( HWND hWnd );
    void Go();
    void ReCalculateViewportOffsets();
}

...// windows stuff and handle to window created
Game theGame( hWnd );
...// windows loop starts
theGame.Go();

```

Half-way through my game, someone changes the resolution so I need to fire a redraw with new offsets to center my viewport... I would like to call that from my `WM_RESIZE` handler, but `theGame` has been declared as a local in my main function rather than a global. Probably a good thing? but how on earth can I get hold of `theGame` in my windows procedure function without declaring it globally:

```
case "WM_RESIZE":
    //...
    theGame.ReCalculateViewportOffsets( newWidth, newHeight );

```

# Answer
There is no need to declare the game instance as a global, fortunately.

Windows allows you to store extra "user data" alongside each window instance you create, and you can subsequently access that data any time you have a handle to that window (which you do in your window procedure).

The functions you'll want to use are SetWindowLongPtr and GetWindowLongPtr. These functions retrieve a pointer-sized chunk of data associated with the window -- you'll probably want to use them with the `GWLP_USERDATA` constant to access the specific pointer-sized chunk of memory reserved by the window system for *your* use.

If you need to store more than a pointer-sized chunk of data, you can request extra storage bytes during the creation of your window's window class by filling out the `cbWndExtra` parameter in the class definition structure when you call RegisterClassEx. However, it sounds like `GWLP_USERDATA` will be sufficient for your needs.

So, in summary:

* Create your `HWND`.
* Use `SetWindowLongPtr` with `GWLP_USERDATA` to store a pointer to your `Game`.
* User `GetWindowLongerPtr` to recover that pointer later.

It's also possible to pass a pointer-sized chunk of data to the window when you create it via CreateWindowEx. That pointer-sized chunk of data will be passed to the window procedure via the `WM_CREATE` message (and that will happen before `CreateWindowEx` returns), so you can use that to store data with the window as well.
> 3 votes

---
Tags: c++, windows
---


# Question
Title: Should many constants utilize constant variables or a database?
If you decide to design some sort of in-depth customization system for the player that utilizes a ton of different options, would you be better off using SQLite or just a whole bunch of constant variables in the program?

For instance, let's say you want the player to be able to build their own weapons. For a sword, they can put together a hilt, a blade, and maybe a jewel and inscription. That's 4 parts, of which there can be many different options, and that's just for one weapon. For the sake of example, let's say there are hundreds of different parts alone, which makes for a great number of combinations. The parts themselves are of course just weapon components, and don't have any special properties that need to be programmed - just certain attributes that say how they interact with the weapons (like which ones they can be attached to) and how they interact with other parts (if there is a special effect when combined with other ones, for instance - though this is probably better off programmed).

Presumably, this would allow for a great deal of customization, so there would be an in-game system in place that would allow the player to easily search for parts of a certain type/with a certain effect/of a certain element/etc. by using search filters, which sounds perfect for a database and not-so-perfect for program variables.

As a general question, how do you know when it is time to manage all of your constants through a database as opposed to doing it through the program? Is it the number of your variables? How valuable search/sort is? Will using a database quicken or slow the performance of these customization options?

# Answer
> 3 votes
There's a third option, one between "constants in the program" and "data in a database," and that's data in regular old files on the disk (for example, JSON files).

If the primary operations you are going to be doing here are (1) editing the data files and (2) loading all the data into memory, you don't really need to employ the additional complexity of a database; you don't need the additional complicated query functionality and that way you won't have to manage the additional overhead of the table schema or deployment problems (for non-trivial games). If your searches are simple enough (it sounds like they are primarily compatibility-matching searches), you can do them easily enough without a SQL query.

Although SQLite specifically is a compact exception, many database solutions are overkill for this kind of simple data-driven game data problem.

Even if you opt to put the data into SQLite or some other database eventually, moving to a file-based approached first might be a good stepping stone as it will allow you to reduce the scope of the overall change slightly, letting you get your work done in smaller chunks.

As for knowing when to put things in data versus code... it's almost always better to put them in data, unless you have a really trivial project. What kind of data format you use depends heavily on the kind of project, and often a really good data-driven architecture (that supports awesome things like live-edit loops and cascading hot-reloads) can be more work up front, but in the long it's usually far more efficient.

The value of searching and sorting depends, again, on the way your game will use that data. It's really rare, in my experience, that you'll want the user to be given an interface (of any kind) to a search that is complex enough to warrant SQL. However, if the data you are tracking is analytical in nature, for example, if you are tracking events users perform in an online game and you'll need to query that data after-the-fact to discover user trends and help tune your design decisions... in that case complex queries are a good thing and you can justify the extra complexity of a database backing store. But then again, that's not constant data we're talking about.

# Answer
> 0 votes
Go with your SQLite idea. You'll find that it's very easy to integrate and use, plus much faster than you would think.

First reason is that you can add new "stuff" just by editing the database and your code never has to change, this makes tweaking and updating end users much simpler. Plus even a non-programmer can adjust these things, which is great since you will have a ton of them.

Second reason is that organizing data is kind of what databases do, why reinvent the wheel?

Third reason is that SQLite is great at "give me all the sword hilts that are red colored and require \> level 25 to use" whereas your own code... why reinvent the wheel?

The decision point on when to convert from in-program data and external data mostly ties into the above reasons: how much data do I have to wrangle? how often will I need to update the variables? will I need to organize? and how do I find what I need at runtime?

Here's the neat thing, once you start thinking "data driven" many tasks become simpler. Your programs will become more flexible, your designs more dynamic, and so on.

---
Tags: databases
---


# Question
Title: How do I determine if one value is within a certain range of another in Python
I've been working on the attacking in my RPG. The problem I have recently encountered is, I have to be in **Exactly** the same x coordinate as the Enemy. When I want to attack the enemy this is what happens:

```
 ...

    elif event.key == pygame.K_SPACE:
                    attack = True

if attack == True:
    if enx == x: #this is the line my qeustion is about
        endead = True

attack = False # I put this in so attack doesn't stay true forever

...

if endead == False:
            screen.blit(Enemy, [enx, eny])

```

How do I make it work if the enemy's position (enx) is equal to within a certain number of pixels to the player's position (x)?

So if I'm close but not Exactly the same place it works

(I know this only takes the x coords into account I'll add y later)

# Answer
> 4 votes
You are probably looking for the absolute value!

You can implement it like this:

```
def abs(value):
    if value < 0:
        return -value
    else:
        return value

```

You can use it like this:

```
radius = 20
if abs(playerPositionX - enemyPositionX) < radius:
  enemyCollidesWithPlayer()

```

However, if your game is in 2D, and you wish to find the circular radius you can calculate the Euclidean distance (distance from origin to point A) to your target like this:

```
radius = 20 # value is in pixels, but you can modify it to fit your needs
if (sqrt((playerPositionX - enemyPositionX)**2 +
         (playerPositionY - enemyPositionY)**2)) < radius:
  enemyCollidesWithPlayer()

```

This is what is used in the above code:

The calculation `sqrt((playerX - enemyX)**2 + (playerY - enemyY)**2)` above is the distance between the player object and the enemy object (it is actually an application of the Pythagorean Theorem!). The green circle is the `radius`, it can be represented as a single number (the length from the origin to the border of the circle). After we have calculated the distance we can check if it is less than the radius. If it is, we know there is a collision between the two objects!

For an easy to understand explanation you can read this!

If you want to optimize your code, you can do the calculation like this instead:

```
radius = 20
if ((playerX - enemyX)**2 + (playerY-enemyY)**2) < (radius**2):
    enemyCollidesWithPlayer()

```

which saves the number of instructions that the computer has to perform because you don't have to use the somewhat costly sqrt() function!

---
Tags: python, rpg, pygame
---


title: Broadcasting terrain data

text:
# Question
Title: Broadcasting terrain data
How can i send from server to client a large amount of tile data? Having chunks of almost 2MB of data seems prohibitive to send this information just like that. Minecraft compress each chunk and Terraria uses RLE, but im not sure if they send so much information.

# Answer
There's a few strategies you can employ:

1. **Break the data into chunks**. This allows you to only send what's needed by the client (as mentioned in Elviss's answer). This will also be useful to implement for many other aspects of the terrain.
2. **Use the organization of the data to your benefit**. You don't need to have labels for all your data. The client should always be expecting the data in the same order, so it knows what the next bytes belong to. For example, the client should always expect two bytes for tile type, two bytes for lighting information and then two bytes for extra info. So it knows that after 6 bytes, it's time to move onto the next tile.
3. **Don't send position information, it should be implied in the tile order**. Always send the tile information in chunks, one column at a time (or one row at a time). This allows your client to know the position of the next tile, without needing to read it from the byte stream. You send the starting position of the chunk, then the first tile is placed at the position. The client then knows the second tile will be placed at the chunk position plus one in the Y direction (if sending column per column).
> 5 votes

# Answer
You can divide your map into regions, generate them procedurally and send only the parameters of each of them to clients. For example, if there is a mountain somewhere on terrain that is being seen by player, you can send parameters of the mountain (like height, radius, angle of slopes etc.). This is a little bit tricky to manage (you will have to modify your terrain editor to allow creating terrain that can be generated procedurally), but will reduce the amount of data needed to generate the terrain on clients' machines.
> 3 votes

---
Tags: networking, maps
---


title: Pong pygame problem

text:
# Question
Title: Pong pygame problem
I've been following a tutorial to make my first Pong clone. Here is the tutorial: http://muagames.com/tutorials/pygame-3-pong/pygame-3-pong-step-1/

When I try to run it I get this error message:

> Traceback (most recent call last): File "/Users//Documents/Pygame/pong2.py", line 133, in game = Game() File "/Users//Documents/Pygame/pong2.py", line 66, in **init** self.sprites.add(self.leftpaddle) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pygame/sprite.py", line 319, in add sprite.add\_internal(self) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pygame/sprite.py", line 147, in add\_internal self.\__g\[group\] = 0 AttributeError: 'Paddle' object has no attribute '*Sprite*\_g'

I could not figure out why, my code looks pretty much the same as the one in the tutorial.

```
    # Pong V2 OOP
import pygame, sys, random, os, math
from pygame.locals import *

class Paddle(pygame.sprite.Sprite):
    def __init__(self, xy):
        #initialize the pygame sprite part
        self.image = pygame.image.load(os.path.join('images','pong_paddle.gif'))
        self.rect = self.image.get_rect()

        #set position
        self.rect.centerx, self.rect.centery = xy

        #movement speed of paddle
        self.movementspeed = 5

        #current velocity
        self.velocity = 0

    def up(self):
        self.velocity -= self.movementspeed

    def down(self):
        self.velocity += self.movementspeed

    def move(self, dy):
        if self.rect.bottom + dy > 400:
            self.rect.bottom = 400
        elif self.rect.top + dy < 0:
            self.rect.top = 0
        else:
            self.rect.y += dy

    def update(self):
        self.move(self.velocity)

class Game(object):
    def __init__(self):
        pygame.init()

        self.screen = pygame.display.set_mode((800,400),0,32)

        pygame.display.set_caption('Pong V2')
        self.clock = pygame.time.Clock()

        pygame.event.set_allowed([QUIT, KEYDOWN, KEYUP])

        # set background:
        self.background = pygame.Surface((800,400))
        self.background.fill((255,255,255))

        # draw line in middle
        pygame.draw.line(self.background, (0,0,0), (400,0), (400,400), 2)
        self.screen.blit(self.background, (0,0))

        pygame.display.flip()

        # a sprite rendering group for our ball and paddles
        self.sprites = pygame.sprite.RenderUpdates()

        # create our paddles and add to sprite group
        self.leftpaddle = Paddle((50,200))
        self.sprites.add(self.leftpaddle)
        self.rightpaddle = Paddle((750,200))
        self.sprites.add(self.rightpaddle)

    def run(self):
        print('Starting Event Loop')

        running = True

        while running:
            self.clock.tick(60)

            running = self.handleEvents()

            #Update title with fps
            pygame.display.set_caption('Pygame Tutorial 2 - Basic   %d fps' % self.clock.get_fps())

            # update sprites
            for sprite in self.sprites:
                sprite.update()

            # render sprites
            self.sprites.clear(self.screen, self.background)
            dirty = self.sprites.draw(self.screen)

            # blit
            pygame.display.update(dirty)

        print('Quitting, thanks for playing!')
        pygame.quit()
        sys.exit()

    def handleEvents(self):

        # poll for events
        for event in pygame.event.get():
            if event.type == QUIT:
                return False
            elif event.type == KEYDOWN:
                if event.key == K_ESCAPE:
                    return False

                # paddle control
                if event.key == K_UP:
                    self.rightpaddle.up()
                if event.key == K_DOWN:
                    self.rightpaddle.down()
                if event.key == K_w:
                    self.leftpaddle.up()
                if event.key == K_s:
                    self.leftpaddle.down()
            elif event.type == KEYUP:
                # paddle control
                if event.key == K_w:
                    self.leftpaddle.down()
                if event.key == K_s:
                    self.leftpaddle.up()

                if event.key == K_UP:
                    self.rightpaddle.down()
                if event.key == K_DOWN:
                    self.rightpaddle.up()

        return True

if __name__ == '__main__':
    game = Game()
    game.run()

```

Can anyone help me?

# Answer
Look here: http://www.nongnu.org/pygsear/doc/api\_html/private/pygame.sprite.Sprite-class.html

> When you subclass Sprite, you must call this pygame.sprite.Sprite.\__init\__(self) before you add the sprite to any groups, or you will get an error.

That seems to be what is missing in order to make `Paddle` a proper subclass of `Sprite`.
> 3 votes

---
Tags: python, pygame
---


# Question
Title: Formula for converting ratio of current device to target device
I am designing my (Android/OpenGL ES 2.0) app on one device and want it to run all all other devices while keeping the screen ratio of the development device (so the image doesn't stretch / squash), by altering the GLViewport ratio of the current device to match the development device, thus having either pillarboxing or letterboxing.

The only values I know for sure, are the physical screen ratio of the development device (in landscape) and the current device (regardless of orientation).

Please refer to my other question (which was regarding centering the viewport once I'd set it's size here: Centering GLViewport position within physical screen ) - on further study I see that my maths is somewhat incorrect (maybe too simplistic?) and the viewport doesn't seem to be getting sized correctly on all targets.

Is there a 'formula' for doing what I'm trying to do?

I get my ratio by doing the following:

```
float ratio = width / height;

```

Then I simply want to set my viewport like so:

```
GLES20.glViewport(0+offsetX, 0-offsetY, widthToUse, heightToUse);

```

The offsetX and Y values I think I'm OK with as per my previous Q. It's the 'widthToUse' and 'HeightToUse' that I can't seem to work out properly.

You can see from my other question, that I'm working out the 'widthToUse' value my multiplying the *current device's height* by the \[development devices\] ratio. However, this doesn't work on all devices as the resulting figure could actually be larger (wider) than the physical screen.

Here are some examples of what I'm trying to achieve, for illustration (ratio's much exaggerated here)

In the pics, the black outter-box is the physical screen of the devices and the blue square is the viewport.

***Side note:*** I realise that my game will most likely be locked to a particular orientation (the one I'm currently developing will, eventually be locked to landscape mode) so I probably don't *need* to handle orientation changes, however, I would like to know, if possible, how to display at a particular ratio in either orientation in case this is required in the future. So in other words, I may develop an app for landscape, but 'allow' it to run in portrait (albeit with large letterboxing).

Also I know there are similar questions on here, but I've read them over and over and they either don't apply to my situation (or way of doing things), or I'm otherwise not able to get my answer from them.

# Answer
> 2 votes
Pretty simple, there are two candidate solutions, one where the full width is used and one where the full height is used, you must always pick the smaller of those:

```
widthToUse = Math.min(screenWidth, screenHeight * ratio)
heightToUse = Math.min(screenHeight, screenWidth / ratio)
offsetX = (screenWidth - widthToUse) / 2
offsetY = (screenHeight - heightToUse) / 2

```

# Answer
> 0 votes
I'm using code similar to the following:

```
public static final float NOMINAL_WIDTH = 1700;
public static final float NOMINAL_HEIGHT = 1000;
public static final float NOMINAL_ASPECT_RATIO = NOMINAL_WIDTH/NOMINAL_HEIGHT;

float aspectRatio = width / height;
if (aspectRatio < NOMINAL_ASPECT_RATIO) {
    viewportHeight = height;
    viewportWidth = width/height*NOMINAL_HEIGHT;
} else { // aspectRatio >= NOMINAL_ASPECT_RATIO
    viewportHeight = height/width*NOMINAL_WIDTH;
    viewportWidth = width;
}

```

---
Tags: android, screen, aspect-ratio, viewport, screen-management
---


# Question
Title: Jogl2 won't accept jogl 1.0 code - GL_LIGHTING and GL_LIGHT_MODEL_AMBIENT cannot be resolved or is not a field?
I'm trying to run my code on jogl 2.0 , for the first time (until now I worked with jogl 1.0) however Eclipse throws to almost every that I have a "cannot be resolved or is not a field" message .

The files that are in the library of the jogl 2.0 are :

```
gluegen-rt.jar
jogl-all.jar
gluegen-rt.dll
joal.dll
jocl.dll
jogl_cg.dll
jogl_desktop.dll
jogl_mobile.dll
nativewindow_awt.dll
nativewindow_win32.dll
newt.dll

```

And the code is pretty simple :

```
import javax.media.opengl.GL;
import javax.media.opengl.GLAutoDrawable;
import javax.media.opengl.awt.GLCanvas;
import javax.media.opengl.GLCapabilities;
import javax.media.opengl.GLEventListener;
import javax.media.opengl.glu.GLU;
import javax.media.opengl.glu.GLUquadric;
import javax.swing.JFrame;
import com.jogamp.opengl.util.Animator;

public class Practice10IlluminateSphere extends JFrame implements KeyListener{

    private static float deltaZ=0;

    float t=0;

    public static void main(String[] args) {
        Practice10IlluminateSphere frame=new Practice10IlluminateSphere();
        frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
        frame.setVisible(true);
    }

    public Practice10IlluminateSphere(){
        setSize(600,600);
        setTitle("Hello Universe");

        GraphicListener listener=new GraphicListener();
        GLCanvas canvas = new GLCanvas(new GLCapabilities());
        canvas.addGLEventListener(listener);
        getContentPane().add(canvas);

        Animator animator = new Animator(canvas);
        animator.start();

        addKeyListener(this);
    }

    public class GraphicListener implements GLEventListener{

        public void display(GLAutoDrawable arg0) {

            GL gl=arg0.getGL();
            gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT);

            gl.glEnable(GL.GL_DEPTH_TEST);
            gl.glCullFace(GL.GL_FRONT);
            gl.glEnable(GL.GL_CULL_FACE);
            gl.glFrontFace(GL.GL_CCW);

            GLU glu=new GLU();
            GLUquadric quadric=glu.gluNewQuadric();
            glu.gluQuadricNormals(quadric, GL.GL_TRUE);

            gl.glLoadIdentity();
            gl.glTranslatef(-0.5f,0,0);

                gl.glColor3f(0.7f,1,0.7f);
                glu.gluSphere(quadric, 0.5f, 90, 90);

            gl.glLoadIdentity();
            gl.glTranslatef(0.5f,0,deltaZ);

                gl.glColor3f(1,0.7f,0.7f);
                glu.gluSphere(quadric, 0.4f, 90, 90);

            t+=0.05f;
            float position3[]= {(float)(Math.cos(t)),-1.0f,0,1};
            gl.glLightfv(GL.GL_LIGHT2, GL.GL_POSITION, position3, 0);

        }

        public void displayChanged(GLAutoDrawable arg0, boolean arg1, boolean arg2) {

        }

        public void init(GLAutoDrawable arg0) {

            GL gl=arg0.getGL();
            gl.glEnable(GL.GL_LIGHTING);

            float ambient[]= {0.2f,0.2f,0.2f,1};
            gl.glLightModelfv(GL.GL_LIGHT_MODEL_AMBIENT , ambient,0);

            gl.glEnable(GL.GL_LIGHT2);
            float position3[]= {1.0f,0.0f,0.0f,1};
            gl.glLightfv(GL.GL_LIGHT2, GL.GL_POSITION, position3, 0);
            float intensity3[]= {1,1,0,1};
            gl.glLightfv(GL.GL_LIGHT2, GL.GL_DIFFUSE, intensity3, 0);
            gl.glLightf(GL.GL_LIGHT2,GL.GL_LINEAR_ATTENUATION,0.9f);
            gl.glLightf(GL.GL_LIGHT2,GL.GL_CONSTANT_ATTENUATION,0.9f);
            gl.glLightf(GL.GL_LIGHT2,GL.GL_QUADRATIC_ATTENUATION,0.9f);

            gl.glEnable(GL.GL_LIGHT3);
            float position4[]= {1.0f,1.0f,1.0f,1};
            gl.glLightfv(GL.GL_LIGHT3, GL.GL_POSITION, position4, 0);
            float intensity4[]= {1,1,0,1};
            gl.glLightfv(GL.GL_LIGHT3, GL.GL_DIFFUSE, intensity4, 0);
            float dir4[]= {-1.0f,-1.0f,-1.0f,1};
            gl.glLightfv(GL.GL_LIGHT3, GL.GL_SPOT_DIRECTION, dir4, 0);
            gl.glLightf(GL.GL_LIGHT3, GL.GL_SPOT_CUTOFF, 50);
            gl.glLightf(GL.GL_LIGHT3, GL.GL_SPOT_EXPONENT, 50);

//          gl.glEnable(GL.GL_COLOR_MATERIAL);
//          gl.glColorMaterial(GL.GL_FRONT_AND_BACK, GL.GL_AMBIENT_AND_DIFFUSE);
            float specColor[]= {1,1,1,1};
            gl.glMaterialfv(GL.GL_FRONT_AND_BACK,GL.GL_SPECULAR, specColor,0);
            gl.glMaterialf(GL.GL_FRONT_AND_BACK,GL.GL_SHININESS, 80);
            GL.gl_
        }

        public void reshape(GLAutoDrawable arg0, int arg1, int arg2, int arg3, int arg4) {

        }
    }

    public void keyPressed(KeyEvent arg0) {
        if(arg0.getKeyCode()==KeyEvent.VK_A){
            deltaZ+=0.05;
        }
        if(arg0.getKeyCode()==KeyEvent.VK_B){
            deltaZ-=0.05;
        }
    }

    public void keyReleased(KeyEvent arg0) {

    }

    public void keyTyped(KeyEvent arg0) {

    }

    static final long serialVersionUID=100;
}

```

And when I try the compile it , here are some of the problems , the **short version** :

```
GL_DIFFUSE cannot be resolved or is not a field

GL_LIGHT0 cannot be resolved or is not a field

The method glVertex3f(int, float, int) is undefined for the type GL

The method glEnd() is undefined for the type GL

GL_LIGHTING cannot be resolved or is not a field

GL_LIGHT0 cannot be resolved or is not a field

GL_LIGHT1 cannot be resolved or is not a field

```

and more ... here is the **long version** :

```
Description Resource    Path    Location    Type
The method glLoadIdentity() is undefined for the type GL    Practice10IlluminateSphere.java /TESTING_opengl/src line 83 Java Problem
The type Practice10IlluminateSphere.GraphicListener must implement the inherited abstract method GLEventListener.dispose(GLAutoDrawable)    Practice10IlluminateSphere.java /TESTING_opengl/src line 64 Java Problem
The method glColor3f(float, int, float) is undefined for the type GL    Practice10IlluminateSphere.java /TESTING_opengl/src line 86 Java Problem
The method glTranslatef(float, int, int) is undefined for the type GL   Practice10IlluminateSphere.java /TESTING_opengl/src line 84 Java Problem
The method glTranslatef(float, int, float) is undefined for the type GL Practice10IlluminateSphere.java /TESTING_opengl/src line 90 Java Problem
The method glLoadIdentity() is undefined for the type GL    Practice10IlluminateSphere.java /TESTING_opengl/src line 89 Java Problem
GL_LIGHT2 cannot be resolved or is not a field  Practice10IlluminateSphere.java /TESTING_opengl/src line 98 Java Problem
The method glColor3f(int, float, float) is undefined for the type GL    Practice10IlluminateSphere.java /TESTING_opengl/src line 92 Java Problem
GL_LIGHTING cannot be resolved or is not a field    Practice10IlluminateSphere.java /TESTING_opengl/src line 109    Java Problem
GL_POSITION cannot be resolved or is not a field    Practice10IlluminateSphere.java /TESTING_opengl/src line 98 Java Problem
GL_LIGHT2 cannot be resolved or is not a field  Practice10IlluminateSphere.java /TESTING_opengl/src line 114    Java Problem
GL_LIGHT_MODEL_AMBIENT cannot be resolved or is not a field Practice10IlluminateSphere.java /TESTING_opengl/src line 112    Java Problem
GL_POSITION cannot be resolved or is not a field    Practice10IlluminateSphere.java /TESTING_opengl/src line 116    Java Problem
GL_LIGHT2 cannot be resolved or is not a field  Practice10IlluminateSphere.java /TESTING_opengl/src line 116    Java Problem
GL_DIFFUSE cannot be resolved or is not a field Practice10IlluminateSphere.java /TESTING_opengl/src line 118    Java Problem
GL_LIGHT2 cannot be resolved or is not a field  Practice10IlluminateSphere.java /TESTING_opengl/src line 118    Java Problem
The method glVertex3f(float, int, float) is undefined for the type GL   Practice11IlluminateGeometry.java   /TESTING_opengl/src line 105    Java Problem
GL_LIGHT2 cannot be resolved or is not a field  Practice10IlluminateSphere.java /TESTING_opengl/src line 119    Java Problem
The method glVertex3f(int, int, int) is undefined for the type GL   Practice11IlluminateGeometry.java   /TESTING_opengl/src line 104    Java Problem
GL_LINEAR_ATTENUATION cannot be resolved or is not a field  Practice10IlluminateSphere.java /TESTING_opengl/src line 119    Java Problem
The method glNormal3f(int, int, int) is undefined for the type GL   Practice11IlluminateGeometry.java   /TESTING_opengl/src line 103    Java Problem
GL_LIGHT2 cannot be resolved or is not a field  Practice10IlluminateSphere.java /TESTING_opengl/src line 120    Java Problem
The method glBegin(int) is undefined for the type GL    Practice11IlluminateGeometry.java   /TESTING_opengl/src line 101    Java Problem
GL_CONSTANT_ATTENUATION cannot be resolved or is not a field    Practice10IlluminateSphere.java /TESTING_opengl/src line 120    Java Problem
The method glColor3f(int, int, int) is undefined for the type GL    Practice11IlluminateGeometry.java   /TESTING_opengl/src line 100    Java Problem
GL_LIGHT2 cannot be resolved or is not a field  Practice10IlluminateSphere.java /TESTING_opengl/src line 121    Java Problem
The method glTranslatef(float, float, float) is undefined for the type GL   Practice11IlluminateGeometry.java   /TESTING_opengl/src line 98 Java Problem
GL_QUADRATIC_ATTENUATION cannot be resolved or is not a field   Practice10IlluminateSphere.java /TESTING_opengl/src line 121    Java Problem
The method glLoadIdentity() is undefined for the type GL    Practice11IlluminateGeometry.java   /TESTING_opengl/src line 97 Java Problem
GL_LIGHT3 cannot be resolved or is not a field  Practice10IlluminateSphere.java /TESTING_opengl/src line 123    Java Problem
The type Practice11IlluminateGeometry.GraphicListener must implement the inherited abstract method GLEventListener.dispose(GLAutoDrawable)  Practice11IlluminateGeometry.java   /TESTING_opengl/src line 83 Java Problem
GL_LIGHT3 cannot be resolved or is not a field  Practice10IlluminateSphere.java /TESTING_opengl/src line 125    Java Problem
Animator cannot be resolved to a type   Practice11IlluminateGeometry.java   /TESTING_opengl/src line 77 Java Problem
GL_POSITION cannot be resolved or is not a field    Practice10IlluminateSphere.java /TESTING_opengl/src line 125    Java Problem
Animator cannot be resolved to a type   Practice11IlluminateGeometry.java   /TESTING_opengl/src line 77 Java Problem
GL_LIGHT3 cannot be resolved or is not a field  Practice10IlluminateSphere.java /TESTING_opengl/src line 127    Java Problem
The constructor GLCapabilities() is undefined   Practice11IlluminateGeometry.java   /TESTING_opengl/src line 73 Java Problem
GL_DIFFUSE cannot be resolved or is not a field Practice10IlluminateSphere.java /TESTING_opengl/src line 127    Java Problem
GLCanvas cannot be resolved to a type   Practice11IlluminateGeometry.java   /TESTING_opengl/src line 73 Java Problem
GL_LIGHT3 cannot be resolved or is not a field  Practice10IlluminateSphere.java /TESTING_opengl/src line 129    Java Problem
GLCanvas cannot be resolved to a type   Practice11IlluminateGeometry.java   /TESTING_opengl/src line 73 Java Problem
GL_SPOT_DIRECTION cannot be resolved or is not a field  Practice10IlluminateSphere.java /TESTING_opengl/src line 129    Java Problem
The import com.sun.opengl cannot be resolved    Practice11IlluminateGeometry.java   /TESTING_opengl/src line 31 Java Problem
GL_LIGHT3 cannot be resolved or is not a field  Practice10IlluminateSphere.java /TESTING_opengl/src line 130    Java Problem
The import javax.media.opengl.GLCanvas cannot be resolved   Practice11IlluminateGeometry.java   /TESTING_opengl/src line 26 Java Problem
GL_SPOT_CUTOFF cannot be resolved or is not a field Practice10IlluminateSphere.java /TESTING_opengl/src line 130    Java Problem
GL_LIGHT3 cannot be resolved or is not a field  Practice10IlluminateSphere.java /TESTING_opengl/src line 131    Java Problem
Syntax error, insert "AssignmentOperator Expression" to complete Expression Practice10IlluminateSphere.java /TESTING_opengl/src line 139    Java Problem
GL_SHININESS cannot be resolved or is not a field   Practice10IlluminateSphere.java /TESTING_opengl/src line 138    Java Problem
GL_SPECULAR cannot be resolved or is not a field    Practice10IlluminateSphere.java /TESTING_opengl/src line 137    Java Problem
GL_SPOT_EXPONENT cannot be resolved or is not a field   Practice10IlluminateSphere.java /TESTING_opengl/src line 131    Java Problem
gl_ cannot be resolved or is not a field    Practice10IlluminateSphere.java /TESTING_opengl/src line 139    Java Problem
Syntax error, insert ";" to complete Statement  Practice10IlluminateSphere.java /TESTING_opengl/src line 139    Java Problem
GL_POSITION cannot be resolved or is not a field    Practice11IlluminateGeometry.java   /TESTING_opengl/src line 128    Java Problem
GL_LIGHT0 cannot be resolved or is not a field  Practice11IlluminateGeometry.java   /TESTING_opengl/src line 130    Java Problem
GL_DIFFUSE cannot be resolved or is not a field Practice11IlluminateGeometry.java   /TESTING_opengl/src line 130    Java Problem
GL_LIGHT1 cannot be resolved or is not a field  Practice11IlluminateGeometry.java   /TESTING_opengl/src line 132    Java Problem
GL_LIGHT1 cannot be resolved or is not a field  Practice11IlluminateGeometry.java   /TESTING_opengl/src line 134    Java Problem
GL_POSITION cannot be resolved or is not a field    Practice11IlluminateGeometry.java   /TESTING_opengl/src line 134    Java Problem
GL_LIGHT1 cannot be resolved or is not a field  Practice11IlluminateGeometry.java   /TESTING_opengl/src line 136    Java Problem
GL_DIFFUSE cannot be resolved or is not a field Practice11IlluminateGeometry.java   /TESTING_opengl/src line 136    Java Problem
The method glVertex3f(int, float, int) is undefined for the type GL Practice11IlluminateGeometry.java   /TESTING_opengl/src line 106    Java Problem
The method glVertex3f(float, float, float) is undefined for the type GL Practice11IlluminateGeometry.java   /TESTING_opengl/src line 107    Java Problem
The method glVertex3f(float, float, int) is undefined for the type GL   Practice11IlluminateGeometry.java   /TESTING_opengl/src line 108    Java Problem
The method glEnd() is undefined for the type GL Practice11IlluminateGeometry.java   /TESTING_opengl/src line 110    Java Problem
GL_LIGHTING cannot be resolved or is not a field    Practice11IlluminateGeometry.java   /TESTING_opengl/src line 121    Java Problem
GL_LIGHT_MODEL_AMBIENT cannot be resolved or is not a field Practice11IlluminateGeometry.java   /TESTING_opengl/src line 124    Java Problem
GL_LIGHT0 cannot be resolved or is not a field  Practice11IlluminateGeometry.java   /TESTING_opengl/src line 126    Java Problem
GL_LIGHT0 cannot be resolved or is not a field  Practice11IlluminateGeometry.java   /TESTING_opengl/src line 128    Java Problem
GL_SPECULAR cannot be resolved or is not a field    Practice11IlluminateGeometry.java   /TESTING_opengl/src line 138    Java Problem
The constructor GLCapabilities() is undefined   Practice10IlluminateSphere.java /TESTING_opengl/src line 54 Java Problem
GL_LIGHT1 cannot be resolved or is not a field  Practice11IlluminateGeometry.java   /TESTING_opengl/src line 138    Java Problem
GL_AMBIENT_AND_DIFFUSE cannot be resolved or is not a field Practice11IlluminateGeometry.java   /TESTING_opengl/src line 142    Java Problem
GL_COLOR_MATERIAL cannot be resolved or is not a field  Practice11IlluminateGeometry.java   /TESTING_opengl/src line 141    Java Problem
GL_SHININESS cannot be resolved or is not a field   Practice11IlluminateGeometry.java   /TESTING_opengl/src line 145    Java Problem
GL_SPECULAR cannot be resolved or is not a field    Practice11IlluminateGeometry.java   /TESTING_opengl/src line 144    Java Problem

```

So, what's wrong here ? I added all the relevant jars but still nothing that worked in jogl 1.0 , still works on jogl 2.0 . Why ?

Much appreciated

# Answer
jogl 2.0 have added profiles, this is important in order to support the new shader only based OpenGL contexts. The base GL class only contain functionality that is still common across all OpenGL profiles. http://jogamp.org/jogl/doc/Overview-OpenGL-Evolution-And-JOGL.html

To fix your code you first need to request a fixed function compatible profile. This is done in jogl 2 at the GLCapabilities constructor:

Example 1 to request a profile that is compatible with fixed functionality use:

```
GLCapabilities caps = new GLCapabilities(GLProfile.getMaxFixedFunc(true));

```

Example 2 to request a profile that is compatible with both desktop OpenGL 2 and mobile OpenGL ES 2 devices using the programmable pipeline use:

```
GLCapabilities caps = new GLCapabilities(GLProfile.get(GLProfile.GL2ES2));

```

Inside the GLEventListener functions you now need to specifically get the GL object that match functionality according to the profile you selected.

```
public class GraphicListener implements GLEventListener{
    public void display(GLAutoDrawable arg0) {
        GL2 gl=arg0.getGL().getGL2();

```

gl will now resolve all the missing methods for your application.
> 1 votes

---
Tags: java, graphics, graphics-programming, jogl
---


# Question
Title: I have a frag shader, one with an empty s_lightMap, how and why is it effecting the output?
I have an image of concrete rocks of different shades of colors, and I'm applying this shader, but **without referencing s\_lightMap's uniform in my program**:

```
        precision mediump float;
        varying vec2 v_texCoord;
        uniform sampler2D s_baseMap;
        uniform sampler2D s_lightMap;
        void main()
        {
          vec4 baseColor;
          vec4 lightColor;

          baseColor = texture2D( s_baseMap, v_texCoord );
          lightColor = texture2D( s_lightMap, v_texCoord );
          gl_FragColor = baseColor * (lightColor + 0.25);
        }

```

it displays a **picture with variable light color added** to the final pixel color, but s\_lightMap isn't even linked into the program, what is happening in this case, at first I thought it would just do the baseColor as the FragColor, but the addition of the 0.25 makes a non-negative result to (lightColor + 0.25). I'm confused, one minute I think lightColor would be set to a texture of 1's the next an array of 0's.

**Or is it just random data?** It **doesn't appear at all random in the picture**, it looks like it's obeying a rule of shading.

I'd like to mimic this effect in code that's not broken.

Here's the unshadded image:

Example "gimped" image of how it has variable shades (though this is an invert):

# Answer
After close inspection I found that the line:

```
gl_FragColor = baseColor * ( lightColor + 0.25 );

```

is probably exactly equal to:

```
gl_FragColor = baseColor * ( baseColor + 0.25 );

```

when uniform sampler2D s\_lightMap isn't being loaded into the program.

EDIT: This may or may not be because of the State Functionality of openGL es 2.0, but I wouldn't bet on using it.
> 0 votes

---
Tags: shaders, opengl-es2, fragment-shader
---


title: Generating terrain using Marching Cubes

text:
# Question
Title: Generating terrain using Marching Cubes
I searched around the web but I found nothing that could help me, so I'm asking here.

I'm trying to procedurally generate terrain using the marching cubes algorithm, and I can generate a mesh. The problem is that the mesh that may be anything!

https://www.dropbox.com/s/w99lvynrfra2a5v/question.JPG

As you can see in that screenshot, everything is messed up.

Is this a problem with the noise function? I'm using a simple Perlin noise function. How can I achive a result like this:

http://www.youtube.com/watch?v=-hJkrr5Slv8

If the problem is with the noise, what do I need to change to achieve this? I want to create natural terrain with hills, mountains, plains etc.

(I'm using Unity3D, but I don't think this makes any difference.)

# Answer
> 2 votes
I suggest scaling down the vertical component of the sample point before sampling the noise function.

The starting point of the voxel terrain in the video looks like a heightmap, so they may have multiplied the component by 0.

Also, you have to add the vertical component to the field function.

so your field function should look something like this:

```
const float noise_vertical_scale = 0.2;
const float field_vertical_scale = 0.01;
const float iso_surface = 0.5;

/*
 * returns field at point (pos):
 *     negative = inside
 *     0 = surface
 *     positive = outside
 */
float sampleField(vector3 pos)
{
    vector3 sample_pos = pos;
    sample_pos.y *= scale;
    return noise3D(sample_pos) + pos.y * field_height_scale - iso_surface;
}

```

Hope that helps.

# Answer
> 3 votes
The good news: your Marching Cubes algorithm looks just fine to me! That 3d surface reconstruction looks gorgeous. If you're committed to a voxel-based approach with isosurface visualization, you're off to a fine start.

The problem is that 3d noise in this form really isn't suitable for use with a Marching Cubes-type algorithm for terrain. If you want to be able to do the sort of terrain modification that the demo you point to does, what I would suggest is to build the heightmap *first* and then build your volumetric data based on the heightmap.

Building the heightmap in the first place is relatively straightforward; I'd just use one of the classic fractal methods. You can use an approach like square-diamond midpoint displacement (probably the most common), but I would encourage a Fourier-based approach instead because it should allow you a lot more control over how 'rolling' your terrain is (and you can always 'postfilter' by applying a gamma-type effect, e.g. setting h(x,y) -\> c\*h(x,y)^3 or h(x,y) -\> c\*sqrt(h(x,y)), to make the terrain more or less jagged - if you look at the early articles on fractal terrain you'll see a lot of this).

Once you've got your heightmap data, there are a bunch of different procedures for converting that information into volume data. For simplicity's sake I'll assume that your heightmap data has been stored at higher resolution than your voxel data has; this makes a lot of sense, since a 3d array with the same XY resolution would (obviously) have to be a lot larger than the 2d heightmap. The easiest way to do it is as simple as

```
for (0 < vx < VOXEL_X_RES) {
  for (0 < vy < VOXEL_Y_RES) {
    pick the closest point (x,y) on the heightmap corresponding to (vx,vy)
    (e.g. x = HEIGHTMAP_X_RES*vx/VOXEL_X_RES, etc)
    find the z value of the heightmap at (x,y) (and convert it to a voxel-space value vz)
    fill every value below (vx, vy, vz) with 1 to indicate it's in the terrain
    fill every value above (vx, vy, vz) with 0
  }
}

```

Because this fills the voxel array with only 0s and 1s, it can mean that the marching cubes interpolation along edges looks a little too 'regular' and results in surfaces with too many identical slopes on them. Instead, you may want to 'subsample' the heightmap to build your voxel array, using something like:

```
for (0 < vx < VOXEL_X_RES) {
  for (0 < vy < VOXEL_Y_RES) {
    find all 'pixels' on the heightmap corresponding to (vx,vy)
    for ( 0 < vz < VOXEL_Z_RES) {
      compute how many of the pixels in the set above have z > vz
      set the value of the voxel array at (vx, vy, vz) to the proportion of pixels with z > vz
    }
  }
}

```

The set of pixels on the heightmap for this second version can be anything from a straight subsampled grid (i.e., find `hxmin = HEIGHTMAP_X_RES*vx/VOXEL_X_RES` and `hxmax = HEIGHTMAP_X_RES*(vx+1)/VOXEL_X_RES`, similarly for `hymin` and `hymax`, and consider all pixels `(hx, hy)` with `(hxmin <= hx < hxmax)` and `(hymin <= hy < hymax)` ) to an 'overlapping samples' approach where you look at every heightmap-pixel within a circle centered around wherever (vx, vy) maps to on the heightmap; you could even subsample your heightmap and interpolate between heightmap pixels for finer detail.

One major caveat with this whole approach is that fractal terrain isn't really very 'terrain-aware' - it knows height, but it doesn't know anything about *features* : it doesn't really know what a river is or the effect it has on the surrounding geography; it can't distinguish easily between 'old' and 'new' geography; etc. If you want truly realistic terrain then you should consider some of the more simulationist approaches - but these tend to directly conflict with the kind of terrain modifications that the linked video shows, so if realism is your goal then it may be worth rethinking the voxel approach entirely.

---
Tags: terrain, procedural, marching-cubes
---


# Question
Title: What is the rationale behind this method of computing the w-component from MD5 mesh files?
In tutorials regarding the MD5Mesh format, like this one, we often see code like

```
float t = 1.0f - (q.x * q.x) - (q.y * q.y) - (q.z * q.z);

if (t < 0.0f) {
   q.w = 0.0f;
} else {
   q.w = -sqrt (t);
}

```

for computing the w-component of a unit quaternion given `x, y, z`. Why do we obtain w in this manner?

# Answer
> 3 votes
The MD5 file format assumes unit quaternions, which are of norm one. The norm of some quaternion `q` is:

```
|q| = sqrt((x * x) + (y * y) + (z * z) + (w * w))

```

You can rearrange this equation in terms of `w` by squaring both sides and then subtracting the terms containing `x`, `y` and `z` to yield:

```
(w*w) = (|q|*|q|) - (x*x) - (y*y) - (z*z)

```

Since the quaternion is assumed to be of norm 1, the `|q|*|q|` term is thus 1, and that's how you arrive at the initialization of `t` in your code snippet. Taking the square root of `t` yields the value of the final component, the sign of which is chosen as an orientation convention.

---
Tags: quaternion
---


# Question
Title: Randomly placing items script not working - sometimes items spawn in walls, sometimes items spawn in weird locations
EDIT: I changed some code after getting advice from colleagues. However it still has problems occasionally, though the problems aren't as bad or frequent. Here's the new code I'm actually using: \`

```
             //This is what randomly generates all the items.
void SpawnItems () {
    if (Application.loadedLevelName == "Menu" || Application.loadedLevelName == "End Demo" || Application.loadedLevelName == "Controls")
        return;
    //The bottom corner of the box we want to spawn items in.
    Vector3 spawnBoxBot = Vector3.zero;
    //Top corner.
    Vector3 spawnBoxTop = Vector3.zero;

    //If we're in the dungeon, set the box to the dungeon box and tell the items we want to spawn.
    if (Application.loadedLevelName == "dungeonScene") {
        spawnBoxBot = new Vector3 (8.857f, 0, 9.06f);
        spawnBoxTop = new Vector3 (-27.98f, 2.4f, -15);
        itemSpawn = dungeonSpawn;
    }

    //Spawn all the items.
    for (i = 0; i != itemSpawn.Length; i ++) {
        spawnedItem = null;
        //Zeroes out our random location
        Vector3 randomLocation = Vector3.zero;
        //Gets the meshfilter of the item we'll be spawning
        MeshFilter mf = itemSpawn[i].GetComponent<MeshFilter>();
        //Gets it's bounds (see how big it is)
        Bounds bounds = mf.sharedMesh.bounds;
        //Get it's radius
        //float maxRadius = new Vector3 (bounds.extents.x + 10f, bounds.extents.y + 10f, bounds.extents.z + 10f).magnitude * 5f;
        float maxRadius = new Vector3 (bounds.extents.x, bounds.extents.y, bounds.extents.z).magnitude;

        //If we're in the dungeon, certain items need to spawn on certain halves.
        if (Application.loadedLevelName == "dungeonScene") {
            if (itemSpawn[i].name == "key2" || itemSpawn[i].name == "teddyBearLW" || itemSpawn[i].name == "teddyBearLW_Admiration" || itemSpawn[i].name == "radio")
                randomLocation = new Vector3(Random.Range(spawnBoxBot.x, -26.96f), Random.Range(spawnBoxBot.y, spawnBoxTop.y), Random.Range(spawnBoxBot.z, -2.141f));
            else
                randomLocation = new Vector3(Random.Range(spawnBoxBot.x, spawnBoxTop.x), Random.Range(spawnBoxBot.y, spawnBoxTop.y), Random.Range(-2.374f, spawnBoxTop.z));
        }
        //Otherwise just spawn them in the box.
        else
            randomLocation = new Vector3(Random.Range(spawnBoxBot.x, spawnBoxTop.x), Random.Range(spawnBoxBot.y, spawnBoxTop.y), Random.Range(spawnBoxBot.z, spawnBoxTop.z));

        //Get a list of objects this item is hitting.
        Collider[] hit = Physics.OverlapSphere(randomLocation, maxRadius);

        //This is what actually spawns the item. If the space is clear, spawn the item. Otherwise we have to repeat the whole process again.
        if (hit.Length < 1 || hit[0].name != "")
            spawnedItem = Instantiate(itemSpawn[i], randomLocation, Random.rotation);
        else
            i --;

        //If we spawned something, set it's name to what it's supposed to be. Removes the (clone) addon.
        if (spawnedItem != null)
            spawnedItem.name = itemSpawn[i].name;
    }
}`

```

I'm trying to figure out a way to randomly spawn items throughout my level, however I need to make sure they won't spawn inside another object (walls, etc.)

Here's the code I'm currently using (no longer using this, just keeping it for reference), it's based on the Physics.CheckSphere(); function. This runs OnLevelWasLoaded(); It spawns the items perfectly fine, but sometimes items spawn partway in walls. And sometimes items will spawn outside of the SpawnBox range (no clue why it does that.)

```
//This is what randomly generates all the items.
void SpawnItems () {
    if (Application.loadedLevelName == "Menu" || Application.loadedLevelName == "End Demo")
        return;

    //The bottom corner of the box we want to spawn items in.
    Vector3 spawnBoxBot = Vector3.zero;
    //Top corner.
    Vector3 spawnBoxTop = Vector3.zero;

    //If we're in the dungeon, set the box to the dungeon box and tell the items we want to spawn.
    if (Application.loadedLevelName == "dungeonScene") {
        spawnBoxBot = new Vector3 (8.857f, 0, 9.06f);
        spawnBoxTop = new Vector3 (-27.98f, 2.4f, -15);
        itemSpawn = dungeonSpawn;
    }

    //Spawn all the items.
    for (i = 0; i != itemSpawn.Length; i ++) {
        spawnedItem = null;
        //Zeroes out our random location
        Vector3 randomLocation = Vector3.zero;
        //Gets the meshfilter of the item we'll be spawning
        MeshFilter mf = itemSpawn[i].GetComponent<MeshFilter>();
        //Gets it's bounds (see how big it is)
        Bounds bounds = mf.sharedMesh.bounds;
        //Get it's radius
        float maxRadius = new Vector3 (bounds.extents.x + 10f, bounds.extents.y + 10f, bounds.extents.z + 10f).magnitude * 5f;
        //Set which layer is the no walls layer
        var NoWallsLayer =  1 << LayerMask.NameToLayer("NoWallsLayer");
        //Use that layer as your layermask.
        LayerMask layerMask = ~(1 << NoWallsLayer);

        //If we're in the dungeon, certain items need to spawn on certain halves.
        if (Application.loadedLevelName == "dungeonScene") {
            if (itemSpawn[i].name == "key2" || itemSpawn[i].name == "teddyBearLW" || itemSpawn[i].name == "teddyBearLW_Admiration" || itemSpawn[i].name == "radio")
                randomLocation = new Vector3(Random.Range(spawnBoxBot.x, -26.96f), Random.Range(spawnBoxBot.y, spawnBoxTop.y), Random.Range(spawnBoxBot.z, -2.141f));
            else
                randomLocation = new Vector3(Random.Range(spawnBoxBot.x, spawnBoxTop.x), Random.Range(spawnBoxBot.y, spawnBoxTop.y), Random.Range(-2.374f, spawnBoxTop.z));
        }
        //Otherwise just spawn them in the box.
        else
            randomLocation = new Vector3(Random.Range(spawnBoxBot.x, spawnBoxTop.x), Random.Range(spawnBoxBot.y, spawnBoxTop.y), Random.Range(spawnBoxBot.z, spawnBoxTop.z));

        //This is what actually spawns the item. It checks to see if the spot where we want to instantiate it is clear, and if so it instatiates it. Otherwise we have to repeat the whole process again.
        if (Physics.CheckSphere(randomLocation, maxRadius, layerMask))
            spawnedItem = Instantiate(itemSpawn[i], randomLocation, Random.rotation);
        else
            i --;

        //If we spawned something, set it's name to what it's supposed to be. Removes the (clone) addon.
        if (spawnedItem != null)
            spawnedItem.name = itemSpawn[i].name;
    }
}

```

What I'm asking for is if you know what's going wrong with this code that it would spawn stuff in walls. Or, if you could provide me with links/code/ideas of a better way to check if an item will spawn in a wall (some other function than Physics.CheckSphere).

I've been working on this for a long time, and nothing I try seems to work. Any help is appreciated.

# Answer
Coming back to this much later, I completely forgot about this question.

The problem ended up being caused by the artist I was working with, he set the meshes on the items to nearly 100x the size they visually were. This meant when I was trying to spawn items with the script above they were colliding with EVERYTHING in the level. After fixing the meshes on the items the above script worked perfectly fine.
> 3 votes

# Answer
One thing is that the CheckSphere will return true if it hits more than one thing as well, so it may hit the ground and a wall and will still return true. So this is possibly the reason your items sometimes spawn sticking out of the wall.

What you could try is once you hit something, do a few ray casts in each direction with the ray starting in the center of the object and the distance set to a little over half the width/length of the object to determine if any walls or objects are nearby.

This way can also help you tell if your item will be stuck somewhere inaccessible as well

It may not be the most efficient way but I've done similar before and it seemed to work pretty good and fast for my purposes.
> 2 votes

# Answer
I am not sure how you have your level set up completely, but would you be able to check for just a collision against a tagged wall?

```
if (hit.Length < 1 || hit[0].tag != "wall")
        spawnedItem = Instantiate(itemSpawn[i], randomLocation, Random.rotation);

```

This might not be possible of course if your level mesh is set up as a single object. If you can tag the walls this may give you a quick and dirty way to do it.

However, a better way might be to create the grid that michael.barnett suggested.
> 2 votes

---
Tags: c#, unity, random
---


# Question
Title: Saving data across same game in multiple devices
Is there any library or something that works like iCloud but for different operating systems (Android, IOS, Windows Phone) that allow me to save game data to cloud and open the game data from another device to sync the game progress?

# Answer
> 4 votes
You could develop your own SOAP or REST API, host it on a website and have your apps connect to that. You'd have full control over it and wouldn't have to pay for anything (other than hosting, of course). There is more of a development cost up front than using some kind of pre-built package, but you have the control to scale as you need to and make the API do exactly what you'd want.

Unfortunately, I don't know of any libraries or packages that provide this functionality so I can't help you there.

---
Tags: android, ios, windows-phone-7, savegame
---


# Question
Title: Stronger Hack-proof MMO Game Comparison: Game Client Based Vs. Via Web Browser
I was wondering. I observed most of any MMO that are hack-prone area. Hacks used one-hit kills, stealing accounts, instant level up, aimbots (mostly MMOFPS), and questionable wallers (also in MMOFPS). These hackers might affect the fairness and excitement of the gamers which lead to doubts, abuse kickers (mostly in MMOFPS\*, and misunderstandings. Even in MMORPG referred to hacks for instant money for purchase items. I saw these examples via *Wikipedia*.

This leads me to my question:

**Which kind of MMO game platform or model would be best for making MMO games whilst reducing the possibility of hacking?**

For example I could make an MMO game for the web browser (by website or via *Facebook*) or making an MMO game using installers/clients that fetches for patches and graphics that could run only through program via computer. What will help with preventing hacking and how?

In the case of making an installer/client based MMO games, are there anti-hack programs or techniques you can recommend in MMO context?

# Answer
Whichever you do, it doesn't matter. If you rely on clientside calculation of anything you will get hacked. All the "anti-hacker" tooling has AFAIK been thoroughly penetrated, new versions often themselves being hacked in a matter of hours after release.
Given that, browser games are a major PITA IMO (poor usability) though they do offer ease of installation.
So push as much as you can to the server, validate and counter validate everything sent by the clients to the server, and aggressively detect and ban any violators.
Of course you do have to account for lag which can cause weird results being sent (or received), which is another reason you don't want to rely on clientside anything.
So the client tells the server he's moving in direction alpha, let the server decide the next position, not the client. Client tells the server he's pulling the trigger, let the server decide whether there's bullets left, where they're going, and whether anything is hit (and what damage they do).
Done like that, the client becomes little more than a tool for rendering the world and allowing the user to request things (data, movement, etc.) from the server with the server deciding whether those requests should be honoured based on what it knows about the real abilities of the client (this also makes it impossible to render walls invisible for example, unless the client avatar is known to the server to have X-ray vision, a decision made based on gameplay and resources the server assigned to the avatar, not the client software).
Of course this places a major burden on the servers, your server hardware is going to have to be rather more serious than that of old fashioned gaming servers which were little more than portals to transmit data between clients, but that's what it takes to deflect hacking/cheating attempts.
> 8 votes

# Answer
Anti cheat tools are software, just like the game client itself. Just like a hack is able to manipulate the game software, it can also manipulate the anti cheat software.

Any software which runs on the users machine is under their control. For that reason **it is physically impossible to create unhackable client-sided anti cheat tools**. When you want your game to be impossible to hack, you have to move any calculations which are worth manipulating to the server.

* Don't send information to the client the user isn't supposed to know (like enemies behind walls)
* Don't trust the client when it reports its location or any other game state information - only receive input commands and then tell the client the results
* Do any collision- and hit detection on the server.
* Save, maintain and persist the game state on the server, not the client (When a game allows the client to increase its cash shop credits without a server confirmation, the developers seriously don't know what they are doing).

When you do all that, the only thing which a client-sided hack is still able to do, is automation (like an aimbot). Unfortunately there isn't much you can do about that, except for a heuristic approach to detect unusual input on the server.

There is, however, a drawback of doing everything on the server. The more you do on the server, the harder will it be for the client to hide latency problems. Modern online game clients do a great job at extrapolating object movements, hiding discrepancies between client and server and combensating for latency. But the more information you hide from the client, the less information is available on the client for doing all that. And when you do everything on the server, there will be a discrepancy between what the player sees on their screen and how the server sees the game due to latency ("ping"). The game will inevitably *feel* more laggy to the player
> 2 votes

---
Tags: performance, mmo, server, anti-cheat, hacks
---


# Question
Title: Compiling a Monogame Game into a single .exe
Is it possible to compile a monogame game into a single .exe? I know if you go in the debug or release bin, there is in fact a .exe your game, except you move this .exe's file location or try to run in on another computer it crashes. I am also aware of the one-click application except this seems like a really messy way of redistributing a monogame game. How come when you build your game, the exe for it wont work anywhere but that file location and that computer. I am also aware that the computer probably needs the XNA framework downloaded to play the monogame game, so in short is it possible to redistribute a monogame game by creating a single .exe and assume that person who is using it doesnt have XNA or monogame installed?

# Answer
> 2 votes
You can use tools like http://madebits.com/netz/index.php.

There is also an application that I personally used: SmartAssembly (http://www.red-gate.com/products/dotnet-development/smartassembly/). Even thought it says it's an obsfucator, you can use it just to pack every .dll and the main .exe into a single .exe.

However, please note that the 'Content' folder which contains the game assets will need to be held alongside with the single .exe file.

---
Tags: monogame
---


# Question
Title: When would a GPU need to write data to a vertex (or other) buffer?
I'm trying to understand why, when and how a GPU would need to write data to some buffer inside its own Video Ram.

In Direct3D 11, there are two flags that concern this, which are `D3D11_USAGE_DEFAULT` and `D3D11_USAGE_IMMUTABLE`. The former gives the ability to read and write, the latter only the ability to read.

So, apart from the resources that imply actual rendering to, like back buffers or textures set to use in a render-to-texture scenario, is there any other case where one would prefer to use DEFAULT over IMMUTABLE? How would you get the GPU to change this data? (I guess from a shader?) Why is it not the default one the one that gives you read only access?

# Answer
> 3 votes
You'd use it for stream output (a technique frequently seen in GPU particle systems) and as output from a compute shader stage.

---
Tags: directx11
---


# Question
Title: MMORPG game map in-memory storage techniques
For 2-3 years I've been interested into MMO development. I'm browsing some emulators source codes and open source projects.

Usually I'm checking how the game server stores data about the 2D map. There are 2 popular solutions:

* map is stored only on the server it's sent to the client in parts (eq. tiles like in OpenTibia https://github.com/opentibia/server)
* map is stored in the client and on the server, server sends only coordinates and client got knowedgle of it.

I'm generally interested in this first attitude, do you know any good and bad aspects of it?

How to store this structure on the server? In memory on in database? Open Tibia uses memory storage but there is one drawback: 2000x2000x16 map uses a lot of memory - something around 2GB. Is this because of bad design? Are you able to provide me some examples of good design?

# Answer
"Map is stored only on the server it's sent to the client in parts":

* **Pros**
    + Client always has most up-to-date map
    + Can keep map data hidden until the user has visited the area
    + System already in place for pushing expanded or updated map data
* **Cons**
    + Client has to always download map data even if it's un-changed and they've been there before
    + Due to the above, server bandwidth is always taxed. This increases costs significantly over the lifetime of the game.

"map is stored in the client and on the server, server sends only coordinates and client got knowedgle of it":

Pros and cons are essentially the opposite of the above.

**I'd suggest a hybrid of the two systems**. The client can download the game, with the map data. When they enter a new area, the client asks if there is a newer version of the map data. If so, download the latest data from the server, otherwise use the local version.

I assume when you say "store in memory" you actually mean some kind of custom flat file format on disk. If you only stored it in memory, you'd lose it as soon as the server restarted. So, using your own format or a database is up to you. It depends on how you want to access your data and the requirements of your game. If you know well the pros/cons of each, paired with the requirements of your game, you'll know which one to choose.
> 4 votes

---
Tags: mmo, server, memory-efficiency, memory
---


title: unlimited (wraparound) 3d terrain

text:
# Question
Title: unlimited (wraparound) 3d terrain
How can I create a wrap around unlimited 3D terrain: To make it clear: If I step out of terrain in (1) or (A) I want to get to (2) resp. (B)

```
        |B
        V
     +----------+
2 -->|          |--> 1
     |          |
     |          |
     +----------+
        |A
        V

```

I do not know how to wrap around the terrain and all the items which are on the terrain(NPCs etc) I thought of portals, but then I have problems on the corners of the terrain. In 2D it is quite simple(even trivial), but on 3D I cannot find a solution.. Any advice or tutorial ailable?

# Answer
Have a matrix of chunks that make up the visible area around the camera. The chunks will use modulo, just like in 2D, to determine which chunk of your wrapped 3D world they should contain.

Each dimension is like a conveyor belt, loading and unloading chunks as the camera moves along its axis.

Now, when it comes to drawing, you just reference the chunks loaded around your camera. If the wrap of the world was small, there would be duplicate chunks referenced in the chunk matrix. The view frustum doesn't need to know anything about where the world wraps, it just looks at the loaded chunks.
> 4 votes

---
Tags: terrain-rendering
---


# Question
Title: Are there alternatives to Vertex Tweening?
Now that I'm getting into animating 3D entities in my game, I was wondering what the best approach for this would be. I did some research and came across something called "Vertex Tweening". However, most of these articles (like this one: http://archive.gamedev.net/archive/reference/articles/article2017.html) are from 2003, if not older!

In a DirectX 9 game which makes proper use of HLSL to do its rendering magic, is Vertex Tweening still the way to go these days (anno 2013), or are there other techniques I'm not aware of yet?

# Answer
> 0 votes
Vertex tweening for animation is an outdated technique, and there aren't many good reasons to use it in modern graphics code. I'm fairly certain it isn't even supported at the API level in D3D10+ (although you could always still implement it yourself).

One of the big problems with it is that it requires complete copies of the vertex data for each keyframe, which is very expensive. Furthermore, since the interpolations between keyframe vertices are usually simple linear interpolations, you need quite a few keyframes to have a high-quality animation, especially if lots of rotations are involved.

The current standard technique for animation of 3D bodies as of this writing is skeletal animation. There's a lot of information on this available via Google and even on this site; at the heart of it, you define a simple 3D rig (or "skeleton"), and you animate that by storing a series of transformations to the bones that skeleton. The actual mesh data includes weight information per-vertex that indicates which bones affect which vertex at what strength, and that information can be combined on the GPU or CPU to animate the mesh.

---
Tags: animation, hlsl, directx9, skeletal-animation
---


title: First person camera with Bullet Physics

text:
# Question
Title: First person camera with Bullet Physics
Before integrating the Bullet Physics, the camera worked fine. But instead of using my own simple struct for transform data, I use rigid body structs provided by the physics library now.

There are two issue with the first person camera at the moment. First, it is stuck in the ground and when I try to move it, it slips back to it's position. Second, When I get the camera out of the ground, which sometimes happens, The applied rotation isn't in the way I move the mouse. When I move the mouse straight, the camera is moved in circles.

This is how the rigid body it set up.

```
float mass = 1.0f;
btCollisionShape* shape = new btBoxShape(btVector3(0.5f, 0.5f, 0.5f));
btDefaultMotionState* state = new btDefaultMotionState(btTransform(btQuaternion(0, 0, 0, mass), btVector3(0, 0, 0)));
btVector3 inertia;
shape->calculateLocalInertia(mass, inertia);
Body = new btRigidBody(mass, state, shape, inertia);

```

This is how I get and set rotations and positions of rigid bodies.

```
vec3 Position()
{
    btVector3 pos = Body->getWorldTransform().getOrigin();
    return vec3(pos.getX(), pos.getY(), pos.getZ());
}
void Position(vec3 Position)
{
    btTransform transform = Body->getCenterOfMassTransform();
    transform.setOrigin(btVector3(Position.x, Position.y, Position.z));
    Body->setCenterOfMassTransform(transform);
}
vec3 Rotation()
{
    vec3 rot;
    Body->getWorldTransform().getBasis().getEulerZYX(rot.z, rot.y, rot.x);
    return rot;
}
void Rotation(vec3 Rotation)
{
    btTransform transform = Shape->getCenterOfMassTransform();
    transform.setRotation(btQuaternion(Rotation.y, Rotation.x, Rotation.z));
    Shape->setCenterOfMassTransform(transform);
}

```

And this is how I calculate the view matrix of the camera.

```
const float pi = glm::pi<float>();
if      (Rotation().x < -pi) Rotation(vec3(Rotation().x + pi*2, Rotation().y, Rotation().z));
else if (Rotation().x >  pi) Rotation(vec3(Rotation().x - pi*2, Rotation().y, Rotation().z));

const float margin = 0.2f;
if      (Rotation().y < -pi/2+margin) Rotation(vec3(Rotation().x, -pi/2+margin, Rotation().z));
else if (Rotation().y >  pi/2-margin) Rotation(vec3(Rotation().x,  pi/2-margin, Rotation().z));

vec3 lookat(
    sinf(Rotation().x) * cosf(Rotation().y),
                         sinf(Rotation().y),
    cosf(Rotation().x) * cosf(Rotation().y)
);

cam->View = lookAt(Position(), Position() + lookat, vec3(0, 1, 0));

```

How can I move and rotate a rigid body to use it as camera?

# Answer
The solution was to create a character or actor class representing a rigid body in the physics simulation. An instance of that class can be attached to the camera. Both actor and camera have distinctive transforms thus position and rotation.

The camera then updates its position and yaw from the attached actor's rigid body. Pitch and roll aren't synchronized. The position can be shifted say 1.8 meters up so that the viewpoint is located where in reality eyes are located.

Moreover the rigid body contained in an actor is restricted to not change pitch and roll, so that the collision shape cannot fall on its side.

That way the camera can freely rotate in pitch and yaw, the actor turns around with the camera but doesn't rotate upwards and downwards. So the collision shape, which might be a cylinder or an ellipsoid, always stays upright. To move the camera, we can simply apply forces to the attached actor instance.
> 1 votes

# Answer
I don't really understand your matrix creation code so I can't comment on the rotation but if you give the camera a mass of 1 bullet physics will apply gravity to it, which would cause that dropping into the ground effect whenever you stop moving the camera yourself. Try setting it to 0 instead.

Also I don't think messing with the Center of Mass transform should really be done outside of initialisation.
> 0 votes

---
Tags: opengl, camera, bullet-physics
---