# Question
Title: Is chess-like AI really inapplicable in turn-based strategy games?
Obviously, trying to apply the min-max algorithm on the complete tree of moves works only for small games (I apologize to all chess enthusiasts, by "small" I do not mean "simplistic"). For typical turn-based strategy games where the board is often wider than 100 tiles and all pieces in a side can move simultaneously, the min-max algorithm is inapplicable.

I was wondering if a partial min-max algorithm which limits itself to N board configurations at each depth couldn't be good enough? Using a genetic algorithm, it might be possible to find a number of board configurations that are good wrt to the evaluation function. Hopefully, these configurations might also be good wrt to long-term goals.

I would be surprised if this hasn't been thought of before and tried. Has it? How does it work?

# Answer
It depends on the mechanics of the game. Game tree min-max may be inapplicable overall, but maybe it applies in some areas. It's common that some locations on a map are strategically important. Min-max may apply at a strategic level for which of those locations to control. At a tactical level, for the x squares around each strategic location, min-max might be used to decide how units deploy to capture and defend it.
> 5 votes

# Answer
This isn't a minimax algorithm, however the guys responsible for the Killzone AI released a paper based on position evaluation functions which some chess AI also uses.

It's very simple in that all it does is picks a position on the board based on the agent's current knowledge. So if the agent is low on health, then positions further away from its enemy will be awarded a higher score as it is more desirable to be out of the enemy's range.

The paper can be found in AI Game Programming Wisdom 3 and has the title Dynamic Tactical Position Evaluation.

A draft of the paper can be found online here:
http://www.cgf-ai.com/docs/straatman\_remco\_killzone\_ai.pdf

Hope that helps.
> 9 votes

# Answer
I don't think that it would be good enough. Choosing the specific N configurations, how many and which ones, would be virtually impossible in something that complex. Remember that if your game features infinite resources or something similar, then there may be circles in how it can be played, making exploiting such an AI relatively easy.
> 2 votes

# Answer
I would suggest at least implementing min-max with alpha-beta pruning.

Without trying it and deciding it is impractical (i.e. terrible performance), and without more background on the game mechanics, I don't see why you think min-max is inapplicable.

The size of the board is potentially an issue, but with pruning, discarding losing pathways enables a deeper search with the same amount of computation, so perhaps the larger board areas will not be an issue when pruned? Additionally, assuming the board size itself is an issue may be premature, it is not so much the size of the board as the complexity of the mechanics and how many moves are possible from each board position. If your game has a large but sparsely populated area, the number of possible moves from each board state may not be much different than if the board was just large enough to fit all the pieces. Of course if you have a gigantic board that is 90% full and everything can move anywhere every turn, that's going to require a lot of searching. One of the reasons Go is so difficult to write AI for is that there is so much freedom of movement, although it is also a very difficult game to write an evaluation function for.

I'm also not sure why simultaneous movement is inherently a problem. As long as you transition from one discreet board state to another, and have an evaluation function, the algorithm ought to apply.

I assume you need to have an evaluation function anyway, and regardless of the search you use, the evaluation function is where most of the work is likely to go. The min-max algorithm with pruning is itself very simple to implement, something you can probably do in an hour or two and much of the infrastructure work like board state storage, evaluation, move generation, is likely going to be the same regardless of the search you settle on.
> 2 votes

# Answer
The winner of the 2011 Google AI challenge used min-max (of depth 1). Another top contestant used random sampling. This contestant mentioned that a mix of min-max and random sampling, which is basically what I described in my question, performed poorly. This settles it, I guess.

On the other hand, it does show it's possible to use min-max in large games. It seems it was however necessary to limit it to small-ish groups of ants, working with the full set of all ants would have probably been too slow. Another interesting observation is that a depth of 1 was enough. We (humans) have become pretty good at playing chess, and an AI for this game needs much deeper search trees to be challenging. New more complex games haven't been played and studied for so long, and dumber AIs may have sufficient entertainment value.
> 1 votes

# Answer
The basic idea of a chess AI is to make a list of all possible moves from the currently estimated best move, then to rate them and to repeat the process. It drops those with too little chance as they won't be taken (or can be assumed not to be taken as they do not appear to give an advantage).

The basic idea requires you to make a list of all possible moves, and to repeat that process for all those moves etc. This is possible in chess (where the list of likely next moves is effectively enumerable; a starting chess board has 20 possible moves) and up to a point for other things such as backgammon, checkers and solving a Rubik's cube.

If I take a simple turn-based game (Civilization 2) as an example, each of your guys can move to a total of 8 squares (or 24) in a single turn. If you have 10 guys (which isn't a lot, you typically have more by the time it starts to get somewhat interesting) the total number of possible "moves" from the current state (so a single level) is already 8^10 or about 4 billion. Even if you prune 99.99% of those, you still can't go deep on the tree as the number of possible moves explodes really quickly.

Add to that that the game is a bit like the Rubik's cube problem, where you only see progress after some 10 or 12 moves, the problem explodes to a point where the advantages of a standard min/max are only prevalent at a memory capacity of more than your typical computer will have.

In other words, the strategies it will find will be reproducible but bad.

For the actual problem, how to make a decent AI, I would go in the direction of basically steered random movement (move each guy with a bit of basic intelligence), evaluation and tuning. Do this in parallel for 100 or 1000 different ones and pick the one that ends up being the best. You can feedback the results from this into the original intelligent steering to tune it again. A bit like monte-carlo simulation.
> 1 votes

# Answer
To successfully apply min/max to a turn based strategy game, you need to correctly apply all available chess-techniques...

## Evaluation function

Even chess engines have a very bad strength, if your evaluation functions is bad. The most simple version of a evaluation function is: 1=game won by white, -1=game won by black, 0 = all other cases; But, this would give you a very bad performance. The same happens to your turn based game! If you want to use min/max (with alpha/beta pruning and stuff) like in chess, you must also implement a reasonable evaluation function! Else, you cannot compare those algorithms performance when being applied to your strategy game to the case it's applied to chess.

What evaluation functions of chess engines do, is evaluating stuff like:

* How well is a position of a piece on the board?
* How many times is a piece attacked?
* How many times is the piece protected?
* How well can each piece freely "move" on the board? (or: How many tiles does it "control")

Those parts of the evaluation function must first be "translated" to your game:

* Position of piece: Is it e.g. on a hill, which is extending its shooting range?
* Attacked: How much is each piece in danger? (e.g. sum of attack values of units able to attack a special unit multiplied by some probability to be attacked by it; probability increases, if the unit is already damaged; decreases if many other units are in range of the attacking unit)
* Own Attack: How many units can be attacked by this each unit?
* Protection: How much own pieces are next to it (to help)? Maybe a unit may not attack units under a minimum distance and its preferable to protect it by unit having the possibility to attack nearby units.
* Mobility: How mobile is your unit? (can it flee?)

The different ratings must be summed up by weighting function (factor\_a * rating\_a + factor\_b * ranting\_b + ...) for all units...

In strategy games also the resources (gold, wood, ...) left must be taken into account.

If your evaluation function is well enough, you do not need to really search "deep" into the tree for most cases. So you probably only need to take a closer look at the 3 or 10 most promising choices. See next chapter...

## Possible moves at each position

The most problematic thing about using min/max for strategy games is that you can command multiple units in one turn, whereas in chess you are only be allowed to command one unit (except for castling, but this is a clearly defined move combination). This causes 5^N possible moves for N units for each "position" (chess term), if you would only decide between "move north, south, west, east OR stop" for each unit. You could solve this by breaking down the complex command into the low level commands: e.g. choose action for unit A, go into depth and decide for unit B.... decide for unit N ... and then end this turn. But, this alone doesn't change the complexity! You must optimize the order in which actions are assigned to units (e.g. first unit B, C, D and then unit A). You could record the impact of the decision for each unit during the last calculation and then sort by importance. This way alpha-beta pruning can be used to cut away any bad combination from the search tree very early. The highest priority should always be "do nothing more and end your turn" (null move pruning) in each iteration. This way you can "skip" assigning most tasks to most units and let them just continue what they did before. This way the search will go into depth quickly by just taking a look at the "critical" units (e.g. the ones really in combat right now). Make sure to only command each unit once... You can also use some randomness to make sure that the "important" units are getting a command from time to time, too. Especially, units finishing some job (e.g. harvesting - or having no enemy assigned anymore) should slightly increase in importance.

## Iterative Deepening + Caching/Hash Table

Then, you can "interative deepening" to go into depth more and more until some time limit has been reached. So you will search deeper if there are less units, and you have always some "result" if you stop searching for a better solution. Iterative deepening would require to use a hash table to cache former results of searches. This also enables to reuse some of the results from the last turns search (the branch of the search tree that covers the commands that were actually executed in the last turn). To implement this, you need a very good hashing function (have a look at the "zobrist key"), which is able to be iteratively updated. Updating the hash key means, that you can just take the hash key of the old "position" and can just kick in the change in the position (e.g. take away unit at position x and put it at position y). This way calculating the hash key is quick and you don't need to process the whole boards situation to calculate it, just to check if the hash contains a former entry for this position. In a way you must make sure that no hash collisions happen.

## Non-deterministic Behaviour

Non-deterministic behaviour is a problem for min/max searches. This means, it isn't sure if you will hit an attacked target (e.g. probability is 10%). Then you can not just plan this happens. In that case you need to modify the algorithm and put a "probabilty" layer in between. It's a bit like "its the probabilities turn". Each independent result must be regard separately. The evaluation through this depth "layer" must then be sampled (monte carlo sampling) and the result of the in-depth evaluation must be weighted by the probabilty of occurance. Different results of the probability layer must be regarded like different opponenent moves (but instead of min/max the "average" must be calculated). This will of course increase the complexity of the search tree. So this would in fact be something like min/max/avg-search (not min/max-search anymore).

## Summary

When applying all those techniques (which are all used by current chess engines) to a deterministic game, you will surely be able to achieve reasonable results for a game, too. For non-deterministic games, this will be probably more complicated, but I think still manageable.

A good resource for explanation of those techniques (for chess) is http://chessprogramming.wikispaces.com/

You can even implement some sort of directed randomness in min/max searches. Instead of deterministically investigate the best results first in each iteration, you can just randomize this and let its order be decided by a probability distribution that is based on the current evaluations...
> 0 votes

---
Tags: ai, turn-based
---


# Question
Title: Libgdx OrthogonalTiledMapRenderer not rendering map properly
I'm using a little hack to change the coordinate system to the one i'm accustomed to (left and up is negative and right and down is positive) but this causes the tiled map renderer to render the map incorrectly, as shown below

Whereas it looks like this in the Tiled map editor

This is the "hack" I'm using to change the coordinate system:

```
float w = Gdx.graphics.getWidth();
float h = Gdx.graphics.getHeight();

Camera = new OrthographicCamera(w, h);
Camera.setToOrtho(true, w, h);

```

My render code

```
renderer.setView(Camera);
renderer.render();

```

So is there a workaround to this? Or perhaps a better way to change the coordinate system that doesn't screw up everything?

**Edit: The rendered tiles are correct now but the map and everything rendering is still flipped along the y-axis. If I was drawing sprite and stuff, I could always draw them flipped but I don't know how to do it with the tiled map renderer.**

# Answer
> 5 votes
seeing your both images i am sure that you are using following constructor for your code

```
randerer = new OrthogonalTiledMapRenderer(map);

```

this constructor set your map unit:pixel ratio 1:1. It is ok for non-side scrolling games but if you are planning to make a platformer side scrolling game you have to change the ratio so that you can move your camera.

replace the code with the second constructor like this

```
randerer = new OrthogonalTiledMapRenderer(map , 1/16f);

```

Now every unit of map is displaying the 16px So no set your camera to orthographic projection like this

```
camera.setToOrtho(false,width/16,height/16);

```

first parameter make y axis pointing upwords , width/16 and height/16 display the map in units(like 800px/16=50 units)

now set the

```
render.setView(camera);

```

now see the whole code at once.....

```
@Override
public void show() {
    TmxMapLoader loader = new TmxMapLoader();
    map = loader.load("data/l.tmx");
    camera = new OrthographicCamera();
    renderer = new OrthogonalTiledMapRenderer(map,1/10f);
}

@Override
public void resize(int width, int height) {
    // TODO Auto-generated method stub

    camera.setToOrtho(false, width/10,height/10);

}

  @Override
 public void render(float delta) {
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    renderer.render();
    camera.update();
    renderer.setView(camera);

            // to move the camera
    if(Gdx.input.isKeyPressed(Keys.A)){

            camera.position.x -=2;

    }
    if(Gdx.input.isKeyPressed(Keys.D)){

        camera.position.x +=2;

}
}

```

# Answer
> -2 votes
use

```
Camera.setToOrtho(false, w, h);

```

it will flip your y axis to down

and renderer to

```
renderer.setView(camera.combined,0,0,width,height);

```

---
Tags: libgdx, tiles
---


# Question
Title: How to Construct a Perspective Projection With 4 Vanishing Points
Is it possible to construct a projection matrix which will create a perspective with four (or more) vanishing points?

This question have an OpenGL tag, but general insights are welcomed as well.

# Answer
To the simple question of "can you use a projection matrix" to do this, the answer is no. The reason is that a matrix multiplication can only result in an linear or affine transform that maps lines to lines, whereas you're looking to map a line to a curve.

To the question of "how do I implement a fisheye projection", see:

### How do I create a wide-angle / fisheye lens with HLSL?
> 11 votes

---
Tags: opengl, graphics, mathematics
---


# Question
Title: Why is there high performance hit with many meshes?
I am currently reading upon Geometry Instancing, as I want to render a lot of animatable objects on the screen.

However I have come to a more fundamental question first: Why do I even need to use it?

Consider this setup:

* A plane as the base of the game world
* On top of that a lot of tiles, which can be destructable with the use of a Physics Engine.
* A camera which you can control with WASD + mouse for direction.

Now I do understand that there definately must be a performance hit at some point. I thought it would occur when sending all object data (vertices) to the GPU.

However the performance hit remains to be there, at every single frame it renders, what is actually happening in the background? Considering nothing at my scene is changing at all, it even happens when I do not move the camera at all.

I have no clue what exactly is going on and would definately want to read up more about it before starting to fix an issue that I do not understand, thus making the fix also harder to understand. I do know however that the fix (Geometry Instancing) works by sending the vertex data only once per multiple of objects based on that same vertex. So somehow it would have to do with the amount of vertices, yet I don't see what is going on?

Also: I am using the Ogre3D engine, so any specific answers/tips to that engine would also be welcome.

Regards.

# Answer
> 3 votes
Since you talk about drawing tiles, I presume the geometry of a tile is pretty simple, e.g. just 2 triangles in a square. If that's the case, and you're drawing a large number of tiles, geometry instancing could certainly help you.

There is a certain amount of performance overhead per draw call on both the CPU and the GPU. The details depend on your hardware, drivers, etc. but in general, if you have fewer than a couple hundred vertices per draw call, you're not likely to be using the GPU efficiently; and if you have more than a few thousand draw calls per frame, you're likely using too much CPU and becoming CPU-limited. Instancing allows you to put more stuff in each draw, making each draw do more work, so the per-draw overhead doesn't hurt you so much.

The reason too-small draws hurt on the GPU is that internally, GPUs need to store a little bit of data about each draw call currently in flight, and they have a limited buffer of memory for this data, so only somewhere around 8 draw calls at most can run at the same time. If the draws are so small (have so few vertices) that 8 draw calls don't use all the GPU's capacity, then that extra capacity is being left idle, and could be put to work by using instancing to make the draws bigger.

On the CPU side, the graphics driver has to do some validation, memory management and other housekeeping tasks whenever you submit a draw call, and this can add up. The rule of thumb for D3D9 is no more than 2,000 to 3,000 draw calls per frame to avoid becoming CPU-limited. I'm not sure about OpenGL or about newer D3Ds, but the limit is going to be in the range of a few thousand. This work is not really dependent on the number of vertices drawn, just on the number of individual draw calls. So fewer, larger draw calls are more efficient here as well.

---
Tags: 3d, graphics, performance, geometry, ogre
---


title: Using multiple passes in OpenCL .net

text:
# Question
Title: Using multiple passes in OpenCL .net
I'm new to opencl but I have some experience using HLSL. In HLSL multiple passes are used when you need to finish a computation before moving on to the next step.

I would like to know how this sort of thing is done in opencl.

I would like to do something like

```
__kernel void imagingTest(__read_only  image2d_t srcImg, __write_only image2d_t dstImg)
{
    //DO Some stuff here

    // write the image
    write_imageui(dstImg, coord, bgra);
}

```

I would like to apply this kernel multiple times

**EDIT**

At the moment the C# code I have to call the kernel is

```
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Runtime.InteropServices;

using Emgu.CV;
using Emgu.Util;
using Emgu;
using Emgu.CV.Structure;

using OpenCL.Net;

namespace HLSLTest
{
    public class Computations
    {
        private Cl.Context _context;
        private Cl.Device _device;
        private Cl.Kernel kernel;
        private Cl.Kernel kernel2;

        private void CheckErr(Cl.ErrorCode err, string name)
        {
            if (err != Cl.ErrorCode.Success)
            {
                Console.WriteLine("ERROR: " + name + " (" + err.ToString() + ")");
            }
        }

        private void ContextNotify(string errInfo, byte[] data, IntPtr cb, IntPtr userData)
        {
            Console.WriteLine("OpenCL Notification: " + errInfo);
        }

        public void Setup()
        {
            Cl.ErrorCode error;
            Cl.Platform[] platforms = Cl.GetPlatformIDs(out error);
            List<Cl.Device> devicesList = new List<Cl.Device>();

            CheckErr(error, "Cl.GetPlatformIDs");

            foreach (Cl.Platform platform in platforms)
            {
                string platformName = Cl.GetPlatformInfo(platform, Cl.PlatformInfo.Name, out error).ToString();
                Console.WriteLine("Platform: " + platformName);
                CheckErr(error, "Cl.GetPlatformInfo");

                //We will be looking only for GPU devices
                foreach (Cl.Device device in Cl.GetDeviceIDs(platform, Cl.DeviceType.Gpu, out error))
                {
                    CheckErr(error, "Cl.GetDeviceIDs");
                    Console.WriteLine("Device: " + device.ToString());
                    devicesList.Add(device);
                }
            }

            if (devicesList.Count <= 0)
            {
                Console.WriteLine("No devices found.");
                return;
            }

            _device = devicesList[0];

            if (Cl.GetDeviceInfo(_device, Cl.DeviceInfo.ImageSupport, out error).CastTo<Cl.Bool>() == Cl.Bool.False)
            {
                Console.WriteLine("No image support.");
                return;
            }

            _context = Cl.CreateContext(null, 1, new[] { _device }, ContextNotify, IntPtr.Zero, out error); //Second parameter is amount of devices
            CheckErr(error, "Cl.CreateContext");

            //Load and compile kernel source code.
            string programPath = Environment.CurrentDirectory + "/../../../ImagingTest.cl";  //The path to the source file may vary

            if (!System.IO.File.Exists(programPath))
            {
                Console.WriteLine("Program doesn't exist at path " + programPath);
                return;
            }

            string programSource = System.IO.File.ReadAllText(programPath);

            using (Cl.Program program = Cl.CreateProgramWithSource(_context, 1, new[] { programSource }, null, out error))
            {
                CheckErr(error, "Cl.CreateProgramWithSource");

                //Compile kernel source
                error = Cl.BuildProgram(program, 1, new[] { _device }, string.Empty, null, IntPtr.Zero);
                CheckErr(error, "Cl.BuildProgram");

                //Check for any compilation errors
                if
                (
                    Cl.GetProgramBuildInfo
                    (
                        program,
                        _device,
                        Cl.ProgramBuildInfo.Status,
                        out error
                    ).CastTo<Cl.BuildStatus>() != Cl.BuildStatus.Success
                )
                {
                    CheckErr(error, "Cl.GetProgramBuildInfo");
                    Console.WriteLine("Cl.GetProgramBuildInfo != Success");
                    Console.WriteLine(Cl.GetProgramBuildInfo(program, _device, Cl.ProgramBuildInfo.Log, out error));
                    return;
                }

                //Create the required kernel (entry function)
                kernel = Cl.CreateKernel(program, "imagingTest", out error);
                kernel2 = Cl.CreateKernel(program, "imagingTest", out error);
                CheckErr(error, "Cl.CreateKernel");

            }
        }

        public void ImagingTest(Image<Gray, Single> InputImage, out Image<Gray, Single> outputImage)
        {
            Cl.ErrorCode error;

            int intPtrSize = 0;
            intPtrSize = Marshal.SizeOf(typeof(IntPtr));

            //Image's RGBA data converted to an unmanaged[] array
            byte[] inputByteArray;
            //OpenCL memory buffer that will keep our image's byte[] data.
            Cl.Mem inputImage2DBuffer;

            Cl.ImageFormat clImageFormat = new Cl.ImageFormat(Cl.ChannelOrder.RGBA, Cl.ChannelType.Unsigned_Int8);

            int inputImgWidth, inputImgHeight;
            int inputImgBytesSize;
            int inputImgStride;

            inputImgWidth = InputImage.Width;
            inputImgHeight = InputImage.Height;

            System.Drawing.Bitmap bmpImage = InputImage.ToBitmap();

            //Get raw pixel data of the bitmap
            //The format should match the format of clImageFormat
            BitmapData bitmapData = bmpImage.LockBits
            (
                new Rectangle(0, 0, bmpImage.Width, bmpImage.Height),
                ImageLockMode.ReadOnly,
                PixelFormat.Format32bppArgb
            );

            inputImgStride = bitmapData.Stride;
            inputImgBytesSize = bitmapData.Stride * bitmapData.Height;

            //Copy the raw bitmap data to an unmanaged byte[] array
            inputByteArray = new byte[inputImgBytesSize];
            Marshal.Copy(bitmapData.Scan0, inputByteArray, 0, inputImgBytesSize);

            //Allocate OpenCL image memory buffer
            inputImage2DBuffer = Cl.CreateImage2D
            (
                _context,
                Cl.MemFlags.CopyHostPtr | Cl.MemFlags.ReadOnly,
                clImageFormat,
                (IntPtr)bitmapData.Width,
                (IntPtr)bitmapData.Height,
                (IntPtr)0,
                inputByteArray,
                out error
            );

            CheckErr(error, "Cl.CreateImage2D input");

            //Unmanaged output image's raw RGBA byte[] array
            byte[] outputByteArray = new byte[inputImgBytesSize];

            //Allocate OpenCL image memory buffer
            Cl.Mem outputImage2DBuffer = Cl.CreateImage2D
            (
                _context,
                Cl.MemFlags.CopyHostPtr | Cl.MemFlags.WriteOnly,
                clImageFormat,
                (IntPtr)inputImgWidth,
                (IntPtr)inputImgHeight,
                (IntPtr)0,
                outputByteArray,
                out error
            );

            CheckErr(error, "Cl.CreateImage2D output");

            //Pass the memory buffers to our kernel function
            error  = Cl.SetKernelArg(kernel, 0, (IntPtr)intPtrSize,  inputImage2DBuffer);
            error |= Cl.SetKernelArg(kernel, 1, (IntPtr)intPtrSize, outputImage2DBuffer);
            CheckErr(error, "Cl.SetKernelArg");

            //Create a command queue, where all of the commands for execution will be added
            Cl.CommandQueue cmdQueue = Cl.CreateCommandQueue(_context, _device, (Cl.CommandQueueProperties)0, out error);
            CheckErr(error, "Cl.CreateCommandQueue");

            Cl.Event clevent;

            //Copy input image from the host to the GPU.
            IntPtr[] originPtr = new IntPtr[] { (IntPtr)0, (IntPtr)0, (IntPtr)0 };  //x, y, z
            IntPtr[] regionPtr = new IntPtr[] { (IntPtr)inputImgWidth, (IntPtr)inputImgHeight, (IntPtr)1 }; //x, y, z
            IntPtr[] workGroupSizePtr = new IntPtr[] { (IntPtr)inputImgWidth, (IntPtr)inputImgHeight, (IntPtr)1 };
            error = Cl.EnqueueWriteImage(cmdQueue, inputImage2DBuffer, Cl.Bool.True, originPtr, regionPtr, (IntPtr)0, (IntPtr)0, inputByteArray, 0, null, out clevent);
            CheckErr(error, "Cl.EnqueueWriteImage");

            //Execute our kernel (OpenCL code)
            error = Cl.EnqueueNDRangeKernel(cmdQueue, kernel , 2, null, workGroupSizePtr, null, 0, null, out clevent);
            //Cl.WaitForEvents(1, new Cl.Event[] { clevent } );
            CheckErr(error, "Cl.EnqueueNDRangeKernel");

            //Wait for completion of all calculations on the GPU.
            error = Cl.Finish(cmdQueue);
            CheckErr(error, "Cl.Finish");

            //Read the processed image from GPU to raw RGBA data byte[] array
            error = Cl.EnqueueReadImage
            (
                cmdQueue,
                outputImage2DBuffer,
                Cl.Bool.True,
                originPtr,
                regionPtr,
                (IntPtr)0,
                (IntPtr)0,
                outputByteArray,
                0,
                null,
                out clevent
            );

            CheckErr(error, "Cl.clEnqueueReadImage");

            //Clean up memory
            Cl.ReleaseKernel(kernel);
            Cl.ReleaseCommandQueue(cmdQueue);

            Cl.ReleaseMemObject( inputImage2DBuffer);
            Cl.ReleaseMemObject(outputImage2DBuffer);

            //Get a pointer to our unmanaged output byte[] array
            GCHandle pinnedOutputArray = GCHandle.Alloc(outputByteArray, GCHandleType.Pinned);
            IntPtr outputBmpPointer = pinnedOutputArray.AddrOfPinnedObject();

            //Create a new bitmap with processed data and save it to a file.
            Bitmap outputBitmap = new Bitmap(inputImgWidth, inputImgHeight, inputImgStride, PixelFormat.Format32bppArgb, outputBmpPointer);

            outputImage = new Image<Gray, Single>(outputBitmap);

            //outputBitmap.Save(outputImagePath, System.Drawing.Imaging.ImageFormat.Png);

            pinnedOutputArray.Free();
        }
    }
}

```

I've been thinking that after the

```
error = Cl.EnqueueNDRangeKernel(cmdQueue, kernel , 2, null, workGroupSizePtr, null, 0, null, out clevent);

```

line I should add

```
Cl.WaitForEvents(1, new Cl.Event[] { clevent } );

```

Then enqueue another kernel but I'm not sure how to do it.

# Answer
I've figured it out. (I'm using cloo now)

I needed to do this in the opencl code.

I put in a barrier.

```
barrier(CLK_GLOBAL_MEM_FENCE);

```

So for example

```
__kernel void AnisoDiff2D
(
    __global double* img1,
    __global double* img2
)
{
    const int x = get_global_id(0);
    const int y = get_global_id(1);
    int index   = CoordinateToIndex(  x, y  );

    //write some stuff to img2
    //img2[index] = ...

    //put in a barrier, this ensures all the processing is done before proceding
    barrier(CLK_GLOBAL_MEM_FENCE);

    //Set img1 based on some calculation from img2
    //img1[index] = f(img2[index]);

    //Repeat this as many times as you need
}

```
> 1 votes

---
Tags: c#, hlsl
---


title: Unrealscript Vector Invert function

text:
# Question
Title: Unrealscript Vector Invert function
Could I please get an example of the correct syntax for calling the

> Invert ( out vector X, out vector Y, out vector Z )

function

# Answer
> 1 votes
While I couldn't find and examples of that function specifically, we can look at the `out` parameter modifier to get an idea of how this function might work.

In the example:

```
Function Clamp(Out Int Value, Int Min, Int Max) {
    if( Value < Min)
      Value = Min;
    else if( Value > Max)
      Value = Max;
}

```

And it's usage:

```
Clamp(Health, 0, 100);

```

We see that for the `out` parameter, we need to pass in variable that's been defined already (similar to other languages that have an `out` parameter modifier). Based off that, I would assume the correct syntax for the `Invert` function would be something like:

```
var Vector xVec;
var Vector yVec;
var Vector zVec;

//set vectors to something to be inverted

Invert ( xVec, yVec, zVec );

```

Where a `Vector` is defined as:

```
struct Vector
{
    var float X;
    var float Y;
    var float Z;
};

```

---
Tags: udk
---


# Question
Title: The physics equation for a perpetual seesaw
I am trying to create a game that involves two or more people jumping on a seesaw and propelling each other in the air. I need help with the physics equations

Assume no friction and no air resistance for now. Ideally when you hit the sweet spot of the seesaw at the very end person B should go a little bit higher than person A who just came down. Also, if you hit close to the pivot, then the reverse should happen (I don't know if that is really physics but that is what I am going for).

I know the classic example of two forces on each side and `t = r x F` so if you had a mass heavier on one side that heavier mass would have to be closer to the pivot.

What I am not grasping is if `F=ma`, and assuming that the masses are all equal then `F=a`. Now gravity is `9.8/m/s/s` on both objects. Is this true even if one of them is at rest on the ground so the seesaw is tilted up?

So because force is not related to velocity the following doesn't make sense:

I would have thought dropping an object from 10 meters would have created more `F` then from 5 meters if they hit the same spot and have the same mass. So while the velocity increases the acceleration is constant isn't the force constant?

What am I not grasping?

# Answer
It doesn't sound like your use of the word "force" is precise here. If you drop an object from 10 meters instead of 5 meters, the acceleration (and therefore the total force) will have to be higher if it stops in the same amount of time in both cases, so that's true. In the sitting case, the total force is zero, even though the force of gravity is present, nothing a. In the physical sense the mentions of "energy" here are misleading. You don't really have much conservation of energy here, because the collisions with the see-saw are inelastic and do not conserve energy. You don't have much F=ma here, because if you used some force like that you'd still have to deal with angular things. You don't even have conservation of linear momentum: the fact that the see-saw is attached to the essentially infinite mass earth ruins that, and it means that momentum is not conserved during collisions with the seesaw.

So: No energy, force (save for m\*g), or linear momentum needed. Instead: **Torque and angular momentum**.

We need a few variables:

* `I0`, the moment of inertia of the see-saw (it plays the same role as mass).
* `g`, the acceleration of a free body due to gravity.
* `m[i]`, the mass of the ith particle sitting on the seesaw.
* `x[i]`, the position of the ith particle sitting on the seesaw.
* `q`, the angle of the seesaw, with q=0 meaning it's flat.
* `qdt`, the rate of change of the angle of the seesaw.
* `k`, since seesaws have springs in them, "k" can be our spring constant which tries to return the seesaw to its original position.
* `mu`, seesaws have friction and don't continue bouncing forever, so mu will be our friction variable which tries to slow the seesaw down.

So, what's the problem we want to solve. There are two things we want to do: Solve for the **dynamics** of the system when no one is sitting down on or jumping off the seesaw, and the **instantaneous collisions**, which happen when someone sits down or jumps off. The first one we can figure out using arguments about **torque**, and for the second we can use **angular momentum**.

(for a quick refresher: torque is the rate of change of angular momentum, just like how force is the rate of change of momentum. When I say "moment of inertia is like mass", that's because the equation "force=mass\*acceleration" takes the form "torque=moment of inertia\*angular acceleration". Likewise, "momentum=mass\*velocity" is "angular momentum=moment of inertia * angular velocity")

## Dynamics

Lets start out with the dynamics of the seesaw (that is, ignoring the people jumping on and off it). The actual moment of inertia of the seesaw with all those extra masses on it is `I=I0+m[0]*x[0]*x[0]+m[1]*x[1]*x[1]+...`. (this is a simple consequence of the definition of moment of inertia as the sum of m\*r^2 terms)

We'll denote the variable for angular acceleration as `qddt`. There are only a few torques we need to take into account. As stated above, torque=moment\*angular acceleration, so we know that the total torque is equal to `I*qddt`.

* **Torque due to the seesaw's spring**: The spring constant should try to restore `q` to zero, according to the spring constant k. The standard way of doing this is to add a torque of `-k*q`.
* **Torque due to gravity**: The torques from the `m[i]*g` forces are `r x F`. I won't go through the details here (because people frown on defining "cross product" for 2D vectors and I don't want to add the disclaimers), but basically this just means we tack a factor of r (=`x[i]`) and sine or cosine onto the `m[i]*g` force. We find the resulting torque from mass `i` is `-x[i]*m[i]*g*cos(q)`.
* **Torque due to friction**: This should act against the seesaw's velocity according to `mu`. Like with the spring there are a few ways we could do it, but the easiest is to let the friction be proportional to angular velocity, so we add a torque of `-mu*qdt`.

The resulting equation is `I*qddt=-k*q-mu*qdt-(x[0]*m[0]+x[1]*m[1]+...)*g*cos(q)`, and we can divide through by `I` to get the angular acceleration.

## Instantaneous Collisions

To solve for what happens during instantaneous collisions, we use conservation of angular momentum. This states that the angular momentum before a collision is the same as the angular momentum after the collision. Lets say mass `i=0` suddenly leaves the seesaw with velocity `v`, at an angle `a` away from the center of the seesaw. (where I take `a=0` to mean straight away from the center of the seesaw, and `a=90 degrees` to be straight up off the surface of the seesaw \[in the right-handed sense\])

* **Before the collision**: This is simple. With `I` the same as in the last section, the angular momentum of the whole system is `I*qdt`.
* **After the collision**: Let `I2=I-x[0]*x[0]*m[0]` be the moment of inertia without taking m\[0\] into account. Then the angular momentum of the seesaw alone is `I2*qdt2`, where `qdt2` is the angular velocity of the seesaw without mass 0 on it. Using the definition of angular momentum with the vector cross product `r x v`, we can argue that the angular momentum of mass 0 about the center of the seesaw is `x[0]*m[0]*v*sin(a)`. So, the total angular momentum is `I2*qdt2+x[0]*m[0]*v*sin(a)`.

Putting them together, we have that `I*qdt=I2*qdt2+x[0]*m[0]*v*sin(a)`. If we solve for `qdt` we can solve for what happens when a mass hits and sticks to the platform, and if we solve for `qdt2` we can figure out what happens when a mass jumps off the platform.

## Summary of Equations

* `I=I0+m[0]*x[0]*x[0]+m[1]*x[1]*x[1]+...` (definition of `I`)
* `I2=I0+m[1]*x[1]*x[1]+...` (definition of `I2`)
* `I*qddt=-k*q-(x[0]*m[0]+x[1]*m[1]+...)*g*cos(q)-mu*qdt` (dynamics to solve for acceleration)
* `I*qdt = I2*qdt2+x[0]*m[0]*v*sin(a)` (conservation of angular momentum where mass 0 jumps off the platform and moves with velocity v away from the platform at angle a, \[where a=0 implies you're heading parallel to the seesaw's platform, and a=90 degrees implies you're heading perpendicular to the seesaw's platform\]. qdt is the velocity whall m\[0\] is attached, qdt2 is the velocity after m\[0\] is detached. Solve for qdt or qdt2 depending on which case you have.)

So, there. I always like to start from a physically-motivated model, and the terms are understandable "torque" and "angular momentum" equations, so they can be modified if you don't like the behavior! Like, if you want a different formula for pushing down when someone jumps off, you could fiddle around with that `x[0]*m[0]*v*sin(a)` term and multiply it by some fun function, or you could apply a torque for a period of time, etc.

## Example

I wrote an uncommented application to show that the equations are valid, but there are a few issues: the velocities of the balls leaving the platform might not be right, due to factors introduced when changing between screen coordinates and `x[i]` coordinates. https://www.khanacademy.org/cs/see-saw/2232261551
> 2 votes

# Answer
> (I don't know if that is really physics but that is what I am going for)

This is the key statement. You don't want real physics. You want fun, pretend physics. Your focus should be on something that feels good and looks right-ish, irrespective of how physical it actually is.

The real problem here is that you're using static intuition for a dynamic environment. You'll have a much easier time thinking in terms of energy. Imagine that the landeing person transfers all of his Kinetic energy to the standing person. Then you can scale the transferred energy based on how far he is away from the pivot. The closer to the pivot, the more energy the pivot will absorb. Farther out limits the maximum velocity that the faller can impart.

Here is a method of getting something like what you're asking for, or what it sounds like you have in mind. Imagine applying a scalar down the seesaw based on how far it is from the pivot. From the Pivot:

20% - - 40% - - 60% - - 80% - - 100% - 110% - 100% - - 90%

Apply the same to the opposite side. When someone lands, take the product of the scalar tied to where he landed with the scalar for where the other guy is standing. Then transfer that much energy to him.

Start with something like this, then start tweaking it. Game physics is considerably less about getting it right, and considerably more about making it feel right.

I can elaborate on the actual physics if that's still what you want.
> 3 votes

# Answer
> Ideally when you hit the sweet spot of the seesaw at the very end person B should go a little bit higher than person A who just came down.

No, if that were the case, energy would not be conserved. At the peak of person A's height, he has `mgh` potential energy. When he hits the seesaw, all that potential energy is now kinetic energy `1/2mv^2`. Ideally, the seesaw will perfectly transfer the kinetic energy to person B. If his mass is the same, then his kinetic energy is the same at launch, which means it'll take the same amount of height to transfer it all to potential energy.

However, seesaws are not ideal and take some amount of energy, so realistically the height will be lower and lower with each launch until all energy is lost.

This is for a game though, which means that you don't have to follow the laws of physics exactly. If you want this kind of positive feedback loop for height, then give the player control to move the character downwards faster than gravity (by holding `S` or something), or just add/multiply to the initial launch velocities.
> 1 votes

# Answer
In adittion to the answers, the reason why the movement changes depending on the distance from the pivot is because the contact with the seesaw also generates torque = r x F, where r is the aforementioned displacement and F is the applied force.
> 1 votes

---
Tags: mathematics, physics, xna-4.0
---


title: Mesa 9.2 does not support OpenGL 3

text:
# Question
Title: Mesa 9.2 does not support OpenGL 3
I'm trying to install OpenGL 3.0 for studying examples about GLUS , which require OpenGL 3 or 4.

I read on the official Mesa website that Mesa 9.2 support OpenGL 3.0, but after I installed Mesa 9.0, it only support OpenGL 1.4. This is the information from the command line "glxinfo | grep "OpenGL" ":

```
OpenGL vendor string: Intel Open Source Technology Center
OpenGL renderer string: Mesa DRI Mobile Intel® GM45 Express Chipset
OpenGL version string: 1.4 (2.1 Mesa 9.1.4)
OpenGL extensions:

```

My question is how can I get OpenGL 3.0 in Mesa 9.2. I hope to see your answer!

# Answer
Different hardware drivers support different levels of OpenGL. The GM45 is an old chip that receives minimal support from developers. Newer chips, such as those embedded in the Sandy Bridge or Ivy Bridge, generally support the very latest features of Mesa.

You could try using the software rasterizer (llvmpipe being the "high-speed" software rasterizer in Mesa) instead of the hardware drivers. There is an llvmpipe installation/usage guide available, which admittedly is not all that great. The gist is that an alternative libGL.so/OpenGL32.dll will be created which you need to put in the right place so the dynamic linker will find it.

If you're on Linux, there may be a package you need to install to get llvmpipe. Depends on which distro specifically.
> 2 votes

---
Tags: opengl
---


# Question
Title: How do I export a .tmx file into a custom format?
I just created a map in tiled software. The problem is that it has created a .tmx file. But I need a different format than that, something I can easily store in 2D `int` array.

By 2D `int` array I mean:

```
0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 2 0 0 0
1 1 1 1 1 1 1 1 1 1 1 1

0 = sky
1 = ground
2 = tree

```

How do I go about converting the .tmx file into this format?

# Answer
> 1 votes
Converting a file from one format to another isn't too hard if you have decent documentation on both formats (or you're making up your own target format). Luckily, Tiled has some software that is available for it that allows you to easily read .tmx files. To convert, follow these basic steps:

1. Read the current format
2. Process the data read into some intermediate state
3. Write the intermediate state into the new format

You can skip step 2 if you don't need to do any rearranging or complex changes and just write directly to the new format from the current format.

First you'll want to learn more about the existing format, so you know what you're reading. Then make a set of rules for converting the existing format into your new format. For example, when you see a land tile, you'll write a `1` to your new file.

It's sometimes a tedious process. You may want to explore your rationale for converting the files in the first place. .tmx files are widely supported, and you might want to stick with that standard and choose a different data structure than a `int` array for storing your map.

---
Tags: maps, tilemap, file-format
---


title: Adding Leniency to Jumping Mechanic

text:
# Question
Title: Adding Leniency to Jumping Mechanic
I have written some jumping code for my player in a platformer game. At the moment it has some basic logic which says that the player can jump if he is on the ground. The pseudocode looks something like this:

```
### Input Handling ###
if(jumpButtonPressed){
    if(onGround){
        jump
    }
}

### Player Update Loop ###
onGround = false
movePlayer
resolveCollisions
if(player collided with ground){
      onGround = true
}

```

This works fine for basic static tile levels, but when the player is standing on a descending platform, or moving down a downward slope for instance, it becomes very difficult to jump. The reason for this (in the case of the descending platform) is that the platform has moved from underneath him in that frame, so for that moment he is not actually colliding with the ground, and therefore the condition to be able to jump is not fulfilled.

Is there a general way to add some leniency into the jump mechanic so that the player can jump even if they are not technically on the ground for that exact frame? This seems like it should be quite a common problem but I cannot seem to find any similar questions on stackexchange or google.

# Answer
The best solution for this is largely going to be a product of tweaking and testing. If you've seen the documentary Indie Game, one of the designers/programmers of Super Meat Boy talks about all of the time he spent endlessly tweaking jumping and wall sliding, until it felt right.

There may not be a perfect solution, and moving platforms have long posed an issue for physics, but here is something you can try. Rather than using a boolean to keep track of whether you are touching the ground, try using a timer. Every time the player has a collision with the ground, reset the timer, and allow him to jump while the timer is non-zero. Jumping should kill the timer, obviously. The time should be very short, and it may allow characters to jump in the air *just* after running off a platform, which you may see as good or bad.

An alternative, depending on the implementation of gravity, is just tracking a frame count (like 2 or 3 frames). I don't like this as much because it's performance-dependent, but it could be that the character is actually standing on the descending platform only every-other frame, and this would resolve that. (collide & become still, then the platform drops and he has a collision-less fall).

You could, as a third solution, check to see how your physics deals with the character once he hits the platform. Namely, does it set his y-velocity to 0, or to the y-velocity of the object he had a collision with? If the answer is 0, adjusting that could be sufficient.
> 1 votes

---
Tags: collision-detection, physics, movement, control, jumping
---


title: Best practice child and parent script

text:
# Question
Title: Best practice child and parent script
What is the best practice coming to where to place the code in this scenario.

I have a gamobject called **player**. It has lots of child objects. One of them is **sword**. Like this:

**Player**

* **Body**
* + **Head**
* + **Torso**
* + **Sword**

So i have code that controls the player in **player**. It controls movement and triggers an attack animation which swings the **sword**. The code that checks if the sword is swinging and if it has hit something is at the moment inside the sword. My question is, what model is best practice? I can think of some:

1. All code in **player**. **player** checks if **sword** is colliding and handles what happens to the **enemy** that was hit.
2. **sword** checks for collision but **player** handles it by polling **sword** and takes care of what happens with **enemy** and **player** after.
3. **sword** checks for collision but **player** handles it by listening to an event that **sword** triggers and takes care of what happens with **enemy** and **player** after.
4. **sword** handles everything by handling what happens to **enemy** and **player** communicating with parent through a reference.

# Answer
It's true, as said by Byte56 that's quite a matter of opinion. But the choiche you have proposed have different consequences:

> 1 - All code in player. player checks if sword is colliding and handles what happens to the enemy that was hit.

and

> 2 - sword checks for collision but player handles it by polling sword and takes care of what happens with enemy and player after.

1 and 2 are basically the same (am I wrong? otherwise correct me), because its the child object(sword) that will be notified of the collision. So if the child doesn't awake the player, then the player must perform some kind of polling. Personally I hate polling for several reasons:

1. Polling code looks ugly
2. Performance: you are doing a lot of unuseful polling checks at every frame, in order to catch an event that is some way occasional (sword hit enemy)

Personal opinion: I'd stay away from polling whenever possible.

> 3 - sword checks for collision but player handles it by listening to an event that sword triggers and takes care of what happens with enemy and player after.

I think that's the best.

1. Player's code will be more clean and efficient.
2. It's really simple to enable/disable the hit handling, simply removing the delegate associated with the event.
3. If you have more classes interested to listen to the hit event, it's easy to broadcast this event to all listeners (es. audio manager that plays an effect on sword hit)

Personally I'll go this way (or something similar).

> 4 - sword handles everything by handling what happens to enemy and player communicating with parent through a reference.

This is better than polling for what concern player's code, but introduce a not necessary dependency of the player inside sword class. This means that if you want to reuse your sword component for other entities than player (es. enemies) you'll probably end up with branching in the sword code ( or eventually you need interface or some kind of abstraction to interact with player and enemies through the same methods).
> 1 votes

---
Tags: unity, design-patterns
---


# Question
Title: How to Make Objects Fall Faster in a Physics Simulation
I used the collision physics (i.e. Box2d, Physics Body Editor) and implemented onto the java code. I'm trying to make the fall speed higher according to the examples:

* It falls slower if light object (i.e. feather).
* It falls faster depending on the object (i.e. pebble, rock, car).

I decided to double its falling speed for more excitement. I tried adding the mass but the speed of falling is constant instead of gaining more speed. check my code that something I put under input processor's *touchUp()* return method under same roof of the class that implements *InputProcessor* and *Screen*:

```
@Override
public boolean touchUp(int screenX, int screenY, int pointer, int button)
{
    // TODO Touch Up Event

    if(is_Next_Fruit_Touched)
    {
        BodyEditorLoader Fruit_Loader = new BodyEditorLoader(Gdx.files.internal("Shape_Physics/Fruity Physics.json"));

        Fruit_BD.type = BodyType.DynamicBody;
        Fruit_BD.position.set(x, y);

        FixtureDef Fruit_FD = new FixtureDef(); // --> Allows you to make the object's physics.
        Fruit_FD.density = 1.0f;
        Fruit_FD.friction = 0.7f;
        Fruit_FD.restitution = 0.2f;

        MassData mass = new MassData();
        mass.mass = 5f;

        Fruit_Body[n] = world.createBody(Fruit_BD);
        Fruit_Body[n].setActive(true); // --> Let your dragon fall.
        Fruit_Body[n].setMassData(mass);
        Fruit_Body[n].setGravityScale(1.0f);

        System.out.println("Eggs... " + n);

        Fruit_Loader.attachFixture(Fruit_Body[n], Body, Fruit_FD, Fruit_IMG.getWidth());
        Fruit_Origin = Fruit_Loader.getOrigin(Body, Fruit_IMG.getWidth()).cpy();

        is_Next_Fruit_Touched = false;
        up = y;
        Gdx.app.log("Initial Y-coordinate", "Y at " + up);

        //Once it's touched, the next fruit will set to drag.
        if(n < 50)
        {
            n++;

        }else{

            System.exit(0);

        }
    }

    return true;
}

```

And take note, at *show()* method , the view size from the camera is at 720x1280:

```
    camera_1 = new OrthographicCamera();
    camera_1.viewportHeight = 1280;
    camera_1.viewportWidth = 720;
    camera_1.position.set(camera_1.viewportWidth * 0.5f, camera_1.viewportHeight * 0.5f, 0f);
    camera_1.update();

```

I know it's a good idea to add weight to make the falling object falls faster once I released the finger from the *touchUp()* after I picked the object from the upper right of the screen but the speed remains either constant or slow. How can I solve this? Can you help?

# Answer
It's basic physics: heavier objects don't fall faster!

A feather has a bigger area than a pebble; hence it gets slowed down by air resistance a lot more. Introduce a drag force that slows down objects the faster they fall, in the opposite direction of the velocity. The drag force will cancel out gravity once terminal velocity has been reached.

`drag_force = object_specific_constant * velocity^2`

The object specific constant is a combination of a lot of factors, including object size, fluid density and viscosity. The most important factor is size though! A feather is big with a lot of surface area; a pebble of the same mass is a lot smaller. The force gravity inflicts is the same (since they are the same mass) but the drag on the feather is a lot higher, so the feather slows down and reaches terminal velocity much sooner.

Pick a value that makes it behave like you want. I'd suggest something based on the object area (`width * height * magic_value_that_makes_it_behave_like_I_want`) for simplicity.

Box2d has something they call linear damping which works similar to this.
> 12 votes

# Answer
As ccxvii said, heavier objects do not fall faster. The only reason lighter objects sometimes fall more slowly is because the have higher air resistance. In a vacuum, all objects fall at the same speed. LibGdx uses Box2D for physics and Box2D is pretty realistic so changing mass will not affect how fast an object falls. However, there are two ways around this to achieve what you are looking for:

1. Simulate air resistance on your objects (more for lighter objects like feathers). Do this with the following code: `yourBody.setLinearDamping(someFloatValue);`
Don't be afraid to set that value well above 1.
2. Change the gravitation scale for each object. This is not a physically accurate option, but it may be just what you are looking for. In my platformer, I set my main character's gravitational scale to 1.4f so that he doesn't float as much while jumping and is easier to maneuver at high speed. Use this method: `yourBody.setGravityScale(someFloatValue);`
Keep this value around 1 to avoid too much of the effect.

Set either of these values once when you are creating you objects.
> 3 votes

# Answer
Changing the mass will only have an effect on how the body's inertia (F=m\*a), how it reacts to forces. Have you heard of Galileos experiment at the leaning tower of Pisa? If you want them to fall att different speeds you have to either:

1. Set the velocity of the body after creation

Body.setLinearVelocity(Vector2 v)
2. Apply a force to the body after creation Body.

Body.applyForce(Vector2 force, Vector2 point)
3. Apply an impulse to the body after creation

applyLinearImpulse(Vector2 impulse, Vector2 point)
> 1 votes

# Answer
Seems like your Box2d world is using 1 px = 1 meter. Imagine that you are playing with huge objects with tons weight in real world - that is what happening in your game. Make it ~50 (+/-20) px = 1 meter and play with it.

Wish you luck.
> 1 votes

# Answer
Just increase the gravity acceleration, there is a basic formula:

```
V = 0.5 * g * t^2

```

g -\> gravity acceleration t -\> time in the air
> -2 votes

---
Tags: java, physics, libgdx
---


# Question
Title: Why doesn't RGB565 lead to a smaller memory footprint on Android?
I'm using LibGDX for my game. I'm loading 9 bitmaps into memory at once using the AssetManager, about 512x512 pixels each on average.

```
TextureParameter texParam = new TextureParameter();
texParam.format = Format.RGBA8888;

assetManager.load("islands/island_0.png", Texture.class, texParam);
assetManager.load("islands/island_1.png", Texture.class, texParam);
assetManager.load("islands/island_2.png", Texture.class, texParam);
assetManager.load("islands/island_3.png", Texture.class, texParam);
assetManager.load("islands/island_4.png", Texture.class, texParam);
assetManager.load("islands/island_5.png", Texture.class, texParam);
assetManager.load("islands/island_6.png", Texture.class, texParam);
assetManager.load("islands/island_7.png", Texture.class, texParam);
assetManager.load("islands/island_8.png", Texture.class, texParam);

```

However, if I switch the format to Format.RGB565, then run the Heap allocation tracker in the DDMS view of Eclipse, I see absolutely no change in the memory allocated. The bitmaps being drawn on the screen though are being rendered differently (without an alpha channel when I use RGB565).

Am I missing something? Why aren't the bitmaps using less memory?

# Answer
http://developer.android.com/tools/debugging/ddms.html#heap

> DDMS allows you to view how much heap memory a process is using.

Textures are allocated in GPU memory, not heap memory. This would be expected behaviour.
> 2 votes

---
Tags: android, libgdx, memory
---


# Question
Title: FOSS games using original assets, is it legal?
Can I make a game that uses the assets of another game on the users' computer, without legal issues? For example, I make a game that requires the user have game X installed, and I use the assets of game X in my game. The assets of game X would not be distributed with my game.

I realize it will be hard for companies to check, but can you use the assets for other purposes than originally intended (playing the original game)?

As a more concrete example, is playing a game like OpenXcom really legal, when you own the original game?

# Answer
Copyright is about copying, not only distribution. Courts have ruled that even loading a program into memory is copying and subject to limitations on copyright.

IANAL but I think you would probably be OK, although it is a murky situation. By requiring the other game to be present you are in essence creating a derivative work containing your code and the assets of the other game. Could you create your own assets (single color textures, empty maps, whatever) and allow the user to select different assets when running the game? If your game *requires* someone else's copyrighted assets to function at all then an argument could be made that it is a derivative work.
> 5 votes

# Answer
Copyright is only about distribution, not about use.

When you obtained copyrighted content, you are free to do whatever you want with it, as long as you don't give it away to others.

Also, when you obtain copyrighted content from somewhere, you aren't violating the copyright. The violation is committed by the person who distributes the content without permission.
> 1 votes

---
Tags: legal, assets, open-source
---


# Question
Title: Approaching the Fun Factor in Game Design
As designers there has to be some ways you've approached establishing the 'fun-factor' in your games. You've likely done something in one game that may very well transfer into the future games you've worked on. You've likely played a game that did something really fun and you noticed that formula being applied to other games.

What are some ways to improve the fun-factor in game design? What makes Zynga games on Facebook so popular? Do rewards lead to more fun? Does failure lead to more fun? Does making a player come back in 2 hours lead to more fun? Have you read any good quotes or thoughts that really sticks in your mind?

There could be a good list of things to think about when approaching fun.

# Answer
One design goal that I've seen be pretty successful is to get players into a tight retry loop.

It's very disheartening as a gamer to be playing something, lose, and then have to go through a lot of rigamarole to get back to where they were. "Just one more time" isn't really what people think if it takes them a few minutes to get back to the fun stuff.

Some examples in various genres that try to get the player back into the game quickly:

* "rewind time" in games like Dirt 2/Grid, or Prince of Persia: Sands of Time
* near-instant retry in games like Canabalt
* quicksaves that are frequent and generous in pretty much most modern games

I realize this is sort of meta-level on the fun factor, but it does help keep people glued to the game for a longer period of time.
> 22 votes

# Answer
I recently did some research on this and talked to Dr. Clayton Lewis (computer Scientist in Residence @ CU Boulder). Much of my answer comes from the copy of Engagement Analysis he gave me.

**To make *popular* games, Look at *Engagement* not *Fun***
*Fun is poorly understood. Engagement is the real path to popular games and easier to understand.*

It's more useful to think about this in terms of Engagement rather than Fun. They are very similar, but you can have one without the other (answering Stack Exchange questions isn't exactly fun, but it is engaging). There are plenty of people playing Solitaire and other games where it does not appear they are *fun* but they *are* engaged. (This is also why Csikszentmihalyi talks about Flow rather than Fun. His definition of Flow is very similar to Engagement. And Engagement is the more powerful force here. It's what keeps them coming back for more, which is, after all, the goal.

**Factors that Encourage Engagement**

* **Competition**. For some people, competing against someone face to face, or against a highest score list, or against a personal best, promotes engagement.
* **Goals with tuned difﬁculty level**. If a gamelet's goal is too easy to attain the game will be boring; if too difﬁcult, it will be frustrating. Since people get better with practice, especially in an educational gamelet, there has to be some way to escalate the difﬁculty to compensate. Many games do this with explicit levels; some do it with automatic difﬁculty changes based on player performance.
* **Peer Validation** \- This is one Dr. Lewis didn't have in his Analysis but I think it's very very important. The Facebook Like button, the Voting on StackExchange (on this very QA site) are all driven by Peer Validation. To have someone *else* who has the *same* deep interest in some obscure topic (like What is Fun) Like your Answer is incredibly motivating. Its what keeps folks taking Instagram photos. Put another way :
*If you posted a photo of a falling tree on Facebook and no one Liked it, did you really post it?*
* **Partial reinforcement**. Though it violates common sense, it is very clear from a great deal of data that rewarding someone for their behavior occasionally creates much more dedication to a task than rewarding them consistently. This is related to difﬁculty level: if you win every time the game is too easy; if you never win you can get discouraged, but if you win occasionally you may stay with game for a long time. So, in a game design, partial reinforcement is a reward that is given only occasionally. Note that partial reinforcement is a good example of a powerful factor in engagement that doesn't seem to relate to fun or enjoyment.
* **Observable progress toward the goal**. Engagement seems to be increased if you can identify clear progress as you approach the goal, even if you don't ultimately win. If you are just randomly drifting around in the game, and then with no warning you ﬁnd that you've won, that doesn't build engagement as effectively as an extended process in which you feel you are working your way towards the goal.
* **Emergent gameplay**. Dr. Lewis talks about Emergent Events but I went to a WikiPedia definition of Emergent Gameplay and found it very useful. complex situations in video games, board games, or table top role-playing games that emerge from the interaction of relatively simple game mechanics. I think most people would call this "hacking the game". Deus Ex is often cited as a game responsible for promoting the idea of emergent gameplay, with players developing interesting solutions such as using wall-mounted mines as pitons for climbing walls. In many solitaire games you may be able to play off a bunch at cards on one play, also if you have set things up right. In Tetris, you can hope for a cascade of level clearances. Having these things happen may act as intermediate rewards during play, and help to sustain your interest. (Again, the partial reinforcement idea says these things will be more effective if they don't happen too often.) In game design, an emergent event is something that is positive, that results from user actions (not just randomly), is extended in time (not just a short sound effect or a bump to the score), and gives a sense of progress with reduced (or no) effort.
* **Cycles of tension and release.** In baseball, it happens all the time that a team makes progress, say by getting a runner on base, or even by having a batter get ahead in the count, only to have the batter make an out, or the inning end. In soccer, a team may have a promising attack on goal, only to have a shot saved and the ball cleared. It appears that these cycles of nearing the goal, with heightened tension as it approaches, followed by release, as the apparent progress dissipates, build engagement. Interestingly, analogous cycles seem to be important in music (see ), and in screenplays (see ). The fact that these cycles are so universal in ﬁlm (even "serious" ﬁlms like "Frost/Nixon", as well as potboilers like "The Golden Compass", have this in a very obvious way... the struggle upwards, with sucess looking possible, then the episode of despair, it's hopeless after all,and then the culminating triumph) suggests that this may actually be the most important of the engagement factors. Emergent events may also play into the cycles: watching an emergent event releases tension. Observable progress towards the goal is also important: it doesn't matter if there is a cycle, if the player can't tell there is one.
> 26 votes

# Answer
> What are some ways to improve the fun-factor in game design?

Iteration on your design. Seriously, that's the best way I've seen. Allow time in your schedule to playtest the game on your own, watch playtesters with the game, and then modify the game based on your results. Every time you do this, the game gets a little better and a little more fun. The more iterative design loops you go through, the better the final game will be.

The flip side is, know when it's time to kill an idea. Some things are just not fun no matter how much you iterate (I've heard this referred to as "trying to polish a turd"), and you just have to go back to the drawing board and start again.

So in practice (in my experience, at least) it's a lot of trial-and-error, mostly, and when you do manage to find the fun it's pretty obvious that you found it.
> 12 votes

# Answer
Zynga games are an interesting case because they are NOT fun as it is described in Flow or is present in a game like tetris or space invaders. It's not about matching skill to challenge. Frankly Farmville is not "fun" at all in that sense.

Instead, Facebook games are designed to be engaging, which is subtly different. An engaging game is one that draws people to come back to it regularly, and there are several factors that can increase the level of engagement. In the case of Farmville, it's a combination of Relatedness and Autonomy that really keeps the players coming back. The autonomy (which is a fancy way of saying allowing a player to have their choices be reflected in a game) comes into play with the aesthetic elements of building a farm featuring the crops and decorations that each player wants. This is inherently satisfying. Relatedness is even more important for Farmville, as people come back because Farmville is really a channel for being social with other players. Features such as gifts between players encourage social reciprocation, and the every-two-hours pacing encourages players to come back and "keep up their garden", and be a good citizen. The 3rd pillar of engagement is increasing competence, but FarmVille isn't really about that.

I recommend this gamasutra article as a good overview of the interaction of those factors to create long term engagement. Basically it's about applying concepts from the field of motivational psychology to game design, and I think it goes a long way to explain why games like Civilization and RPGs are as compelling as they are.
> 11 votes

# Answer
> What makes Zynga games on Facebook so popular?

I read an article a while back about Zynga, and the thing that stuck with me is that they approach what they do completely as an empirical science. Their back-end systems are set up to track *tons* of metrics about their games. They know which ones gets played the most, by whom, how frequently, which features get the most play, etc.

Using that, they are in a constant feedback loop of refining their games to improve the metrics they care about. It's not that they have genius game designers, they just have a well-oiled process for responding to what the players are doing.
> 6 votes

# Answer
I have seen a couple of things in the past where I have seen a crowd majority buck their heads. One really sticks out in my mind:

**Little Challenge**
In a prior project, I leaned against the word 'casual' a little too much. I imagined people picking up this game and simply solving a simple feat and moving on. I didn't integrate any kind of losing mechanism per say, but left that for the player to determine. A 'did the player meet his/her expectation' type of situation.

Judging from the feedback I received I see not giving a clear losing mechanism a mistake and a missed opportunity. It seemed that those players who wanted a way to lose actually enjoy knowing they've lost.

I guess that may sound obvious, but I wasn't quite thinking about it that way.

**Reward a Player**
By nature humans are always trying to achieve that next best thing. I think there are some instincts at play there. At a young age our mind was a buzz when we got a new toy, for example.

So in a game I imagine that a player who is given something along the way will improve the fun-factor. I assume this is exactly what Achievements are targeting - a direct reward.
> 2 votes

# Answer
In Mihaly Csikszentmihalyi's book Flow, he talks about the area between the players skill and the challenge. The key is to keep the player in this area. As their skill increases so should the challenge.

If there is too much challenge then the player may give up. If the player is too skilled they may get bored.
> 2 votes

# Answer
You should check out Gamefeel by Steve Swink. His thesis is basically that a lot of the fun in a game comes from the way the avatar moves, interacts with the world and "feels". You should tune speed, acceleration etc to this end.
> 2 votes

# Answer
One good read that has stayed with me for a long time is Richard Bartle's Hearts, Clubs, Diamonds, Spades: Players Who Suit MUDs.

When designing for "fun", I always tend to envision some distinct playing styles that I want to cater to.
> 0 votes

# Answer
I need to add to many good answers that indeed you have to look at engagement rather, but it is close to fun, and is what you want, what makes people play your game.

Though, a word about rewards. A reward is an extrinsic motivation, and a reward is not going to engage your player if the process to it is painful.

You need to keep that in mind, intrinsic motivation is what gets people to play infinitely to something. Like the legos, its not because you have finished your car that you are happy it is because it was "fun" building it, and learning about its insides and whatever psycological event.

Intrinsic motivation is achieved when you fulfill basic "needs" (versus "wants"), and needs related to motivation are known to be "relatedness", "skillship", "autonomy".

* relatedness : this is collaborative gameplay, serious sam, tower defense, world of warcraft...
* skillship : feedback that you are developping skill. headshot in shooters, better timing in racing, frags in multiplayer deatchmatchs...
* autonomy : open world, freedom of choice, better physics...

This is not a personal view, this is all psychology related stuff, you can watch the presentations given at GDC and CEDEC by the people in the know, that is what they mention.
> 0 votes

# Answer
Read this book:
http://www.amazon.com/Designing-Games-Guide-Engineering-Experiences/dp/1449337937/ref=sr\_1\_3?ie=UTF8&qid=1381948557&sr=8-3&keywords=game+design+experience

Thank me later!
> 0 votes

---
Tags: game-design
---


title: Resource management

text:
# Question
Title: Resource management
I've come across a strange thing in DirectX 11:

I'm trying to implement large scale volume visualization engine. My approach is like this: if the volume is HUGE (could not fit to GPU memory directly), tile it into smaller "volume bricks". render all of those bricks separately (offscreen) and blend them properly to screenbuffer.

I've read, that DX11 manages GPU memory by itself. But for volumes \> 4GB I've got unexpected exceptions, when trying to create further resources. (using 64bit system - so no 32bit limit should be present)

So I implemented my own GPU memory manager, which handles resource allocations, and if there should be allocated more, than GPU memory size, all previously created resources are transferred to RAM and DX resource is released.

But the DX behavior is the same.

I'm also calling DeviceContext.Flush() after every release of resource. (to make it really happen)

It seems to me, that DX is not releasing and deallocating resources properly. (Or am I missing something?). Could it be problem, that all this alloc/dealloc operations are done within one frame?

I'm getting mad about this. (even tried to setup eviction priorities of resources, but no luck.)

Thanks for any advice.

# Answer
You should avoid allocating and deallocating resources multiple times per frame. Instead, you should create a single "brick" volume (or how ever many you need concurrently to perform a single Draw call) with usage type DYNAMIC. Then use Map with DISCARD flag to update the contents on the fly.

Regarding the problem with your current approach, this is likely due to some stray ID3D11View\*s (e.g. ShaderResourceView) that you're failing to destroy or unbind. You must destroy and unbind all objects associated with the resource in order for it to be destroyed.
> 3 votes

---
Tags: textures, directx, directx11, resource-management
---


# Question
Title: How to load a simple minimap, and hide the background?
I developed a small and simple 3D games minecraft style. I would add a "MiniMap". Until here everything is fine. I had the idea to load the entire map in the background, and then I added the edge of the minimap over. So I can move the map when the player moves. My problem is that I do not know how to make hidden anything above the minimap. Have you any idea?

I'm stuck in my development

Here is a schematic of what I would do with my minimap. And hide all that is striped in red, outside the minimap.

Thank a looooot ;-)

# Answer
All you need is texture masking. There is more information about that in this answer:

Best way to mask 2D sprites in XNA?
> 0 votes

---
Tags: xna, maps, ui-design
---


# Question
Title: How to deallocate/release/delete of a glTexStorage2D?
I tried to find this but found nothing.

Does anyone know how to 'deallocate' textures/mipmap from glTexStorage2D once you don't need it anymore?

# Answer
> 3 votes
glDeleteTextures is the standard way to delete texture objects in OpenGL, but note that this isn't like malloc/free - glDeleteTextures only promises that the texture *names* become available for subsequent reuse, it says nothing about the actual memory used for storage, which will be driver-dependent behaviour.

Some drivers may keep the storage allocated so that they can reuse it for satisfying future allocations (rather than having to allocate new storage - a common misunderstanding this behaviour leads to is people thinking they have a memory leak), other drivers may not.

This is consistent with the API specification for all other GL objects; glGen\* to create object names, glBind\* to use them, glDelete\* to make the names available for reuse. See e.g. glDeleteBuffers for another example.

So, actually releasing the backing storage is not something you need to worry about yourself; drivers will handle this automatically and you can work on the basis that the memory usage pattern is selected by the driver writers using their own knowledge of what's best for the hardware.

---
Tags: opengl
---


title: Material, Pass, Technique and shaders

text:
# Question
Title: Material, Pass, Technique and shaders
I'm trying to make a clean and advanced Material class for the rendering of my game, here is my architecture:

```
class Material
{
    void sendToShader()
    {
        program->sendUniform( nameInShader, valueInMaterialOrOther );
    }

private:

    Blend       blendmode;      ///< Alpha, Add, Multiply, …
    Color       ambient;
    Color       diffuse;
    Color       specular;
    DrawingMode drawingMode;    // Line Triangles, …
    Program*    program;
    std::map<string, TexturePacket> textures;   // List of textures with TexturePacket = { Texture*, vec2 offset, vec2 scale}
};

```
* How can I handle the link between the Shader and the Material? (sendToShader method)
* If the user want to send additionals informations to the shader (like time elapsed), how can I allow that? (User can't edit Material class)

Thanks!

# Answer
> 7 votes
It's a good idea to separate parameters into a few categories based on how often they're changed, or which other parts of the renderer they hook up to. For instance:

* Frame parameters - like the camera matrix, screen size, and current time
* Material parameters - like textures, specular and gloss values, etc.
* Object parameters - like an object's world matrix, skinning matrices, etc.

If you're using uniform buffer objects it's convenient to make each category its own UBO as well; that way you can re-use UBOs, e.g. use the same frame parameters UBO across all shaders in the scene.

You can then write a little class to handle each group - for instance, have a `FrameParams` class that would handle setting all those parameters for a shader program. It would look up uniform locations at initialization, then later set all the uniforms appropriately, or update the UBO and bind it, each frame. You'd have one instance of this class for each shader program, probably as a member in your `Program` class.

If there are a few fixed sets of parameters used by different materials, you could write similar `MaterialParams` classes for each variation. For instance, one class could handle diffuse and specular colors while another could handle textures. If you need more variation than that, you're looking at a dynamic, data-driven parameter set - which is going to be more complicated, but still doable.

Each shader program could have a set of these parameter objects, kind of like a component-based system. When you want to set the parameters for a particular material, you find the appropriate parameters object in the program and call a method on it, passing in the parameter values for that material.

---
Tags: opengl, architecture, rendering, materials
---


title: What does "Poser-like" mean?

text:
# Question
Title: What does "Poser-like" mean?
The Wavefront OBJ exporter of 3DSMax says it can flip YZ axis. Claiming this is "Poser-like". What does this mean?

And what is the exact transformation if we decide to flip?
Is it simply this?

```
x => x
y => -z
z => y

```

UPDATE: related matrix transformation

```
1  0  0
0  0 -1
0  1  0

```

# Answer
> 1 votes
Coordinate systems can be whatever you decide. Some common tools use a different coordinate system that you might consider "normal." Though there are a couple very common coordinate systems, they really can be whatever you want them to be, so the correct transformation could be application-defined.

+Z being "up" is normal for some model editors and tools but in games +Y is generally "up" with +Z being either "going into the screen" (in a left-handed coordinate system, common in Direct3D-based code) or "going away from the screen" (in a right-handed coordinate system, common in OpenGL-based code). Nothing stops you from making +X up, +Z left, and +Y into the screen; that would be awkward and "weird" to most people, though.

Max can flip the coordinates for you if you want. You don't generally need it to. I'm unsure about its OBJ exporter, but you'll generally need to convert the axis yourself anyway. Using FBX or the exporter plugin API you can figure out which coordinate system the model is using; OBJ has no such feature so you'll need to do the conversion yourself.

I'm afraid I don't have the "default" Max or Poser coordinate systems for OBJs memorized. Simple trial-and-error should give you the correct coordinate system: make a rough non-symmetrical model of a person or the like, export/import to your game, and see in which way it's flipped or rotated to determine the right transformation matrix to use during model load to get the data into your game's preferred coordinate system.

---
Tags: coordinates, 3dsmax
---


# Question
Title: All libGDX input statements are returning TRUE at once
I'm fooling around with Box2D and libGDX and running into a peculiar problem with polling for input. Here's the code for the `Screen`'s `render()` loop:

```
@Override
public void render(float delta) {
    Gdx.gl20.glClearColor(0, 0, .2f, 1);
    Gdx.gl20.glClear(GL20.GL_COLOR_BUFFER_BIT);
    camera.update();
    game.batch.setProjectionMatrix(camera.combined);
    debugRenderer.render(world, camera.combined);
    if(Gdx.input.isButtonPressed(Keys.LEFT)){
        Gdx.app.log("Input", "Left is being pressed.");
        pushyThingyBody.applyForceToCenter(-10f, 0);
    }
    if(Gdx.input.isButtonPressed(Keys.RIGHT)){
        Gdx.app.log("Input", "Right is being pressed.");
        pushyThingyBody.applyForceToCenter(10f, 0);
    }
    world.step((1f/45f), 6, 2);
}

```

And the constructor is largely just setting up the `World`, `Box2DDebugRenderer`, and all the `Bodies` in the world:

```
public SandBox(PhysicsSandboxGame game) {
    this.game = game;
    camera = new OrthographicCamera(800, 480);
    camera.setToOrtho(false);

    world = new World(new Vector2(0, -9.8f), true);
    debugRenderer = new Box2DDebugRenderer();

    BodyDef bodyDef = new BodyDef();
    bodyDef.type = BodyType.DynamicBody;
    bodyDef.position.set(100, 300);

    body = world.createBody(bodyDef);

    CircleShape circle = new CircleShape();
    circle.setRadius(6f);

    FixtureDef fixtureDef = new FixtureDef();
    fixtureDef.shape = circle;
    fixtureDef.density = .5f;
    fixtureDef.friction = .4f;
    fixtureDef.restitution = .6f;

    fixture = body.createFixture(fixtureDef);
    circle.dispose();

    BodyDef groundBodyDef = new BodyDef();
    groundBodyDef.position.set(new Vector2(0, 10));
    groundBody = world.createBody(groundBodyDef);
    PolygonShape groundBox = new PolygonShape();
    groundBox.setAsBox(camera.viewportWidth, 10f);
    groundBody.createFixture(groundBox, 0f);
    groundBox.dispose();

    BodyDef pushyThingyBodyDef = new BodyDef();
    pushyThingyBodyDef.type = BodyType.DynamicBody;
    pushyThingyBodyDef.position.set(new Vector2(400, 30));
    pushyThingyBody = world.createBody(pushyThingyBodyDef);
    PolygonShape pushyThingyShape = new PolygonShape();
    pushyThingyShape.setAsBox(40f, 10f);
    FixtureDef pushyThingyFixtureDef = new FixtureDef();
    pushyThingyFixtureDef.shape = pushyThingyShape;
    pushyThingyFixtureDef.density = .4f;
    pushyThingyFixtureDef.friction = .1f;
    pushyThingyFixtureDef.restitution = .5f;
    pushyFixture = pushyThingyBody.createFixture(pushyThingyFixtureDef);
    pushyThingyShape.dispose();
}

```

Testing this on the desktop. Basically, whenever I hit the appropriate keys, neither of the `if` statements in the loop return true. However, when I click in the window, both statements return true, resulting in a 0 net force on the body. Why is this?

# Answer
> 0 votes
It seems you're mixing up the keyboard and mouse a little bit. Your line: `if(Gdx.input.isButtonPressed(Keys.LEFT)) {`

should either be:

`if(Gdx.input.isKeyPressed(Keys.LEFT)) {` (Keys Javadoc if you're wanting keyboard input)

or

`if(Gdx.input.isButtonPressed(Buttons.LEFT)) {` (Buttons Javadoc if you want mouse input)

I'm not sure if you've got any other problems just by looking at your code.

---
Tags: java, libgdx, input
---


# Question
Title: I get GL_INVALID_VALUE after calling glTexSubImage2D
I am trying to figure out why my texture allocation does not work. Here is the code:

```
glTexStorage2D(GL_TEXTURE_2D, 2, GL_RGBA8, 2048, 2048);
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 2048, 2048, GL_RGB,
                GL_UNSIGNED_SHORT_5_6_5_REV, &BitMap[0]);

```

`glTexSubImage2D` returns `GL_INVALID_VALUE` but the maximum texture allowed is 16384x16384 on my card.

The source of the image is 16bit (Red 5, Green 6, Blue 5).

# Answer
> 1 votes
You try to write an RGB image in an RGBA buffer. This is probably what is causing the problem. Since your source image is in RGB format, you should change GL\_RGBA to **GL\_RGB** at glTexStorage2D.

```
glTexStorage2D(GL_TEXTURE_2D, 2, GL_RGB8, 2048, 2048);

```

---
Tags: opengl
---


title: coloring box2d body in LibGDX

text:
# Question
Title: coloring box2d body in LibGDX
I want to color polygon of box2d in LibGDX. Found below useful class for that.

http://libgdx.badlogicgames.com/nightlies/docs/api/com/badlogic/gdx/graphics/glutils/ShapeRenderer.html

But, it is not coloring the body instead making colored shapes. I want colored bodies having all the property like gravity, restitution etc. In brief, I want to make colored ball and surface.And i don't want to attach sprite on bodies. Want just fill color in bodies.

Need some guidance????

# Answer
You have to separate your physics simulation (bodies) from the graphical representation of the physics world.

Lets assume you have a Box2d body defined like this

```
float radius=3.0f;
CircleShape shape=new CircleShape();
shape.setRadius(radius);
FixtureDef fd = new FixtureDef();
fd.shape = shape;
BodyDef bd = new BodyDef();
bd.type = BodyType.DynamicBody;

Body body=world.createBody(bd);

```

Now in the render() method your first step the physics world

```
world.step(...)

```

Then you draw your body

```
Vector2 pos = body.getWorldCenter();
float angle = body.getAngle(); //if you need rotation

shapeRenderer.begin(ShapeType.Filled);
shapeRenderer.setColor(someColor);
shapeRenderer.circle(pos.x, pos.y, radius);
shapeRenderer.end();

```

The same goes for all bodies (static and dynamic) in the physics world you want to render.

Of course you have to set up the physics world, camera and so on properly first.
> 3 votes

---
Tags: box2d, libgdx, color, body
---


title: LWJGL Java 2D collision when lagging

text:
# Question
Title: LWJGL Java 2D collision when lagging
I'm using a tile based collision, but when the game is lagging (the lag isn't the problem) the collision fails and the player falls through tiles.

This is the movement/collision detection code of my Player class:

```
gravity.y = gspeed;

speed.y+=gravity.y;

position.set(position.x + direction.x * speed.x * deltaSeconds, position.y + direction.y * speed.y * deltaSeconds);

for (int i = (int) Math.round(position.x / 32) - 2 * t; i < (int) Math.round(position.x / 32) + 3 * t; i++)
            {
                for (int j = (int) Math.round(position.y / 32); j < (int) Math.round((position.y + height + 64) / 32); j++)
                {
                    checkCollision(i, j, deltaSeconds);
                }
            }

public void checkCollision(int i, int j, float deltaSeconds)
    {
        bbox.setBounds((int) position.x, (int) position.y, (int) width, (int) height);
        Tile t = null;
        t = Map.getTile(i, j);
        if (t != null)
        {
            if (t.isSolid())
            {
                if (t.getTop().intersects(bbox))
                {
                    if (position.y + height < t.y * 32 + 32)
                    {
                        if (speed.y >= 0)
                        {
                            position.y = t.y * 32 - height;
                            speed.y = 0;
                            gravity.y = 0;
                            jumpState = 0;
                        }

                    }

                }
                if (t.getBottom().intersects(bbox))
                {
                    if (position.y < t.y * 32 + 32)
                    {
                        position.y = t.y * 32 + 32;
                        speed.y = 0;
                    }
                }
                else
                {
                    if (t.getLeft().intersects(bbox))
                    {
                        if (position.x + width > t.x * 32)
                        {
                            position.x = t.x * 32 - width;
                            speed.x = 0;
                        }
                    }
                    if (t.getRight().intersects(bbox))
                    {
                        if (position.x < t.x * 32 + 32)
                        {
                            position.x = t.x * 32 + 32;
                            speed.x = 0;
                        }
                    }
                }
            }

        }
    }

```

Is it possible to fix my code, if yes how? Or is it possible to tell if the game is lagging?

# Answer
You have a variable called `deltaSeconds`, which I presume is declared something like: `float deltaSeconds` in your Player update code.

You can work out a threshold that deltaSeconds can cross, at which you can consider your game to be lagging. For example, if your game runs at 30fps normally, deltaSeconds should be roughly ~0.033f. If the fps degrades to 20fps, it will be 0.05f.

So you need to work out a good value for deltaSeconds to be greater than to be considered lag.

As to what you can do to fix lag - you could clamp how far an object can move in one frame, or you could clamp the deltaSeconds to your threshold.

I/others can elaborate more if needed.

EDIT (I can't comment yet): Even if you want unlimited fps, I'd imagine you still have a minimum desired rate. You don't want your game running at less than a certain fps, but you'd like it to run anywhere faster than that. That should be your lag threshold.
> 0 votes

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


# Question
Title: Why i can not load a simple pixel shader effect (. fx) file in xna?
I just want to load a simple \*.fx file into my project to make a (pixel shader) effect.

But whenever I try to compile my project, I get the following error in visual studio Error List:

```
Errors compiling ..
ID3DXEffectCompiler: There were no techniques
ID3DXEffectCompiler: Compilation failed

```

I already searched on google and found many people with the same problem. And I realized that it was a problem of encoding. With the return lines unrecognized '\ n' .

I tried to copy and paste to notepad and save as with ASCII or UTF8 encoding. But the result is always the same.

Do you have an idea please ? Thanks a looot :-)

Here is my \[.fx\] file :

```
sampler BaseTexture : register(s0);
sampler MaskTexture : register(s1)
{
    addressU = Clamp;
    addressV = Clamp;
};

//All of these variables are pixel values
//Feel free to replace with float2 variables
float MaskLocationX;
float MaskLocationY;
float MaskWidth;
float MaskHeight;
float BaseTextureLocationX;  //This is where your texture is to be drawn
float BaseTextureLocationY;  //texCoord is different, it is the current pixel
float BaseTextureWidth;
float BaseTextureHeight;

float4 main(float2 texCoord : TEXCOORD0) : COLOR0
{
    //We need to calculate where in terms of percentage to sample from the MaskTexture
    float maskPixelX = texCoord.x * BaseTextureWidth + BaseTextureLocationX;
    float maskPixelY = texCoord.y * BaseTextureHeight + BaseTextureLocationY;
    float2 maskCoord = float2((maskPixelX - MaskLocationX) / MaskWidth, (maskPixelY - MaskLocationY) / MaskHeight);
    float4 bitMask = tex2D(MaskTexture, maskCoord);

    float4 tex = tex2D(BaseTexture, texCoord);

    //It is a good idea to avoid conditional statements in a pixel shader if you can use math instead.
    return tex * (bitMask.a);
    //Alternate calculation to invert the mask, you could make this a parameter too if you wanted
    //return tex * (1.0 - bitMask.a);
}

```

# Answer
I'd say your problem is perfectly explained by the error message. There are no techniques in your file. You just have a pixel shader.

An effect contains one or more techniques, each one described by one or more passes, each one implemented by a vertex shader and a pixel shader.

Your file only contains a pixel shader, and that's what the compiler is complaining about. If you use an effect file, you should have at least one pixel shader, one vertex shader, and a technique with at least one pass that makes use of your shaders.

You can find more information on how to write an effects file at the official documentation.
> 2 votes

---
Tags: xna, shaders, fragment-shader
---