# Question
Title: Camera rotation around point, but without centering
Let's say i have the following:

* Point somewhere in space
* Camera with position and orientation (up, right, forward)

I want to rotate camera around the point, but also keep this point in same place on screen. So, if point was on (32, 32) on window, after rotation i want it to still be on (32, 32).

I've seen How can I orbit a camera about it's target point? , and it was somewhat helpful. I needed code to rotate point around arbitrary axis (camera's up and right), so i used this resource.

Problem is, i got something like numerical errors and my camera started to wander weirdly when rotating around camera's both up and right (it seems fine when i rotate only around one of them).

I tested my implementation with code:

```
Matrix m1=MatrixRotate(Vector(-1, -1, 1),  33);
Matrix m2=MatrixRotate(Vector(-1, -1, 1), -33);
Vector a=Vector(-1, -1, -1);
Vector c=a;

c=m1*c;
c=m2*c;
printf("%f %f %f %f\n", c.x, c.y, c.z, c.w);

```

And got:

```
-1.028036 -0.960396 -1.124331 0.000000

```

It worked fine when rotation axis was something 'normal' like (1, 0, 0) or (0, 0, -1).

So, how else can i rotate camera around point, while keeping said point in same point on screen?

# Answer
> 2 votes
Looks like you got some very big rounding errors in there. I have no idea why but I have written some code for matrix rotations once. It's in Java though but should be very easy to translate to C++.

Vector class:

```
public class Vec {
    public final static Vec X_AXIS=new Vec(1,0,0);
    public final static Vec Y_AXIS=new Vec(0,1,0);
    public final static Vec Z_AXIS=new Vec(0,0,1);
    public final static Vec ORIGIN=new Vec(0,0,0);

    public final double x,y,z;

    public Vec(double x, double y, double z) {
        this.x=x;
        this.y=y;
        this.z=z;
    }

    public double dotProduct(Vec v) {
        return x*v.x+y*v.y+z*v.z;
    }

    public Vec crossProduct(Vec v) {
        double rx=y*v.z-z*v.y;
        double ry=z*v.x-x*v.z;
        double rz=x*v.y-y*v.x;
        return new Vec(rx, ry, rz);
    }

    public Vec newLength(double newLength) {
        double length=getLength();
        if(length==newLength) return this;
        if(length==0) return X_AXIS.newLength(newLength);
        return new Vec(x*newLength/length, y*newLength/length, z*newLength/length);
    }

    public Vec rotationAxis() {
        return rotationAxis(X_AXIS);
    }

    //The rotation axis to rotate v onto this
    public Vec rotationAxis(Vec v) {
        return normalizedCrossProduct(v);
    }

    public Vec normalizedCrossProduct(Vec v) {
        Vec r=crossProduct(v);
        if(r.getLength()<0.0001) {
            r=crossProduct(X_AXIS);
        }
        if(r.getLength()<0.0001) {
            r=crossProduct(Y_AXIS);
        }
        if(r.getLength()<0.0001) {
            return X_AXIS;
        }
        return r.normalize();
    }

    public double angle() {
        return angleTo(X_AXIS);
    }

    public double angleTo(Vec v) {
        double cosTheta=dotProduct(v)/(getLength()*v.getLength());

        return Math.acos(cosTheta);
    }

    public double getLength() {
        return Math.sqrt(x*x+y*y+z*z);
    }

    public Vec rotate(Matrix m) {
        return m.mul(this);
    }

    public Vec normalize() {
        double length=getLength();

        if(length==1) return this;
        if(length==0) return X_AXIS;
        return new Vec(x/length, y/length, z/length);
    }

    public Vec addX(double a) {
        return new Vec(x+a, y, z);
    }

    public Vec addY(double a) {
        return new Vec(x, y+a, z);
    }

    public Vec addZ(double a) {
        return new Vec(x, y, z+a);
    }

    public Vec add(Vec v) {
        return new Vec(x+v.x, y+v.y, z+v.z);
    }

    public Vec sub(Vec v) {
        return new Vec(x-v.x, y-v.y, z-v.z);
    }

    public Vec mul(double m) {
        return new Vec(x*m, y*m, z*m);
    }

    public Vec div(double d) {
        return new Vec(x/d, y/d, z/d);
    }

    public Vec neg() {
        return new Vec(-x, -y, -z);
    }

    @Override
    public boolean equals(Object o) {
        if(!(o instanceof Vec)) return false;
        Vec v=(Vec)o;
        return v==this || sub(v).getLength() < 0.0001;
    }

    public String toString() {
        return String.format(java.util.Locale.ENGLISH,
            "(%.3f, %.3f, %.3f)", x, y, z);
    }

}

```

Matrix class:

```
public class Matrix {
    public final static Matrix IDENTITY=new Matrix(Vec.X_AXIS, Vec.Y_AXIS, Vec.Z_AXIS);
    public final Vec xAxis, yAxis, zAxis;

    public Matrix(double ... e) {
        if(e.length!=9) throw new RuntimeException();
        xAxis = new Vec(e[0], e[3], e[6]);
        yAxis = new Vec(e[1], e[4], e[7]);
        zAxis = new Vec(e[2], e[5], e[8]);
    }

    public Matrix(Vec xAxis, Vec yAxis, Vec zAxis) {
        this.xAxis = xAxis;
        this.yAxis = yAxis;
        this.zAxis = zAxis;
    }

    public Matrix(Vec axis, double theta) {
        Vec u=axis.normalize();
        double sin=Math.sin(theta);
        double cos=Math.cos(theta);
        double uxy=u.x*u.y*(1-cos);
        double uyz=u.y*u.z*(1-cos);
        double uxz=u.x*u.z*(1-cos);
        double ux2=u.x*u.x*(1-cos);
        double uy2=u.y*u.y*(1-cos);
        double uz2=u.z*u.z*(1-cos);
        double uxsin=u.x*sin;
        double uysin=u.y*sin;
        double uzsin=u.z*sin;

        xAxis = new Vec(cos+ux2, uxy+uzsin, uxz-uysin);
        yAxis = new Vec(uxy-uzsin, cos+uy2, uyz+uxsin);
        zAxis = new Vec(uxz+uysin, uyz-uxsin, cos+uz2);
    }

    static public Matrix xRotationMatrix(double theta) {
        double cos = Math.cos(theta), sin = Math.sin(theta);
        return new Matrix(Vec.X_AXIS,
                          new Vec(0, cos, sin),
                          new Vec(0, -sin, cos));
    }

    static public Matrix yRotationMatrix(double theta) {
        double cos = Math.cos(theta), sin = Math.sin(theta);
        return new Matrix(new Vec(cos, 0, -sin),
                          Vec.Y_AXIS,
                          new Vec(sin, 0, cos));
    }

    static public Matrix zRotationMatrix(double theta) {
        double cos = Math.cos(theta), sin = Math.sin(theta);
        return new Matrix(new Vec(cos, sin, 0),
                          new Vec(-sin, cos, 0),
                          Vec.Z_AXIS);
    }

    public Matrix rotX(double theta) {
        return xRotationMatrix(theta).mul(this);
    }

    public Matrix rotY(double theta) {
        return yRotationMatrix(theta).mul(this);
    }

    public Matrix rotZ(double theta) {
        return zRotationMatrix(theta).mul(this);
    }

    public Matrix mul(double d) {
        return new Matrix(xAxis.mul(d), yAxis.mul(d), zAxis.mul(d));
    }

    public Vec mul(Vec v) {
        return xAxis.mul(v.x).add(yAxis.mul(v.y)).add(zAxis.mul(v.z));
    }

    public Matrix mul(Matrix m) {
        return new Matrix(mul(m.xAxis), mul(m.yAxis), mul(m.zAxis));
    }

    public Matrix rotateRel(Matrix m) {
        return mul(m);
    }

    public Matrix rotateAbs(Matrix m) {
        return m.mul(this);
    }

    public Matrix normalize() {
        Vec vz=xAxis.crossProduct(yAxis);
        Vec vy=vz.crossProduct(xAxis);
        return new Matrix(xAxis.normalize(),
                          vy.normalize(),
                          vz.normalize());
    }

    public Matrix transpose() {
        return new Matrix(xAxis.x, xAxis.y, xAxis.z,
                          yAxis.x, yAxis.y, yAxis.z,
                          zAxis.x, zAxis.y, zAxis.z);
    }

    public double determinant() {
        return xAxis.x*(yAxis.y*zAxis.z-zAxis.y*yAxis.z) -
               yAxis.x*(zAxis.z*xAxis.y-zAxis.y*xAxis.z) +
               zAxis.x*(xAxis.y*yAxis.z-yAxis.y*xAxis.z);
    }

    public Matrix inverse() {
        Vec A = yAxis.crossProduct(zAxis);
        Vec B = zAxis.crossProduct(xAxis);
        Vec C = xAxis.crossProduct(yAxis);
        return new Matrix(A,B,C).transpose().mul(1/determinant());
    }

    public Matrix oppositeRotMatrix() {
        return transpose();
    }

    @Override
    public boolean equals(Object o) {
        if(!(o instanceof Matrix)) return false;
        Matrix m=(Matrix)o;
        return m==this || xAxis.equals(m.xAxis) && yAxis.equals(m.yAxis) && zAxis.equals(m.zAxis);
    }

    public String toString() {
        return String.format(java.util.Locale.ENGLISH,
            "[%.3f, %.3f, %.3f]\n[%.3f, %.3f, %.3f]\n[%.3f, %.3f, %.3f]",
            xAxis.x, yAxis.x, zAxis.x,
            xAxis.y, yAxis.y, zAxis.y,
            xAxis.z, yAxis.z, zAxis.z);
    }
}

```

When I test it with this code

```
Matrix m1 = new Matrix(new Vec(-1, -1, 1), Math.toRadians(33));
Matrix m2 = new Matrix(new Vec(-1, -1, 1), Math.toRadians(-33));
Vec a = new Vec(-1, -1, -1);
Vec c = a;

c = m1.mul(c);
c = m2.mul(c);
System.out.println(c);

```

I get (-1.000, -1.000, -1.000), so no significant rounding errors.

btw. I took my equations for axis/angle rotations from http://en.wikipedia.org/wiki/Rotation\_matrix

---
Tags: opengl, c++, camera, rotation
---


# Question
Title: How to correctly handle multiple movement key presses resulting in double the speed?
I am trying to implement **acceleration** and **drag** into my top-down 2D game. The player can move using the WASD keys. Acceleration works fine, but the way I handle the directional velocity causes the player to abruptly stop when the movement keys are released instead of coming to a stop. Here is the code I currently have:

**EDIT:** I officially solved the above issue by implementing an **applyForce** method and triggering it when the movement keys are pressed as seen here:

```
    public void applyForce(float angle, float amount)
    {
        Vector2 v = new Vector2((float)(Math.Cos(angle)), (float)(Math.Sin(angle)));
        v.Normalize();
        v = Vector2.Multiply(v, amount);

        velocity = Vector2.Add(velocity, v);
    }

            if (oldKeys.IsKeyDown(Keys.A))
            {
                applyForce((float)Math.PI, CurrentSpeed);
            }
            if (oldKeys.IsKeyDown(Keys.D))
            {
                applyForce(0, CurrentSpeed);
            }
            if (oldKeys.IsKeyDown(Keys.W))
            {
                applyForce((float)Math.PI * 1.5f, CurrentSpeed);
            }
            if (oldKeys.IsKeyDown(Keys.S))
            {
                applyForce((float)Math.PI * 0.5f, CurrentSpeed);
            }

```

As you may have guessed, the new problem is that when 2 keys are pressed the method is called twice causing the player to move faster than he should be. Are there any effective ways of handling this?

# Answer
> 1 votes
Someone answered the question earlier then either deleted it or I accidentally deleted it (and if so I apologize). Regardless, they pointed out that it was odd that my applyForce method was based on an angle so I fixed that, then used a modified version of their idea to fix my problem.

Here are the two new overloaded versions of **applyForce**:

```
    public void applyForce(Vector2 direction, float amount)
    {
        if (direction.Length() > 0)
            direction.Normalize();

        direction = Vector2.Multiply(direction, amount);

        velocity = Vector2.Add(velocity, direction);
    }

    public void applyForce(Vector2 v)
    {
        velocity = Vector2.Add(velocity, v);
    }

```

And the new movement key code:

```
            int x = 0, y = 0;

            if (oldKeys.IsKeyDown(Keys.A))
                x = -1;
            if (oldKeys.IsKeyDown(Keys.D))
                x = 1;
            if (oldKeys.IsKeyDown(Keys.W))
                y = -1;
            if (oldKeys.IsKeyDown(Keys.S))
                y = 1;
            if (oldKeys.IsKeyUp(Keys.A) && oldKeys.IsKeyUp(Keys.D))
                x = 0;
            if (oldKeys.IsKeyUp(Keys.W) && oldKeys.IsKeyUp(Keys.S))
                y = 0;

            Vector2 mv = new Vector2(x, y);
            applyForce(mv, CurrentSpeed);

```

---
Tags: xna, c#, 2d, physics, game-mechanics
---


# Question
Title: Slick2D : translate -> scale -> translate doesn't return to the old position
I am trying to implement zoom using Slick2D library.

As I understand, to zoom something on non (0,0) coordinates, we need:

* translate so the target point is in (0,0)
* apply scale factor
* translate the target point back from (0,0)

Code example :

```
 aGraphics.translate(-width/2, -height/2);
 aGraphics.scale(2,2);
 aGraphics.translate(width/2, height/2);

```

The issue is, as far I understand, that the scale factor is applied to the translation too. To compensate this, I have use the next code :

```
 aGraphics.translate(-width/2, -height/2);
 aGraphics.scale(2,2);
 aGraphics.translate(width/4, height/4);

```

Is this expected behaviour for graphics ? Can I workaround the above effect using push/pop matrix ?

# Answer
Seems that slick 2d doesn't consider the center coordinates when scaling. It just multiplies any coordinates using current scale.
> 0 votes

---
Tags: graphics, slick
---


# Question
Title: GLSL: can i use matrix transformation functions in vertex shader?
I have a working OpenGL code where i render a terrain with some trees.

I am doing all the matrix mathematics on the client side. Because of which the frame rate of my app is very low, around 25-30 \[its not LOW but, i used to get 60 before the calculations\]

If i were to do all these matrix transformations on server side, in say vertex shader, or even better a geometry shader, are there functions in GLSL which translate, rotate, ans scale?

for example, what would the following client side code look on server side?

```
        model   = tes_terr.glm_model; //get the current camera movement matrix
        model   *=  glm::translate( glm::mat4(1.0f),  glm::vec3(tvec.x, tvec.y, tvec.z))
                  * glm::rotate   ( glm::mat4(1.0f), -90.0f, glm::vec3(1, 0, 0))
                  * glm::scale    ( glm::mat4(1.0f),  glm::vec3(scaleFactor));

```

Or do i have to write these function in vertex shader separately.

# Answer
> 4 votes
You should create the matrices on the cpu and pass them to the gpu so there's as little redundancy as possible( you don't want to create new transforms per vertex if all of your vertices for a mesh have the same transform. )

As for multiplying matrices on the gpu, you simply use the * operator with any two valid operands.

To answer your question; there is no function in glsl to create any matrices for you. You either need to create them yourself or upload them from the cpu. The common practice for this is to create you model, view and projection matrices on the cpu and upload them separately so that we have all the information needed for each coordinate space.

# Answer
> 4 votes
The CPU is very unlikely to be overloaded by this.

Let's look at an example. Let's say you have a model with 5000 vertices. You want to draw it.

Setting up your matrix on the CPU involves:

* One translation.
* One rotation.
* One scale.
* One matrix upload.

Doing it on the GPU involves:

* 5000 translations.
* 5000 rotations.
* 5000 scales.

While it's true that GPUs are faster than the CPU for this kind of calculation, doing it 5000 times rather than once is going to totally burn through your performance and on balance it will run even slower.

Reading this question, you have a performance problem but it seems as though you've decided where the problem *must* be without any proper profiling. **Your performance problem is not where you think it is**. You're doing something else that's causing it to be slow, and the challenge is to find out what that "something else" might be. Without seeing the rest of your code it's difficult to be more specific.

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


title: How can I reduce Unity's package size?

text:
# Question
Title: How can I reduce Unity's package size?
I've been experimenting with Unity3D 4.3's 2D features. I've created a simple prototype game to learn how Unity works, how to create sprite animations, collisions and all the basic things. My project compiled for PC was approximately 23MB.

The game includes one larger bitmap for a background (originally 1MB JPEG). The player spritesheet was black and white with almost no details. So all the assets had (in their original, compressed form) no more than 2-3 MB. I ended up with one large executable file (about 10MB) and a folder with *.dll* files and assets (5-6MB).

Can that be reduced?

My experience with C# WinForms code makes me believe that executables and DLLs grow that big only when binary data was involved (images, sound, etc). Is that the case with Unity? I am interested in developing 2D applications for Android and iOS, where low total app size is a priority.

# Answer
Thesedays, 23MB for mobile game sounds not that big at all. Unity has many great advantages, but it's shared libraries, mono files and so on takes a lot of place unfortunately.

The other way round, Apple has limited their apps to be downloaded over 3G to 100MB, so the 23MB is not that much anyway, in comparison to this limit. Especially, that now the size won't be increasing very rapidly.

A lot of not very big apps was made with Unity and I suppose that users aren't expecting the apps to be very small. You can take a look at Unity's Showcase and filter it by iOS/Android platform, then check the app size in the store - they're about 40MB for simple 2D game, so it's not that unusual.

Unity development is just mush more faster than native, or even cross platform development like Adobe AIR, and you have all platforms you need. Also the performance is almost as good as native, especially for smaller teams without extra time and money to tweak their own, specialised engines.

EDIT: With other C++/C# executables it is often common, that these installers doesn't include shared Redistributable packages, which add few MB to the overall build size if they were included. Here Unity is including everything. Also being managed, not native language seems to add some overhead.

Also the overhead according to the Unity documentation, could be reduced from 23MB to 12MB:

> How small can an app be made with Unity? An empty project would take less than 22 MB in the App Store if all the size optimizations were turned off. If you own an Advanced License (and therefore have access to the stripping option), the empty scene with just the main camera can be reduced to less than 12 MB in the App Store (zipped and DRM attached).

Here's the guide to decreasing this size: build size optimization.
> 3 votes

# Answer
I'd say yes. I have been using unity for this purpose. You will have that 20Mb lump of the unityengine to start off with, but after that your project will increase in size normally.
If your really concerned you could try Corona SDK which is a 2d sdk that builds to iOS and Android, but you may run into limitations with it though (like facebook integration for example)
The reason I use a pre-existing engine/framework/sdk rather than write my game from scratch is because I want the following benefits..

1. Development speed
2. Can make it once and then build to multiple devices.
3. Less weird random "not working" or performance problems on particular hardware setups.

I think Unity3D is the best solution out at the moment to provide these, also it has a lot less limitations that other things Ive tried, a large community and lots of libraries (assets) available for it.

To save space you can compress all your game assets like images and whatnot. This is actually the default, images will be compressed and also squished to a 1024 maximum resolution. You can override and change these settings in the inspector when you select your asset.
> 0 votes

---
Tags: unity, compression
---


# Question
Title: Game Taking too long during render cycles
Firstly, I'm not asking anyone to read my code. It is only posted as a reference just in case you want to. I am asking for *general tips* on how to get my game running at higher FPS on android, for people who have had the same problem before.

I've been looking all over the web to a specific fix to my problem, but it seems its too generic of a problem to fix, so I thought i'd ask here and see if anyone has experience with this sort of problem. I'm developing a game on android using the native libraries only. my rendering cycle is taking 1/5th of a second to complete, which is ludicrous and drops my frame rate to 5. My game uses very simple PNG graphics i made in GIMP, and i only have a total of 10 images. It doesn't make sense for the game to be running this slow.

Things that I've tried from the web:

-Load each image once and then retrieve them from a cache - done.

-Diagnose using DDMS/MAT to fix memory leaks - there were none.

-Get a sampled size of the image instead of full image - no effect

-Draw onto a off-screen, mutable bitmap, then draw that bitmap onto your main canvas - no effect

-reduce the capped frames/second in my main game loop to around "20" - no effect

The only thing I haven't done is use completely non-scaled images, which i don't see as being practical since every android device has different resolutions and screen sizes.

Does anyone have any other things I should try? If i can't figure this out I'm at a complete loss, because this is crippling the game and making it unplayable. If anyone has steps I can take, please help. *In case you'd like to view my code*, I've posted the relevant code below and my basic loop (a copy of which can be found online under "basic android loops" search term):

My Input/Output Handler Class:

```
public abstract class FileIO{....

public static synchronized Bitmap getImage(String imageName, Context context){

    for (int i = 0; i < bitmapList.size(); i++){
        if (fileNameList.get(i).equals(imageName)){
            return bitmapList.get(i);
        }
    }
    Bitmap bitmapReturn = null;
    try {
        assetManager = context.getAssets();
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inPreferredConfig = Bitmap.Config.ARGB_8888;
        inputStream = assetManager.open(imageName);
        bitmapReturn = BitmapFactory.decodeStream(inputStream, null, options);

.......
    }
    fileNameList.add(imageName);
    bitmapList.add(bitmapReturn);
    return bitmapList.get(bitmapList.size()-1);
}

}

```

My "Drawable Sprite" Base Class:

```
public class Physical {

public void draw(){
        ImageBuffer.bufferCanvas.drawBitmap(FileIO.getImage(imageName, GameLoop.context), null, getRect(), null);
        }
}

```

My Main Loop:

```
public class Loop extends Activity{

static Canvas canvas;
public final static int MAX_FPS = 45;
public final static int MAX_FRAME_SKIPS = 5;
public final static int FRAME_PERIOD = 1000 / MAX_FPS;
public final static int GAME_STATE_TITLE_SCREEN = 1;
public static Context context;
public RenderView renderView;

 @Override
    protected void onCreate(Bundle savedInstanceState) {

        context = this;
        super.onCreate(savedInstanceState);
        renderView = new RenderView(this);
        setContentView(renderView);
    }

    public void renderAll(){

        //In this method, I have a call to all my "Physical" objects to draw() themselves.
    }

    public class RenderView extends SurfaceView implements Runnable {

        public Thread renderThread = null;
        public SurfaceHolder holder;
        public volatile boolean running = false;

        public RenderView(Context context) {
            super(context);
            holder = getHolder();
        }

        public void onSizeChanged (int w, int h, int oldw, int oldh){

            if (ImageBuffer.bufferCanvas == null) new ImageBuffer();
        }

        public void resume() {
            running = true;
            renderThread = new Thread(this);
            renderThread.start();
        }

        public void run() {

            long beginTime;
            long timeDiff;
            int sleepTime;
            int framesSkipped = 0;

            sleepTime = 0;

            while (running){

                canvas = holder.lockCanvas();
                canvas.drawRGB(0, 0, 0);

                beginTime = System.nanoTime();
                framesSkipped = 0;

                updateAll();
                renderAll();

                timeDiff = System.nanoTime() - beginTime;
                sleepTime = (int)(FRAME_PERIOD - (timeDiff/1000));

                if (sleepTime > 0) {
                    try {
                    Thread.sleep(sleepTime);
                }

                while (sleepTime < 0 && framesSkipped < MAX_FRAME_SKIPS) {
                    updateAll();
                    sleepTime += FRAME_PERIOD;
                    framesSkipped++;
                }

                ImageBuffer.flipBuffer();
                holder.unlockCanvasAndPost(canvas);
            }
        }
    }
}

```

This code is post-image buffer implementation (which did nothing). I was drawing directly to the main canvas before. In the "renderAll()" method inside the main loop, I just have a call to all of my "Physical" objects to ".draw()" themselves.

Does anyone know what is wrong with my game??

# Answer
> 2 votes
You seem to be loading the images in memory from the storage every frame when you draw them. This is very slow and is most likely the main reason for the slowdown you are experiencing. You need to reuse the previously loaded image to get the proper draw speed you are looking for. Never load the images on every frame again and again, that will just kill the framerate.

You currently have the following code:

```
public class Physical {
    public void draw(){
        ImageBuffer.bufferCanvas.drawBitmap(FileIO.getImage(imageName, GameLoop.context), null, getRect(), null);
    }
}

```

You can improve this by storing the bitmap reference, and checking you have loaded it before drawing. Something like this:

```
public class Physical {
    Bitmap bitmap = null;
    public void draw(){
        if(bitmap == null) {
            bitmap = FileIO.getImage(imageName, GameLoop.context);
        }
        ImageBuffer.bufferCanvas.drawBitmap(bitmap, null, getRect(), null);
    }
}

```

---
Tags: android, rendering, game-loop, frame-rate
---


# Question
Title: How can I choose a pathfinding target for a unit group and move the group to that target?
So I've got some units which should move to a specific position which is given by the player. Currently the units can move there by finding a path with the A\* algorithm (to be more precise: A\* Pathfinding Library for Unity)

I was wondering what the best way to move the units is? When the player has selected e.g. 20 units, some of them are near each other, some of them are far away from the others, what is the best way to navigate them to a single position defined by the user. Obviously they cannot just all have the same target since they would never reach it when the first unit moved to it. Thus what do I have to do? Do I have to assign different targets to each unit or do I calculate the target position relative to the position they were to each other before?

# Answer
When you have a group selection and you issue a movement order for that group by clicking, the natural expectation of the player is that the destination point will be the new "center" of the group once they arrive.

One possible approach to this problem is to compute the centroid of the group when the movement order is issued, and then construct a path from that centroid to the clicked location. You can also compute the offsets from the centroid to each unit in the group at the start of the movement order, and store this in some kind of transient "formation" data structure. When units get within a certain distance of the target point -- a good value for this distance could be the radius of the circle that encloses the full unit group(\*) -- have them move to the final destination, which you can compute by applying their stored formation offset to the clicked target position.

Of course, it does mean your units will try to clump up into a single tight ball while moving. You can solve this by enforcing proximity constraints, or by use the formation deltas to move the entire group "in formation." Doing either of those raises another question: you computed an A\* path from one point to the other, but you aren't moving everybody exactly along that path, so how do you deal with obstacles in the way?

The solution is to employ a simpler form of local pathfinding to move units around local obstructions. Edge-walking (where you simply move a unit around the border of an obstacle until it gets back on the path or strays too far from it) can be useful because it doesn't have nearly the computational cost of A\* and it will produce acceptable results for very small search spaces, which is what you're using it for.

This is good, because the main benefit of this overall approach is not doing N A\* searches for N units; since A\* is computationally expensive, you want to minimize its use. This approach allows you to scale up the number of units in a selection group without negatively impacting search performance (at least not *linearly* impacting it).

A key thing to keep in mind for pathfinding in RTS games is that a divide-and-conquer approach is going to provide huge wins, especially given the size of RTS maps and the number of pathfinding agents generally involved. Any way you can seize upon to reduce pathfinding complexity or put it into increasing granularity hierarchies will help improve the overall performance of the system.

(\*) You may also want to handle "outlier" units (for example, you have five guys close together and one guy really, really far away from the others -- all selected) by adjusting their formation delta to some maximum distance from the centroid. This means the outlier will move in closer to be with his friends by the time the move ends.
> 1 votes

---
Tags: unity, path-finding
---


# Question
Title: Can SFML load anything other than RGBA8888? (RGBA4444, RGB565, etc.)
I can't see this mentioned in the documentation. Am I missing something obvious? Or does SFML really give you no option, forcing everything to be loaded as RGBA8888?

Searches on Google and the SFML forums have been unproductive.

# Answer
> 1 votes
SFML, at least as of version 2 and as of this writing, uses `stb_image` (available here) to load image data, except on Android platforms. You can verify this by checking the source (`Image.cpp` and `ImageLoader.cpp` in particular).

Most of the documentation for `stb_image` is in the header file; SFML's particular version of it is here (be warned: it is large). However, while the header comments do point out some limitations for particular file formats, there's nothing in there that seems to imply `RGBA8888` only (although for the PNG format, it sounds like you can only have 8-bit channels so `RGBA4444` is probably out).

Thus, the short answer is: *yes*, but with some limitations depending on the file format.

---
Tags: sfml, image, loading, file-format
---


# Question
Title: Why haven't graphics cards been designed for voxel rendering?
I stumbled across the following article on Wikipedia regarding voxels that says:

> One such problem cited by Carmack is the lack of graphics cards designed specifically for such rendering requiring them to be software rendered, which still remains an issue with the technology to this day.

Does anyone know why this is the case and why voxels are not supported or optimized on a hardware level by graphics cards?

# Answer
> 6 votes
Primarily because, as of this writing, hardware vendors likely don't have a reason to implement such a thing. Mainly because there isn't any benefit to doing so.

The majority of games and 3D software applications are based heavily around the traditional scan-line rasterization model, and would see no benefit (and in fact, likely significant drawbacks) to adopting a voxel-based model.

Further, there are no emerging standards for software-side APIs for voxel rendering that are backed by significant industry powerhouses (like already exist with D3D and OpenGL).

With ATI starting to explore the direction of moving away from industry-standard APIs towards something proprietary (Mantle), and the possibility of VR headset technology actually becoming a realizable commodity technology via Oculus Rift, there is a slightly greater possibility of seeing something like this in the next few decades.

But up until now, and likely for quite some time yet, the cost/benefit ratio for all parties concerned is just not favorable.

# Answer
> 2 votes
It's a chicken/egg problem. There are no serious voxel-based graphic engines, so there is no need to develop a voxel-optimized GPU, and as long as there are no voxel-optimized GPUs, nobody will create voxel-based engines.

However, the quote by Carmack was specific to Quake III which is 15 years old by now. While it is true that there is still no standardized abstraction layer for voxel-based graphics which could be compared to OpenGL or Direct3d, GPUs have become a lot more flexible in the past years. Today, a hardware-accelerated compute-shader can be useful to speed up various voxel-operations.

One might wonder why we still see so few serious voxel-engines outside of the demoscene then. The reason is that while the development of voxel-based rendering essentially stopped in the 90s, polygon-based graphics made a trendemous development since then. The voxel technology first needs to get over this huge research gap before it can again compete visually.

# Answer
> 0 votes
There's a company that claims to be seriously developing a point-data engine, and that it somehow gets by on software rendering. They had previously stated that graphics hardware developers were uninterested in non-polygon methods of rendering, so they've more recently begun pursuing geospatial applications.

This technology description gives no technical details, though various pitch videos claim that they "only load the point data required for the render", "can work with a total pool including terabytes of data", and "have overcome the problem of frequent, tiny disk-reads".

That last claim is the most suspect to me. If they've overcome file I/O latency, that is a bigger accomplishment than their point-data render. Their demo may be a complete fabrication, but they seem to be very persistent if only perpetrating a hoax. On the other hand, they seem to be rendering not "unlimited data", but rather "unlimited instances of flat-shaded algorithmic geometry".

Interesting, nonetheless. https://www.youtube.com/channel/UCI9bdH0LDRCVxeeAFC1Sk3w

---
Tags: graphics, rendering, voxels
---


# Question
Title: Gaps appearing between Sprites when scaling the stage
I'm learning to use createjs using this game level to-be as a sandbox: http://www.mboyeman.com/dashingdog/
The level is composed of a single background image and 64X64pixel Sprites all coming from the same Spritesheet.
Sprites were placed edge to edge, but spaces still appear between them when the page loads and the stage's scaleX and scaleY are set to .2 using a tween. I thought all elements of the stage should scale evenly with it, since they are its children, so am a bit lost.
Any tips on how I can to make the whole page scale uniformly during a tween :?

# Answer
You haven't shown any code, so I don't know for sure but I think your sprites have an origin that lies in the middle of it.

Here is how the actual sprite is created in model space:

As you can see we have 4 vertices at each corner. This makes our quad and we texture map it with the sprite we want. The important thing to note here is that the origin is in the center of the quad.

What does this mean? If you've done a bit of 3D programming you'll know that any rotation , scale or translation will be done to the center of the quad. So, if we rotate, we'll rotate about the middle, and if we scale, we'll scale inwards.

The vector ( -1, -1 ) scaled by 0.2 will result in the vector ( -0.2, -0.2 ). The quad becomes smaller from all directions.

You may have been expecting the opposite:

As you can see, the origin is now in the top left corner, this means every thing scales towards that. So, if you scale the vector ( 1, 1 ) by 0.2 we get ( 0.2, 0.2 ), and if we scale the vector ( 0, 0 ) by 0.2, we still get ( 0, 0 ). This was everything will stay together. However, the map will still, as a whole, scale towards the top left corner.

The answer here is really just perform the correct translations after the scale. Once something is scaled to the center, you'll want to translate it by half the new size towards the center of the entire map.
> 1 votes

---
Tags: tiles, tilemap, platformer, tweening
---


# Question
Title: Having issues with pong physics, is my approach wrong?
I've been working on a pong clone, i've made games in the past but they have all been very hacky. This time I was trying to go for a better approach in terms of using OOP or patterns. So far the games not posed many issues, I am however having problems thinking about the collision system and ball physics. In my main loop the collision code is as follows:

```
if (ball->Y < 0)
{
    ball->direction = -ball->direction;

    if (ball->ballSpeed < 700)
    {
        ball->ballSpeed += 25;
    }
}

if ((ball->X + ball->width > player2->X)
    && (ball->X + ball->velocityX) + (ball->width) < player2->X + player2->width
    && (ball->Y + ball->velocityY) + (ball->height) > player2->Y
    && (ball->Y + ball->velocityY) + (ball->height) < player2->Y + player2->height)
{
    ball->direction -= 70;

    if (ball->ballSpeed < 700)
    {
        ball->ballSpeed += 25;
    }
}

if ((ball->X + ball->width) > player1->X
    && (ball->X + ball->velocityX) + (ball->width) < player1->X + player1->width
    && (ball->Y + ball->velocityY) + (ball->height) > player1->Y
    && (ball->Y + ball->velocityY) + (ball->height) < player1->Y + player1->height)
{
    ball->direction += 70;
    if (ball->ballSpeed < 700)
    {
        ball->ballSpeed += 25;
    }
}

```

The program checks the points of the objects rect's to see if they have passed any of the paddles and then applies changes to the balls public variables. Here is the ball update code:

```
if(move)
{
velocityX = int(cos((direction + 0.0) * M_PI / 180.0) * (ballSpeed *deltaTime));
velocityY = int(sin((direction + 0.0) * M_PI / 180.0) * (ballSpeed *deltaTime));

    rect.x += velocityX;
    rect.y += velocityY;
}

X = rect.x;
Y = rect.y;
width = rect.w;
height = rect.h;

```

This PARTIALLY works however the ball goes in weird directions sometimes, on top of that the ball can actually go through the bottom portion of the paddle (it seems that from the bottom of the paddle, there is a gap the ball can exactly fit through). Really the physics of the ball just seem weird and not fluid at all. I'm not brilliant at maths so I don't really know of any other way to go about this. Help would be greatly appreciated.

# Answer
> 1 votes
I think your code has two problems: **incorrect X-coordinate bounces**, and **tunneling**.

First the X-coordinate bounces. This code:

```
if (...)
{
    ball->direction -= 70;

    ...
}

```

is trying to reflect the ball in the opposite X-direction (I think), but all it's going to do is rotate the velocity by a fixed angle. You could fix that by doing the proper arithmetic, but I encourage you to try reimplementing this using **vector math** instead of using angles. This makes axis-aligned bounces much simpler.

Bouncing:

```
if (ball->Y < 0)
{
    // ball->direction = -ball->direction;
    ball->velocityY *= -1;
}

if (/* X-coordinate bounces*/)
{
    // ball->direction += 70;
    ball->velocityX *= -1;
}

```

Motion:

```
if(move)
{
    // velocityX = int(cos((direction + 0.0) * M_PI / 180.0) * (ballSpeed *deltaTime));
    // velocityY = int(sin((direction + 0.0) * M_PI / 180.0) * (ballSpeed *deltaTime));

    // rect.x += velocityX;
    // rect.y += velocityY;
    rect.x += velocityX * ballSpeed*deltaTime;
    rect.y += velocityY * ballSpeed*deltaTime;
}

```

As for tunneling, I won't cover too much because it can be a huge topic, with solutions ranging from small hacks (such as small increments, or slowing things down) to complex robust algorithms (search for swept volume). Without seeing your game in action it's hard to say what you can get away with.

---
Tags: collision-detection, physics, sdl
---


title: SlimDX and Parsing .X Files

text:
# Question
Title: SlimDX and Parsing .X Files
I'm trying to parse a .x file using SlimDX. I can create the XFile object and register templates but I'm having problems with the enumeration object. The enumeration object has a child count of 0 for a file I know to have valid data. Here is code to create file, enumeration, and data objects:

```
public void Parse(string filename, string templates, ref Frame aParam)
        {
            XFile xfile = null;
            XFileEnumerationObject enumObj = null;
            XFileData dataObj = null;

            // create file object
            xfile = new XFile();

            // register templates
            if (xfile.RegisterTemplates(XFile.DefaultTemplates).IsFailure)
            {
                Console.WriteLine(Result.Last);
                xfile.Dispose();
                return;
            }

            // create enumeration object
            enumObj = xfile.CreateEnumerationObject(filename, System.Runtime.InteropServices.CharSet.Auto);
            if (enumObj == null)
            {
                xfile.Dispose();
                return;
            }

            // get child count( returns 0 here )
            long ncElements = enumObj.ChildCount;

            for (int i = 0; i < ncElements; ++i)
            {
                // never reached...
                dataObj = enumObj.GetChild(i);
                if (dataObj.IsReference) continue;

                try { Parse(dataObj, ref aParam); }
                catch (Exception e) { e.Write(); }
                finally { dataObj.Dispose(); }
            }

            enumObj.Dispose();
            xfile.Dispose();
        }

```

...There are no exceptions thrown by this function...the child count is 0 so the conditional loop breaks right away, the file objects are disposed of and the function returns...

Here is .x file...a simple cube:

```
xof 0303txt 0032

Frame Root {
  FrameTransformMatrix {
     1.000000, 0.000000, 0.000000, 0.000000,
     0.000000, 1.000000, 0.000000, 0.000000,
     0.000000, 0.000000, 1.000000, 0.000000,
     0.000000, 0.000000, 0.000000, 1.000000;;
  }
  Frame Cube {
    FrameTransformMatrix {
       1.000000, 0.000000, 0.000000, 0.000000,
       0.000000, 1.000000, 0.000000, 0.000000,
       0.000000, 0.000000, 1.000000, 0.000000,
       0.000000, 0.000000, 0.000000, 1.000000;;
    }
    Mesh Cube{ //Cube Mesh
      36;
      -1.000000; 1.000000; 1.000000;,
      -1.000000;-1.000000; 1.000000;,
       0.999999;-1.000001; 1.000000;,
      -1.000000;-1.000000;-1.000000;,
       1.000000;-1.000000;-1.000000;,
       0.999999;-1.000001; 1.000000;,
       1.000000; 0.999999; 1.000000;,
      -1.000000; 1.000000; 1.000000;,
       0.999999;-1.000001; 1.000000;,
      -1.000000; 1.000000;-1.000000;,
      -1.000000;-1.000000;-1.000000;,
      -1.000000; 1.000000; 1.000000;,
      -1.000000; 1.000000; 1.000000;,
       1.000000; 0.999999; 1.000000;,
       1.000000; 1.000000;-1.000000;,
       1.000000; 0.999999; 1.000000;,
       0.999999;-1.000001; 1.000000;,
       1.000000;-1.000000;-1.000000;,
      -1.000000;-1.000000;-1.000000;,
      -1.000000;-1.000000; 1.000000;,
      -1.000000; 1.000000; 1.000000;,
       1.000000; 1.000000;-1.000000;,
       1.000000;-1.000000;-1.000000;,
      -1.000000; 1.000000;-1.000000;,
       1.000000; 1.000000;-1.000000;,
       1.000000; 0.999999; 1.000000;,
       1.000000;-1.000000;-1.000000;,
      -1.000000; 1.000000;-1.000000;,
      -1.000000; 1.000000; 1.000000;,
       1.000000; 1.000000;-1.000000;,
      -1.000000;-1.000000; 1.000000;,
      -1.000000;-1.000000;-1.000000;,
       0.999999;-1.000001; 1.000000;,
       1.000000;-1.000000;-1.000000;,
      -1.000000;-1.000000;-1.000000;,
      -1.000000; 1.000000;-1.000000;;
      12;
      3;0;1;2;,
      3;3;4;5;,
      3;6;7;8;,
      3;9;10;11;,
      3;12;13;14;,
      3;15;16;17;,
      3;18;19;20;,
      3;21;22;23;,
      3;24;25;26;,
      3;27;28;29;,
      3;30;31;32;,
      3;33;34;35;;
      MeshNormals { //Mesh Normals
        36;
         0.000000;-0.000000; 1.000000;,
         0.000000;-0.000000; 1.000000;,
         0.000000;-0.000000; 1.000000;,
        -0.000000;-1.000000;-0.000000;,
        -0.000000;-1.000000;-0.000000;,
        -0.000000;-1.000000;-0.000000;,
        -0.000000;-0.000000; 1.000000;,
        -0.000000;-0.000000; 1.000000;,
        -0.000000;-0.000000; 1.000000;,
        -1.000000; 0.000000;-0.000000;,
        -1.000000; 0.000000;-0.000000;,
        -1.000000; 0.000000;-0.000000;,
         0.000000; 1.000000; 0.000000;,
         0.000000; 1.000000; 0.000000;,
         0.000000; 1.000000; 0.000000;,
         1.000000;-0.000001; 0.000000;,
         1.000000;-0.000001; 0.000000;,
         1.000000;-0.000001; 0.000000;,
        -1.000000; 0.000000;-0.000000;,
        -1.000000; 0.000000;-0.000000;,
        -1.000000; 0.000000;-0.000000;,
         0.000000; 0.000000;-1.000000;,
         0.000000; 0.000000;-1.000000;,
         0.000000; 0.000000;-1.000000;,
         1.000000; 0.000000;-0.000000;,
         1.000000; 0.000000;-0.000000;,
         1.000000; 0.000000;-0.000000;,
         0.000000; 1.000000; 0.000000;,
         0.000000; 1.000000; 0.000000;,
         0.000000; 1.000000; 0.000000;,
        -0.000000;-1.000000; 0.000000;,
        -0.000000;-1.000000; 0.000000;,
        -0.000000;-1.000000; 0.000000;,
         0.000000;-0.000000;-1.000000;,
         0.000000;-0.000000;-1.000000;,
         0.000000;-0.000000;-1.000000;;
        12;
        3;0;1;2;,
        3;3;4;5;,
        3;6;7;8;,
        3;9;10;11;,
        3;12;13;14;,
        3;15;16;17;,
        3;18;19;20;,
        3;21;22;23;,
        3;24;25;26;,
        3;27;28;29;,
        3;30;31;32;,
        3;33;34;35;;
      } //End of Mesh Normals
      MeshMaterialList { //Mesh Material List
        1;
        12;
        0,
        0,
        0,
        0,
        0,
        0,
        0,
        0,
        0,
        0,
        0,
        0;;
        Material Material {
           0.640000; 0.640000; 0.640000; 1.000000;;
           96.078431;
           0.500000; 0.500000; 0.500000;;
           0.000000; 0.000000; 0.000000;;
           TextureFilename {"Yellow.jpg";}
        }
      } //End of Mesh Material List
      MeshTextureCoords UVMap{ //Mesh UV Coordinates
        36;
         0.000000; 1.000000;,
         1.000000; 1.000000;,
         1.000000; 0.000000;,
         0.000000; 1.000000;,
         1.000000; 1.000000;,
         1.000000; 0.000000;,
         0.000000; 0.000000;,
         0.000000; 1.000000;,
         1.000000; 0.000000;,
         0.000000; 1.000000;,
         1.000000; 1.000000;,
         0.000000; 0.000000;,
         0.000000; 1.000000;,
         1.000000; 1.000000;,
         1.000000; 0.000000;,
         0.000000; 1.000000;,
         1.000000; 1.000000;,
         1.000000; 0.000000;,
         1.000000; 1.000000;,
         1.000000; 0.000000;,
         0.000000; 0.000000;,
         0.000000; 0.000000;,
         0.000000; 1.000000;,
         1.000000; 0.000000;,
         0.000000; 0.000000;,
         0.000000; 1.000000;,
         1.000000; 0.000000;,
         0.000000; 0.000000;,
         0.000000; 1.000000;,
         1.000000; 0.000000;,
         0.000000; 0.000000;,
         0.000000; 1.000000;,
         1.000000; 0.000000;,
         0.000000; 1.000000;,
         1.000000; 1.000000;,
         1.000000; 0.000000;;
      } //End of Mesh UV Coordinates
    } //End of Mesh Mesh
  } //End of Cube
} //End of Root Frame

```

# Answer
Ok figured out the problem...The template strings in the XFile object do not include the standard templates(eg. Frame, Mesh, MeshMaterial, MeshNormals...etc). In order to register those templates you must save the following templates into a text file, load the text file at runtime using FileStream, and register the file in memory ... Here is text file with standard templates...be sure not to use any extra newline characters:

```
xof 0303txt 0032
template Frame {
<3d82ab46-62da-11cf-ab39-0020af71e433>
[...]
}
template Matrix4x4 {
<f6f23f45-7686-11cf-8f52-0040333594a3>
array FLOAT matrix[16];
}
template FrameTransformMatrix {
<f6f23f41-7686-11cf-8f52-0040333594a3>
Matrix4x4 frameMatrix;
}
template Vector {
<3d82ab5e-62da-11cf-ab39-0020af71e433>
FLOAT x;
FLOAT y;
FLOAT z;
}
template MeshFace {
<3d82ab5f-62da-11cf-ab39-0020af71e433>
DWORD nFaceVertexIndices;
array DWORD faceVertexIndices[nFaceVertexIndices];
}
template Mesh {
<3d82ab44-62da-11cf-ab39-0020af71e433>
DWORD nVertices;
array Vector vertices[nVertices];
DWORD nFaces;
array MeshFace faces[nFaces];
[...]
}
template MeshNormals {
<f6f23f43-7686-11cf-8f52-0040333594a3>
DWORD nNormals;
array Vector normals[nNormals];
DWORD nFaceNormals;
array MeshFace faceNormals[nFaceNormals];
}
template Coords2d {
<f6f23f44-7686-11cf-8f52-0040333594a3>
FLOAT u;
FLOAT v;
}
template MeshTextureCoords {
<f6f23f40-7686-11cf-8f52-0040333594a3>
DWORD nTextureCoords;
array Coords2d textureCoords[nTextureCoords];
}
template ColorRGBA {
<35ff44e0-6c7c-11cf-8f52-0040333594a3>
FLOAT red;
FLOAT green;
FLOAT blue;
FLOAT alpha;
}
template ColorRGB {
<d3e16e81-7835-11cf-8f52-0040333594a3>
FLOAT red;
FLOAT green;
FLOAT blue;
}
template Material {
<3d82ab4d-62da-11cf-ab39-0020af71e433>
ColorRGBA faceColor;
FLOAT power;
ColorRGB specularColor;
ColorRGB emissiveColor;
[...]
}
template MeshMaterialList {
<f6f23f42-7686-11cf-8f52-0040333594a3>
DWORD nMaterials;
DWORD nFaceIndexes;
array DWORD faceIndexes[nFaceIndexes];
[Material <3d82ab4d-62da-11cf-ab39-0020af71e433>]
}
template TextureFilename {
<a42790e1-7810-11cf-8f52-0040333594a3>
STRING filename;
}
template VertexDuplicationIndices {
<b8d65549-d7c9-4995-89cf-53a9a8b031e3>
DWORD nIndices;
DWORD nOriginalVertices;
array DWORD indices[nIndices];
}

```

You can add skin templates and any others just be cautious of newline characters...

Here is updated code:

```
public void Parse(string filename, string templates, ref Frame aParam)
        {
            XFile xfile = null;
            XFileEnumerationObject enumObj = null;
            XFileData dataObj = null;

            try
            {
                byte[] temp = null;
                using (FileStream fs = new FileStream(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
                    + @"\DXTemplates.txt", FileMode.Open, FileAccess.Read))
                {
                    temp = new byte[fs.Length];
                    fs.Read(temp, 0, (int)fs.Length);
                }

                // create file object
                xfile = new XFile();

                // Register the templates from the text file
                xfile.RegisterTemplates(temp);

                // create enumeration object
                enumObj = xfile.CreateEnumerationObject(filename, System.Runtime.InteropServices.CharSet.Auto);

                // get child count( returns 1 here now )
                long ncElements = enumObj.ChildCount;

                for (int i = 0; i < ncElements; ++i)
                {
                    // never reached...
                    dataObj = enumObj.GetChild(i);
                    if (dataObj.IsReference) continue;

                    try { Parse(dataObj, ref aParam); }
                    catch (Exception e) { Console.WriteLine(e.ToString()); }
                    finally { dataObj.Dispose(); }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            finally
            {
                if(enumObj != null)enumObj.Dispose();
                if(xfile != null)xfile.Dispose();
            }
        }

```
> 1 votes

---
Tags: c#, directx9, slimdx
---


title: Animations / OpenGL (ES 2) in game menu

text:
# Question
Title: Animations / OpenGL (ES 2) in game menu
(I am specifically asking for Android)

If you look at Angry Birds (and in fact many other games), you can already see a lot of animations & effects going in the main menu and in other places even before starting to play. I assume they are done with OpenGL, more precisely a `FrameLayout` is used and inside it a `GLSurfaceView` is somewhere at the bottom of the hierarchy; above the `GLSurfaceView` you have regular Android buttons and texts.

Is this how it's done\*? Also would you reuse the same `GLSurfaceView` when running the actual game or should another one be created?

\*I am aware an alternative approach would be to make absolutely everything in OpenGL. Of these two I prefer the `FrameLayout` one, but I don't know whether other developers agree.

# Answer
The UI animations for games like Angry Birds is almost always done manually, i.e. not using platform specific elements. The reason of course being that the game will be released on multiple platforms. Using platform specific code will require rewriting it for each target platform, and even then there may be slight differences in how the end result looks and behaves.
> 1 votes

---
Tags: android
---


# Question
Title: Can I make a "fan game" with characters of one game that already exists?
(I'm sorry about my english, I'm from Chile)

Hi! I'm making a game based on Alone In The Dark, and the history would happen before the events on the game of PS1. However, I would like to make a game with the character Aline, but with 10 years old. The game mechanism would be the same, and the name of a lot of characters and places. I don't really want to make any money, I just want to make a good game, I love the AiTD game. Can I do that or I can be on jail because of that? Thanks!

# Answer
Well, I would not do/start this project before contacting the original copyright owner and ask them for permission. Often big studios/publisher hold the copyrights for whole franchines, sell them or keep them in "stock" to respin a series a bunch of years later.

Don't understand me wrong, I am no lawyer, but in my country this would not be allowed. I don't know if there are any laws in your country (perhaps non-profit laws, educational purpose laws) which give you the freedom to do that. Maybe if you declare it as a "parody", you may have luck to do this legally.
> 0 votes

# Answer
There are a lot of examples of games where famous characters are used. You can see many adult oriented games with characters like Princess Peach from SMB for instance. While in theory there should be no risk involved, things will probably get out hand if you try to sell this game or advertise it well enough that some companies would feel obliged to protect their copy rights. The general rule is that if you are "small" and "unprofitable" then companies leave you alone. I can only prove this by example and this is not legal advice. If you don't wish to sell this game for profit I doubt that I would worry. You can always rename the characters and say "the game is inspired by" xyz.
> 0 votes

---
Tags: character, copyright
---


# Question
Title: Conditionally use java or android classes
I'm using bezier curves in my libgdx project. I was testing the desktop version using java.awt.geom with GeneralPath but when I went to test on android, it raised an error saying that I can't import java.awt. Android have corresponding classes for GeneralPath, Point2D etc so my question is how can I use those classes in their respectives environments?

# Answer
> 2 votes
Make use of the Abstract Factory pattern and instantiate according to the current context. Provide separate implementations of your logic in the Desktop and Android projects respectively and provide instantiation in your core project.

A brief example of this approach would be (it turned out to be rather extensive in the end):

Since your core project does not have access to the code in the Desktop or Android projects (this dependency points in the opposite direction), you would have to pass something as parameter to your `Game` constructor. (that will be then passed in as parameter to the `LwjglApplication` constructor on Desktop and to the `initialize()` method on Android.) For example, your initializers would like like this:

```
new LwjglApplication(new MyGame(new DesktopFactoriesCollection()), cfg);

```

on Desktop, and

```
initialize(new MyGame(new AndroidFactoriesCollection()), cfg);

```

on Android,
where `DesktopFactoriesCollection` and `AndroidFactoriesCollection` are concrete implementations of a collection of various factories you may need for different purposes (including that of running different code for your bezier curves logic on different platforms), when it comes to providing code specific to the platform you're expecting it to run on.

So, in fact, the `MyGame` constructor looks like this:

```
public MyGame(AbstractFactoriesCollection afs, Object...params) {
   // some init code
   afs.init();
   // some other init code
}

```

where `Object...params` is anything else you might need to provide here.

Each of the concrete implementations of the `AbstractFactoriesCollection` specified above implements a `init()` method, where it instantiates all the factories used in your project. Example of such an implementation:

```
public class AndroidFactoriesCollection extends AbstractFactoriesCollection {
   @Override
   public void init() {
      bezierCurvesLogicFactory = new AndroidBezierCurvesLogicFactory();
   }
}

```

where `bezierCurvesLogicFactory` is a protected field of the `BezierCurvesLogicFactory` type in the AbstractFactoriesCollection class.
Do the same for the Desktop project.

So, you should now have two new classes: one in the Desktop project, and the other one in the Android project respectively: `DesktopBezierCurvesLogicFactory` and `AndroidBezierCurvesLogicFactory`. Since the `bezierCurvesLogicFactory` object is of `BezierCurvesLogicFactory` type, this means you should have an abstract factory class for your bezier curves logic in the core project.

The `BezierCurvesLogicFactory` abstract factory class should have an abstract method `buildBezierLogic()` or something, that both of its concrete implementations should implement, and each of them should return that logic implementation that is found on the given platform:

```
public abstract class BezierCurvesLogicFactory {
   public abstract BezierCurvesLogic buildBezierLogic();
}

```

Furthermore, have an abstract class in the core project, for the bezier curves logic implementation itself. Put platform specific code for each implementation in the Dekstop and Android projects respectively. For example:

```
public abstract class BezierCurvesLogic {
}

public class AndroidBezierCurvesLogic extends AbstractBezierCurvesLogic {
}

public class DesktopBezierCurvesLogic extends AbstractBezierCurvesLogic {
}

```

where `AndroidBezierCurvesLogic` is placed under the Android project and `DesktopBezierCurvesLogic` is placed under the Desktop project, respectively.

And ultimately, in your code in your core project, when you are instantiating the bezier curves logic, do this:

```
final BezierCurvesLogic logic = game.afs.bezierCurvesLogicFactory.buildBezierLogic();

```

you can store the `afs` (the `AbstractFactoriesCollection` object) as a public field in your `MyGame` class.

And that's it.

This is a lot of information, I was even thinking of writing an article on implementing the Abstract Factory pattern with libGDX on diifferent platforms :)

I hope this helps. If there is any confusion caused by anything written above, please let me know and I will try to clear that up.

Good luck!

# Answer
> 0 votes
I suggest copying the source code from either the appropriate Android classes or from `java.awt` (OpenJDK) to your project.

---
Tags: libgdx
---


# Question
Title: Mapping a 3D texture to a standard hollow-hull 3D model
I have 3D models which are typical hollow hulls. If such a model also had a 3D volumetric/voxel texture map then given a point `P` inside such a model, I'd like to be able to find its `uvw` coordinates within the 3D texture.

Is this possible by simply setting 3D texcoords on my existing mesh or does it *have* to be broken up into polyhedra? Is there a way to map a 3D texture onto a mesh without doing this?

# Answer
All you have to do is to normalize the model-coordinates on your mesh to the range textures use which is \[0~1\] from top left to bottom right in DirectX or from bottom left to top right in OpenGL. You can store these texture coordinates in your mesh as attributes which you can set up to be accessed in the vertex shader. Then simply pass these texture coordinates to the pixel/fragment shader (using some form of interpolation).

Then you can simply use the normalized XYZ coordinates of the point on the mesh as UVW coordinates in your 3D-Texture.
> 1 votes

---
Tags: 3d, textures, 3d-meshes, voxels
---


title: Directx9, FBX sdk and indices problem

text:
# Question
Title: Directx9, FBX sdk and indices problem
So I've set up my program, know how to get everything going except for one thing: indices. I've been stumped as to how I retrieve that set of data. Does anyone know what I function I need to get them? Thanks in advance!

# Answer
Assuming you're using the latest fbx sdk, read:

http://www.gamedev.net/page/resources/\_/technical/graphics-programming-and-theory/how-to-work-with-fbx-sdk-r3582

Fundamentally, the FBX sdk stores vertex and index data in a way that is not conducive for rendering api requirements in order save on repeated data. We have to construct the vertices themselves. To do this, for each vertex, retrieve the indices (mentioned in the above link), and construct your own 'vertex reference' structure, then store them in an array, and add an index to your index buffer. But before you do that, check to see if past vertices have any duplicated vertices (by comparing indices of the 'vertex reference' structure), in which case, use that index instead.
> 0 votes

# Answer
If the data has no indices, you can simply feed linear list if your rendering API requires them.

I.e,

```
int *indices = new int[max_vertex_count];
int i;
for (i = 0; i < max_vertex_count; i++)
    indices[i] = i;

```
> 0 votes

---
Tags: c++, directx, directx9, fbx
---


# Question
Title: Is it possible to mod a game to use a scripting language like Lua?
So my questions are:

1. Is it possible to mod a game to use a scripting language?
2. How would I go about doing so?

I really like Arma 2 but like many games it does not have much in terms of capabilities beyond using server commands in scripts. That makes it pretty limited.

Personally I would like to add the ability to use a different language than Arma 2's scripting language; possibly Lua.

How could I make Arma 2 use Lua? Is there a way?

I remember from when I just a teenager and into modding Halo PC some people had created scripting mods for that game. How did they do that? I hope this question isn't too general or difficult to answer.

# Answer
> 7 votes
It depends on what kind of modding the game allows.

When the game in question already includes a sufficiently powerful script interpreter, one could write a transcompiler which takes a script written in Lua and transforms it into a program in the scripting language of the game so that it can be executed. Alternatively, one could even create a Lua interpreter in that scripting language directly when the language is powerful enough to do so. But seriously, when the scripting language is already that powerful, I would recommend to just learn that language instead, because this approach will not enable you to do anything not already possible with the existing language.

When the game is modded via plugins in form of dynamically linked libraries (DLLs), one could write such a library which includes a Lua interpreter and exposes the whole API of the original engine to that interpreter.

When the game has no modding support at all, you would need to create some through hacking the binary code of the game executable. This is a very hard and tedious way of doing software development, so when you are determined to create a very ambitioned mod for a game which isn't meant to be modded, it would not be a bad idea to start with paving a way to get stuff done in a more high-level language like Lua so you can work more productively. This could take the form of jumping into a Lua interpreter while also exposing all kinds of interesting functions of the game to that interpreter so it can call them.

Usually mod-friendliness is a complex design requirement you need to take into account during the whole development process of a game. Adding it later as an afterthought is often difficult, and even moreso when you don't have access to the original sourcecode. It might in fact be easier to create a clone of the game from scratch.

---
Tags: scripting, modding, arma2
---


# Question
Title: Text contains characters that cannot be resolved by this SpriteFont
I'm trying to draw currency symbols in an Arial Spritefont. According to this site, the font contains these symbols. I've included the Unicode character region for these symbols in the Content Processor SpriteFont file, like so:

```
<CharacterRegions>
  <CharacterRegion>
    <Start> </Start>
    <End>~</End>
  </CharacterRegion>
  <CharacterRegion>
    <!-- Currency symbols -->
    <Start>₠</Start>
    <End>₺</End>
  </CharacterRegion>
</CharacterRegions>

```

However, whenever I try to draw a € (Euro) symbol, I get this exception:

> Text contains characters that cannot be resolved by this SpriteFont

Inspecting the SpriteFont in the IDE at that breakpoint shows the € symbol is in there. I'm at a loss at what could be wrong. Why is this exception thrown?

# Answer
The best way to handle this is to take advantage of the characters collection `SpriteFont.Characters` and see if it contains the character. Any character that returns false will result in an error when rendered using the sprite font.

For example the below is what I use to filter out non usable characters from my textboxes.

```
if (!Font.Characters.Contains(character) && character != '\r' && character != '\n') { return; }

```
> 1 votes

# Answer
The problem wasn't in the € sign, but another char embedded in the string.

This char was added by the NSNumberformatter (I'm using Xamarin), which is A0 or 160. As my font only went from 32 through 126, and 8352 through 8378, this obviously wouldn't work.

As such, the following code solved the problem, and the string is properly drawn now.

`using System.Text;`

`if (priceString.Contains((char)160))
 {
 priceString = priceString.Replace(((char)160).ToString(), "");
 }`

The reason I thought the problem was in the € was because it would work for the $ sign - in truth, the formatter didn't add the non-breaking space in that currency format.
> 1 votes

---
Tags: xna, monogame, fonts
---


# Question
Title: How can I determine if the player holds the top leaderboard spot in Game Center?
I have integrated Game Center into my game and I want to make an achievement that is earned if the user holds the #1 spot on Game Center.

How do I access that information with code?

# Answer
You can do this with the `GKLeaderboard` API. As described in the documentation for recovering score data, you want to use the leaderboard object to represent a query to the Game Center service for leaderboard information, specifically setting the range to `[1, 1]` to return only the top score. This code would look something like this:

```
GKLeaderboard * request = [[GKLeaderboard alloc] init];
request.range = NSMakeRange(1, 1);
[request loadScoresWithCompletionHandler:^(NSArray * scores, NSError * error) {
   // Handle the error or process the scores.
}];

```

The `scores` array contains `GKScore` objects, which have a player ID field you can use to compare against the current player's ID to determine if they are the player holding the top score or not.
> 1 votes

---
Tags: game-center
---


# Question
Title: How can I animate a portion of the textures on a model?
I have a model to which I have attached multiple textures. Both textures are currently static, but if I want to move (or slide) the texture which is on the top (in UV space), is that possible?

Maybe by moving the texture coordinates or something?

# Answer
> Maybe by moving the texture coordinates or something?

Yes, the simplest way to do this is to animate the texture coordinates of the relevant geometry over time. You could either:

* Create a shader uniform variable representing "time," which you periodically update before rendering, and use to offset the texture coordinate U or V component (as desired) prior to sampling the texture. This approach implies any geometry rendered with this shader will have the animating texture, and so you'll need to render your object in two passes (one containing the geometry with fixed textures, the other containing the geometry with animated textures).
* Update the texture coordinates of the affected portion of the geometry directly on the CPU (using a similar time-based offset as above, just on the CPU). This avoids the need to render the object in two passes, but it also means you are constantly updating the vertex buffer data, which is potentially performance-intensive depending on your buffer creation options and how you need to use the rest of the buffer.
> 3 votes

---
Tags: opengl, textures, glsl
---


# Question
Title: Text not being rendered until I recreate the text class in SDL
I made a Text class, it is as shown below:

```
Text::Text(const int score, const float &x, const float &y, const float &w, const float &h, SDL_Renderer *rend)
{
    font = TTF_OpenFont("font/Subway.ttf", 50);
    if (font == NULL)
    {
        std::cout << "Something went wrong\n%s\n" << TTF_GetError();
    }

    rect = { x, y, w, h };
    color = { 100, 100, 100 };

    tempSurface = TTF_RenderGlyph_Blended(font, *std::to_string(score).c_str(), color);
    tex = SDL_CreateTextureFromSurface(rend, tempSurface);

    SDL_FreeSurface(tempSurface);
}

void Text::draw(SDL_Renderer *rend)
{
    SDL_RenderCopy(rend, tex, NULL, &rect);
}

Text::~Text()
{
    //Clean up stuff
    font = nullptr;
    tempSurface = nullptr;
    SDL_DestroyTexture(tex);
    tex = nullptr;
}

```

I created two of these class objects to hold the image that is created from the players score variables. Issue is that the first time these objects are created, they are not shown on the screen. It's only when the objects are created again that they are shown.

In gameloops constructor class:

```
GameLoop::GameLoop()
{
    window = new Window("Pong Test", 640, 480, SDL_WINDOW_SHOWN);
    player1 = new Paddle(50, 50, 10, 60);
    player2 = new Paddle(580,50,10,60);

    player1ScoreText = new Text(player1Score, SCREEN_WIDTH * .25 - 50 / 2, SCREEN_HEIGHT * .25, 50, 75, r);
    player2ScoreText = new Text(player2Score, SCREEN_WIDTH * .75 - 50 / 2, SCREEN_HEIGHT * .25, 50, 75, r);

    ren = new Renderer((*window).GetWindow(), -1, SDL_RENDERER_ACCELERATED);

    r = (*ren).getRenderer();

    ball = new Ball("ball.bmp", r);
}

```

It's created then its rendered here:

```
void GameLoop::Render()
{
    ren->setColor(0, 0, 0, 0);
    ren->clear();
    player1->Draw(r,255,255,255,255);
    player2->Draw(r,255,255,255,255);
    player1ScoreText->draw(r);
    player2ScoreText->draw(r);
    ball->draw(r,255,255,255);

    ren->present();
}

```

It's not showing.. not until this happens:

```
void GameLoop::Score()
{
    delete ball;

    player1ScoreText = new Text(player1Score, SCREEN_WIDTH * .25 - 50 / 2, SCREEN_HEIGHT * .25, 50, 75, r);
    player2ScoreText = new Text(player2Score, SCREEN_WIDTH * .75 - 50 / 2, SCREEN_HEIGHT * .25, 50, 75, r);

    ball = new Ball("ball.bmp", r);
}

```

From what I can see it doesn't matter where you recreate the classes, it will work. Is this due to how the classes are being initialised?

My first thought is that it would be this line:

```
tempSurface = TTF_RenderGlyph_Blended(font, *std::to_string(score).c_str(), color);

```

due to the fact I pass in a pointer to converted integer. However if I don't pass in a pointer I get this error:

error C2664: 'SDL\_Surface \*TTF\_RenderGlyph\_Blended(TTF\_Font \*,Uint16,SDL\_Color)' : cannot convert argument 2 from 'const char \*' to 'Uint16'

Any help would be greatly appreciated.

# Answer
> 0 votes
This type of issue is best left to debugging, but I'll take a shot.

My concern is these lines:

```
player1ScoreText = new Text(player1Score, SCREEN_WIDTH * .25 - 50 / 2, SCREEN_HEIGHT * .25, 50, 75, r);
player2ScoreText = new Text(player2Score, SCREEN_WIDTH * .75 - 50 / 2, SCREEN_HEIGHT * .25, 50, 75, r);

```

Now if you look, we are dependent on the following variables:

* player1Score (and player2Score), which my guess is a simple int - no need to worry.
* SCREEN\_WIDTH and SCREEN\_HEIGHT, which my guess is a const - no need to worry.
* r - which is your renderer. Now tell me, at the time you are initializing the player1ScoreText and player2ScoreText, what is r?

Here's my corrected code:

```
GameLoop::GameLoop()
{
    window = new Window("Pong Test", 640, 480, SDL_WINDOW_SHOWN);
    ren = new Renderer((*window).GetWindow(), -1, SDL_RENDERER_ACCELERATED);
    r = (*ren).getRenderer();

    player1 = new Paddle(50, 50, 10, 60);
    player2 = new Paddle(580,50,10,60);

    player1ScoreText = new Text(player1Score, SCREEN_WIDTH * .25 - 50 / 2, SCREEN_HEIGHT * .25, 50, 75, r);
    player2ScoreText = new Text(player2Score, SCREEN_WIDTH * .75 - 50 / 2, SCREEN_HEIGHT * .25, 50, 75, r);

    ball = new Ball("ball.bmp", r);
}

```

---
Tags: rendering, sdl, text
---


# Question
Title: Is this technique for stat tracking without a database workable?
If I wanted to create a chess game, for iOS, that tracked both player moves (for retracing the progression of a game and for player stats), what would be the simplest route to take?

To clarify, I want to track not only the moves a player has made in a particular game, but how often that player has made that move in past games. For example I want to be able to track:

* How many times a given player has opened by moving the king pawn up two squares (e4) as white, on move number one.
* What is the percentage of time the player responds to white's e4 opening move, with moving his own king pawn to e5?
* What percentage of time does he respond by moving his queenside bishop pawn to c5?

And so on. If it's not clear, the stat tracking system should also be able to report how many times this player, as black, move his queen to h1, on move number 30.

I'm using Parse.com for my back-end as a server (BaaS) service. If I were to create a class that

* writes strings that identify move number, player color, moved piece, algebraic notation of the square (e.g. "d8") to a file, locally in the file system
* saves the file to Parse, and deletes the temporary file from file system
* upon opening the same game in my tableview (a la a "With Friends" game), download this file from Parse, parse through it and retrieve all stats/history, assign all relevant values to variables

Is this plan viable, or is there an easier way?

# Answer
> 1 votes
You can certainly do all of this by simply storing the move list for a game in a text file. That would be the simplest way to *store* the data, but at the expense of forcing you to build all of the *query* mechanisms yourself.

Something more structured like an XML or JSON file will probably make querying slightly easier (since you are on iOS, you may want to consider the APIs for reading `.plist` files, which are effectively the same thing).

It's unclear to me what you are actually using Parse for; your description here makes it sound like it's just a file storage system that is redundant with local storage (do you want to also collect the stats for the opposing player in a peer-to-peer game?). A SQLite DB would serve your described needs just as well and avoid the latency involved with round-tripping this file over the network. If your aversion to using 'a database' stems from not wanting to have something like a SQL Server instance up and running to deal with this data, SQLite (perhaps via CoreData, which will then give you all the `NSPredicate`-based queries you probably want) is worth looking into.

But barring that, your described implementation using text files seems workable.

---
Tags: ios, databases, turn-based, filesystem
---


title: Using Box2d to model rotating turret

text:
# Question
Title: Using Box2d to model rotating turret
I would like to model a rotating "turret" on top of a tank-like object in 2D from the side view like pictured here:

tank with turret http://uofitorn.net/static/images/tankwithbox2dturret.png

Notice the faint outline of a gun protruding to the upper left courtesy of libgdx's debug renderer (the actual gun sprite is not being rendered).

How do I best implement this using Box2d? Should I use two bodies? If so, how? Or one body with two fixtures?

I tried using two bodies connected by a Revolute Joint, but the turret "gun" does not maintain a constant angle but instead rotates down until it is vertical and then just hangs there.

Or should I not model the turret aspect of the tank in box2d at all?

# Answer
The approach using two bodies connected with a revolute joint is the best approach. It just sounds like you have already tried this but encountered a bug.

The simplest way to implement the rotating-towards-the-cursor part is to find the angle of the vector connecting the pivot point and the cursor, and call `Body::setTransform` on the turret every cycle. Use the following pseudo code as a starting point:

```
// pivotOffset is the displacement vector pointing from the turret body origin to the pivot point
// get the world co-ordinates of the pivot point
vector turretPivot = turretBody.getWorldPoint(pivotOffset);

// get the world co-ordinates of the cursor position
vector cursorPos = libgdxgetCursorPositionFunction();

// get the displacement vector between the cursor and the turret pivot
vector displacement = cursorPos - turretPivot;

// set the angle of the turret body to the angle of the displacement vector
turretBody.setTransform(turretBody.getPosition(),displacement.getAngle());

```

Alternatively, look at my Simple Solution in this related answer to see how this would work with a prismatic joint.
> 1 votes

---
Tags: libgdx, box2d
---


# Question
Title: How can I rotate my picture using Pygame?
I want to make the Dragon on the picture rotate softly to the left when he flies to the left and rotate to the right when he flies to the right and up and down also.

How can I do that with the `W``A``S``D` keys? The Dragon can fly already up, down, lef, and right....but he doesn't turn...

My Code:

```
import pygame, sys
from pygame.locals import *

pygame.init()

size = width, height = 1600, 848
speed = [2, 2]
black = (0, 0, 0)

pygame.mouse.set_cursor(*pygame.cursors.broken_x)

screen = pygame.display.set_mode(size)
background = pygame.image.load("background.PNG")
dragon1 = pygame.image.load("dragon1.gif")
x,y=0,0
clock=pygame.time.Clock()
speed=250
movex, movey=0,0

while True:
screen.blit(background, (0,0))
screen.blit(dragon1, (x,y))

for event in pygame.event.get():
    if event.type == QUIT:
        pygame.quit()
        sys.exit()

if event.type==KEYDOWN:
        if event.key==K_a:
            movex=-4
        elif event.key==K_d:
            movex=+4
        elif event.key==K_w:
            movey=-4
        elif event.key==K_s:
            movey=+4
if event.type==KEYUP:
        if event.key==K_a:
            movex=0
        elif event.key==K_d:
            movex=0
        elif event.key==K_w:
            movey=0
        elif event.key==K_s:
            movey=0
x+=movex
y+=movey

pygame.display.flip()

```

# Answer
Use `pygame.transform.rotate` function:

```
    screen.blit(background, (0,0))
    angle = None
    if movex == 0 and movey < 0:
        angle = -180
    elif movex > 0 and movey >= 0:
        angle = 20
    elif movex < 0 and movey >= 0:
        angle = -20
    elif movex > 0 and movey < 0:
        angle = 160
    elif movex < 0 and movey < 0:
        angle = -160

    if angle:
        dragon = pygame.transform.rotate(dragon1, angle)
    else:
        dragon = dragon1

    screen.blit(dragon, (x,y))
    ...

```

You can always keep the original surface `dragon1` and transform it when you are going to blit it (like the example), or keep three variations pre-calculated and choose which one you want to blit.
> 3 votes

---
Tags: python, pygame
---


# Question
Title: MonoGame ArgumentNullException in Spritebatch.End()
I switched my Project from XNA 4 to MonoGame 2.5.1. The port went somewhat unproblematic but I am stumpled across a problem i can't resolve. For your interest, the code worked on XNA:

When I am drawing a spritebatch with a basicEffect I get an ArgumentNullException on calling the End() method. This is the simplified draw call

```
// polyEffTest is defined somewhere else, not in the draw function
polyEffTest = new PolygonBasicEffect(gd);

// the simplified draw call
sbTest.Begin(
  SpriteSortMode.BackToFront,
  BlendState.AlphaBlend,
  SamplerState.LinearClamp,
  DepthStencilState.Default,
  GraphicsDevice.RasterizerState,
  polyEffTest,
  Matrix.CreateTranslation(offX, offY, 0f)
);

// draw something [...]

sbTest.End() // <- End-call causes Exception

```

when I replace polyEffTest with NULL in sbTest.Begin I won't get the ArgumentNullException but nothing gets drawed either (obvious). So I guess it has to do something with the BasicEffect

Here is the stacktrace

```
>   at OpenTK.Graphics.ES11.GL.GetError () [0x00000] in <filename
> unknown>:0    at OpenTK.Graphics.ES11.ErrorHelper.ResetErrors ()
> [0x00000] in <filename unknown>:0    at
> OpenTK.Graphics.ES11.ErrorHelper..ctor (IGraphicsContext context)
> [0x00000] in <filename unknown>:0    at
> OpenTK.Graphics.ES11.GL.Viewport (Int32 x, Int32 y, Int32 width, Int32
> height) [0x00000] in <filename unknown>:0    at
> Microsoft.Xna.Framework.Graphics.GLStateManager.Viewport (Rectangle
> viewport) [0x00000] in <filename unknown>:0    at
> Microsoft.Xna.Framework.Graphics.BasicEffect.Apply () [0x00000] in
> <filename unknown>:0    at
> Microsoft.Xna.Framework.Graphics.SpriteBatch.End () [0x00000] in
> <filename unknown>:0    at RustyMoon.Game1.Draw
> (Microsoft.Xna.Framework.GameTime gameTime) [0x001b1] in
> /home/mereddyn/projects/c#/RMoonMono/RMoonMono/Game1.cs:306    at
> Microsoft.Xna.Framework.Game.DoDraw (Microsoft.Xna.Framework.GameTime
> gameTime) [0x00000] in <filename unknown>:0    at
> Microsoft.Xna.Framework.GameWindow.OnRenderFrame (System.Object
> sender, OpenTK.FrameEventArgs e) [0x00000] in <filename unknown>:0
> at OpenTK.GameWindow.OnRenderFrame (OpenTK.FrameEventArgs e) [0x00000]
> in <filename unknown>:0    at OpenTK.GameWindow.OnRenderFrameInternal
> (OpenTK.FrameEventArgs e) [0x00000] in <filename unknown>:0    at
> OpenTK.GameWindow.RaiseRenderFrame (System.Diagnostics.Stopwatch
> render_watch, System.Double& next_render, OpenTK.FrameEventArgs
> render_args) [0x00000] in <filename unknown>:0    at
> OpenTK.GameWindow.DispatchUpdateAndRenderFrame (System.Object sender,
> System.EventArgs e) [0x00000] in <filename unknown>:0    at
> OpenTK.GameWindow.Run (Double updates_per_second, Double
> frames_per_second) [0x00000] in <filename unknown>:0    at
> OpenTK.GameWindow.Run (Double updateRate) [0x00000] in <filename
> unknown>:0    at Microsoft.Xna.Framework.GameWindow.Run (Double
> updateRate) [0x00000] in <filename unknown>:0    at
> Microsoft.Xna.Framework.LinuxGamePlatform.RunLoop () [0x00000] in
> <filename unknown>:0    at Microsoft.Xna.Framework.Game.Run
> (GameRunBehavior runBehavior) [0x00000] in <filename unknown>:0    at
> Microsoft.Xna.Framework.Game.Run () [0x00000] in <filename unknown>:0
> at RustyMoon.Program.Main () [0x00010] in
> /home/mereddyn/projects/c#/RMoonMono/RMoonMono/Program.cs:20

```

I am using MonoGame 2.5.1 on Ubuntu 14.04 with MonoDevelop. The polyEffTest is defined like that:

```
public class PolygonBasicEffect : BasicEffect
{
    public PolygonBasicEffect(GraphicsDevice graphicsDevice)
        : base(graphicsDevice)
    {
        this.VertexColorEnabled = true;
        this.TextureEnabled = true;
        this.Projection = Matrix.CreateOrthographicOffCenter(
            0, graphicsDevice.Viewport.Width, graphicsDevice.Viewport.Height, 0, 0, 1
        );
    }

    public PolygonBasicEffect(BasicEffect effect)
        : base(effect)
    {
    }

    public BasicEffect Clone()
    {
        return new PolygonBasicEffect(this);
    }
}

```

Even if I am calling the End call imediatly after the Begin i get the Exception. I even get the exception if I am replacing polyEffTest with a new BasicEffect()

**Update**

I did some testing on a different machine. I downloaded the same Mono Version 2.5.1 and tried it on a Windows 7 System with Visual Studio. It works. I will try it with a different linux machine the end of the day. In addition, I stumpled across something. I guess there is an issue with unsafe code within MonoDevelop on my main system. But I can't tell you anything until tomorrow.

# Answer
> 0 votes
I got it to work. I updated all Versions and build the Assembly from Source and invoked the DLLs. Now it works as expected.

---
Tags: c#, monogame
---


# Question
Title: How many views can be bound to a 2D texture at a time?
I am a newbie trying to learn on DX11.x. While reading about resources and views in MSDN, I thought this question For a given 2D Texture created with `ID3D11Texture2D`interface (or for that matter any kind of resource), how many of following views can be bound to it?

1) DepthStencilView
2) RenderTargetView
3) ShaderResourceView
4) UnorderedAccessView

Thanks in advance. PS: I know the answer would be app specific, but still any insight into this would be helpful.

# Answer
There is no API-imposed limit on the number of views of a single texture you can create. Views are just a way to access the same texture data in different ways, interpreting it as different formats or referring to different mip levels and so forth. They're very lightweight objects.
> 1 votes

---
Tags: directx11
---


# Question
Title: Using textureGrad for anisotropic integration approximation
I'm trying to develop a real time rendering method using real time acquired envmap (cubemap) for lightning.

This implies that my envmap can change as often as every frame and I therefore cannot use any method base on precomputation of the envmap (such as convolution with BRDF...)

So far my method worked well with Phong BRDF. For specular contribution I direclty read the value in my sampleCube and I use mipmap levels + linear filter for simulating the roughtness of the material considered:

```
int size                = textureSize(envmap, 0).x;
float specular_level    = log2(size * sqrt(3.0)) - 0.5 * log2(ns + 1);
vec3 env_specular       = ks * specular_color * textureLod(envmap, l_g, specular_level);

```

From this method I would like to upgrade to a microfacet based BRDF. I already have algorithm for evaluating the shape (including anisotropic direction) of the reflection but I cannot manage to read the values I want in my sampleCube.

I believe I have to use

```
textureGrad(envmap, l_g, X, Y);

```

with l\_g being the reflection direction in global space but I cannot manage to find which values to give to X and Y in order to correctly specify the area I want to consider.

What value should I give to X and Y in orther for

```
textureGrad(envmap, l_g, X, Y);

```

to give the same result as

```
textureLod(envmap, l_g, specular_level);

```

# Answer
> 2 votes
The gradient values are normally (when you do a standard texture lookup) the screen-space derivatives of the texture coordinates, `dFdx(l_g), dFdy(l_g)`.

In order to do anisotropic filtering while also specifying the base mip level as `specularLevel`, you could try rescaling the derivatives so the length of the smaller derivative is `pow(2.0, specularLevel)`. You want to maintain the relationship between the two derivatives so that the aniso filter has the same shape. Something like this:

```
vec3 derivX = dFdx(l_g);
vec3 derivY = dFdy(l_g);
float minLength = sqrt(min(dot(derivX, derivX), dot(derivY, derivY)));
float desiredLength = pow(2.0, specularLevel);
float scale = desiredLength / minLength;
derivX *= scale;
derivY *= scale;
... textureGrad(envmap, l_g, derivX, derivY);

```

---
Tags: opengl, cubemap, mipmaps, filtering, pbr
---


# Question
Title: Could you explain this calculation of tiling and offset?
I don't understand why we add `+colNumber` when we calculate the `offset = Vector2 ((uIndex+colNumber) * size.x`, which gives us `x=3` for the index 13, which is the square located at the coordinates `x:1, y:0` on the image (one square to the right, and "v" starts from the bottom). If the UV of the big image is on \[0,1\] for U and for V, why do we reach 3 for uIndex? And why don't we only do :

```
u = uIndex * sizeUV.x = 1 * 0.25 = 0.25
v = vIndex * sizeUV.y = 0 * 0.25 = 0

```

Here is the code from http://wiki.unity3d.com/index.php/Animating\_Tiled\_texture\_-\_Extended :

```
// Calculate index
var index : int = Time.time * fps;
// Repeat when exhausting all cells
index = index % totalCells;

// Size of every cell
var size = Vector2 (1.0 / colCount, 1.0 / rowCount);

// split into horizontal and vertical index
var uIndex = index % colCount;
var vIndex = index / colCount;

// build offset
// v coordinate is the bottom of the image in opengl so we need to invert.
offset = Vector2 ((uIndex+colNumber) * size.x, (1.0 - size.y) - (vIndex+rowNumber) * size.y);

renderer.material.SetTextureOffset ("_MainTex", offset);

```

# Answer
Here is how I understand it (I'm not saying that it's also how author of that script meant it):

Column count is total number of **tiles in sheet**. (the same for row)

Column number is **number of a tile, where your animation begins** (in picture in your question, it should be always 0, but you could also have for example 2 rows and 8 columns - 2 colors in one row).

Total cells is total number of **tiles in animation**.

Lets say you have the picture as is in your question, but you only want to animate last two faces (quick blinking) - these two: 8-) and :-)

So you will call function as this: SetSpriteAnimation(4, 4, 2, 2, 2, 10);

ColCount = 4

RowCount = 4

RowNumber = 2 (zero based and it's calculated from the top, because in the code author is inverting them)

ColNumber = 2 (zero based, so this is 3th column)

TotalCells = 2 (our animation has only 2 tiles)

FPS = 10 (doesn't matter)

If you try to put these values in script, index can be only 0 or 1 after line index = index % totalCells and OffsetX can be 0.5 or 0.75.

Lets say you want to animate blue faces from 2nd row (1 based indexing).

What is important: Your ColNumber has to be number of first tile of animation. TotalCells is total count of tiles in animation.

=============================

And about your comment to the question:

let's take 11, 11%16 = 11, then 11 % 4 (colCount) = 3, then (3+4) * 0.25 = 1.75 ... So the fourth blue head is at offsetX = 1.75 ? I don't understand.

Total cells count can't be 16 (it should be 4, because you are animating just one row, not all 4 rows), when your ColNumber is 4 (it should be 3, because it's 0 based). If you take ColCount = 3, your animation starts in 4th row and has only 1 frame.

If you have any questions to my answer, don't hesitate to ask. It's little complicated :)
> 0 votes

---
Tags: unity, coordinates, uv-mapping, materials
---


title: Unity's pack 4 floats

text:
# Question
Title: Unity's pack 4 floats
Linked to: GLSL pack floats into an RGBA texture

I found EncodeFloatRGBA/DecodeFloatRGBA shader functions in Unity https://gist.github.com/hecomi/9580605

Now I try to figure out how they work. So I try them on C++ http://coliru.stacked-crooked.com/a/345f8c403d4a78f9

But I got wrong results. Also I tried that with Mathematica, and got the same wrong results. http://www.sendspace.com/file/qmlu8b

I tried to encode {0.1, 0.2, 0.3, 0.4} - but after encode/decode got {0.0980392,0.698039,0.79649,0.93266}

# Answer
I got wrong results due to use of numbers which are not fraction of 255. In example used 255 (max int number of 8bit), so all numbers used in encoding/decoding should be a fraction of 255.

{0.1, 0.2, 0.3, 0.4} is not a fraction of 255, it is fraction of 10 or 100 or 1000...
With values like {1/255, 2/255, 3/255, 4/255} it works ok.

So when one use pack functions like that - pay attention to this. Actually you rather store integer values (which divided by number base) than float.
> 3 votes

---
Tags: c++, unity, shaders, glsl
---