title: 3d Water Simulation formula questions

text:
# Question
Title: 3d Water Simulation formula questions
I have created a Grid:

At each point along the grid, is a vertex (Intersection Points):

Each of these points has an x,y,z position. Vector3f(x,y,z). In an attempt to animate the grid into a group of ocean waves, I used this formula to adjust the y position of each “Vertex”:

This is my attempt at implementing the formula into java:

```
private float sineY(int x, int y, float time) {
Vector2f position = new Vector2f(x, y);
float yPos = (float) ( (2 * amplitude) *Math.pow((Math.sin((wavenumber.dot(position))  + temporal_angular_freq * time +  initiatory_phase) + 1)/2, k));
    return yPos;
}

```

This function is running from inside a for loop that is updated every ms:

```
Time ++;
for (int y = 0; y < sizeY; y++) {
        for (int x = 0; x < sizeX; x++) {
            float xPos = x;
            float yPos = 0;
            float zPos = y;
            xPos += 0;
            yPos += sineY(x,y,time);
            zPos += 0;
            waterVertexPos.set(xPos, yPos, zPos);
            vertBufArray[index++] = waterVertexPos.getX();
            vertBufArray[index++] = waterVertexPos.getY();
            vertBufArray[index++] = waterVertexPos.getZ();
        }
    }

```

As you can see, for each vertex, along the grid, the yPosition of the vertex is set to whatever value the sineY method returns, which is whatever the above formula returns. Running this code reults in this:

WHEN K = 1.0:

WHEN K = 1.5

As you can see, they both do not follow in accordance with this image here:

All the formulas and graphs have been retrieved from this pdf file. The aim of this program is to simulate water using the presented equations. The pdf is really interesting have a read if you like :)

Source: http://http.developer.nvidia.com/GPUGems/gpugems\_ch01.html

Thank you VERY MUCH for all of your time :)

EDIT:

After implementing the fix suggested by msell. It fixed this previous issue, however a new issue arose when the waves peaks still do not look as they did in the above graph:

WHEN K = 2.0:

The pdf specifies:

A common complaint about waves generated by summing sine waves directly is that they have too much "roll," that real waves have sharper peaks and wider troughs. As it turns out, there is a simple variant of the sine function that quite controllably gives this effect. We offset our sine function to be nonnegative and raise it to an exponent k. The function and its partial derivative with respect to x are.

And then refers to the formula mentioned above, and another formula:

Is there something wrong with my implementation?

And again. I cannot thank you enough for your time :)

Sidney de Vries

# Answer
> 4 votes
You have incorrectly implemented the formula as a function. The function is missing `+ 1` after the call to `Math.sin()`, which moves the wave to the range \[0, 2\].

Regarding your second problem, I don't see anything wrong. In fact the screenshot looks exactly like it should and seems to match the plotted curve. Try with k=10 and you should see the difference clearly.

---
Tags: java, physics, linear-algebra, water
---


# Question
Title: Issue with interpolation on a burn shader (lerp and smoothstep)
I'm trying to create a simple burn shader. See here for more info on the method I'm using. However, I don't get why replacing the smoothstep with a lerp results in completely different results. Am I missing something from my knowledge of maths? As far as I know they should return similar values given the same parameters.

```
// clips materials, using an image as guidance.
// use clouds or random noise as the slice guide for best results.
Shader "Custom/Dissolving" {
Properties {
  _MainTex ("Texture (RGB)", 2D) = "white" {}
  _BorderTex ("Border Texture (RGBA)", 2D) = "white" {}

  _EdgeColor ("Edge Color", Color) = (1,0,0)
  _EdgeSize ("Edge Size", float) = 0.1

  _SliceGuide ("Slice Guide (RGB)", 2D) = "white" {}
  _SliceAmount ("Slice Amount", Range(0.0, 1)) = 0.2

  [MaterialToggle] UseClipInstruction ("Use Clip Instruction", Float) = 0
}
SubShader {
  Tags {"Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Transparent"}
  //Cull Off
  Blend SrcAlpha OneMinusSrcAlpha

  CGPROGRAM
  //if you're not planning on using shadows, remove "addshadow" for better performance
  #pragma surface surf Lambert alpha addshadow

  struct Input {
      float2 uv_MainTex : TEXCOORD0;
      float2 uv_SliceGuide : TEXCOORD1;
      float _SliceAmount;
  };

  sampler2D _MainTex;
  sampler2D _BorderTex;
  sampler2D _SliceGuide;
  half _SliceAmount;
  half _EdgeSize;
  half3 _EdgeColor;

  void surf (Input IN, inout SurfaceOutput o) {
    o.Alpha=1;

    //Green is a good color for estimating grayscale values
    half fragSliceValue = tex2D(_SliceGuide, IN.uv_SliceGuide).g;

    #ifdef UseClipInstruction
    clip(fragSliceValue - _SliceAmount);
    #else
    //TODO: look for an alternative to this
    if (fragSliceValue - _SliceAmount<0)
        o.Alpha=0;
    #endif

    half rampX = smoothstep(_SliceAmount,_SliceAmount + _EdgeSize, fragSliceValue);
    half3 ramp = tex2D(_BorderTex,half2( rampX,0) ) * _EdgeColor.rgb;
    o.Emission = ramp * (1-rampX);

    o.Albedo = tex2D(_MainTex,IN.uv_MainTex);
  }
  ENDCG
}
Fallback "Diffuse"
}

```

Left is the result of smoothstep (the provided code), right is what happens when I replace smooth with lerp.

# Answer
> 6 votes
They are very different:

```
smoothstep(x, y, z);

```

basically does saturate((z-x)/(y-x)) and then smoothes the result to start and end smoothly. The result always lies between 0 and 1.

```
lerp(x, y, z);

```

returns z\*y+(1-z)\*x As long as x lies between 0 and 1 the result lies between x and y.

What you want is saturate((z-x)/(y-x)) which gives you the same range as smoothstep but without the smoothing.

---
Tags: unity, shaders, hlsl, cg
---


title: Area of surface contained in pixel

text:
# Question
Title: Area of surface contained in pixel
Let's say I have some surface rasterized and stored to a texture. How do I calculate the actual surface area that is visible in one of the rasterized pixels, from some other location?

So far, I'm assuming it's

A\_visible = A * cos(theta) / d^2

where d = distance from viewer, theta = angle between normal and viewer-surface direction, A = ... I'm not even sure how to express it. I guess you could call it the "world space area" of the pixel.

Is the above equation even correct? How do I determine "A? Notice that I'm not only looking for the area strictly as visible from the (e.g. perspective) camera. I'd also like to compute this area as visible from other surfaces, i.e. other surface areas that receive light from all around its hemisphere above the surface.

# Answer
> 3 votes
To find the area that a pixel contains you can use the solid angle equation where

```
A_s / ||d_s||^2 = A_near / ||d_near||^2
A_s    = the surface of the pixel at d_s distance
A_near = the surface of the pixel at the near plane

```

You know `d_s` and `d_near` so you have to find `A_near`

```
A_near = width * height = 4 * tan(FOV/2)^2 * d_near^2 / ( aspectRatio * Nx * Ny )
Where  width and height are the width and height of the pixel
FOV = Field of View of your projection matrix
AspectRatio = height to width ratio
Nx and Ny are the number of texels in horizontal and vertical directions of the image

```

This way you can find the `A_s` which is the surface area of your pixel when its normal is perpendicular to the viewing direction. To find the correct area surface you just have to multiply `A_s` with `cos(theta)` where `theta` is the angle of normal and view direction (actually `-viewDirection`).

---
Tags: mathematics
---


title: Gerstner wave function simplified?

text:
# Question
Title: Gerstner wave function simplified?
The gerstner wave function is a commonly used method to calculate waves and simulate water in video games and movies or most 3d simulations. It is however quite complex so it is very hard for young developers such as myself to understand and implement it into code.

Would it be possible to simplify the formula:

* A = amplitude of wave (Float)
* W = wave number (Vector)
* D = direction (Vector) how do i know what to set the direction to?
* S = Speed
* L = wave length
* phase-constant = S x 2\* pi/L.

According to the article Q = 1/(W * A)

Issues and Questions:

* Why are all three lines of the formula seperated by commas?
* D refers to a directional vector (i think)
* Q = 1/(W * A) but W is a vector and A is a float?
* What does this line mean: wiDi.(x,y) is that reffering to w * dot product of(d , (x,y))
    + sigma returns the sum of what exactly?

Here is my attempt to implement it into java code:

```
float yPos = (float) ((steepness * amplitude) * direction.y * Math.cos(wavenumber.y * (direction.dot(position)) + phase_const * time));

```

Dont know if its correct

This may help:

https://github.com/armanuguray/water-surface/blob/master/src/engine/waterengine.cpp

# Answer
> 4 votes
Why are all three lines of the formula seperated by commas?

* P(x,y,t) is a vector valued function. Its values are thus 3D vectors. The commas just separate these components, probably akin to a Matlab style of coding.

D refers to a directional vector (i think)

* D is a 2D vector in the (x,y) plane. It describes the direction (and magnitude, if not noramlized!) of a principal wave component. Several such components (`D_i`s) are actually added together, as seen in the formula, to equate the desired wavy/wobbly effect. It's akin to a Fourier decomposition of a signal into `A sine + B cosine` polynomials

Q = 1/(W * A) but W is a vector and A is a float?

* W\_i and A\_i are both scalars! (1D values!). The A\_i is the wave amplitude or height, whereas W\_i should control the wave's sharpness (more pronounced crests)

What does this line mean: wiDi.(x,y) is that reffering to w * dot product of(d , (x,y)) sigma returns the sum of what exactly?

* W\_i multiplies the `dot(Di,(x,y))`. Thus the dot is taken between the wave direction and the current grid position, (x,y). This dot product appears in the arguments of two trig functions (cos and sin), and it is present in there to introduce a phase difference into the waves, otherwise all points on the surface of the wave would have the same water level height (this explanation is a layman's view of something a bit more complicated - I can't fit the whole explanation here :( ).

Your pseudocode is looking ok-ish. It should actually be written as:

`yPos += (float) ((steepness[i] * amplitude[i]) * direction[i].y * Math.cos(w[i] * (direction[i].dot(position[i])) + phase_const[i] * time));`

..that is, you need at least N=2 (i=0,1,..N) different wave directions for something more interesting to develop, otherwise you're going to end up with a sine-like wave (pretty bland looking).

---
Tags: physics, linear-algebra, water
---


title: Is there a successor to RenderMonkey?

text:
# Question
Title: Is there a successor to RenderMonkey?
I'm starting with GLSL shader programming and have been looking into RenderMonkey. Sadly, AMD no longer supports it. Why? Is there a successor to it?

# Answer
*The bulk of this answer is going to be a response to the "Why?" part of your question, alas.*

Well, there's FX Composer, from NVIDIA, which is a similar product -- it doesn't support GLSL but the languages it does support are quite similar. But it was last updated in 2009 and I know of no plans to update it further. Most high-end 3D modelling packages have material construction tools in them as well, which may or may not support GLSL.

I think the reason you see these products reaching end-of-life (and nothing coming out to replace them) is that **the direction that shader development has taken doesn't lend itself well to generalized IDEs** like this.

Even back when we just had vertex and pixel shaders, there tended to be a strong coupling between the game/engine-side data formats (and how that data is processed) and the shader input layouts and operations programmed within the shaders -- at least for the more interesting, complex effects.

Consider water-related effects, for example, which often involve deforming the geometry slightly in response to sums of sine waves (in addition to running a computation that sums similar waves into a texture to be bound to the pipeline as a bump map), as well as needing framebuffer copy textures to bind in order to simulation reflection, and so on. Most of that data comes from the CPU, and isn't built in to the shader itself.

As the nature of that coupling increased (due to increases in parallelism on the CPU side, allowing us to balance the interesting computations more evenly between CPU and GPU), it got harder and harder to design a general-purpose shader IDE because that IDE also has to have a way to script and replicate the data pipeline that a game is going to send to shader -- essentially it needed to be a plugin to an engine. **As we added extra programmable stages to the pipeline -- geometry shaders, hull shaders, et cetera -- this only compounded the issue.**

D3D tried to alleviate the problem with SAS, but I don't think that ever really caught on and it certainly hasn't scaled with advances in GPU technology.

**As a result, specialized in-house or in-engine tools for building shaders evolved, and tools like FX Composer and RenderMonkey fell into disuse** and were ultimately abandoned.
> 30 votes

# Answer
GLSL hacker. That's your answer http://www.geeks3d.com/glslhacker/
> -2 votes

---
Tags: shaders, glsl
---


# Question
Title: How do you divide the screen into tiles?
I have been reading alot on tile-based game programming but i could not find a satisfying answer to this question.

I want to know how i can divide the screen into tiles of a size like 32?

I am doing it in JAVA.

# Answer
> 5 votes
You do not divide a screen into tiles, you create a field that renders tiles in a grid sequence. Those are usually some sort of bitmaps that are stored in memory and are placed one after another to form a bigger picture - the tile grid. For a 2 dimensional grid, you'd use two for..loops (one inside another) to render rows and columns.

```
for(int i=0; i<rows; i++){
    for(int u=0; u<columns; u++){
        // render tile with the coordinates [i,u] at position [32*i,32*u]
        // that is assuming your tile size is 32x32
    }
}

```

---
Tags: java, tilemap
---


title: Using LibGDX within Android Fragment

text:
# Question
Title: Using LibGDX within Android Fragment
I want to use LibGDX with Android, but instead of modifying my Activity to extend

> AndroidApplication

I want my to render my graphics inside Android Fragment

The problem is that my class already extends Fragment, so I can't make it extend LibGDX AndroidApplication (Multiple Inheritance)

is there any workaround for this ?

Thanks

# Answer
Ok, after searching I got this solution:

instead of using a fragment I used a generic View to render my graphics in it:

```
game=new MyGdxGame();
View gameView=initializeForView(game,cfg);

```

this is how I was able to display other views in my activity
> 3 votes

# Answer
I just made a pull request with the fragment feature implemented.

Instead of extending `AndroidApplication` by an activity, you can extend `AndroidFragmentApplication` by a `Fragment` and return `initializeForView()` on the `onCreateView` callback.
> 3 votes

---
Tags: android, libgdx
---


# Question
Title: How does this formula for generating water waves work?
I have been trying to implement the wave equation described in this paper ("Water Simulating in Computer Graphics," Kai Li and Liming Wu) in Java. Part of the paper discusses modeling waves as a sum of sine waves ("sine wave piling"); in that section there an equation for describing a single sine wave:

```
Y（x，y，t）= A * cos（w *（x，y）+ wt * t + FI;

```

where

* `A` = amplitude of wave
* `L` = wave length
* `w` = spatial angular frequency
* `s` = speed
* `wt` = temporal angular frequency
* `d` = direction
* `FI` = initiatory phase

I understand that it returns a vector, but I don't see what this section of the formula means:

```
w *（x，y）

```

I believe that `w` is a vector, but I'm not sure if it's a 3D vector or 2D vector, and how it is used. If you have time, could you please explain this formula to me?

# Answer
The function returns a scalar, but the variable ***w*** is indeed a vector. More traditionally, the one-dimensional wave function is written as:

*Ψ(x,t) = A cos( k x - ω t )*

In more than one dimension, for example waves in water instead of on a rope, the spatial part is written as the dot product of two vectors:

*Ψ(**x**,t) = A cos( **k**·**x** \- ω t )*

In the formula you referred to, ***x*** is written in full as the two-dimensional vector *(x,y)*, the vector ***k*** is called ***w*** and the symbol *** is used to denote a dot product. The wavenumber (or angular spatial frequency) ***k*** indicates the direction in which the wave propagates and its magnitude is inversely proportional to the wavelength. The effect of different wavenumbers on the propagation of the wave is illustrated below.

Per request, below the Mathematica code used to generate these images:

```
a = 1;
k = {1,1};
\[Omega] = 2\[Pi];
Export["C:\\Users\\Mark\\tmp.gif",
    Table[
        Plot3D[
            a Cos[k.{x,y} - \[Omega] t],
            {x,-2,2},{y,-2,2},
            PlotRange->{-a,a},
            PlotLabel->"k = " <> ToString[k],
            AxesLabel->{"x","y",None},
            Ticks->{Automatic,Automatic,None}
        ],
        {t,0,.96,.04}
    ]
]

```
> 2 votes

# Answer
The formula returns a scalar (the height of the water surface at coordinates `x,y`), not a vector.

It is hard to tell what the authors had in mind, because the paper is very confused, but my guess is that it should have looked like this:

```
Y（x,y,t） = A * cos(w * f(x,y) + wt * t + FI)

```

Where `f` is a function that controls the shape of the wave.

This function will generate a circular wave centred at `x0,y0`:

```
f(x,y) = sqrt((x - x0)² + (y - y0)²)

```

This function will generate a directional wave with angle `α`:

```
f(x,y) = x * cos(α) + y * sin(α)

```
> 5 votes

---
Tags: java, physics, water
---


# Question
Title: Batching and Z-order with Alpha blending in a 3D world
I'm working on a game in a 3D world with 2D sprites only (like Don't Starve game). (OpenGL ES2 with C++)

Currently, I'm ordering elements back to front before drawing them without batch (so 1 element = 1 drawcall). I would like to implement batching in my framework to decrease draw calls.

Here is what I've got for the moment:

* Order all elements of my scene back to front.
* Send order list of elements to the Renderer.
* Renderer look in his batch manager if a batch exist for the given element with his Material.

+ Batch didn't exist: create a new one.
    + Batch exist for element with this Material: Add sprite to the batch.
* Compute big mesh with all sprite for each batch (1 material type = 1 batch).
* When all batches are ok, the batch manager compute draw commands for the renderer.
* Renderer process draw commands (bind shader, bind textures, bind buffers, draw element)

Image with my problem here:

But I've got some problems because objects can be behind another objects inside another batch.

**How can I do something like that?**

# Answer
A sprite-batch means that all the sprites of the batch exist in the same Z-distance. That means that it isn't possible for one sprite of batch A to be between two sprites of batch B. When that happens, the two sprites of batch B don't actually belong to the same batch and need to be drawn separately.
> 1 votes

# Answer
You could do something like this:

1. Go through list of sprites from back to front

1.1 sprite already rendered -\> next

1.2 check if 2d sprite extends collide with any sprite in the current batch or with any sprite coming before this one that is not yet marked as rendered (partly overlapping)

*TRUE*: continue with next sprite; rendering the current sprite with the current batch may result in sorting issues

*FALSE*: add sprite to batch and mark as rendered (eg: flag)
2. render and clear current batches
3. still any sprites not flagged as rendered? Resume at 1.

This will lead to an error free result with heavily reduced draw calls. Note: For multiple materials you need to maintain multiple sprite batches during this loop but the algorithm basically stays the same.
> 1 votes

---
Tags: opengl, c++, spritebatch, alpha-blending
---


# Question
Title: Moving a character according to the animation, rather than code
I'm using 3ds Max to export character animations in which my character is moving. I expected this to mean that the character will move in Unity, but it doesn't...

For example, if my animation (in 3ds Max) moves my character forward for a second, from `0,0,0` to `1,0,0`, in Unity, the character snaps back to `0,0,0` once the animation ends.

Is there a way to change the position of the character according to the *animation*, without something like `CharacterController.Move`?

# Answer
The prevailing wisdom has been to separate your animations from your movement. I.e. Animate the character in-place and move it via code. Dependent on your game type, this can indeed be the better method.

However, Unity (4.x) provides the Mecanim animation system, which allows for root motion to be applied from the animation to the character's in-game transform. In order for root motion from the animation to be applied, make sure the "Apply Root Motion" option is checked in the animator component.

Mecanim will also retarget animations for humanoid rigs auto-magically. By using the retargeting with root motion, you can use the same animations for a long-legged character and a short-legged character, and the movement will then (auto-magically) line up with the animation.

Skeletal meshes should include an animator component by default as of Unity 4.3, and I believe this is still the case as of 4.3.4.

Using Mecanim will also require you to make an Animator Controller, which is a state machine for controlling your animations.

The Mecanim reference can be found in the Unity manual pages here.
> 7 votes

---
Tags: unity, animation
---


# Question
Title: Get Tile Location On Screen (Java Slick and Tiled2D)
I want to create a rectangle around each tile that's blocked value = true. How can I find the X and Y (on screen) coords of the each individual Tile?

# Answer
> 1 votes
You can calculate each tile position on screen if you know the width and height of each tile like this:

```
pos.x = x * tileWidth;
pos.y = y * tileHeight;

```

Therefore, you can go through all the tiles:

```
for(x = 0; x < tilemap.getWidth(); x++)
for(y = 0; y < tilemap.getHeight(); y++)
{
    if(tilemap.tiles[x][y].blocked == true){
        // This tile is blocked, get it's position on screen
        pos.x = x * tileWidth;
        pos.y = y * tileHeight;
    }
}

```

---
Tags: java, tiles, slick
---


# Question
Title: CDK (as3) false positives when using it with array elements
I'm having problems when using the CDK (Collision Detection Kit) with elements in an array. It keeps getting me false positives of collision.

I'm making a game in which the player controls a “ship”, that has to avoid both enemies and the terrain in which it moves through, like a “tunnel” with obstacles. To make the “tunnel” random every time, I emit “pieces” of different walls into stage so it seems like an infinite tunnel with obstacles inside. In order to do this, I created an array, called wallArray, which stores the display objects from the class Walls, which is the class where in each frame, there's a different shape of wall.

Everything works like a charm, except the collision, which uses CDK. I'm using the regular CollisionList method:

```
//On the document class, on the enter frame (eventListener) function:
wallArray[(index - 1)].x -= wall_mov_speed;
wallArray[index].x -= wall_mov_speed;
if(wallArray[index].x < 0){
    spawn_wall_piece();
}
if(index == 5){
//We call this function for cleaning the array and readding walls to it
    adequate_array_of_walls(false);
}
if(wall_mov_speed < 15){
    wall_mov_speed += 0.009;
}

wall_collisions = myWallCollisionList.checkCollisions();

if(wall_collisions.length > 0){
    trace("hit!");
    if(myShip.visible == true){
        //We only kill the ship if it's visible, if not, it means it is already dead
        Ship.receiveDamage(Ship.max_health);
     }
    wall_collisions = 0 as Array;
}

```

And here we have the functions for rearranging the wallArray, also in the document class (and where I add the elements to the CollisionList):

```
function adequate_array_of_walls(init:Boolean):void{
    //This only executes if we are initialitizing the array
    if(init == true){
        for(index = 0; index < 10; index++){
            var aWall:Walls = new Walls();
            randomize = Math.floor(Math.random()*4) + 1;
            aWall.gotoAndStop(randomize);
            wallArray.push(aWall);
            myWallCollisionList.addItem(wallArray[index]);
        }
        wallArray[0].gotoAndStop(1);
        stage.addChild(wallArray[0]);
        wallArray[1].x = 800;
        wallArray[1].y = 0;
        stage.addChild(wallArray[1]);
    //if not, then we are just cleaning it so it doesn't grow bigger and bigger
    }else{
        for(var a:Number = 0; a < index - 1; a++){
            myWallCollisionList.removeItem(wallArray[a]);
            wallArray.splice(0,1);
        }
        for(a = index - 1; a < (10-2); a++){
            var aWall2:Walls = new Walls();
            randomize = Math.floor(Math.random()*4) + 1;
            aWall2.gotoAndStop(randomize);
            wallArray.push(aWall2);
            myWallCollisionList.addItem(wallArray[a]);
        }
    }
    //Then, either way, we tell index to be 1 since the reference in the function is [index - 1] and [index], so it starts with [0] and [1]
    index = 1;
}
function spawn_wall_piece(){
    index++;
    wallArray[index].x = (wallArray[index - 1].x + wallArray[index - 1].width);
    wallArray[index].y = 0;
    stage.addChild(wallArray[index]);
    stage.removeChild(wallArray[index - 2]);
}

```

Well, as I said, everything works except the collision, it keeps me detecting collisions even though there's none. I was troubled that it was the walls' too intrincate shape, but tried this method before even with mazes and worked perfectly. I don't know what could cause this, am I missing something?

I would appreciate very much any help or comment.

Thank you in advance.

EDIT: I post the full code related to the wall collision to cover every possibility just in case:

```
package  {
import flash.display.MovieClip;
import flash.display.Stage;
import com.coreyoneil.collision.CollisionList;
//...

public class Game extends MovieClip {
    //...
    //Wall generation variables
    static var wall_mov_speed:Number;
    var randomize:Number;
    var wallArray:Array = new Array();
    var index:int = 0;
    //
    //Wall collision variables
    var myWallCollisionList:CollisionList = new CollisionList(myShip);
    var wall_collisions:Array = new Array();
    //
    //...
    public function Game() {
        //...
        //Movement speed of the walls
        wall_mov_speed = 8;
        //Calling to the generating/adequating wallArray function
        adequate_array_of_walls(true);
        //
        //Collision managements
        wall_collisions = 0 as Array;
        //
        //...
    }

```

# Answer
Ok, so finally I found a solution for it!

The reason for the method to fail was that I added the items for collision when I initialized or rearranged the wallArray. I must have had done something wrong and it didn't work. However, if I added the items in the `spawn_wall_piece()` function, there's no problem:

```
function spawn_wall_piece(){
    index++;
    wallArray[index].x = (wallArray[index - 1].x + wallArray[index - 1].width);
    wallArray[index].y = 0;
    stage.addChild(wallArray[index]);
    myWallCollisionList.addItem(wallArray[index]);
    myWallCollisionList.removeItem(wallArray[index - 2]);
    stage.removeChild(wallArray[index - 2]);
}

```

So with that minor modifications, and adding in the constructor:

```
myWallCollisionList.addItem(wallArray[0]);
myWallCollisionList.addItem(wallArray[1]);

```

so as to not make null references, everything works fine.
> 0 votes

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


# Question
Title: IsoMetric Map draw: sort with Z-Buffer and anchor point
I'm writing an IsoMetric renderer for my html5 isometric game. The isometric renderer should be able to render objects with floating point coordinates.

SOURCE: https://github.com/ilmattodel93/EaselJs-Isometric-with-Heightmaps

As now, the renderer works pretty well, but I have some questions and a problem to fix. Note that little square is the anchor point, and lines are AABB (not correctly drawn I think).

**THE PROBLEM**

If you have a look at the demo, you should note that when the dragon is behind the tree on a higher level, it will be rendered over the tree instead of behind, as expected.

As you can see in js/mmo/renderer/IsoEntity.js#L91 and js/mmo/renderer/IsoLayer.js#L65, i have a "rough" implementation, and maybe it is'nt good. I've googoled around and find something called "topological sort", i've attempted to implement it, but it does'nt seems to solve.

For each tile I have information about minX, minY, minZ, maxX, maxY, maxZ. An AABB as you can notice.

**THE QUESTION**

My question is, how can I solve this problem? Is it better (and will be faster) to maybe implement a depth-buffer? And how can I implement it? Will it ensure high performance? Maybe will a correct anchor point (represented with little square) solve the problem?

Thanks for any help! :D

# Answer
> 4 votes
Basically if you number X and Y iso-coordinates their sum is the number of the diagonal, you sort tiles by diagonal, and then draw first tiles with lower Z. This is indipendent of screen coordinates. (of course assuming the camera is in the bottom left corner of the image)

# Answer
> 1 votes
I wanted to write this as a comment because I have not the time to dig that deep into your code at the moment but I don't have enough reputation nevertheless I wanted to maybe help you so I have to write an answer (maybe someone could correct/improve it):

It seems you sort the order of the sprites by a value you get by adding and subtracting the x,y,z values. This is also the way I did it in my isometric engine. Every object gets a "depth" value describing the distance from the camera and every object is put in a list which is sorted by this depth-value. Then everything is rendered in the order of the list.

You have to take into account that you are using isometric view so that the axis are shortened. Try multiplying or dividing by sqrt(2) (or maybe factor of 2). The exact factor and axis depends on your architecture of your map and the use of the axis, which I did not fully understand by now.

As far as I know you can not use min/max values but must use only one single point for sorting (because otherwise you should have to render a part in front and another part behind)

EDIT: Also try browsing some related questions. There are some more detailed answers already.

---
Tags: html5, isometric, depth-buffer
---


# Question
Title: Can global Illumination via path tracing replace all other current lighting techniques?
In the sense that you currently have algorithms like HDR, shadows, reflections, caustics, motion blur and so on, does complete path tracing take care of all these effects, or would you still have to implement these effects separately?

# Answer
Firs of all I want to point out that Global Illumination is a general group of algorithms that deal with simulating realistic lighting, it takes into consideration indirect illumination. Path tracing is just one way to achieve Global illumination (and btw it doesn't take into account all the effects you mentioned).

Path tracing uses a rendering method similar to ray tracing with a fundamental difference that the cast rays are chosen at random, and at each intersection with a diffuse object in the scene a new reflection ray is picked at random. Path tracing is also not great when it comes to performance concerns where it needs to sample each pixle hundreds of times in order to get a better quality images, which makes it a poor choice for real time rendering. On the other hand Path tracing is not the only method to achieve global illumination, photon mapping is a valid alternative, here is a list of other methods that can produce global illumination.

Unfortunately there will never be solution that fits everything, as a conclusion, these are the basic points why path tracing will never be 100%

* For instance Path tracing doesn't have an out of the box hardware support like rasterization which makes algorithms like shadow mapping exists that are more suitable for the current hardware.
* Even with hardware acceleration Path Tracing is still considerably slower than other methods. Even ray tracing.
* Hybrid rendering approaches exists, And it will continue to exist because of different requirements.
* There are alternative algorithms even for off-line rendering and the use highly depend on the scene and the requirements each can do several effects better than the others.
> 3 votes

# Answer
In principle, yes, path tracing can do all the things you mentioned.

* HDR is just about using realistic light intensities in your scene, plus tone-mapping the result for display. It's not dependent on a specific rendering technology.
* Shadows and reflections are a strong point of raytracing methods.
* Motion blur can be done by distributing your sample rays over time as well as space. It does mean you have to be able to do intersection tests with rays at any time within the frame interval, so there are some nontrivial implications for how you represent geometry, BVHs, etc.
* Caustics are bad for "vanilla" path tracing because working from the eye toward the lights, the probability of generating paths that are part of caustics is very low. But other algorithms in the path tracing / photon mapping family (e.g. bidirectional path tracing, Metropolis, VCM) can handle caustics pretty well.

If the question is *will* path tracing replace all other algorithms, I doubt it. Path tracing is elegant, but elegantly simple algorithms turn into more complex ones when you want them to run fast. Witness the aforementioned family of path tracing / photon mapping algorithms—many of them are quite complex, and they are all basically designed to shore up path tracing in scenarios where it performs badly.

Moreover, for highly ordered sets of rays, like primary rays from the camera and light rays from small sources, rasterization has definite advantages over raytracing for finding intersections with a polygonal scene. And people have done work on generalizing rasterization to handle correct depth of field and motion blur (not postprocessing fakery)—which was long seen as the province of raytracing alone.

My guess is we will continue to see hybrid strategies in real-time graphics—games today already use forms of raytracing, like screen-space reflections. We'll see more raytracing used on the lighting and shading side of things, but rasterization will continue to be king for finding intersections in the primary view. Smart caching and filtering strategies are also important, since the memory/compute gap is still growing and brute-forcing huge numbers of pixels/rays is bad.
> 3 votes

---
Tags: rendering, lighting, global-illumination
---


# Question
Title: Improving the performance of smooth movement up and down
I would like to achieve a smooth movement of a game object up and down. The way I have always seen this done is via a sine wave, and adding the value of y for a specified X to the game objects value of Y.

This method seemed slightly slow so I had the idea of using two parabolas, one of which is negative such as the following two: and then one would only use the values above or below zero depending on the parabola. However even this seems like an obtuse and slow method so I was wondering if there was a better way?

# Answer
> 1 votes
Simple harmonic motion is still easy to achieve with a sine wave and `sin` is a pretty fast function. However, there are some optimizations you can make since you'll be using it over and over. Since this movement code does not require much accuracy from `sin`, you can limit the input to `sin` and store the results. Using something like a hash table or in this example, an array, you can do the following:

```
float[] sinValues = new float[361];

public void Initialize() {
   for(int i = 0; i <=360; i++) {
       //store the values of sin from 0 to 360
       sinValues[i] = Math.sin(i * (Math.PI / 180f));
   }
}

public float FastSin(float value) {
    //convert the value to value within 360 degrees
    int inputAngle = (int)((value % (2*Math.PI)) * (180/Math.PI));
    return sinValues[inputAngle];
}

```

Now you can use `FastSin` to simply retrieve the stored value of `sin`.

---

Included below is my misinterpretation of your original question.

If you want to to be faster, increase the frequency. If you want it to move more, increase the amplitude. What does that look like in code? Examples:

```
//Increase the frequency (faster up and down)
float factor = 3;
Math.sin(deltaTime*factor);

//Decrease the frequency (slower up and down)
float factor = .3f;
Math.sin(deltaTime*factor);

//Increase the amplitude (more distance up and down)
float factor = 3;
Math.sin(deltaTime)*factor;

//Decrease the amplitude (less distance up and down)
float factor = .3f;
Math.sin(deltaTime)*factor;

//All together now, faster up down over a smaller distance
float ampFactor = .4f;
float freqFactor = 4f;
Math.sin(deltaTime*freqFactor)*ampFactor;

```

Finally, you can make the whole wave above zero by adding one:

```
(Math.sin(deltaTime*freqFactor) + 1f)*ampFactor; //now go from 0 to 2
((Math.sin(deltaTime*freqFactor) + 1f)/2f)*ampFactor; //now we go from 0 to 1

```

# Answer
> 1 votes
I think the `sin` function is still slow. You can approximate it with a function like

```
y = 1 - (x - 1) ^ 2

```

The code looks like this:

```
/**
 * @src_x       source x coordination
 * @dst_x       destination x coordination
 * @time_len    length of time
 * @time_cur    current time (from 0 to time_len)
 * @final_x     output result of x coordination
 *
 * math function: y = 1 - (x - 1) ^ 2 { x >= 0 & x <= 1 }
 * (you can use another function like: y = 1 - (x - 1) ^ 3 { x >= 0 & x <= 1 })
 */
void MoveByTime(const float src_x, const float dst_x, const float time_len, const float time_cur, float* final_x)
{
    if (0 >= time_cur)
    {
        *final_x = src_x;
        return;
    }
    if (time_len <= time_cur)
    {
        *final_x = dst_x;
        return;
    }
    float t = time_cur / time_len;
    // math function: y = 1 - (x - 1) ^ 2
    t = 1.0f - (t - 1.0f) * (t - 1.0f);
    *final_x = src_x + (dst_x - src_x) * t;
}

```

Here's how Wolfram Alpha would plot it:

The rest of the sine wave can be approximated just by repeating mirror images of that output.

---
Tags: movement, performance, curves
---


# Question
Title: What does "non commercial use" mean in terms of game assets?
I recently got an app for my iOS device called "123D Design." It is a 3D model editor. Upon creation of an account, the application tell you that "your models may not be used commercially."

What exactly does this mean? If I were to create a 3D game and sell it, does this mean I cannot use any models made with that app in my game?

This seems quite ridiculous if it's true. Can companies do that?

# Answer
> 2 votes
Generally Yes, here No. The key reason is simple: you're told *upon creation of an account*. That's too late.

There's a large degree of contractual freedom in most of the Western World. Selling a product X under terms that disallow its use for goal Y is not an unreasonable limitation or in violation of any law.

However, contracts have fixed terms that generally cannot be modified unilaterally, especially when that would impact the reason for one of that parties to enter that contract in the first place.

I've checked the public Autodesk Terms of Service, and they do not appear to have such a limitation on commercial use of 123Design.

# Answer
> 10 votes
Non commercial

> ...refers to an activity or entity that does not in some sense involve commerce.

Selling the game involves commerce. Yes, companies are allowed to do that, the details of that aren't on topic here. You may want to look into a paid version of the software, which likely doesn't have the same restrictions. Alternatively, use a different tool that doesn't have those restrictions.

# Answer
> 4 votes
This is a very tricky question that heavily depends on jurisdiction and the specific circumstances.

As a general rule, the content you create belongs to you, and you can do whatever you want with it, no matter what tools you used to create it. Also, as a general rule, claims made by others are just empty words unless it's a law or a contract that you agree to.

This is probably the key question - do you have a valid contract with the toolmaker, where you give away those rights? "the application tell you ..." is not specific enough. I can make an application that tells you that you owe me $1000, and that doesn't mean anything. For example, if you go to the store and buy a paintbrush and afterwards see that it has a label on it "Paintings made with this brush may not be sold commercially", then again it doesn't mean anything.

However, if there is an EULA where the contract or T&C is shown to you before using the application, and you need to agree to it before using it - then it's complicated. It may be a valid contract, or it may be empty words, depending on where you live and the exact details of how it's done. In some locations, any terms shown to you after the purchase is made are null and void, but not in all of them - so you may need legal advice from a *local* lawyer.

Another specific rule that might apply - if the content you create includes content owned by others, then this is derived work and you require permission to distribute it - this applies to all kinds of game content where you use pre-made sprites/sounds/whatever in your game; or if you make a 3d model that includes parts of other models or ready-made templates, then it also may require that permission to distribute your creation - but it doesn't apply if you create a model 'from scrath' simply by using the tool; if you use a complex tool but the 'creativity' is 100% yours then copyright law doesn't require any permission from the toolmaker unless you have a binding contract where you agree not to do X.

# Answer
> -1 votes
> your **models** may not be used commercially.

I think they key word here is "models", i.e. they don't want you to sell the models you create. So I don't think it should be any problem creating a game using the models.

But I do think such a restriction is pretty far fetched, and I have my doubts to whether or not they are legally valid. But I have no qualification to give such legal advice.

---
Tags: 3d, models
---


# Question
Title: Texture mapping a complex object on openGL ES
I dont have much experience with openGL ES (or openGL), but i do get the general idea of texture mapping, which is each vertex should be mapped for the relevant UV coordinates of the texture we choose to map. but what happens when i have complex objects?

Lets say i have the known Stanford bunny:

and i want to map this texture:

It is not very simple to calculate all vertices locations on the image at all. Are there any known methods or best practices for doing that?

Where should i begin regarding this kind of mappings?

Thanks!

# Answer
This is usually done by an artist using an application like maya or 3Ds max where the artist can manually maps the UV point on the image.

If you want to automate this operation you can generate UVs using one of the known methods, these automatic UV generation are usually used as a starting point for artists. For example you can use planar or spherical texture coordinates generation, the first method is to project the vertices on a plane and generate UVs based on the projected vertices. The other method is project them on a sphere. There are other methods like projecting it on a cube or using ray casting. The choice of approach depends on the shape of the object, for example a human body might start with a cube based UV generation so each side of the human is projected on a side of the cube (might also apply for stanford bunny). There is no golden bullet, and those algorithms are usually just a starting point for the artist unless you have a systematic or procedural shape.
> 2 votes

---
Tags: opengl, textures, opengl-es, opengl-es2
---


title: Getting entity type object

text:
# Question
Title: Getting entity type object
I have a custom entity class and what it does is create a SQUARE object.

```
public class Entity {
    Rectangle rect;

public Entity() {
    this.rect = new Rectangle(20,20);
    rect.relocate(200,200);
}

// I want it to be public Entity getEntity() {return this.rect;}
public Rectangle getEntity() {
    return this.rect;
  }
}

```

The problem is that I can't get my class to return an **Entity** object, instead of a Rectangle one.

How do I go about doing that?

# Answer
> 1 votes
```
// I want it to be public Entity getEntity() {return this.rect;}
public Rectangle getEntity() {
    return this.rect;
}

```

You have it all wrong, you seem to say you want to return `this.rect` and also have the function state that it returns an entity. That cannot be done. Te object you return has to be of the same type or a subclass type of the object your function definition/declaration says you"ll return.

For instance you can't do:

```
...
Orange orange
public Apple getApple() {
    return this.orange;
}

```

You can do:

```
class MagicApple extends Apple{}
...
MagicApple magicApple
public Apple getApple() {
    return this.magicApple;
}

```

You need to read more about oop, inheritance, polymorphism and strongly typed languages.

# Answer
> 1 votes
In your code,

```
public Rectangle getEntity() {
    return this.rect;
}

```

The "Rectangle" before getEntity() is the type of variable that the function will return. If you want the function to return another type, simply change it.

```
public Entity getEntity() {
    return this.rect;
}

```

The function is now set to return an Entity type, but still returns a Rectangle type. This will give you an error(as you've probably noticed). So the return statement has to be adjusted as well.

```
public Entity getEntity() {
    return new Entity();
}

```

Now the function will return a new instance of the Entity Class. But i suspect you want to return a specific Entity.

```
private Entity specificEntity = new Entity();
public Entity getEntity() {
    return specificEntity;
}

```

# Answer
> 0 votes
If you are calling `getEntity()` then you already have the Entity object, it is what you are calling `getEntity()` on. If you want it to return another Entity object other than the one you already have you can make a method similar to this:

```
public Entity getEntity(){
    return new Entity();
}

```

although i suspect you want the Entity object that you already have.

If this isn't what you intended please clarify your question, it looks like you want to return Rectangle as an Entity which is not possible unless it is a subclass of Entity, maybe you can explain why you want to do this?

---
Tags: java, 2d, oop
---


# Question
Title: Degenerate AABB (axis aligned bounding box), does this always intersect?
I'm studying ray-AABB intersections and I'm asking myself: what would happen if one of the dimensions of the axis aligned bounding box was degenerated?

For instance:

```
AABB_min = {1,1,1}
AABB_max = {5,5,1}

```

in this case the Z coordinate would be the same for the AABB maximum and minimum point. You can think of this AABB as a 2D rectangle.

In such a case, would this always yield "true" as intersection with a ray if the ray's Tmax and Tmin were something like *+inf* and *-inf* (so that we don't need to bother with them)?

# Answer
> 1 votes
The example you provided is not a degenerate case, and it works. This will give correct results. You didn't mention which algorithm you are talking about but I assume you're talking about the ~~SLABS method (correct me if I am wrong)~~.

The OP was talking about this paper, which is similar to the slabs method and my explanation almost remains the same.

~~I don't know why you assume `Tmin` and `Tmax` will be +/-inf, they will simply be equal for the z coordinates, in other words `TminZ = TmaxZ`. Keep in mind that for `Tmin`, `Tmax` to make sense they are calculated for each axis independently.~~

The case is valid for Tmin and Tmax being +/-infinity the quote from the paper.

> Note that the reason we check the sign of each component direction is to ensure that the intervals produced are ordered (i.e., so that tmin \<= tmax is true). This property is assumed throughout the code, and allows us to reason about whether the computed intervals overlap. Note also that since IEEE arithmetic guarantees that a positive number divided by zero is +1 and a negative number divided by zero is ¡1, the code works for vertical and horizontal lines (see  for a detailed discussion of this)

Note that your degenerate case was not when Zmin = Zmax. your missing point was when a ray is parallel to a certain axis which could yield `Tz = +/-inf`.

If you have a case where the bounding box `min > max` then this is not an AABB, and according to the algorithm it doesn't apply since `max>min` is a pre-condition for any ray/AABB algorithm; that input is undefined for that certain algorithm.

Moreover any anlytical or algebraic solution should define the domain of the problem (domain as in mathematics) on the input, otherwise running that solution on that input is undefined. And the example you provided is defined for that particular algorithm.

---
Tags: 3d, aabb, raytracing
---


# Question
Title: What is the correct way to seperate (react) view from state?
I would like to know the correct implementation to declare game logic and view logic:

I see 3 ways of implementing this:

1.Storing (eg writing preprocessing to store the change to a property) property changes to data entities that are dispatched to listener(s) of the data entity. The main listener being the view, where the view contains the declared rendering logic (ie changing the entities animation based on a property change, changing the entities render object position).

> State Model (x,y,z,state) -\> View (listens to change in x,y,z,state)-\>Scene graph object (x,y,z,animation, gets set by the View)

The issue with this is that it becomes evident that game engines are executing a lot of `char[]` switch statements (eg the names of properties) in the View.

2.Declaring the view as updating to the entirety of the model. Eg, instead of saving the changes as specified in 1) the view updates the render objects on every tick by inspecting the entire model, as opposed to the provided changes of 1). The tradeoff between 1 and 2 is the necessity of the additional execution of storing the property changes on the state tick.

3.Declaring animation logic in the state logic. Eg, instantiated member render objects are dummy objects when rendering is not performed.

***The questions:***

1. As specified in the title, what is the correct implementation to reacting to the game state in the sense of where should one declare display/rendering/animation (view) logic that reacts to the game state?
2. What is the implementation used in most game engines that facilitate large projects? (if possible, please specify for specific engines: SupremeCommander/clones, SC2, Unreal, ID, Frostbite, Anvil)
3. Which implementation do studios implement to architect projects using said engines? It's apparent that it is possible to not seperate model from view in the above engines. Eg, if you implement an entity, you would presumably want it to be viable in multiplayer, coop, and single player.

The questions regarding other engines deals with the fact that perhaps it has been evaluated that it is not a sufficiently optimized implementation to consume the state in a View as opposed to executing direct calls to render objects.

So, on tick we update the game data simulation. For example:

> The state of a unit's weapon is updated to firing. However, updating the view of the weapon to firing (by for example, setting the animation of the weapon and animating the hand) is not necessary in all instances of the simulation.

# Answer
> 1 votes
There is rarely one correct way to accomplish anything when it comes to design patterns. There are of course properties that we as programmers deem useful. When we are required to reuse or extend code we tend to cherish flexibility. This property is often attributed to decoupling objects. Hence I don't believe the third option is strongly advised.

The other issue that was brought up is the amount of granularity that would be preferable; As in should we react to each separate change or instead render the model in it's entirety. This is a tradeoff between additional flexibility and optimization vs. robustness and simplicity. This is nearly entirely opinion based and is heavily influenced by the requirements of the project and the technology that is being used. I always lean towards simplicity because of time budget and debugging concerns. If the system is well made it may leave the issue of granularity to the game designer or rely on the robust solution. I would not advise to force the high granularity approach and I believe it is not forced in any engine I used this far.

---
Tags: state, view
---


# Question
Title: How to do collision detection for fluids in 3D?
Is there an algorithm or a technique which can detect the collision between 3D fluids?

I currently treat my fluids as dynamic meshes. Is it possible to find collisions with these, or will I need a different representation?

I have considered traditional collision detection techniques like bounding boxes and 'trees' of bounding boxes, but they seem to be more accurate for rigid/solid objects, not for fluids.

# Answer
This question is really too broad. But there are some cool references that you can check. They are at the end of the answer.

The usual approach to represent realistic 3D fluids is to use a cell-based representation of the tracked portion of the world in which the fluid will be confined. Each cell has the velocity and pressure info, as shown in the image bellow. Instead of tracking the fluid in the world (Lagrangian viewpoint), the grid give us the possibility of look at fixed points in the space, the cells themselves (Eulerian viewpoint), which turns the problem easier to tackle.

Grid cell. p is the pressure, u, v and w are the velocity components for each axis.

To update the grid in each time step, the Navier-Stokes equation is used. The classic equation is a differential equation that represents the fluid advection, viscosity, pressure and external forces. For computational purposes, the equation is simplified so it does not have the viscosity factor (the error of the numerical solution can be seen as a viscosity component, however). This version of the equation is given bellow.

Momentum equation:

Incompressibility condition:

About the momentum equation, the left side and the first factor of the right side express the advection contribution, the second factor of the right side is the pressure contribution and the last factor of the right side is the external forces contribution.

Starting from the easier factor to compute, the external force contribution is just the acceleration caused by the net force of all fluid external forces (such as gravity, for example).

The advection contribution can be computed using the Semi-Lagrangian algorithm, which just uses the current velocity in a cell to travel to the past and get the value from another cell.

The pressure contribution is the most difficult, since usually it is also used to enforce the incompressibility condition and boundary conditions. It can be shown that the pressure solving leads to a Poisson equation, resulting in a linear system. To solve this equation the Modified Incomplete Cholesky Conjugate Gradient Algorithm can be used. It is fast but difficult to parallelise and implement. On the other hand, the Jacobi iterations are easy to implement and parallelise, so they are being used in shader implementations of fluid dynamics.

With this kind of representation the collision response for fluids comes practically for free, because of the advection and pressure updates. You just need to make sure that all fluid is inside the controlled world space.

In these references you can check shader implementations:

2D: GPU Gems 2D fluid.

3D: GPU Gems 3D fluid.

This last reference is a really great book that explains a lot about fluid simulation in detail: Robert Bridson's Fluid Simulation for Computer Graphics.
> 11 votes

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


# Question
Title: How can I batch-convert TexturePacker .pvr.ccz files to .png?
I am a pixel artist with very little programming knowledge. I have read that it's possible to use Texture Packer to do batch conversion of pvr.ccz files to png using the Command Line Tool.

How do I install the Command Line Tool for Texture Packer? It doesnt seem to be installed by default and the info presented when I select *'File'-\> 'Install Command Line Tool'* makes no sense to me... It says:

*Simply add C:/Program Files (x86)/CodeAndWeb/TexturePacker/bin to your path variable or add the following line to your scripts calling TexturePacker: set "PATH=C:/Program Files (x86)/CodeAndWeb/TexturePacker/bin;%PATH%"*

I dont understand how to carry out these instructions..

>

Then, once I succeed in installing the Command Line Tool, what should I type into the Command Line Tool to convert 50 or so `.pvr.ccz` files to `.png`s in a different folder?

The TexturePacker website has this to say on Batch Converting:

*Write a simple batch file containing these lines to do as mass conversion of images:*

```
`@
echo off
for %%X
in (*.png)
do (C:\Programme\TexturePacker\bin\TexturePacker.exe  <parameters>  %%X)`

```

*Please replace with your parameters needed.*

**Batch converting images to pvr or pvr.ccz**

*You can use TexturePacker to simply convert a complete directory of images with a single command line call into whatever output format you need (pvr.ccz in this example):*

```
`find <directoryname> -name \*.png | sed 's/\.png//g' | \
xargs -I % -n 1 TexturePacker %.png \
--sheet %.pvr.ccz \
--data dummy.plist \
--algorithm Basic \
--allow-free-size \
--no-trim \
--opt RGBA4444 \
--dither-fs`

```

*Replace with the directory to search.*

So this example is converting png to pvr, I need to go the other way. But I have no idea how to open or install the Command Line Tool from within the Texture Packer GUI...

And then Im not sure how to use the code above to write a 'simple batch file' to carry out the conversion I need?

I'm on a PC with Windows 7.

# Answer
> 3 votes
TexturePacker installs a command line tool with the standard installation.

You have to set the path to find it from command line. A description about how to add the path can be found here.

To reach the command prompt: Click the Start button Picture of the Start button. In the Search box, type Command Prompt, and then, in the list of results, double-click Command Prompt.

If you've set the path according to the information in TexturePacker you should be able to type

```
TexturePacker --help

```

Which should list commands available in TexturePacker. If you get "command not found" something went wrong with the path.

From here you should be able to run

```
TexturePacker filename.pvr.ccz --sheet filename.png --data dummy.plist --algorithm Basic --allow-free-size --no-trim

```

This should create a sprite sheet with the single sprite in the `.pvr.ccz` file and convert it into a `.png` file.

---
Tags: art, pipeline
---


# Question
Title: What image sizes should I use for a mobile cross-platfom game?
I'm new to mobile development. I use Monogame.

What device screen resolutions should I consider to target all Android, iOS and Windows Phone devices?

Assuming we have three screen sizes, should I be using different images for each target resolution?

# Answer
I would at least make a difference between high resolution and low resolution devices. You should also distinguish between tablets and phones.

Another important factor is the difference in the aspect ratio. You have 4:3 16:9 and other device formats.

For some explanation on iOS devices look here: http://www.codeandweb.com/blog/2012/12/14/scaling-content-for-retina-display-iphone-and-ipad
> 0 votes

# Answer
Mobile devices can have all kinds of screen resolutions, from small low-end phones to large tablets. While the available resolutions on iOS are manageable, the markets for Android and Windows Phone devices is so fragmented that you can get pretty much anything.

That means you should try to develop as resolution-independent as possible. When you can, you should develop your game in a way that it checks the screen resolution and automatically resize the graphics accordingly, so that the part of the game world shown on each device is the same.
> 1 votes

---
Tags: monogame, mobile, cross-platform, resolution
---


# Question
Title: Events vs Pinging: How should I structure my HUD-updating code?
I'm starting to develop a 2D fighting game using C++ and SMFL. I'm relying (at least sort of) on a Entity Design Pattern.

I'm struggling to see how my code should update and manage a heads-up-display (HUD).

I think there are two main possibilities:

1. The HUD object has references to the players. It periodically updates itself by querying them.
2. The different systems (input, physics, ...) update the HUD anytime by sending it new information.

The first seems costly because the information might not have changed as often as the HUD queries for it. The second one seems less automatic because the systems NEEDS to specifically call to update the HUD (plus the HUD needs to provide various methods).

What should I do?

# Answer
> 2 votes
This is most often done with your second option, the event system. When something happens, send out an event describing what happened. Anything the HUD cares about it will listen for. It will potentially need to keep copies of some data (like health), but this is often beneficial for a variety of reasons.

One example of why the copy is useful is that you can animate these values. The player health may immediately drop by 10 points but the HUD can flash the health bar, set the lost amount to a different color, and then shrink the bar by the lost amount over some short period of time.

Event-based approach is necessary for some other things, as well. For instance, to display the damage of an attack, you can't just query the state of the game. The attack will quite likely have been fully resolved and forgotten by the time the HUD queries if any attacks are going on. If every attack also emits an event then the HUD and buffer those up and display them during the next HUD update.

Event-based approaches also come in handy in larger scale games. Many games make use of UI middleware with embedded but inefficient scripting languages that often have severe performance concerns when calling between script and C++ code. Letting the C++ code buffer up the events and then dispatch them all to the UI script code in one call can be very beneficial for performance, both bercause it reduces C++-to-script calls and because it is more friendly to the CPU cache.

Athur's answer is a good one for some higher-level languages that already have Observer-like properties built-in. For lower-level code the overhead of making some data observable with a generic framework may not be worth the cost, especially if you still also have an event system (which you need anyway for things that aren't state-based, like the attacks example). We've used observers in some Unity code (non-real-time game) combined with an MVVM pattern for the various HUD components and inventory screens and that worked well. In bigger real-time games we have definitely seen observer and reflection systems take up significant portions of frame time and so I recommend avoiding them and going with a simple event-based architecture since you can optimize that down the road quite easily if you end up needing to.

# Answer
> 1 votes
I suggest decoupling the two and relying on an event-like (signals and slots) system.

In short, make a generic base `Observable` class and an `Observed` class. The `Observable` class has a list of `Observing` object instances. When the health changes it notifies everyone who is interested about the new health status. That way health change code can be decoupled from code handling death. So you could have the HUD as an observer and the some other parts of the game perhaps like maybe the rage value handler could observe health changes too.

It is often good to decouple objects when possible and write generic code to reduce duplication.

You can find more on the Observer pattern here.

---
Tags: architecture, events, hud
---


# Question
Title: x-inverted obj importer in BulletSharp - what's wrong?
See \[dead link removed\] at the repository.

Screenshot:

\[broken image removed\]

Left: bullet imported version, right: correct 3ds max version.

It's somehow inverted. If you think that left part is just 180 degrees rotated you are wrong. Just rotate it yourself in Paint and you'll see - they will be different.

What's wrong with the bullet importer?

Usage:

```
        var wo = new WavefrontObj();

        int tcount = wo.LoadObj(path);

        Vector3 localScaling = new Vector3(1, 1, 1) * 1f;

        var vertices = wo.Vertices.Select(v => Vector3.Modulate(new Vector3(v.X, v.Y, v.Z), localScaling)).ToArray();
        var indices = wo.Indices;

        if (tcount > 0)
        {
            var trimesh = new TriangleMesh();
            int i;
            for (i = 0; i < tcount; i++)
            {
                int index0 = indices[i * 3];
                int index1 = indices[i * 3 + 1];
                int index2 = indices[i * 3 + 2];

                Vector3 vertex0 = vertices[index0];
                Vector3 vertex1 = vertices[index1];
                Vector3 vertex2 = vertices[index2];

                trimesh.AddTriangle(vertex0, vertex1, vertex2);
            }
            CollisionShape concaveShape = new BvhTriangleMeshShape(trimesh, false);
            CreateRigidbody(transform.Position, transform.Rotation, concaveShape);
        }

```

I tried to import with Assimp and got the same result. So the importer is correct but something inside the bullet mirrors it.

# Answer
For 3dsMax exported models with flipped YZ (Poser like) setting (checked by default) you should invert Z axis and swap vertices (like 0 1 2 to 2 1 0).

```
    var wo = new WavefrontObj();

    int tcount = wo.LoadObj(path);

    Vector3 localScaling = new Vector3(1, 1, 1) * 1f;

    var vertices = wo.Vertices.Select(v => Vector3.Modulate(new Vector3(v.X, v.Y, -v.Z), localScaling)).ToArray();
    var indices = wo.Indices;

    if (tcount > 0)
    {
        var trimesh = new TriangleMesh();
        int i;
        for (i = 0; i < tcount; i++)
        {
            int index0 = indices[i * 3];
            int index1 = indices[i * 3 + 1];
            int index2 = indices[i * 3 + 2];

            Vector3 vertex0 = vertices[index0];
            Vector3 vertex1 = vertices[index1];
            Vector3 vertex2 = vertices[index2];

            trimesh.AddTriangle(vertex2, vertex1, vertex0);
        }
        CollisionShape concaveShape = new BvhTriangleMeshShape(trimesh, false);
        CreateRigidbody(transform.Position, transform.Rotation, concaveShape);
    }

```
> 0 votes

---
Tags: c#, models, graphics-programming, bullet-physics, import
---


title: Materials and Mesh association

text:
# Question
Title: Materials and Mesh association
I'm trying to implement a Material system in a small engine for training and I've got questions about materials.

Currently I've got that:

* **Material:** A Material with array of Technique
* **Technique:** Stock an array of Pass
* **Pass:** Content RenderState (blend to apply, draw mode, face culling, …), Shader/Program and an array of Parameter
* **Geometry:** Buffers, Indices, Vertices, ….
* **Parameter:** A parameter is use to stock and share values with program (color, texture,…)

Now I'm not sure about that:

1. A Material is something shared by Meshes or each Mesh have his own Material? In my scene, I've got 5 trees: two red trees and 3 blue shiny red trees (same Geometry). Each tree have is own Material or each tree have a reference to the same Material?
2. The Material own by a Mesh is a copy of a Material or a reference to the original Material?
3. In my Material I have texture offset and scale, it's useful for drawing a part of the Texture only, but how can I manage offset and scale if my Material is shared and each owner didn't use the same values? (In the case where all my objects are in the same texture atlas)
4. If each mesh have his own Material instance (a copy of an original Material) how can I know if each Mesh have the same Material? (An ID per Material may be?)

Thanks a lot!

# Answer
> 1 votes
Well, if two meshes have the same exact material without change of textures colors..etc then each mesh will have a reference to the same material.

The usual approach to do this is to have list of resources of materials and each mesh can reference any material. If the original material changed everything that reference it will change. Now if you want to a certain mesh to have a slightly different version you can always clone the material as if it was a new one. It's also a good practice to have template materials that can be cloned and modified (see how unity3D handles this). Keep in mind that this doesn't mean textures for example should be duplicate, material is usually a set of references and settings to other resources.

Regarding the offsets, if it has a different offset, then you will need to duplicate the material. Keep in mind that the material is usually a set of references to other resources so it shouldn't be a heavy object.

If the mesh have a reference to a different object(material) that technically is a different material even if it has the same assets, materials can have a different id and name the name is usually for the human and the id for the engine.

# Answer
> 1 votes
You can split up your data into *heavy* and *light*. Heavy resources are things like shaders, geometry, and textures, which use a lot of memory and have a high cost associated with changing them. However, light data like texture offsets and blending colors are often changed and quick to change.

Thus, you can split up your "renderables" into two distinct sections. One section holds references to the heavyweight resources, and the other section holds unique, lightweight data.

This carries some additional benefits as well. For example, the sharing of heavy resources means that renderables can easily be batched together to cut down on state changes. As well, if enough objects have the same lightweight data signature and the same heavyweight resource references, they can easily be selected for instancing. Finally, the heavy resources, which would probably be handled by one or more resource caches, could be reference counted.

---
Tags: architecture, 3d-meshes, resource-management, materials
---


# Question
Title: How can I "grow" regions representing countries in a 2D grid?
My friend started to make a 'country-generator' type of thing. We have some starting points, and we want to 'grow' countries from them randomly until the whole area is filled. What's is an effect effective way to create something like this?

This is an image of a desired possible end result:

# Answer
> 5 votes
Here is the general algorithm that could be used to achieve a similar result:

`Let N be the number of countries you wish to have`

1. Randomly pick N^2 points on the 2D plain.
2. Create the Voronoi diagram to split the plain into N^2 cells.
3. Use Union Find between 2 random neighboring cells (that are on disjoint sets) N\*(N-1) times
4. Use the newly created trees of cells as the countries' polygons.
5. Apply a wave / noise filter to get the fuzzy look you desire.

You can play with Voronoi here:

http://blog.ivank.net/voronoi-diagram-in-as3.html

Learn how to apply apply noise here (to make the cells less rigid):

How do I make a natural-looking map from some Voronoi regions?

# Answer
> 4 votes
For a 2D grid, like in the image you posted.

While probably not the most efficient in terms of speed and memory usage, I find that a brute force approach could still be useful, since it's easy to get it started. Especially if this is not to be used in places with time or memory constraints.

```
//Get some random cells for countries to start extending from.
for each Country in Countries
  Cell unoccupiedCell = Map.GetRandomUnoccupiedCell()
  Country.OccupiedCells.Add(unoccupiedCell)
  unoccupiedCell.occupier = Country
end for each

//Extend each country at random
while Map.UnoccupiedCells.Count > 0
  for each Country in Countries
    Cell unoccupiedCell = Map.RandomUnoccupiedCellInVicinityOf(Country)
    if (unoccupiedCell exists)
      Country.OccupiedCells.Add(unoccupiedCell)
      unoccupiedCell.Occupier = Country
    endif
  end for each
end while

```

---
Tags: 2d, tiles, procedural-generation
---


# Question
Title: "Quad" background showing on OpenGl ES 1.0/1.1 Sprites
I modeled my sprite drawing on Grid.java and GLSprite.java from SpriteMethodTest, using 2D OpenGl ES 1.0/1.1 on Android, but the "quad" sprite background shows when two sprites overlap each other. I'm not using double buffering though, in onDrawFrame() I just do a gl.glClear(GL10.GL\_COLOR\_BUFFER\_BIT | GL10.GL\_DEPTH\_BUFFER\_BIT);

and the code in onSurfaceCreated() and onSurfaceChanged() and anywhere else is pretty much identical.

My texture images are single layer .png with a transparent background and are "even" sized. And all the bitmap texture loading gl code is the same. I compared my images with the ones from SpriteMethodTest, in Gimp, and they appear to have the same properties.

The display area is black and when the sprites overlap, the "quad" the texture is "on" is like a black square when it goes over another sprite.

What should I be looking for to try to fix it so that only the texture image is visible?

Thanks!

# Answer
> 1 votes
You need to enable blending.

```
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

```

Also note that z-ordering is important when drawing blended sprites. You need to draw the sprites from back to front. If you do not do that and draw a sprite behind another, blending will not be correctly applied. You may want to disable depth buffering if you don't know you really need it.

You can find a great blending mode illustrator from here. Here is also an image which explains different blending functions:

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


title: Unity Spaceship camera control

text:
# Question
Title: Unity Spaceship camera control
I'm trying to make a third person spaceship control system in Unity. In theory, it works like this: Let's suppose you move your mouse to the right. The targeted direction would rotate to the right compared to the current camera direction and the camera would rotate to face towards the new direction as well.

The problem lies in the calculations: how can I calculate the direction change using the current camera rotation? Also, please mind that the ship rolls with Q and E to the left and right, respectively, as to improve player control.

The system is designed this way to help controlling bigger, slower turning ships (where direct, limited mouse following is not an option because of the low turning speed). But if you have a suggestion for a better control system for such ships, I'd be glad to hear it.

# Answer
Get the mouse coordinates in normalized device space (i.e. -1 to 1 in both axes.) Then multiply this by the inverse of the (projection * camera) matrix (with a depth of 1/2 in directx or 0 in OpenGL). This gets you a point in world space, where the mouse is pointing to. Construct a vector from the camera position to this point, and make it unit length. This is the desired direction the player wants to point their ship in.

Now comes the tricky part. You have the forward vector (normalized, of course) of the ship as the current forward direction, and a desired forward direction, which presumably are not the same. What to do next depends on the motion model of your ships. Is it newtonian? If so then you have to be careful not to overshoot, as you likely have limited angular acceleration. The cross product of these two vectors will give you the vector you want to rotate about (the axis), and it is the sin() of the angle. If you don't have angular momentum, then you could just turn the ship by this axis and an angle which is limited by `RAD_PER_SEC * dt`. You can use Quaternion.AxisAngle to turn this into a quaternion which you can multiply onto the spaceship's orientation.

```
vec3 desired = (inverse(projection * camera) * (mx,my, 0.5)) - camera.position;
desired = norm(desired)
vec3 actual = norm(ship.getForwardVector())
vec3 axisangle = crossproduct(desired, actual) // may need to negate
                                               // depending on conventions
float angle = arcsin(length(axisangle))
float dangle = min(angle, RAD_PER_SEC * dt)
quat rotation = Quaterion.AxisAngle(dangle, norm(axisangle))
ship.orientation = ship.orientation * rotation.

```

Make sure that arcsin and AxisAngle both use degrees, or both use radians.
> 1 votes

---
Tags: c#, unity, control, third-person-view
---


title: Referencing engine resources

text:
# Question
Title: Referencing engine resources
Let's assume for the sake of argument, that we have a resource engine in place, and that we use OpenGL. My question is how the engine/game classes should reference the resources.

Lightweight example : among others, we probably have a texture resource. If we now have a class that uses this resource, do we store:

1. a resource id?
2. a resource pointer?
3. the resultant resource (e.g. the GLID of the Texture)

1 gives us the most flexibility, and neat features like being able to reload all textures on the fly (after context destruction), but costs us a lookup each time it is used, and might require a mutex lock.

Another example - a font resource, same questions -- do we hold an id, pointer or a direct font class?

Third example, a model resource has a reference to a texture it uses. Does it store id, pointer or direct link?

If the answers differ between uses, is there a sensible set of rules one can follow to decide what should be used in what case?

---

EDIT: we're talking about a general use, heavy duty (3d, streaming, resource groups, memory managing) resource manager here in a threaded environment.

# Answer
> 1 votes
I would always go with the first. Let's see why we should eliminate the other two:

Having a pointer directly to the resource object is not great. In terms of performance, it's really about the same as an index lookup (assuming an array or hash table of resources). However, it's not flexible. It's meaningless to have it stored in an external file, and requires an extra field for any magic number (to prevent temporal issues).

Storing the library handle directly is borderline useless. My biggest gripe is that it prevents you from associating various levels of detail as the same resource. The resource header that you look up with the ID should have an array or list that contains the library handles associated with detail levels. This also suffers from the same problems as the pointer on top of that.

---

In terms of implementation, you're best off doing something like this.

```
// 4 bytes in total
struct ResourceHandle
{
    unsigned int index :24;
    unsigned int magic :8;
};

```

The `index` field is used to look up the resource itself in an array or map. The `magic` field is used to ensure that if a resource is deleted and another is created that uses the same index, an old handle will correctly report that its resource has been deleted, rather than accessing the new, unrelated resource.

Each resource index has a `magic` field of its own, that is incremented each time the resource at that index is deleted. When returning the handle for a new resource, the `magic` value of that index is part of the result.

---
Tags: resource-management
---


title: Canting of track in a racing game

text:
# Question
Title: Canting of track in a racing game
I am trying to create a small racing game in which the track would be modeled using a BSpline curve for the path's center line and directional vectors to define the canting of the track at each point.

My problem is that I don't know how to calculate the correct canting / slope of the curve, in such a way that it would be optimal or at least visually nice for a car to 'slant in the corner'.

My idea was to use the direction of the 2nd derivatives of the curve, however while this approach looks fine for most of the track, there are points in which the 2nd derivative makes sharp 'twists' / very quick 180 degree flips. I also read about 'knots' of bsplines, but I don't know if such 'twist' in 2nd derivatives is a knot or knots are something else.

Can you tell me that using a BSpline: 1. How could I calculate a visually nice canting of a track for a racing game? 2. Is it possible to do this by using some simple calculations of centripetal force / gravity? 3. Is it possible to do this by using 1st, 2nd and 3rd derivatives of the BSpline curve?

I am not looking for the 'physically correct' canting angle for the track, I would just like to create something which is visually pleasing in a simple game.

I am using a framework which has a built-in class for BSpline, including support for 1st, 2nd and 3rd derivatives of the curve.

# Answer
> 1 votes
The first derivative of the spline points along it: this is the axis which you rotate the roadway about in order to cant. The second derivative is (roughly) the curvature. The second derivative points "in" to the curve. So in a perfectly circular track, the second derivative at each point points directly towards the center of the circle. If you cant so that the second derivative direction is "lower", then you will achieve your desired outcome.

Now your problem is that the curvature changes abruptly. Splines can have different continuities, which basically means that different numbers of derivatives can be continuous. Most of the time a spline is made out of a number of sections, which are joined at then ends. For example, we can make one curve end where the other starts, but with no other constraints there would be a "kink" in the curve, as the derivatives don't have to be the same. Similarly we could require the directions to match (which is the first derivative), but there is nothing to require the second derivative to do so. What you need is cubic splines with continuous second derivatives. How you do this depends on where you are getting these curves from. If you are drawing them in Inkscape, for example, there is an option to make a given node "symmetric," which basically means continuous second derivative. Normally to get smoothness you make sure both handles are on the same line as the node, and to get nice curvature make sure both handles are the same *distance* from the node.

Finally, I would point out that you *should* cant based on the curvature, k, which is

```
k = y''/(sqrt(1 + |y'|^2)^3)

```

as the size second derivative depends on the magnitude of the first. Curvature is "physical," but a good idea because it will make the canting look natural and adapt to the scale of the turns. Just using the length of the second derivative directly might be OK, but only if the parameterization of the curve is by arc length, or at least consistent. Note curvature is a vector quantity, where it points "in" and is bigger when the turn is tighter. This article derives a formula from centripetal/gravity forces which states the optimal slope should be proportional to the curvature. (k=1/r, slope = (h\_a+h\_b)/G, v=speed of cars.)

From wikipedia, some useful formula: http://en.wikipedia.org/wiki/Spline\_interpolation

You might need to introduce transition curves in order to keep the canting from changing too much. This is also something professional tracks would have.

# Answer
> 0 votes
Consider this generated line to be the direction of your track:

You could have your horizontal 'balance' line to be adjusted by the curvature of the line itself (consider you can find the red dots position like in the example i provided). Each red dot would higher the horizon line on the side it lives depending on its distance with the curve. (The challenge is to find the equivalent of the red dots. Maybe some visual representation of its derivatives can help.)

To have this basic principle working, you could calculate those horizon lines at each dot and make any kind of blending method between them (linear\[not\], cosine, quadratic, w/e).

Its a basic idea but i hope it will help.

---
Tags: 3d, mathematics, physics, algorithm
---


# Question
Title: What do the 6 points stand for in Polygon().getPoints().setAll?
I have the following code to create a polygon:

```
Polygon poly = new Polygon();
poly.getPoints().setAll(14d, 17d, 26d, 17d, 20d, 27d); // What do these mean?

```

What do these 6 points stand for?

# Answer
The numbers define a triangle:

Giving the x and y coordinates in order like `((X,Y),(X,Y),(X,Y))`.

Might be easier to understand if you wrote the code like this:

```
poly.getPoints().setAll(
  14d, 17d,
  26d, 17d,
  20d, 27d);

```

When in doubt you can always check the documentation.

> Creates a polygon, defined by an array of x,y coordinates.
> 2 votes

---
Tags: java, 2d
---


title: Get a random vector

text:
# Question
Title: Get a random vector
I'm trying to make a small pariticle-like simulation, and I'm trying to make each parrticle go a random direction from one point (mouse pos). The problem is I don't know how to get the random vector that has a certain speed.

Here is what I'm trying to get the vector:

```
def getVector(self):
    vector = [random.randint(-100, 100), random.randint(-100, 100)]
    return vector

```

when I run this each particle goes either north, west, or northwest. The odd thing is when I tried to record a .gif to show this behavior the frame-rate of the .gif was 15 fps (slow comp) and the particles actually went in all directions. So in my code where I move the particles:

```
self.rect.x -= self.vector[0] * ttime
self.rect.y += self.vector[1] * ttime

```

I took away the `ttime` (the tick to regulate speed) and it worked but the particles were going very fast at various speed. So my question is how can i get a random vector that will give me the correct behavior

# Answer
> 2 votes
You can generate a random vector with a given fixed speed by choosing a random point on the unit circle, then scaling by the desired speed:

```
angle = random.uniform(0, 2.0*math.pi)
vector = [speed * math.cos(angle), speed * math.sin(angle)]

```

You could also choose `speed` randomly as well, using `random.uniform(minSpeed, maxSpeed)`.

As for the change in behavior when `ttime` is included or not, I can't tell based on what you've posted, but particles going only north, west, or northwest suggests that maybe negative velocity values are treated incorrectly somehow. Perhaps it's an integer versus float type error. Your original code was generating integer velocities, but it's generally best to use floats for position and velocity values.

---
Tags: vector, python, pygame, random
---


title: Algorithmic error in tile engine?

text:
# Question
Title: Algorithmic error in tile engine?
I'm toying with creating a tile-based 2D java game engine. I can render the "local" area without issues(I.E. deciding which local tiles to render). The problem came when I introduced floating point locations. I want my "camera" location to be a double. My thought was "I'll multiply the double by the tilesize, round it, and get a pixel approximation". That doesn't work, for one reason or another. The code below is the most functional code I've been able to construct. It works almost entirely correctly except around the 0,0 area it skips tiles(?) and it looks hackish and the code's overall hideous. Is there some easier method I'm missing here, is there an example I can examine?

```
private HashMap<Integer, HashMap<Integer, Tile>> tiles = new HashMap<>(); // Tiles stored here
public double cameraX = 0, cameraY = 0; // Camera location(centered on screen)
private final int TILE_SIZE = 100; // Size of tiles
private final int TILE_BUFFER = 5; // Buffer of tiles to be rendered/loaded around screen
private int screenTileWidth = 0, screenTileHeight = 0; // Tiles that fit onto the screen

@Override
public void render(Graphics g) {
    // Calculate tile width/height of screen
    int screenWidth = this.screenTileWidth + (TILE_BUFFER * 2), screenHeight = this.screenTileHeight
            + (TILE_BUFFER * 2);

            // Supposedly the offsets from the camera's location to be applied to the rest of the tile locations
    int locOffsetX = (int) Math.round((cameraX % 1) * TILE_SIZE);
    int locOffsetY = (int) Math.round((cameraY % 1) * TILE_SIZE);

            // Big mess of "eww" hackish stuff to fix negatives messing with things
    if (cameraX >= 0 && locOffsetX >= 0) {
        locOffsetX *= -1;
    }
    if (cameraX < 0 && locOffsetX < 0) {
        locOffsetX *= -1;
    }
    if (cameraY >= 0 && locOffsetY >= 0) {
        locOffsetY *= -1;
    }
    if (cameraY < 0 && locOffsetY < 0) {
        locOffsetY *= -1;
    }

            // Base offsets to center tile
    int offsetX = ((GameEngine.g.getWidth() / 2) - (screenTileWidth / 2)
            * TILE_SIZE)
            + locOffsetX;
    int offsetY = ((GameEngine.g.getHeight() / 2) - (screenTileHeight / 2)
            * TILE_SIZE)
            + locOffsetY;

    // Loop through loaded tiles(x/y tile coord)
    for (int x = (int) (Math.floor(cameraX) - (screenWidth / 2)); x < Math
            .floor(cameraX) + (screenWidth / 2); x++) {
        for (int y = (int) (Math.floor(cameraY) - (screenHeight / 2)); y < Math
                .floor(cameraY) + (screenHeight / 2); y++) {
                            // The screen-relative tile coord
            int sx = (int) (x - Math.floor(cameraX));
            int sy = (int) (y - Math.floor(cameraY));

                            // Tile pixel location
            int locX = sx * TILE_SIZE + offsetX;
            int locY = sy * TILE_SIZE + offsetY;

            // Draw box/location info
            g.setColor(Color.RED);
            g.drawRect(locX, locY, TILE_SIZE, TILE_SIZE);
            g.drawString(x + ", " + y, locX + 10, locY + 20);
        }
    }
}

```

# Answer
I believe you are taking up a lot of space with the offset stuff. You could make your code a lot simpler by using translation. Translation is the act of moving the origin of rendering to a different location (the default location of the origin is usually at the top left of the screen). Translation is not specific to Java, but in Java it is usually accomplished by calling the translate method on your `Graphics` object. The graphics object accepts two integers as parameters. After calling translate, all objects will be drawn relative to the X and Y that you passed into the `translate` method (note that you may want to first get the AffineTransform from the `Graphics` object so that you can restore it back to the way it was when you are done rendering).

You way me wondering how this helps. The answer is that the `translate` method accepts negative numbers as well as positive numbers. What this means, is that you can pass the negated camera X and Y coordinates as parameters. Then when you draw a tile, it will appear as though the camera has moved. With this knowledge, our new render code will look something like the following:

```
public void render(Graphics g)
{
    AffineTransform at = g.getTransform();
    g.translate(-cameraX, -cameraY);
    for(int x = left; x < right; x++) // left and right represent the horizontal bounds for the tiles that will be drawn.
    {
        for(int y = top; y < bottom; y++) // top and bottom are the same as left and right, except these are the vertical bounds.
        {
            drawTile(g, x, y);
        }
    }
    g.setTransform(at);
}

```

I never defined the left, right, top, and bottom variables, so you will obviously have to adapt this code to fit your program, but this should help you solve your problem.
> 0 votes

# Answer
Double are not always as precise as we may think.

Did you consider using fixed point arithmetic? The would be faster and in your use case it should fix the issue.

For making your code easier to maintain, perhaps you could rethink your coordinate model to have 0,0 in a corner instead of the middle of your tiles map. This way you would have only positive coordinates and you could remove you code which is dealing with sign issues.

Last thing: you may put the expressions you use in your for loops exit conditions in variables so they won't have to be computed for each iteration (this will also make the code easier to read and to debug).
> 0 votes

---
Tags: java, rendering, tiles, floating-point
---


# Question
Title: Calculate tile ID on a Reus style world with canvas context.arc()
I need a bit of math help for my game.

I'm using Javascript and the Canvas tag to create a circular world, think God Finger, and Reus. The current version of my game is here: http://lazyeels-sandbox.appspot.com/

**The problem**:
The Canvas draws an arc (or circle) starting at 90 degrees going clockwise. See an example image.

My game splits the world in to segments (tiles). The world is 10 tiles in length I would like to calculate which tile the mouse is hovering over so the player can add buildings or adjust the height of the tile.

So I need to calculate the offset and deduct it from the mouse angle (either radians or degrees is fine). However, I can't seem to get it right. I know that in theory I should do the following:

* Calculate the angle of the mouse.
* Calculate the tile by dividing by the segment size (as per regular tile maps i.e. y-axis/tilewidth).
* Remove the offset of the angle to point 0 degrees at the top of the circle rather than 90 degrees clockwise).
* Deduct the offset to get the new tile position.

Here is the main function I'm using;

```
var getMouseAngle = function(mouse){
    var world_length = 10;
    var segment = (Math.PI * 2)/world_length;

    // Get the distance
    var dx = mouse.x - ((canvas.width * 0.5) - Game.camera.xScroll);
    var dy = mouse.y - ((canvas.height - Game.camera.yScroll) * Game.camera.zoom);

    // calculate the angle
    var arctan = Math.atan2(dy, dx);

    // Reset the angle if it is a negative value
    var angle =  dy < 0 ? (Math.PI * 2) + arctan: arctan; // perhaps this is where I need to apply the offset.

    // Calculate the tile
    var orig_tile = angle/segment;

    // Calculate the offset
    var offset_tile = ((Math.PI * 3/2)/segment); // calculate offset clockwise = 270 degrees to the top of the circle (where the player sits).

    var tile = (orig_tile - offset_tile) // This is soooooo wrong

    return {
        dx: dx,
        dy: dy,
        degrees: (angle * 180/Math.PI).toFixed(2),
        radian: angle.toFixed(2)
        tile: Math.floor(tile),
    };

```

By comparison the player tile function was way easier:

```
Player.getTile = function(rotation){
    var tile = Math.floor(rotation/Game.level.segment);

    if(rotation > 0){
        tile = Math.abs((Game.level.world.length - tile)-1);
    } else {
        tile = Math.abs(tile)-1;
    }
    if(rotation == 0){
        tile = 0;
    }
    return tile;
};

```

Does anyone know where I'm going wrong in the calculation, i.e. how and when should I apply the offset - on the angle before calculating the tile, or afterwards?

I haven't shown the other permutations I tried, such as deducting the offset from the original angle, all of these resulted in the wrong tile ID being returned.

I know it should be a similar process to the player function, i.e. using the word\_length in the calculation.

# Answer
`Let N be the number of slices:`

`(alpha + beta) * N / (2 * PI)`

\*Please note that `alpha` is the amount the circle is rotated Clock-Wise so if your `alpha` represents rotation Counter-Clock-Wise, you need to subtract it.
> 1 votes

# Answer
@arthur-wulf-white Thanks for your help with this problem. Having this discussion has really helped. I think it works now, but this involved a bit of hacking so I'm not too happy with the code solution but here it goes.

```
Level.prototype.getMouseAngle = function(mouse){
    // Calculate the arctan between the mouse and the level x and y at the world center.
    var dx = mouse.x - (this.x - Game.camera.xScroll);
    var dy = mouse.y - ((this.y - Game.camera.yScroll) * Game.camera.zoom);
    var arctan = Math.atan2(dy, dx);

    // Reset angle to 0 on full rotation
    if(dy < 0){
        angle = (Math.PI * 2) + arctan;
    } else {
        angle = arctan;
    }

    // Deduct world rotation
    angle -= this.rotation;

    // Get original tile position offset tile position and calculate final tile.
    // N.B segment = (Math.PI * 2)/this.world.length.

    var orig_tile = angle/this.segment;
    var offset_tile = this.offset/this.segment;
    var final_tile = Math.floor(offset_tile - orig_tile);

    // Adjust tile according to offset.
    var tile = final_tile;
    if (tile < 0){
        tile = (tile + this.world.length);
    }
    if(tile > 0){
        tile = Math.abs((this.world.length-1) - tile);
    }
    if(this.world.length + final_tile == this.world.length){
        tile = this.world.length - 1;
    }

    return {dx: dx, dy: dy, degrees: (angle * 180/Math.PI).toFixed(2), tile: Math.floor(tile), radian: angle.toFixed(2)};
};

```

If you see a better solution then I'm all ears, in the mean time thanks again for all your effort spent solving my problem, I will give you a big credit if my game ever becomes something. ;-)
> 0 votes

---
Tags: javascript, html5, tilemap, html-canvas
---