# Question
Title: Is this scheduling operation a slowdown for the CPU, or is it a benefit?
I'm making a custom engine, and after much research, I realized that the state changes and the vertex or texture data loadings to VRAM are the most slow operations.

So I want to optimize it making a wrapper between OpenGL and a rendering engine that has a set of functions like OpenGL's, but making it like it saves the calls in arrays. After the "pre-rendering" phase, it schedules all operations, when possible, to make the state changes of GPU less frequent. Next, the scheduler groups vertices to make contiguous packs of vertices, when possible, and render it all, together.

Example of interface

```
class Renderer
    {
        typedef int Texture; // TMP
        class State
        { public:
            Vertex * Start;
            Vertex * End;
        };

        class SOC : public State
        { public:
            Shader * Reference;
            // End Null if update
        };

        class EOC : public State
        { public:
            GLenum * Reference;
            Vertex * Start;
            Vertex * End;
        };

        class FOC : public State
        { public:
            FrameBuffer * Reference;
            // End Null if draw
        };

    public:

        // Rendering api
        //-------------------------------------------------
        static void End();
        static void Begin(GLenum);
        static void Enable(GLenum);
        static void Disable(GLenum);
        static void BlendMode(GLenum, GLenum);
        static void BindShader(Shader *);
        static void UnbindShader(Shader *);
        static void UpdateShader(Shader *);
        static void SamplingType(GLenum, GLenum, GLenum);
        static void DrawFrameBuffer(FrameBuffer *);
        static void BindFrameBuffer(FrameBuffer *);
        static void UnbindFrameBuffer(FrameBuffer *);
        static void Vertex2(int, int);
        static void Vertex2(float, float);
        static void Vertex2(int, int, Color);
        static void Vertex2(float, float, Color);
        static void Vertex2(int, int, Texture);
        static void Vertex2(float, float, Texture);
        static void Vertex2(int, int, Color, Texture);
        static void Vertex2(float, float, Color, Texture);
        //-------------------------------------------------

        // Rendering phases
        //-------------------------------------------------
        static void Initialize();               //   0
        static void PreparePipeline();          //   1
        static void Schedule();                 //   2
        static void StartRenderPipeline();      //   3
        static void RestorePipeline();          // (0.5)
        //-------------------------------------------------

    private:

        // Rendering source
        //-------------------------------------------------
        static Vertex           * GlobalVertexBuffer;
        static std::vector<SOC>   ShaderStates;
        static std::vector<EOC>   EnableStates;
        static std::vector<FOC>   FBOStates;
        //-------------------------------------------------

        // Handlers openGL
        //-------------------------------------------------
        static GLuint StreamVertexBuffer;
        static GLuint Index;
        //-------------------------------------------------

        // Current state
        //--------------------------------------------------------------
        static std::unordered_map<GLenum, bool>         ActiveFlags;
        static std::unordered_map<Shader *, bool>       ActiveShaders;
        static std::unordered_map<VertexBuffer *, bool> ActiveVBOS;

        static GLenum CurrentPrimitive;

```

Is this scheduling operation a slowdown for the CPU, or is it a benefit?

# Answer
As far as I know, modern high performance rendering engines gather render operations into a so called "render queue".

Each such operation is basically a single drawcall: it has buffers, shaders, shader uniform data, textures, whatever other state needed...

These are then sorted, most expensive to switch property first. Shaders are expensive to switch, so maybe sort by those first, then within each chunk of render ops with same shader, sort by the next expensive thing (lets say, by texture) (this is just an example, you want to figure out the best sorting method through profiling and maybe researh of existing solutions)

One way to do that sorting is pack all the data into an integer key (say a 64 bit int) with the keys of the expensive stuff stored in the most significant bits, and keys of less expensive stuff in the other end. This allows for fast sorting by this single key. Same as if you were sorting based on numbers between 0 and 999, and let shader config key be the hundreds, texture config key be the tens, and buffer config key the ones.

There can be a higher level ordering of render stages/passes as well - eg you often want to render all transparent geometry after the opaque geometry, for example.

Thats for the expensive state changes.

For the less expensive changes, sorting would likely not be worth it, so instead you can just maintain a cache of the current state and always check if the state is already at the desired value before setting it. If you dont go with the renderqueue approach (which takes effort to implement) this is definitely better than having nothing at all.

For further research into the specifics, you can search using the phrase "Implementing a render queue" perhaps combined with "OpenGL" (although results for DirectX should apply to OpenGL pretty well too)

To answer the question, yes the sorting will of course take some CPU time (choose a sorting algorithm with good computational complexity in cases where data is already nearly sorted - so assuming you keep the sorted data from previous frame and make the few changes that happened for current frame, sorting should be quick) - if you are bottlenecked by GPU this should not be an issue (its not THAT expensive). Also consider that by avoiding redundant state changes, you avoid any CPU side processing done by drivers (even if they did nothing, there'd still be a trip to the driver), so its likely a win for CPU as well.
> 2 votes

# Answer
I agree with everything @Waterlimon stated, that's how our custom game engine works: traverse the scene graph, collect every item to be rendered into either an opaque or transparent render queue (each entry is a pointer to a mesh plus the current world matrix for that mesh and any other render values calculated during the scene graph traversal, like opacity), then sort the transparent queue by depth (you could also sort the opaque queue by shader, however we don't bother to do this).

Regarding batching, we recently added a batch manager which enabled us to achieve PlayStation 3 performance on an iPhone 4. On mobile devices, especially of that generation, the overhead for each OpenGL call was the killer. Newer APIs like Metal and DirectX 12 (as well as general increases in CPU performance) should alleviate this problem and will probably obviate or at least minimize the need for such batching. But if you want to render lots of objects on older devices your batching and sorting methods will yield benefits.
> 0 votes

---
Tags: opengl
---


# Question
Title: How to handle the birth and death of particle without reading from the buffer
I've implemented a simple particle system where each particle has a position, velocity, age and lifespan stored in different SSBOs.

Most of the data including all the position, velocity and age is updated through a compute shader. And emiting new particles is handled by CPU since it's a serial process. But in order to track whether each particle is alive or dead, I have to read all the lifespan data back to CPU from the SSBO (using glGetBufferSubData()), which do stalls the GPU I'm afraid.

So I was wondering is there any way to prevent reading the data back from GPU. I found a demo particle system made by AMD using directX, which uses a dead list and an alive list in the compute shader. But I have no idea how to achieve this with GLSL. Any ideas?

Demo code:

```
...

// The dead list, so any particles that are retired this frame can be added to this list
AppendStructuredBuffer<uint>            g_DeadListToAddTo       : register( u2 );

// The alive list which gets built using this shader
RWStructuredBuffer<float2>              g_IndexBuffer           : register( u3 );

...

// Dead particles are added to the dead list for recycling
if ( pb.m_Age <= 0.0f || killParticle )
{
    pb.m_Age = -1;
    g_DeadListToAddTo.Append( id.x );
}

...

```

# Answer
If the only way your particles die is through age, then there's no need to read the data back from the OpenGL buffers at all. Keep a CPU side buffer that tracks the current age for each particle (or equivalently, remembers the time at which they will die), then your CPU can scan through that list quickly every frame to find particles which need to be re-born. Then you can update just their portion of the GPU buffer.

I would also look into glMapBuffer() (glMapBufferOES() on OpenGL ES 2.0) for updating the GPU buffer, as I've found they have better performance (not stalling the GPU).

Alternatively you might consider checking for particle death within the shader itself. Depending on the complexity of your particle spawn process this may not be practical but if you're just emitting particles from a point source, for example, you could pass this position in as a shader parameter and then your shader could detect old particles and restart them at the emitter position.
> 2 votes

---
Tags: opengl, glsl
---


# Question
Title: Determine whether an object is 'visible' at a given distance automatically?
I am creating an environment using procedural content. To optimise performance, I am batching small meshes ahead of time. For efficiency's sake, I don't want to batch objects that make only an insignificant contribution to the final frame.

**My question is, how should I determine this? Is there a commonly used or provably 'correct' algorithm?**

I was thinking of something like: calculate the size of the bounding box on the final frame based on the camera parameters and see if its below a certain threshold.

Is there a better one?

(PS. This is not premature optimisation - currently my batches go well over the 65k VBO limit - not batching small meshes may save a number of draw calls. Also to be clear, I am not asking about occlusion, I have a number of small highly detailed objects in a scene so large than some will simply not be noticeable if they are far enough away and can be safely culled.)

# Answer
> 1 votes
Essentially what you want to do is compute the size of the object in pixels, then discard objects that are smaller than some threshold value.

Use a bounding sphere rather than a box and the calculation becomes quite easy. Pre-compute a single radius value R for each object/mesh which is the maximal distance of any vertex from the origin in the object/mesh. Then during rendering, compute the distance from the camera to the object. Divide this distance by R and compare it to a threshold value of your choosing. If the value is less than the threshold value, render the object, otherwise don't. You can even fade the object out as it approaches the threshold value to avoid objects popping in and out as you move towards and away from them.

If your camera can change field of view you should also multiply your threshold value by the ratio of the current field of view to some reference field of view, so that as you zoom in, objects will appear at the same pixel size on screen.

---
Tags: optimization, culling, visibility-determination
---


# Question
Title: Switching bezierpath to follow SpriteKit swift
I am trying to make it so that a SKShapeNode follows a UIBezierPath. Then when the screen is tapped it switches to another UIBezierPath to follow. I have this functionality working except that when the screen is tapped the shape node moves back to where it started. I want it so that when the screen is tapped the circle does not go back to where it starts. Here is my code.

```
override func didMoveToView(view: SKView) {
    //screenWidth and screenHeight
    screenWidth = view.bounds.width
    screenHeight = view.bounds.height

    // Set up the circle track
    let trackWidth = screenWidth/3

    let circleTrack = UIBezierPath(roundedRect: CGRectMake(screenWidth/2 - trackWidth/2, screenHeight/2  - trackWidth/2, trackWidth, trackWidth), cornerRadius: 100)
    let shapeTrack = SKShapeNode(path: circleTrack.CGPath, centered: true)
    shapeTrack.position = CGPointMake(screenWidth/2, screenHeight/2)
    shapeTrack.strokeColor = UIColor.whiteColor()
    self.addChild(shapeTrack)

    //Outside track
    outsideTrack = UIBezierPath(roundedRect: CGRectMake((screenWidth/2 - trackWidth/2) - trackWidth*0.08, (screenHeight/2  - trackWidth/2) - trackWidth*0.08, trackWidth + trackWidth*0.16, trackWidth + trackWidth*0.16), cornerRadius: 100)

    //Inside track
    insideTrack = UIBezierPath(roundedRect: CGRectMake((screenWidth/2 - trackWidth/2) + trackWidth*0.08, (screenHeight/2  - trackWidth/2) + trackWidth*0.08, trackWidth - trackWidth*0.16, trackWidth - trackWidth*0.16), cornerRadius: 100)

    //Set the default track
    track = outsideTrack

    // Create the ball
    circle = SKShapeNode(circleOfRadius: 15)
    //circle.position = CGPointMake(screenWidth/2, screenHeight/2)
    circle.fillColor = SKColor.whiteColor()
    self.addChild(circle)

    //Move the circle
    let followPath = SKAction.followPath(track.CGPath, asOffset: false, orientToPath: false, speed: 200.0)
    let repeatForever = SKAction.repeatActionForever(followPath)

    //Move the circle
    circle.runAction(repeatForever)
}

//Movement of circle
func movemementOfCircle(){
    if track == insideTrack{
        track = outsideTrack
    }else{
        track = insideTrack
    }

    //Actions
    circle.removeAllActions()
    //Move the circle
    let followPath = SKAction.followPath(track.CGPath, asOffset: false, orientToPath: false, speed: 200.0)
    let repeatForever = SKAction.repeatActionForever(followPath)

    //Move the circle
    circle.runAction(repeatForever)
}

```

# Answer
> -1 votes
you need to define two followPath's. e.g.

```
let followPath1 = SKAction.followPath(track.CGPath, asOffset: false, orientToPath: false, speed: 200.0)
let followPath2 = SKAction.followPath(track.CGPath, asOffset: false, orientToPath: false, speed: 200.0)

```

---
Tags: spritekit, beziers, path
---


title: Serialization is not saving high score

text:
# Question
Title: Serialization is not saving high score
I wanted to avoid using playerprefs because they are easy to edit. So, I went with Serialization. Here is my main class that does all the scorekeeping:

```
public class scoreKeeper : MonoBehaviour {

    public static scoreKeeper sk;
    public int score=0,highscore=0;
    public bool increase=false;

    void Awake(){
        if (sk == null) {
            DontDestroyOnLoad(gameObject);
            sk=this;
        }

        if (sk != this)
            Destroy (gameObject);

        highscore=load ();
        Debug.Log (highscore);
    }

    void Update () {
        if (increase) {
            score++;
            increase = false;
        }

    }

    public  void save()
    {
        BinaryFormatter bf = new BinaryFormatter ();
        FileStream file = File.Create (Application.persistentDataPath + "/playerInfo.dat");

        PlayerData data = new PlayerData ();

        if (score >data.highScore)
            data.highScore = score;

        bf.Serialize (file, data);
        file.Close ();

        highscore = load ();

    }

    int load()
    {
        if (File.Exists (Application.persistentDataPath + "/playerInfo.dat")) {
            BinaryFormatter bf = new BinaryFormatter ();
            FileStream file = File.Open (Application.persistentDataPath + "/playerInfo.dat",FileMode.Open);
            PlayerData data = (PlayerData)bf.Deserialize (file);
            file.Close ();

            return data.highScore;

        } else
            return 0;
    }
}
[Serializable]

class PlayerData
{
    public int highScore;
}

```

The Save function is called at a game over condition like this: scoreKeeper.sk.save();

The problem i'm facing is, highscore keeps getting updated even when score is lower than highscore. In my Save method, I have the line if(score\>data.highScore) data.highScore=score;

When I repeatedly run the game, thr high scores are 11, 2, 5, 3, etc. What is the error in my code?

# Answer
Resolved. All i had to do was in my Save method, provide alternate value when highscore is not reached.

The file is created every time Save is called. So, previous value is overwritten only if it was less than current score. May be I could have a condition to check if file exists and update it only if the score is higher than high score.

```
if (score > highscore) {
            data.highScore = score;
        }
        else
            data.highScore = highscore;

```
> 1 votes

---
Tags: unity
---


# Question
Title: Why do my point lights have red X's on them in the Unreal editor?
I've noticed through the first two tutorials I've done that Point Lights begin entering the viewport with red x's on them. When I build those don't turn on. It seems to be implying some limit to the number of Point Lights in a given space. Is that space the lightmass importance volume, or a given scene? I checked the Point Light tutorial explanation to no avail.

# Answer
> 1 votes
You can only have 4 overlapping point lights. I guess your radii must overlap. You can read more about standard issues with lights in the lighting troubleshooting guide.

---
Tags: lighting, unreal-4
---


title: Texture doesn't scale and repeat

text:
# Question
Title: Texture doesn't scale and repeat
I wrote the script for automatic repetition of texture background. To save it I typed Cmd+S. I dragged and dropped the script to **Background** in **Hierarchy**. When hit *play* button the texture doesn't scale and doesn't repeat itself. What is it that I am doing wrong?

```
using System.Collections;

public class TiledBackground : MonoBehaviour {

    public int textureSize = 32;

    void start(){
        var newWidth = Mathf.Ceil (Screen.width / (textureSize * PixelPerfectCamera.scale));
        var newHeight = Mathf.Ceil (Screen.height / (textureSize * PixelPerfectCamera.scale));

        transform.localScale = new Vector3(newWidth * textureSize, newHeight * textureSize, 1);

        GetComponent<Renderer>().material.mainTextureScale = new Vector3(newWidth, newHeight, 1);
    }
}

```

Expected Results:

Results that I'm getting are same as before. Script doesn't seem to work:

# Answer
> 3 votes
Your start method is named wrong. The 's' should be capitalized.

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


# Question
Title: Why is this unity camera moving in weird directions?
I have the following script

```
public class CameraScript : MonoBehaviour {

    public bool AllowZoom;
    public float zoom;
    public float Speed;
    Transform board;
    void Start(){
        board=GameObject.FindGameObjectsWithTag("PlayingBoard")[0].transform;
    }

    void Update(){
       CentreRotate();
    }
    public void arrowMove(){
        if(Input.GetKey(KeyCode.RightArrow)){

            transform.Translate(transform.right*Speed*Time.deltaTime);
        }
        if(Input.GetKey(KeyCode.UpArrow)){
            transform.Translate(transform.up*Speed*Time.deltaTime);
        }
        if(Input.GetKey(KeyCode.LeftArrow)){
            transform.Translate(transform.right*-Speed*Time.deltaTime);
        }
        if(Input.GetKey(KeyCode.DownArrow)){
            transform.Translate(transform.up*-Speed*Time.deltaTime);
        }
    }

    public void CentreRotate(){
        float distance=Mathf.Abs((transform.position-board.position).magnitude);
        float toMove=distance-zoom;
        transform.LookAt(board);
        transform.Translate(transform.forward*toMove);
        arrowMove();
    }
}

```

This script should allow me to rotate around a given point at a constant distance from the center using the arrow keys. However rather then do that it seems to move towards a spot right above the board and then start turning really fast. It also seems that when slowing down the turning (by dividing distance by a large amount) that the arrow keys give "weird" directions, for example the right arrow key sometimes moves the camera forward.

Anybody got any ideas?

Here are some pictures of what is going on.

On startup:

After I press the right arrow key for a about a second:

# Answer
You will probably find that what is happening is that the camera object is being rotated by Unity as you translate it. I myself have had this happen where I wanted to rotate around a point, but because the camera was angled down, it would roll as it moved sideways. The best way I found to fix this issue, was to reset the pitch of the camera to look towards the horizon (0), calculate where the camera had to be moved and move it, then pitch the camera down again. You don't have to keep the camera up the whole time the camera's moving though. So: camera x rotation set to 0 translate the camera reset camera rotation

Hopefully, this will fix your problem.
> 0 votes

---
Tags: unity, c#, camera, movement, geometry
---


# Question
Title: "Render" unsigned integer values to texture without clamping to [0,1]
I am trying to render to an unsigned integer texture, with a blending function enable, so that in the end, the value in each texel will be the number of objects rendered on the texel. So I assume I cannot use normalized integers.

For example, if I have a 2x2 texture, and I render `[ (0,0) (0,0) (0,1) (1,0) ]`, the texture result should be, `[ 2 1 ; 1 0 ]`.

I am trying to set up the frameBuffer, but the call to `glTexImage2D`, causes the `GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT` when I use the formats I assume I need.

```
// this works
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 1024, 768, 0, GL_RGB, GL_UNSIGNED_INT, 0);

// this causes GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT
glTexImage2D(GL_TEXTURE_2D,
             0,
             GL_RGB32UI,
             width,
             height,
             0,
             GL_RGB_INTEGER,
             GL_UNSIGNED_INT,
             0 );

```

Is what I want to do even possible? If so, which settings do I need to use to accomplish this?

# Answer
> 1 votes
GL\_RGB32UI \<- Is this right? Each texel value is 4 32bit integers? The last time I did this and wrote a single 32bit integer to a texture, I used GL\_R32I and GL\_RED\_INTEGER.

I've never had that error before but it seems reasonable if you're texture isn't big enough.

# Answer
> 0 votes
I was not able to get additive blending working with an integer buffer, however I did get it working with a single channel 32 bit float. I got the effect I was going for by outputting 1 / 2^30 in fragment the shader, with glBlendFunc( GL\_ONE, GL\_ONE ), then multiplying by 2^30 after reading back the pixels.

---
Tags: opengl, textures, frame-buffer
---


# Question
Title: What exactly is the difference between Unreal Development Kit and Uunreal Engine 4?
I want to start learning game development and I would obviously come across this tool. So every where I went people mentioned Unreal Engine 4 to be a viable choice, I've tried a bit of Unity and now I want to try Unreal. Only issue I came across UDK and UE4, I downloaded UDK which turns out to be different from tutorials and I can't seem to find any info on that and besides I could only run the software once because after the first time it starts a game, I re-installed UDK I still get the issue, but anyways that's a different topic, what I want to know is whether UDK and UE4 are different and if they are, where do i get UE4, becauuse when I down UE4 (from - https://www.unrealengine.com/dashboard), it downloads a game launcher and no development tool. In case they are same, why is my version of UDK different fr

# Answer
According to this link

> **WHAT IS UDK?**
>
> Unreal Development Kit was the free edition of Unreal Engine 3. It remains available for teams completing projects in UE3. Get UDK (February 2015 UDK).

So you want to avoid using UDK and use Unreal Engine 4
> 5 votes

# Answer
You download the Launcher (which is not a game launcher - it's Epic Games Launcher, because the company is called Epic Games), and from within the launcher you can download UE4. This should be trivial to find out though.
> 0 votes

---
Tags: udk, unreal, unreal-4
---


# Question
Title: How to make sure Sun Shafts are emitted only from background elements?
Currently I have a game scene entirely made of standard sprites using the default material.

I use the Unity standard effect named Sun Shafts.

I have tried many combinations of shaders and other settings. I get the sun shafts to shine properly from the whiter areas in the far background which is fine.

But I noticed they also are emitted from white areas on the characters and foreground which completely defeats the purpose of the sun shafts.

Is there a way to get the sun shafts to be emitted only from elements which are far away of from objects defined in advance?

# Answer
> 1 votes
I'm not sure how to do this in unity specifically, but what you need to do is render the background first, apply the sun ray shader, then render the foreground on top of that.

# Answer
> 0 votes
It won't work for all situations, but if it suits then that's great. A lot of AAA games actually just use a decal type - that is, just place an image of a ray where you want a ray to be. Usually, these are only placed far from the camera too especially when they are poor quality, but it will save the gpu some time to make calculations elsewhere and if done well, can look just as good.

---
Tags: graphic-effects, unity
---


title: Testing Unity 2D Physics

text:
# Question
Title: Testing Unity 2D Physics
I am looking to push the 2D physics in Unity to the extent where when so much is going on that there becomes noticeable lag in a game. This is for testing purposes, so that when so much is going on that a button can be pressed to reduce the amount of physics objects on screen then see what affect that has. So in my small 2D demo I have placed alot of barrels on the map, all of which have physics on them, player bumps into them and they move. I have went to the extent of placing alot of them on the map (864 to be exact), bumping into them I still don't see any effect on the gameplay. Other things I have tried, besides adding alot in, is increasing the mass of the barrels, changing their linear and angluar drag and making them bouncy.

Is there anything I can do besides adding alot more in? Thanks!

# Answer
> 2 votes
I would suggest procedurally spawning the object constantly, and adding mesh colliders. Mesh colliders are very cpu intensive, and if you have a script that continuously creates these barrels, it will keep doing so until you kill unity. You can also track your gameplay statistics by clicking on the stats button up the top of your game window.

# Answer
> 2 votes
I think the amount of entities is the best to test that and to keep things simple just multiply them. Simply add a script to your barrel prefab which will wait 1 second after start and then spawn two more entities of the same object. Add some force to push them away.

That way you only have to place one instance on your screen, start your game and wait a bit. The multiply will come into effect pretty soon as each object will spawn two new ones.

Maybe add a counter as well so you can see how many are on the screen at the moment.

Then all you have to do is to sit and wait until your game becomes sluggish or crashes. Shouldn't take forever... :)

---
Tags: unity, 2d, physics
---


# Question
Title: How to store each rendered frame as image in libgdx for debugging
I have a libgdx screen's render method where I am executing lots of for loops and drawing various shapes on screen in thoese loops. Also I am manupulating (x,y) of each shape at runtime to acheive a smooth animation.Everything was ok until,

**Issue:** Recently I had added few more shape's at some positions in my screen. Due to some mess up, I am getting flicker, and some shapes are getting drawn out of my game world.

I tried to debug my code many times but there are too many loops and shapes so I am unable ***to pin point the exact loop or frame*** where shapes are getting drawn out of my game world.

**Need Input on following approach to debug:**

So I was thinking **to save each frame of my render method as an image locally. Is it possible?** Please provide suggestions or sample code to acheive it.

I will hook up some debug variables in my loops to calculate exact frame where things are getting messed up. That I will take care of. Please advice on above question.

Thanks in advance.

# Answer
> 2 votes
It is absolutly possible. Here's a simple class that, when called, will save a screenshot of the main graphical context:

```
public class ScreenshotFactory {

    private static int counter = 1;
    public static void saveScreenshot(){
        try{
            FileHandle fh;
            do{
                fh = new FileHandle("screenshot" + counter++ + ".png");
            }while (fh.exists());
            Pixmap pixmap = getScreenshot(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), false);
            PixmapIO.writePNG(fh, pixmap);
            pixmap.dispose();
        }catch (Exception e){
        }
    }

    private static Pixmap getScreenshot(int x, int y, int w, int h, boolean yDown){
        final Pixmap pixmap = ScreenUtils.getFrameBufferPixmap(x, y, w, h);

        if (yDown) {
            // Flip the pixmap upside down
            ByteBuffer pixels = pixmap.getPixels();
            int numBytes = w * h * 4;
            byte[] lines = new byte[numBytes];
            int numBytesPerLine = w * 4;
            for (int i = 0; i < h; i++) {
                pixels.position((h - i - 1) * numBytesPerLine);
                pixels.get(lines, i * numBytesPerLine, numBytesPerLine);
            }
            pixels.clear();
            pixels.put(lines);
        }

        return pixmap;
    }
}

```

The only thing you have to do if you have this class in your project is to call the following line in each of your *render* loop:

```
ScreenshotFactory.saveScreenshot();

```

It will save the screenshot as *screenshotX.png*, *X* being the smallest number available, starting with 1.

Just make sure you draw the frame number or an identifier on the image to be able to match it with all your debug messages.

### Source

---
Tags: libgdx, rendering, debugging
---


# Question
Title: How to optimize my movement & collision code?
I am trying to implement movement & collision the simplest way possible.

```
    public void MovePlayer()
    {
        KeyboardState keyState = Keyboard.GetState();

        Vector2 checkVec = location; //get current location

        if (keyState.IsKeyDown(Keys.Left))
        {
            //Check what the next position would be
            Rectangle checkRect = new Rectangle((int)(checkVec.X -= speed), (int)location.Y, texture.Width, texture.Height);
            //Check if the next position would collide with any obstacles
            bool collides = CheckCollision(checkRect);

            //If it does not collide move..
            if (!collides)
            {
                location.X -= speed;
            }

        }

        if (keyState.IsKeyDown(Keys.Right))
        {
            Rectangle checkRect = new Rectangle((int)(checkVec.X += speed), (int)checkVec.Y, texture.Width, texture.Height);
            bool collides = CheckCollision(checkRect);

            if (!collides)
            {
                location.X += speed;
            }
        }

        if (keyState.IsKeyDown(Keys.Up))
        {
            Rectangle checkRect = new Rectangle((int)checkVec.X, (int)(checkVec.Y -= speed), texture.Width, texture.Height);
            bool collides = CheckCollision(checkRect);

            if (!collides)
            {
                location.Y -= speed;
            }
        }

        if (keyState.IsKeyDown(Keys.Down))
        {

            Rectangle checkRect = new Rectangle((int)checkVec.X, (int)(checkVec.Y += speed), texture.Width, texture.Height);
            bool collides = CheckCollision(checkRect);

            if (!collides)
            {
                location.Y += speed;
            }
        }
    }

```

Here ist the CheckCollision() method:

```
        private bool CheckCollision(Rectangle checkRect)
    {
        bool collides = false;

        foreach (Tile t in blockedTiles)
        {
            if (t.rectBounds.Intersects(checkRect))
            {
                return true;
            }
            else
            {

            }
        }
        return collides;
    }

```

So my problem is that due to the order in which I am checking button input when I get a collision from up or down everything works fine. But when it is collision from left or right the code does not recognize if I am simulatneously moving up or down, so in this case the Textture freezes as long as I provoke left or right collision.

Any ideas how to fix this?

# Answer
> 5 votes
### Step 1 - Don't check collisions in each key, test them at the end

In your example, you are checking collisions for each key independantly. This will cause some trouble and code replication. In order to avoid that, I would suggest you use temporary variables that will stock the movement, increment it for each key and test collisions only once at the end:

```
public void MovePlayer()
{
    KeyboardState keyState = Keyboard.GetState();

    float xPlus = 0;
    float yPlus = 0;

    if (keyState.IsKeyDown(Keys.Left))
    {
        xPlus -= speed;
    }
    if (keyState.IsKeyDown(Keys.Right))
    {
        xPlus += speed;
    }
    if (keyState.IsKeyDown(Keys.Up))
    {
        yPlus -= speed;
    }
    if (keyState.IsKeyDown(Keys.Down))
    {
        yPlus += speed;
    }

    Rectangle checkRect = new Rectangle((int)(location.X + xPlus), (int)(location.Y + yPlus), texture.Width, texture.Height);
    bool collides = CheckCollision(checkRect);
    if (!collides) {
        location.x += xPlus;
        location.y += yPlus;
    }
}

```

### Step 2 - Independant X and Y movement

A nice thing to add if independant movement for X and Y so that if the player is moving diagonaly, and is hitting a wall on one axis, it will still move on the other axis:

```
Rectangle checkRect = new Rectangle((int)(location.X + xPlus), (int)location.Y, texture.Width, texture.Height);
bool collides = CheckCollision(checkRect);
if (!collides) {
    location.x += xPlus;
}
checkRect = new Rectangle((int)location.X, (int)(location.Y + yPlus), texture.Width, texture.Height);
collides = CheckCollision(checkRect);
if (!collides) {
    location.y += yPlus;
}

```

### Step 3 - Simplify the CheckCollision method

You have a lot of useless lines in your collision method. It can be simplified as such:

```
private bool CheckCollision(Rectangle checkRect)
{
    foreach (Tile t in blockedTiles)
    {
        if (t.rectBounds.Intersects(checkRect))
        {
            return true;
        }
    }
    return false;
}

```

### Tip - Always use the true position of your object

You were assigning an intermediary variable that stocked the position of your player. The problem with this is the following: if you move your player, the *checkVec* variable will not be updated, so the next collision check will most likely fail. Always use the true position of the player, or at least update the *checkVec* when you move it.

### Warning - Don't use += in tests!

When you use *+=* in your *ifs*, it WILL modify the value! Use only *+* instead! This is probably the reason why your collisions won't work.

### EDIT: Fixed-step vs variable-time

As Shiro pointed out in the comments, this method is not 100% applicable in the case the user modifies the default tiem step method for the variable time step. In this case, we should take into account the time elapsed between two *Update()*. More details in the link Shiro provided in the comments, and on this site.

---
Tags: xna, c#, collision-detection, movement, monogame
---


title: Is it enough to read manuals?

text:
# Question
Title: Is it enough to read manuals?
I want to develop games with Blender and Unity. I don't see any good books out there and so I'm considering reading the manuals of both the software. Should reading the manuals be enough if you're creative enough to figure out how to get a game working if you know how everything works?

# Answer
> 4 votes
Nothing beats practice. Reading the manuals will give you a good start at knowing what features exist and how to use each one individually. But generally, what you want to do is not available in text books so you have to figure out how to assemble parts of what you know to achieve the result you're looking for.

That's where practice comes in. And forums. And stack exchange. Or a teacher. Or a colleague. And youtube. And practice.

So, to answer: **It is good to read manuals, but it is not enough to get good at it.**

---
Tags: unity, blender, books
---


# Question
Title: How can I blend up to 3 textures on a polygon without blend maps?
For my voxel game I need to blend up to 3 textures in the same polygon. It would be preferable if I could specify a texture id for each vertex, but other solutions are accepted as well.

Here's an illustration of what I want.

How can I achieve this type of blending?

Multi texturing with blend maps is *NOT* a solution. Also please notice that there will be a lot of different textures.

# Answer
In very broad strokes, you can accomplish this by:

* Yes, using shaders
* Binding three textures to the shader program before drawing
* On your polygons, have the usual UV vec2 for each vertex. This is used by any of the textures
* Have another attribute which is "weight of each texture at this vertex". It could be a vec3 or three separate floats. For the illustration above, the weights for the three vertexes would be something like (1,0,0), (0,1,0), (0,0,1).
* (If you don't want a smooth fade across the whole triangle, maybe a more confined fade-over towards the middle, you could work out a different interpretation of the weighting-triplet)
* In the shader, sample all three textures at the desired UV coordinate, and multiply each one by the corresponding WEIGHT component. Sum them up for the output pixel.

The shader will interpolate the weights across polygon, just like for the UV.

As described here, you'd have to re-set the three textures for every polygon, or at least batch the ones that use the same three textures.

Changing bits of the context (such as texture bindings) might be a performance bottleneck. If so, an optimization is to use a "Texture Atlas", where your textures are tiled together into one bigger texture. Then you just keep that one, no rebinding.

Then some attributes on each vertex would need to specify, "Within the texture atlas, which tile corresponds to textures 1, 2, and 3.". These would have to be the same for all three vertices of each triangle.

(If you're not already using shaders, this might seem like a steep set of hurdles. But shaders are awesome, so go for it!)
> 4 votes

---
Tags: opengl, java, glsl, lwjgl
---


# Question
Title: How can you merge the geometries of cloned objects in Three.JS?
So I'm testing the best non-voxel way to display a lot of objects at once and so I found how to merge geometries.

Now, I can easily merge most geometries, but I can't seem to merge the geometries of cloned objects.

I've noticed that by simply using cloned objects, I can nearly get the same performance I get when merging geometries.

Is there a way to combine these two things for even better performance?

Here is a sample of my code, with the broken methods commented out.

```
var testGeo = new THREE.BoxGeometry( 1, 1, 1 );
var testMat = new THREE.MeshLambertMaterial( {color: 0xffff00  });
var testMesh = new THREE.Mesh( testGeo, testMat );
testMesh.position.set(1, 5, 1);
testMesh.castShadow = true;
testMesh.receiveShadow = true;
scene.add( testMesh );

//Testing with 900 objects.
var iterLength = 30;
for(var i = 0; i< iterLength; i++) {
    for(var j = 0; j< iterLength; j++) {

        var testGeo2 = new THREE.BoxGeometry( 1, 1, 1 );
        var testMat2 = new THREE.MeshLambertMaterial( {color: 0xffff00  });
        var testMesh2 = new THREE.Mesh( testGeo2, testMat2 );
        testMesh2.position.set(i, 2, j);
        testMesh2.castShadow = true;
        testMesh2.receiveShadow = true;

        //Clone Test (This won't work)
        /*
        var testMesh2 = testMesh.clone();
        testMesh2.position.set(i, 2, j);
        */

        //Reference Material/Geo test. (This also doesn't work)
        /*
        var testMesh2 = new THREE.Mesh( testGeo, testMat );
        testMesh2.position.set(i, 2, j);
        testMesh2.castShadow = true;
        testMesh2.receiveShadow = true;
        */

        //Merge.
        testMesh2.updateMatrix();
        testGeo.merge(testMesh2.geometry, testMesh2.matrix);
    }
}

```

# Answer
Have you tried to use THREE.Object3D? UPDATED:

```
group = new THREE.Object3D();//create an empty container
group.add( testMesh.clone() );//add a mesh with geometry to it
scene.add( group );//when done, add the group to the scene

```
> -2 votes

---
Tags: javascript, three.js
---


title: Why isn't OnTriggerExit working?

text:
# Question
Title: Why isn't OnTriggerExit working?
I have a price of code that looks like this:

```
void OnTriggerExit() {
 Debug.Log("Object leaved trigger");
}

```

But when I move an object that is colliding with the trigger by script it doesn't print to the console, but if i nudge it instead it does. I'm guessing it's because the object ain't actually exiting, but disappearing. Is there a way to solve this? Thank you!

**EDIT:**
Okey, so this is the actual code:

# Craftingstation.cs

```
using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class Craftingstation : MonoBehaviour {

    //GameObject globalScripts;

    bool itemAlreadyCraftable;
    int correctItems;

    public string[,] itemIds;
    // Generic list for holding items on crafter
    public List<string> itemsOnCrafter;
    public List<string> craftableItems;
    // Static 2D array for holding crafting recipes
    string[,] craftingRecipes = new string[,] {
        // {recipe},{result}
        {"potato","tabasco"},{"explosivePotato"},
        {"mentos","cola"},{"colaCannon"},
        {"potato","cola"},{"potatoCola"},
        {"potato","chips"},{"potatoChips"}
    };

    void Start () {
        //globalScripts = GameObject.FindGameObjectWithTag("Global Scripts");
        //string test = globalScripts.GetComponent<items>().nameToId("mentos");
    }

    /*
    void nameToId(string passedName) {
        for (int i = 0; i < globalScripts.GetComponent<items>().itemIds.GetLength(0); i++)
        {
            string loopedName = globalScripts.GetComponent<items>().itemIds[i, 0];
            if (loopedName == passedName) {
                string returnString = globalScripts.GetComponent<items>().itemIds[i, 1];
                Debug.Log(returnString);
            }
        }
        return 0;
    }
    */

    void Update () {
        for (int i = 0; i < craftingRecipes.GetLength(0); i++) {
            itemAlreadyCraftable = false;
            correctItems = 0;
            if (i%2==0) {
                for (int j = 0; j < craftingRecipes.GetLength(1); j++) {
                    for (int k = 0; k < itemsOnCrafter.Count; k++) {
                        if (itemsOnCrafter[k] == craftingRecipes[i, j]) {
                            correctItems++;
                        }
                    }
                    if (correctItems >= craftingRecipes.GetLength(1)) {
                        for (int l = 0; l < craftableItems.Count; l++) {
                            if (craftableItems[l] == craftingRecipes[i+1, 0]) {
                                itemAlreadyCraftable = true;
                            }
                        }
                        if (itemAlreadyCraftable == false) {
                            craftableItems.Add(craftingRecipes[i+1, 0]);
                        }
                    }
                    else {
                        craftableItems.Remove(craftingRecipes[i+1, 0]);
                    }
                }
            }
        }
    }

    void OnTriggerEnter(Collider other) {
        itemsOnCrafter.Add(other.GetComponent<id>().technicalName);
    }
    void OnTriggerExit(Collider other) {
        itemsOnCrafter.Remove(other.GetComponent<id>().technicalName);
    }
}

```

# sendRay.cs

```
using UnityEngine;
using System.Collections;

public class sendRay : MonoBehaviour {

    Ray ray;
    RaycastHit hit;
    bool holding = false;
    public bool pickedUp = false;
    Vector3 tempScale;

    void Update()
    {
        if(Input.GetButtonDown("Pickup"))
        {
            Vector2 screenCenterPoint = new Vector2(Screen.width/2, Screen.height/2);
            ray = Camera.main.ScreenPointToRay(screenCenterPoint);

            if(Physics.Raycast(ray, out hit, 5))
            {
                if(hit.transform.tag == "Pickup") {
                    if(holding == false) {
                        pickedUp = true;
                        tempScale = hit.transform.localScale;
                        hit.transform.parent = GameObject.FindGameObjectWithTag("Hand").transform;
                        float distX = hit.transform.GetComponent<keepOffset>().distX;
                        float distY = hit.transform.GetComponent<keepOffset>().distY;
                        float distZ = hit.transform.GetComponent<keepOffset>().distX;
                        //Debug.Log(distX + ", " + distY + ", " + distZ);
                        hit.transform.localPosition = new Vector3(-distZ, -distX, -distY);
                        hit.transform.localScale = tempScale;
                        hit.transform.rotation = GameObject.FindGameObjectWithTag("Hand").transform.rotation;
                        foreach(Collider c in hit.transform.GetComponents<Collider>()) {
                            c.enabled = false;
                        }
                        foreach(Rigidbody r in hit.transform.GetComponents<Rigidbody>()) {
                            r.isKinematic = true;
                            r.detectCollisions = false;
                        }
                        holding = true;
                        return;
                    }
                }
            }
            if(holding == true) {
                pickedUp = false;
                foreach (Transform child in GameObject.FindGameObjectWithTag("Hand").transform){
                    child.transform.parent = null;
                    child.transform.localScale = tempScale;
                    foreach(Collider c in child.transform.GetComponents<Collider>()) {
                        c.enabled = true;
                    }
                    foreach(Rigidbody r in child.transform.GetComponents<Rigidbody>()) {
                        r.isKinematic = false;
                        r.detectCollisions = true;
                    }
                }
                holding = false;
                return;
            }
        }
    }
}

```

# Answer
Have a look at the online API.

It states that the function requires an argument of type Collider, which is what you're missing.

It should be:

```
void OnTriggerExit(Collider other)

```

Not:

```
void OnTriggerExit()

```

Another note, make sure one of the objects colliding have a rigidbody, Unity requires it to detect collisions.
> 1 votes

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


# Question
Title: LibGdx - Move sprite in the direction of other sprite
I'm kind new to LibGdx and I'm still learning. I'm working on a small game project to learn this nice framework. However, I'm having some issues with my game. My game is a top down shooter. There is a human character(space marine) that has to shoot an alien, which will be always moving in his direction until it dies. My code doesn't have any bullets yet.I was able to make the shooter rotate in the direction of the cursor, as well, the alien rotate in the direction of the shooter, but I can't make the alien move in his direction. I'm pretty sure that my method that does that is completely wrong. I've tried a lot to fix it , but I can't get it fixed ! I appreciate your attention guys ! You can find the full code of the main class here: https://github.com/Igor-Lopes/LibGdx/blob/master/Splash.java#L125

```
public void moveAlien() {
    float mX = 0;
    float mY = 0;
    int velocity = 50;
    vAlien = new Vector2(-1 * (float) Math.sin(Alienbody.getAngle()) * velocity,
            (float) Math.cos(Alienbody.getAngle() * velocity));

    mX = (float) Math.cos(Math.toRadians(spacemarine.getRotation()));
    mY = (float) Math.sin(Math.toRadians(spacemarine.getRotation()));

    vAlien.x = mX;
    vAlien.y = mY;
    if (vAlien.len() > 0) {
        vAlien = vAlien.nor();
    }
    vAlien.x = vAlien.x * velocity;
    vAlien.y = vAlien.y * velocity;
    vAlien.x += vAlien.x * Gdx.graphics.getDeltaTime();
    vAlien.y += vAlien.x * Gdx.graphics.getDeltaTime();
}

public float rotateMarine() {
    float angle = 0;
    float mouseX = 0;
    float mouseY = 0;
    mouseX = Gdx.input.getX();
    mouseY = 677 - Gdx.input.getY();
    angle = (float) Math.toDegrees(Math.atan2(mouseX - spacemarine.getX(),
            mouseY - spacemarine.getY()));
    if (angle < 0)
        angle += 360;
    spacemarine.setRotation(angle * -1);
    return angle;
}

public float rotateAlien(Sprite s, float posX, float posY) {
    float angle = 0;
    float mouseX = 0;
    float mouseY = 0;
    mouseX = posX;
    mouseY = posY;
    angle = (float) Math.toDegrees(Math.atan2(mouseX - s.getX(), mouseY - s.getY()));
    if (angle < 0)
        angle += 360;
    s.setRotation(angle * -1);
    return angle;
}

@Override
public void render(float delta) {
    float angle;
    moveAlien();
    Gdx.gl.glClearColor(0, 0, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    world.step(Gdx.graphics.getDeltaTime(), 6, 2);
    angle = rotateMarine();
    rotateAlien(alien, spacemarine.getX(),
            spacemarine.getY());
    if (Gdx.input.isKeyPressed(Input.Keys.W) == true
            && spacemarine.getY() < 560) {
        Marinebody.setTransform(spacemarine.getX(), spacemarine.getY() + 4,
                angle);
    }
    if (Gdx.input.isKeyPressed(Input.Keys.S) == true
            && spacemarine.getY() > 0) {
        Marinebody.setTransform(spacemarine.getX(), spacemarine.getY() - 4,
                angle);
    }
    if (Gdx.input.isKeyPressed(Input.Keys.D) == true
            && spacemarine.getX() < 920) {
        Marinebody.setTransform(spacemarine.getX() + 4, spacemarine.getY(),
                angle);
    }
    if (Gdx.input.isKeyPressed(Input.Keys.A) == true
            & spacemarine.getX() > 8) {
        Marinebody.setTransform(spacemarine.getX() - 4, spacemarine.getY(),
                angle);
    }
    alien.setPosition(Alienbody.getPosition().x, Alienbody.getPosition().y);
    spacemarine.setPosition(Marinebody.getPosition().x, Marinebody.getPosition().y);
    batch.begin();
    spacemarine.draw(batch);
    alien.draw(batch);
    batch.end();
    // stage.act();
    // stage.draw();
}

```

# Answer
I had the solution for awhile, but I forgot to post. Here's the method to move a list of enemies towards the player.

```
public void moveAlien() {

for (Aliens a : aliens) { //List of Aliens (Enemy)
    Sprite s = a.getSprite(); //Get current enemy's sprite
    float targetX = spacemarine.getX(); //Player's X
    float targetY = spacemarine.getY(); //Player's Y
    float spriteX = s.getX(); //Enemy's X
    float spriteY = s.getY(); //Enemy's Y
    float x2 = s.getX(); //Enemy's new X
    float y2 = s.getY(); //Enemy's new Y
    float angle; // We use a triangle to calculate the new trajectory
        angle = (float) Math
                .atan2(targetY - spriteY, targetX - spriteX);
        x2 += (float) Math.cos(angle) * 125
                * Gdx.graphics.getDeltaTime();
        y2 += (float) Math.sin(angle) * 125
                * Gdx.graphics.getDeltaTime();
        s.setPosition(x2, y2); //Set enemy's new positions.
    }

```

}
> 1 votes

# Answer
Try using vector math instead of cos/sin angles. Something like this might work for you;

```
public void moveAlien() {
    float velocity = 50;

    Vector2 ap = new Vector2(AlienBody.getPosition());
    Vector2 mp = new Vector2(Marinebody.getPosition());

    Vector2 delta = mp.sub(ap).nor(); // This is not a unit vector pointing in the direction from ap to mp

    // Take alien current position and add the delta times velocity times delta-time
    Vector2 newPos = new Vector2(AlienBody.getPosition());
    newPos.add(delta.mul(velocity * Gdx.graphics.getDeltaTime()));

    // At this point newPos has the new position of the alien, now you just need to apply that to
    // the AlienBody position
}

```

I can't see in your code how you apply the newly created position `vAlien` to the alien body, so I've left that out. But at the end of my `moveAlien` method, take `newPos` and set that to the position of the `AlienBody`.
> 2 votes

---
Tags: java, libgdx, jbox2d
---


# Question
Title: How can I calculate the future position of my moving object?
I'm relatively new to games development and I have a 2D game where the playing area is an enclosed rectangle with width w and infinite height. In the playing area there is a ball. A gravity force of strength G acts on the ball. The ball starts at position p and has an initial velocity of v.

How would I calculate the position the ball will be at when it reaches the specified height h. I have a function setup using the following parameters:

```
bool CalculateXPositionAtHeight(float height, Vector2 position, Vector2 velocity, float Gravity, float width, float& xPosition);

```
* The playing area doesn’t have any boundary at the top, so no collision ever happens with it.
* The ball can be considered as a point.
* There are no precision issues and everything can easily fit in a float.
* There is no air resistance.
* All collisions are perfect without any energy loss.
* If the ball hits the bottom it won’t bounce.

# Answer
> 2 votes
Like Pieter mentioned, you can use 1D kinetic equation for height, which in your case will come to:

\\$h = p + vt + 0.5at^2\\$

where a is the acceleration due to gravity. You can then use the quadratic equation to solve for t. Once you have t, you can use the kinetic equations again to calculate how far the ball has traveled width ways. This would tell you where the ball was if there were no walls. Assuming the the walls have no friction, it should be pretty obvious how to figure out where the ball would be between the walls.

If the walls do not just directly reflect the velocity, then you need to calculate the time at which the ball hits the wall, and then repeat with the new velocity until the ball reaches the ground.

Assuming gravity is a negative number, the following code should work:

```
bool CalculateXPositionAtHeight(float height, Vector2 position, Vector2 velocity, float Gravity, float width, float& xPosition)
{
    // kinetic equation for y is: y = position.y + velocity.y * t + 0.5 * Gravity * t^2
    // we want to find when y = height, and have the equation in the form at^2 + bt + c = 0
    // which gives the following:
    float a = Gravity * 0.5f;
    float b = velocity.y;
    float c = position.y - height;

    // the quadratic formula can then be used to solve for t
    // we know that gravity will always be negative and time is positive, so only care about that solution
    float t = (sqrtf(b * b - 4.0f * a * c) - b) / (2.0f * a);

    // now that we have t, we can solve the kinetic equation for x
    // there is no acceleration in the x direction, so this just becomes:
    float x = position.x + t * velocity.x;

    // the following code handles the ball bouncing off the walls
    x = fmodf(x, 2.0f * width);
    if (x > width)
    {
        x = 2.0f * width - x;
    }

    xPosition = x;

    return true;
}

```

# Answer
> 1 votes
@Richard Byron explained well and gave a well-made sample code.

I think it's better to add additional information about the basic math.
I leaved out the wall collision.

Sorry for bad hand writing an drawing.

---

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


# Question
Title: What Shading/Rendering techniques are being used in this image?
My previous question wasn't clear enough. From a rendering point of view what kind of techniques are used in this image as I would like to apply a similar style (I'm using OpenGL if that matters):

http://alexcpeterson.com/

My specific questions are:

How is that sun glare made? How does the planet look "cartoon" like? How does the space around the planet look warped/misted? How does the water look that good?

I'm a beginner so any information/keywords on each question would be helpful so I can go off and learn more. Thanks

# Answer
1) The planet is "cartoon" like because it doesn't use any textures and has a large detail size.

2) The misted effect I'd call atmospheric scattering. There's a GPU Gem about this: http://http.developer.nvidia.com/GPUGems2/gpugems2\_chapter16.html. Alternatively (or additionally), add a fresnel effect to your shader. Alternatively, I've seen people fake this without a shader by adding a ring around the planet that always faces the camera and has a gradient texture appropriately mapped.

3) One thing to remember is that water has much higher specularity than land or clouds. Look at reference pictures of Earth, for example:
> 7 votes

# Answer
There are a few broad approaches to generating a tesselated, spherical surface mesh. Here a couple of the more common ones...

* Construct a cube with densely-subdivided planes, then expand those planes outward into a spherical form: this is simple enough -- for each surface point, calculate a vector from the origin (centre of cube) to that point, normalize the vector such that the point is at distance one from the origin, then multiply the position vector by your desire planetary radius. The nice thing about this approach is that triangulation is extremely simple, because you simply subdivide each plane of the cube as though it were a grid, and then split into two triangles per grid cell (you'll have seen this many times before).
* Construct some set number of points at the planet's origin (core), and push them out to some distance using randomly-rotated quaternions; the distribution over the sphere surface can then be evened out using physical methods; think of how a fibre-optic lamp's fibres spread out fairly evenly over some space, because of physics:

Gravity creates a similar effect here, to what would occur if each fibre-tip repelled the other as though with atomic forces, which is exactly the approach you could apply to create a more even distribution (related to the concept of Lloyd Relaxation, which can also be applied in three dimensions). Once you have these points, you can use something like Delaunay Triangulation (or any other triangulation algorithm you wish) to triangulate the points into a fully-connected mesh.

If you are constructing a voxel-based world...

* 3D cells / voxels provide a simplistic, if brute-force / less performant option. The viability of this approach depends very much on your planetary radius and desired surface resolution, and whether or not you use accelerative, spatial subdivision structures like octrees or KD-trees. Basically, create a cubic voxel volume with a diameter equalling that of your desired planetary body. For every voxel (likely to be in the millions if not billions or trillions), perform a distance check from the centre of the world (i.e. centre of the cubic volume), and if the distance is greater than your desired planetary radius, remove that voxel from the grid. Clearly, this is an `O(n^3)` operation involving multiple square root operations per 3D-vector radial magnitude check, meaning it will be very costly indeed even for a world diameter of 1000 voxels (10^9 checks). However, this may be acceptable for worlds which are generated in their entirety before play commences.
> 5 votes

# Answer
Two things others didn't mention:

The ripples in the water surface are made by Bump-mapping, where you use a texture to add fake depth to your objects(a.k.a. Normal mapping). You could even animate this with noise, so you don't need a texture, just GLSL noise generation.(Quite simple and awesome effect)

The very subtle "fog" around the planet might be a camera-facing billboard with a very low alpha and some foggy texture. And the annoying bands that it creates are probably because they didn't use HDR.
> 3 votes

---
Tags: opengl, shaders, rendering, graphics-programming, post-processing
---


# Question
Title: How can I rotate a quad around it's center?
My code is:

```
GL11.glPushMatrix();

// rotate around center
GL11.glTranslatef(-200/2, -200/2, 0);
GL11.glRotatef(30, 0.0f, 0.0f, 1);
GL11.glTranslatef(200/2, 200/2, 0);
// draw quad
GL11.glBegin(GL11.GL_QUADS);
GL11.glTexCoord2f(0f,0.5f);
GL11.glVertex3f(50,50,1);
GL11.glTexCoord2f(0.5f,0.5f);
GL11.glVertex3f(50+200,50,1);
GL11.glTexCoord2f(0.5f,0f);
GL11.glVertex3f(50+200,50+200,1);
GL11.glTexCoord2f(0f,0f);
GL11.glVertex3f(50,50+200,1);
GL11.glEnd();

GL11.glPopMatrix();

```

and it's not rotating it around the center, am I doing this correctly? if not how would I?

# Answer
> 1 votes
Your problem is your translation matrices. **You are not translating enough**.

Your quad starts at position *(50, 50)* and is of size *(200, 200)*. That means we have 4 vertices:

```
( 50,  50)
(250,  50)
(250, 250)
( 50, 250)

```

You are applying a translation of *200/2 (100)* on both axis, which will transform your vertices to these:

```
(-50, -50)
(150, -50)
(150, 150)
(-50, 150)

```

As you can see, these vertices are not centered. **There is something that is missing: you need to translate according to your initial position *(50, 50)* too**. So the translation you need to make would not be *200/2*, but *200/2 + 50*, which equals *150* and transforms the vertices like so:

```
(-100, -100)
( 100, -100)
( 100,  100)
(-100,  100)

```

Now we're talking! That seems way better! But don't forget to apply the opposite translation for the quad to come back to it's position. It should give this code:

```
// rotate around center
GL11.glTranslatef(-(200/2 + 50), -(200/2 + 50), 0); // Or put -150 for X and Y
GL11.glRotatef(30, 0.0f, 0.0f, 1);
GL11.glTranslatef(200/2 + 50, 200/2 + 50, 0); // Or put 150 for X and Y

```

---
Tags: opengl, java, lwjgl
---


title: 32 Bit colors difference

text:
# Question
Title: 32 Bit colors difference
Im going through a tutorial to create a basic directx framework, and i've noticed that in there (and other tutorials, when i checked out) use `DXGI_FORMAT_R32G32B32A32_FLOAT` inside the input element description. is there any reason to use this in a program over `DXGI_FORMAT_R8G8B8A8_<something>` in terms of noticeable graphical difference? im thinking quadrupling the memory involved to store color would be a little heavy for larger programs.

Also, i don't know if i have this right, but pure coloring isn't used much in more complex programs, and textures are used instead. so does this really matter?

# Answer
For HDR (high dynamic range) rendering, you would want to use more than 8 bits usually - since you are not only encoding color, but also intensity of the light much more precisely (and thus over a greater range) than 8 bit RGB can do.

Of course, your monitor can likely only display 8 bit RGB (if even that), so this only matters if you are actually doing some processing on the data before displaying it using ordinary 8 bit RGB - as is often done with HDR rendering (applying bloom, tone mapping, more realistic lighting...)

So if you use HDR rendering, you sometimes want more bits to more accurately represent the color over a wide range of intensities.

For the CPU side, operating on floating point color values is probably more convenient than working with integers when it comes to operations other than addition/subtraction, as well.

Even if you didnt use HDR rendering, you could use the higher color range to implement dithering on the GPU. This would reduce the color banding effect you get due to 8 bits not being enough for creating visually smooth gradients of color in some cases.

For 'normal' uses of textures, you wont be doing anything that would significantly benefit from more than 8 bits per component.
> 8 votes

---
Tags: c++, directx
---


# Question
Title: Is it really necessary to test collisions against triangle vertices and edges?
I'm reading this paper, and using it to perfect the narrow phase collision system for my game engine. To make the question as self-contained as possible, the essential strategy used to detect collisions is the following: scale your axes to reduce the problem to unit sphere/triangle collision, calculate the triangle plane and such, and see if the closest intersection with the plane is inside the triangle itself (probably using barycentric coordinates).

However, beyond this point (going into section 3.4 in the paper), I begin to get confused. He starts talking about some relatively intensive mathematical calculations to test whether the sphere/plane intersection point is on one of the triangle's *edges or vertices* after testing whether this point is inside the triangle. My question is: why should it possibly be necessary to spend so much computing power on checking against the edges of the triangle? More specifically, why does the original calculation using barycentric coordinates not necessarily account itself for vertices and edges?

# Answer
> 2 votes
I'm sorry for answering my own question: I figured it out and it was just a matter of correct visualization. The inside-triangle check only works if the sphere meets the triangle head-on: in other words, the point of tangency between the sphere and the plane occurs exactly at the correct time. In the other case, if the sphere passes by the triangle such that the initial point of contact is not directly inside the triangle, it waits through the time interval between the two points of tangency to see if any part of the sphere hits the edge of the triangle. Hopefully this isn't too confusing, as I don't have any way of creating relevant diagrams.

---
Tags: collision-detection, mathematics
---


# Question
Title: MonoGame deltaTime isn't the same in Draw function as in Update function
In the Update function `gameTime.elapsedGameTime.TotalSeconds` always gives me **0.01666666667** which is the deltaTime value for 60 FPS, no matter if the FPS is 30 it always shows me **0.01666666667** but the Draw function on the other hand shows **0.03333333333** if the FPS is 30.

Is this a bug or is this how it is meant to be? Should I just create a variable called deltaTime and make it equal to `gameTime.elapsedGameTime.TotalSeconds` in the Draw function? Maybe this is a problem on Macs only

**(I'm on a mac and I'm using Xamarin Studio MonoMac to build the project)**

# Answer
There is no need for the `Update()` to be called as frequent as `Draw()`. Your `Draw()` method is generally called the same or less times than your `Update()`, because games are usually not CPU intense but rather GPU. So locking on 30FPS is normal (or even 15 or 7,5). However, there are probably problems with your code's efficiency, or your mac hardware is really bad, to not be able to handle 60FPS.

The reason that `Update()` being called more times than `Draw()` is acceptable in games, is because even though the visuals doesn't feel smooth, the game still runs at a higher frame rate, so the input you give, gets processed inside your game. So, it feels like the gameplay is the same, but you just don't see as many frames as you would hope to see.

This is why you need to keep in mind that `Draw()` should not change your game's variables or game's logic. This should only be done in the `Update()` method.
> 2 votes

---
Tags: monogame
---


title: Simplex noise heightmap

text:
# Question
Title: Simplex noise heightmap
I'm currently working on a game with an "infinite" programmatically generated terrain. The terrain is being generated by creating a heightmap using simplex noise.

I've followed a tutorial and ended up with the following code (it's vb.net by the way):

```
Public Shared Function GetNoise(ByVal xin As Double, ByVal yin As Double, ByVal zin As Double) As Single
        Dim n0, n1, n2, n3 As Double ' Noise contributions from the four corners
        ' Skew the input space to determine which simplex cell we're in
        Dim s As Double = (xin + yin + zin) * F3 ' Very nice and simple skew factor for 3D
        Dim i As Integer = fastfloor(xin + s)
        Dim j As Integer = fastfloor(yin + s)
        Dim k As Integer = fastfloor(zin + s)
        Dim t As Double = (i + j + k) * G3
        Dim X00 As Double = (i - t) ' Unskew the cell origin back to (x,y,z) space
        Dim Y00 As Double = (j - t)
        Dim Z00 As Double = (k - t)
        Dim x0 As Double = (xin - X00) ' The x,y,z distances from the cell origin
        Dim y0 As Double = (yin - Y00)
        Dim z0 As Double = (zin - Z00)
        ' For the 3D case, the simplex shape is a slightly irregular tetrahedron.
        ' Determine which simplex we are in.
        Dim i1, j1, k1 As Integer ' Offsets for second corner of simplex in (i,j,k) coords
        Dim i2, j2, k2 As Integer ' Offsets for third corner of simplex in (i,j,k) coords
        If (x0 >= y0) Then
            If (y0 >= z0) Then ' X Y Z order
                i1 = 1
                j1 = 0
                k1 = 0
                i2 = 1
                j2 = 1
                k2 = 0
            ElseIf (x0 >= z0) Then ' X Z Y order
                i1 = 1
                j1 = 0
                k1 = 0
                i2 = 1
                j2 = 0
                k2 = 1
            Else ' Z X Y order
                i1 = 0
                j1 = 0
                k1 = 1
                i2 = 1
                j2 = 0
                k2 = 1
            End If
        Else                ' x0<y0
            If (y0 < z0) Then ' Z Y X order
                i1 = 0
                j1 = 0
                k1 = 1
                i2 = 0
                j2 = 1
                k2 = 1
            ElseIf (x0 < z0) Then ' Y Z X order
                i1 = 0
                j1 = 1
                k1 = 0
                i2 = 0
                j2 = 1
                k2 = 1
            Else ' Y X Z order
                i1 = 0
                j1 = 1
                k1 = 0
                i2 = 1
                j2 = 1
                k2 = 0
            End If
        End If
        ' A step of (1,0,0) in (i,j,k) means a step of (1-c,-c,-c) in (x,y,z),
        ' a step of (0,1,0) in (i,j,k) means a step of (-c,1-c,-c) in (x,y,z), and
        ' a step of (0,0,1) in (i,j,k) means a step of (-c,-c,1-c) in (x,y,z), where
        ' c = 1/6.
        Dim x1 As Double = ((x0 - i1) + G3) ' Offsets for second corner in (x,y,z) coords
        Dim y1 As Double = ((y0 - j1) + G3)
        Dim z1 As Double = ((z0 - k1) + G3)
        Dim x2 As Double = ((x0 - i2) + (2 * G3)) ' Offsets for third corner in (x,y,z) coords
        Dim y2 As Double = ((y0 - j2) + (2 * G3))
        Dim z2 As Double = ((z0 - k2) + (2 * G3))
        Dim x3 As Double = ((x0 - 1) + (3 * G3)) ' Offsets for last corner in (x,y,z) coords
        Dim y3 As Double = ((y0 - 1) + (3 * G3))
        Dim z3 As Double = ((z0 - 1) + (3 * G3))
        ' Work out the hashed gradient indices of the four simplex corners
        Dim ii As Integer = (i And 255)
        Dim jj As Integer = (j And 255)
        Dim kk As Integer = (k And 255)
        Dim gi0 As Integer = permMod12((ii + perm((jj + perm(kk)))))
        Dim gi1 As Integer = permMod12((ii + (i1 + perm((jj + (j1 + perm((kk + k1))))))))
        Dim gi2 As Integer = permMod12((ii + (i2 + perm((jj + (j2 + perm((kk + k2))))))))
        Dim gi3 As Integer = permMod12((ii + (1 + perm((jj + (1 + perm((kk + 1))))))))
        ' Calculate the contribution from the four corners
        Dim t0 As Double = (0.6 - ((x0 * x0) - ((y0 * y0) - (z0 * z0)))) ' change to 0.5 if you want

        If (t0 < 0) Then
            n0 = 0
        Else
            t0 = (t0 * t0)
            n0 = (t0 * (t0 * dot(grad3(gi0), x0, y0, z0)))
        End If

        Dim t1 As Double = (0.6 - ((x1 * x1) - ((y1 * y1) - (z1 * z1)))) ' change to 0.5 if you want

        If (t1 < 0) Then
            n1 = 0
        Else
            t1 = (t1 * t1)
            n1 = (t1 * (t1 * dot(grad3(gi1), x1, y1, z1)))
        End If

        Dim t2 As Double = (0.6 - ((x2 * x2) - ((y2 * y2) - (z2 * z2)))) ' change to 0.5 if you want

        If (t2 < 0) Then
            n2 = 0
        Else
            t2 = (t2 * t2)
            n2 = (t2 * (t2 * dot(grad3(gi2), x2, y2, z2)))
        End If

        Dim t3 As Double = (0.6 - ((x3 * x3) - ((y3 * y3) - (z3 * z3)))) ' change to 0.5 if you want

        If (t3 < 0) Then
            n3 = 0
        Else
            t3 = (t3 * t3)
            n3 = (t3 * (t3 * dot(grad3(gi3), x3, y3, z3)))
        End If
        ' Add contributions from each corner to get the final noise value.
        ' The result is scaled to stay just inside [-1,1] (now [0, 1])
        Return (CType(((32 * (n0 + (n1 + (n2 + n3)))) + 1), Single) * 0.5!) ' change to 76.0 if you want

    End Function

```

I've been told that a function like this should return a value between -1 and 1. However, calling GetNoise(0,2,0) for instance returns -6,240867.

Since the returned value of most points next to eachother are quite close to eachother, I believe most of the code is correct. However, with a few of these weird results, my heightmap obviously looks terrible.

Can anybody explain what I'm doing wrong/what I have missed? I've read quite some info as to how perlin/simplex noise works, and I understand the basics. I must however admit that I don't yet fully understand everything that comes with it.\`

EDIT: As Alexandre Desbiens mentioned, it may be best to show you my heightmap output. Because rgb values don't allow negative values, I can only show you the map I created using the height data. here it is:

# Answer
> 4 votes
Assuming you have translated this from the original Java code it looks like you have been a bit careless in adding brackets in a few places. For example the original code has:

```
double t0 = 0.6 - x0 * x0 - y0 * y0 - z0 * z0;

```

while you have:

```
Dim t0 As Double = (0.6 - ((x0 * x0) - ((y0 * y0) - (z0 * z0))))

```

which if you remove the brackets is actually:

```
Dim t0 As Double = 0.6 - x0 * x0 + y0 * y0 + z0 * z0

```

While I'm not familiar with VB.NET I think most of the brackets you added are not required and end up making things more difficult to understand as well as introducing errors like this. It looks like you did the same thing in the `t1`, `t2` and `t3` variables and possibly elsewhere.

---
Tags: xna, heightmap, noise, vb.net
---


# Question
Title: Efficient removal and adding of Components in ECS
i'm working with the Ashley Entity-Component-System (related to libGDX) to program a server-side simulation for an online game and i stumbled upon a serious performance drawback, that is probably caused by how it manages Entity-Sets:

"**Family**", these are basically descriptors for Entities with a **specific set of components**. Removing a component is an costly operation because the Family-instance needs to search through an Array of entities that it manages and remove the Entity from that Array. This is O(n) for every single removal at worst.

**And here's my problem:** I have a Family that describes all Entities that do have a position and a velocity component. If i want to remove the velocity-component, for example, to turn it into an static entity and re-add it later to make it move again, this completely eats up my budget of frame time (50ms-\>20fps) with only ~7000 Entities changing Family back and forth within a frame. At the same time, moving 100000 entities takes only about 15ms at max (without multithreading ~30ms).

I have thought of these options yet:

-Change the data-structure that the Entities are sorted into, this creates new problems, but may still be the most viable Solution, i thought of mapping the Entity IDs to Objects or keeping them in a sorted data-structure.

-Sort everything once after a System has finished execution, requires redesigning a lot of code but probably reduces the time-consumption greatly

-Changing the Entity System, i know of Artemis, but it would be great if you could point me at something else for Java if you know a library that does it better.

-This whole thing may not even become a bottleneck when running the final game-simulation, it might or might not, so just going on and thinking about this later may be acceptable, since I'm probably over-engineering again.

What do you think is the way to go?

# Answer
**Disclaimer:** artemis-odb dev here.

> -Changing the Entity System, i know of Artemis, but it would be great if you could point me at something else for Java if you know a library that does it better.

I'm not sure whether you're referring to vanilla artemis or artemis-odb, but the latter improves on performance considerably with regards to mutating entities. You can find some benchmarks over at junkdog/entity-system-benchmarks

> -Change the data-structure that the Entities are sorted into, this creates new problems, but may still be the most viable Solution, i thought of mapping the Entity IDs to Objects or keeping them in a sorted data-structure.
>
> -Sort everything once after a System has finished execution, requires redesigning a lot of code but probably reduces the time-consumption greatly

This approach can potentially reduce overhead by quite a bit. BitSets are basically your friend here - or should be. Unfortunately, Ashley doesn't recycle ids, making a lot of indexed look-ups difficult/impossible. If you don't mind modifying ashley a bit:

* Entity ids should be recycled: enables representing a lot of internals with bitsets
* An Entity System's primary entity data source is a bitset representing the active entities' ids. Upon inserting/removing entities, the `bitset[entity.id]` is toggled, and the system sets a dirty flag.
* For each system; prior to processing, check if system is dirty. If so, populate the system's array-of-entities from the bits in the bitset. A side effect of this is approach is that entities are always processed in ascending id order (generally, this improves performance somewhat, at least on the JVM).

A poor man's bitset would be a LongMap \- this would probably be the least invasive approach, but wouldn't give the same level of performance boost.
> 4 votes

# Answer
So, i figured out how to do it quick and dirty, i subclassed Array (libGDX.util) to allow for faster removal of Entities and then i swapped it with the normal Array inside the Engine class of Ashley:

```
package de.vatterger.threadedSim.tools;

import com.badlogic.ashley.core.Entity;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.ObjectMap;

public class EntityArray extends Array<Entity> {
    private ObjectMap<Long, Integer> map = new ObjectMap<Long, Integer>();

    public EntityArray() {
        super(false, 16);
    }

    @Override
    public void add(Entity value) {
        map.put(value.getId(), size);
        super.add(value);
    }

    @Override
    public boolean removeValue(Entity value, boolean identity) {
        Integer i = map.remove(value.getId());
        if(i!=null && identity)
            return removeIndex(i) != null;
        else
            return super.removeValue(value, identity);
    }

    @Override
    public Entity removeIndex (int index) {
        if (index >= size) throw new IndexOutOfBoundsException("index can't be >= size: " + index + " >= " + size);
        Object[] items = this.items;
        Entity value = (Entity)items[index];
        size--;
        if (ordered) {
            System.arraycopy(items, index + 1, items, index, size - index);
        } else {
            items[index] = items[size];
            map.put(((Entity)items[index]).getId(), index);
        }
        items[size] = null;
        return value;
    }
    @Override
    public void clear() {
        map.clear();
        super.clear();
    }
}

```

**This doesn't support all features of its superclass Array, only enough to be used with Ashleys Family-Assignment-Code, so it's probably very buggy without further editing it!**
> 1 votes

---
Tags: java, architecture, entity-system, data-structure
---


# Question
Title: OpenGL: How to map point inside frustrum to normal device coordinates (NDC)?
I read this article http://www.songho.ca/opengl/gl\_projectionmatrix.html. It's explain how calculate projection matrix coefficients. But I completely can't understand how author perform mapping from frustrum to NDC.

Why xn perpendicular to xp? I can't imagine it. Maybe someone can explain it? Or share useful source.

# Answer
I think I found answer. I inattentively read article.

> **"Next, we map xp and yp to xn and yn of NDC with linear relationship."**

So, xn is linear function from xp. (http://www.mathsisfun.com/algebra/linear-equations.html) And goal is find value of xn in \[-1, 1\] range.

Anyway I didn't understand how author find bottom projection row W (0,0,-1,0).
> 1 votes

---
Tags: opengl, opengl-es, frustum, clipping, projection-matrix
---


# Question
Title: How to freeze rotation with a Rigidbody 2D?
So I am looking to freeze rotation in the Y axis on a Rigidbody 2D. I'm not sure how to set this in my code. This is what I have so far, can you point out my errors?

```
public class PlayerMovement : MonoBehaviour
{

    public float speed;
    public float height;
    GameObject Player;
    RigidbodyConstraints pos;
    Transform P;
    // Update is called once per frame

    void OnAwake()
    {
        Player = GameObject.Find ("Player");
        pos = RigidbodyConstraints.FreezeRotationY;
        Rigidbody2D. = pos;
    }

    void FixedUpdate ()
    {
        if (Input.GetButton ("Horizontal"))
        {
            transform.Translate (Vector3.right * speed * Time.deltaTime);
        }

        if( Input.GetButton("Left"))
        {
            transform.Translate (Vector3.left * speed * Time.deltaTime);
        }

        if (Input.GetButton ("Jump"))
        {
            transform.Translate (Vector3.up * height * Time.deltaTime);
        }

    }
}

```

# Answer
First of all, since you're working in 2D, you'll want to use the type `RigidbodyConstraints2D` as opposed to just `RigidbodyConstraints`.

Secondly, you can't freeze the y rotation on 2D rigidbodies, only in the z axis, which you can do by saying:

```
pos = RigidbodyConstraints2D.FreezeRotation;

```

Equally, you could just set it in the inspector with the gameobject selected, which would save you the hassle of all this code.

Lastly, `Rigidbody2D. = pos;` in your `OnAwake()` function, which by the way should just be `Awake()`, isn't doing anything. In Unity 5 you can't call the rigidbody directly anymore, you have to find the component.

I'll leave this here to get you on the right track. :)

Good Luck and keep at it!
> 4 votes

# Answer
Expanding upon Anthony Ngo's answer

As of Unity 5.1 you can simply do it in the editor:

Source: http://unity3d.com/unity/whats-new/unity-5.1 To get to that part you can probably do `Ctrl` \+ `F` then type `rigidbody`. Your browser should then highlight that part.
> 1 votes

---
Tags: unity, c#, rigid-body-dynamics
---


# Question
Title: Voxel terrain collision detection with AABBs
I'm working on implementing collision detection on voxel terrain (Like Minecraft) with AABBS.

Right now, I have it so I can tell if a point is within a voxel or not, I do this by having a 2D byte array of active voxels. If a byte at any index is 0, the voxel is air. If its 1, its solid. Right now I'm just testing to see if the voxel at the player's position vector is solid or not.

My problem is, I now wish to implement AABBs to get more precise detection, but I have no idea how to do it without checking if all the voxels within the AABB are solid. That might now be a problem for games like Minecraft, where there would only have to be about 1 extra voxel check, but the voxels in my game are much smaller (The player's dimensions are about 4x10x4), so I would have to check a lot of voxels.

Ive seen one or two other people having a issue similar, but I didn't find the answers they got clear enough, and so I come here asking for your help.

Thanks.

# Answer
Checking all the voxels should not be that bad - modern CPUs can often do brute force processing faster than 'clever' solutions because those clever solutions often contain a lot of branching and jumping around in memory which is very costly compared to simple arithmetic or iterating over an array.

If youre using a low level enough language, you can try optimizing the brute force method to be cache friendly (linear access order, get rid of indirection, dont store unneeded 'cold' data interleaved with 'hot' data you need).

Other than that, I can suggest some optimizations:

1. Instead of checking the entire AABB volume for intersections, only check for intersections against the AABB faces, and only in the directions where the AABB is moving (dot product of face normal and velocity direction \> 0). Add multiple iterations to the physics to prevent the AABB from moving more than a single voxel-width per frame so it wont tunnel through stuff.
2. Only check those face intersections when the particular face has transitioned to a different 2 dimensional plane of voxels on its axis (since only then will it intersect a different set of voxels than last frame)
3. If you have massive AABBs, you can add a hierarchial data structure like an octree to quickly skip checking large empty areas of voxels (usually only the bottom part of the AABB will be colliding and rest will be air, so skipping all that air would be a speedup)

You can go much further by caching some information about the collisions but it will start affecting your ability to easily implement other game features that depend on collision checking so Im not going to suggest anything. Go with the brute force approach if performance is not a problem - its the least restricting one IMO.
> 2 votes

---
Tags: collision-detection, voxels
---


# Question
Title: Keep Image from Drawing Outside Game Area
I was playing around with a pygame tutorial (link for those interested). One thing the tutorial has you do is create a cloud that crosses the screen. Now, the game has a small bit bar at the bottom which is used for information and is outside the game area. The problem is that the cloud is drawn outside the game area, so you see the cloud cross over the user information. I am new to this, so I am not sure what I need to do or what question to ask to fix this. Thanks.

Wade

Here is the code I am using:

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

pygame.display.set_caption('M I N E C R A F T -- 2 D')
pygame.display.set_icon(pygame.image.load('player.png'))

fpsClock = pygame.time.Clock()

#constants representing colours
BLACK = (0,   0,   0  )
BROWN = (153, 76,  0  )
GREEN = (0,   255, 0  )
BLUE  = (0,   0,   255)
WHITE = (255, 255, 255)

#cloud position
cloudx = -200
cloudy = 0

#constants representing the different resources
DIRT  = 0
GRASS = 1
WATER = 2
COAL  = 3
CLOUD = 4

#a dictionary linking resources to textures
textures =   {
                DIRT   : pygame.image.load('dirt.png'),
                GRASS  : pygame.image.load('grass.png'),
                WATER  : pygame.image.load('water.png'),
                COAL   : pygame.image.load('coal.png'),
                CLOUD  : pygame.image.load('cloud.png')
            }

inventory =   {
                DIRT   : 0,
                GRASS  : 0,
                WATER  : 0,
                COAL   : 0
            }

#useful game dimensions
TILESIZE  = 20
MAPWIDTH  = 30
MAPHEIGHT = 20

#the player image
PLAYER = pygame.image.load('player.png')
#the position of the player [x,y]
playerPos = [0,0]

#a list of resources
resources = [DIRT,GRASS,WATER,COAL]
#use list comprehension to create our tilemap
tilemap = [ [DIRT for w in range(MAPWIDTH)] for h in range(MAPHEIGHT) ]

#set up the display
pygame.init()
DISPLAYSURF = pygame.display.set_mode((MAPWIDTH*TILESIZE, MAPHEIGHT*TILESIZE + 50))

#add a font for our inventory
INVFONT = pygame.font.Font('FreeSansBold.ttf', 18)

#loop through each row
for rw in range(MAPHEIGHT):
    #loop through each column in that row
    for cl in range(MAPWIDTH):
        #pick a random number between 0 and 15
        randomNumber = random.randint(0,15)
        #if a zero, then the tile is coal
        if randomNumber == 0:
            tile = COAL
        #water if the random number is a 1 or a 2
        elif randomNumber == 1 or randomNumber == 2:
            tile = WATER
        elif randomNumber >= 3 and randomNumber <= 7:
            tile = GRASS
        else:
            tile = DIRT
        #set the position in the tilemap to the randomly chosen tile
        tilemap[rw][cl] = tile

while True:

    DISPLAYSURF.fill(BLACK)

    #get all the user events
    for event in pygame.event.get():
        #if the user wants to quit
        if event.type == QUIT:
            #and the game and close the window
            pygame.quit()
            sys.exit()
        #if a key is pressed
        elif event.type == KEYDOWN:
            #if the right arrow is pressed
            if event.key == K_RIGHT and playerPos[0] < MAPWIDTH - 1:
                #change the player's x position
                playerPos[0] += 1
            if event.key == K_LEFT and playerPos[0] > 0:
                #change the player's x position
                playerPos[0] -= 1
            if event.key == K_UP and playerPos[1] > 0:
                #change the player's x position
                playerPos[1] -= 1
            if event.key == K_DOWN and playerPos[1] < MAPHEIGHT -1:
                #change the player's x position
                playerPos[1] += 1
            if event.key == K_SPACE:
                #what resource is the player standing on?
                currentTile = tilemap[playerPos[1]][playerPos[0]]
                #player now has 1 more of this resource
                inventory[currentTile] += 1
                #the player is now standing on dirt
                tilemap[playerPos[1]][playerPos[0]] = DIRT

            #placing dirt
            if (event.key == K_1):
                #get the tile to swap with the dirt
                currentTile = tilemap[playerPos[1]][playerPos[0]]
                #if we have dirt in our inventory
                if inventory[DIRT] > 0:
                    #remove one dirt and place it
                    inventory[DIRT] -= 1
                    tilemap[playerPos[1]][playerPos[0]] = DIRT
                    #swap the item that was there before
                    inventory[currentTile] += 1

    #loop through each row
    for row in range(MAPHEIGHT):
        #loop through each column in the row
        for column in range(MAPWIDTH):
            #draw the resource at that position in the tilemap, using the correct image
            DISPLAYSURF.blit(textures[tilemap[row][column]], (column*TILESIZE,row*TILESIZE))

    #display the player at the correct position
    DISPLAYSURF.blit(PLAYER,(playerPos[0]*TILESIZE,playerPos[1]*TILESIZE))

    #display the cloud
    DISPLAYSURF.blit(textures[CLOUD].convert_alpha(),(cloudx,cloudy))
    #move the cloud to the left slightly
    cloudx+=1
    #if the cloud has moved past the map
    if cloudx > MAPWIDTH*TILESIZE:
        #pick a new position to place the cloud
        cloudy = random.randint(0,MAPHEIGHT*TILESIZE)
        cloudx = -200

    #display the inventory, starting 10 pixels in
    placePosition = 10
    for item in resources:
        #add the image
        DISPLAYSURF.blit(textures[item],(placePosition,MAPHEIGHT*TILESIZE+20))
        placePosition += 30
        #add the text showing the amount in the inventory
        textObj = INVFONT.render(str(inventory[item]), True, WHITE, BLACK)
        DISPLAYSURF.blit(textObj,(placePosition,MAPHEIGHT*TILESIZE+20))
        placePosition += 50

    #update the display
    pygame.display.update()
    fpsClock.tick(24)

```

# Answer
> 2 votes
If you want to limit the cloud to the game area, you can set what is called a `clipping rectangle` (docs). This cuts off anything that is blitted outside the rectangle.

Set it like this, *before* blitting the clouds:

```
clippingRect = Rect(0, 0, MAPWIDTH*TILESIZE, MAPHEIGHT*TILESIZE)
DISPLAYSURF.set_clip(clippingRect)

```

This sets `x, y, width, height` of the clipping rect.

Then disable it like this *before* trying to blit the info-bar:

```
DISPLAYSURF.set_clip(None)

```

I recommend that you read the pygame documentation alongside any and every tutorial.

Your modified cloud drawing code might be like this:

```
clippingRect = Rect(0, 0, MAPWIDTH*TILESIZE, MAPHEIGHT*TILESIZE)
DISPLAYSURF.set_clip(clippingRect)

#display the cloud
DISPLAYSURF.blit(textures[CLOUD].convert_alpha(),(cloudx,cloudy))
#move the cloud to the left slightly
cloudx+=1
#if the cloud has moved past the map
if cloudx > MAPWIDTH*TILESIZE:
    #pick a new position to place the cloud
    cloudy = random.randint(0,MAPHEIGHT*TILESIZE)
    cloudx = -20

DISPLAYSURF.set_clip(None)

```

You should actually enable the clipping rect before drawing the game area and only disable it when you are ready to draw outside.

---
Tags: pygame
---


title: Deterministically shuffling of array

text:
# Question
Title: Deterministically shuffling of array
I couldn't find an answer to this so I'm asking here, I've made a voxel engine and it's working reasonably well, except for a small detail: I have yet to figure out how to seed my simplex noise engine, the internet gave me two suggestions:

Generate simplex of one dimension higher with the fourth axis being the seed, this worked but was painfully slow in comparison.

Shuffle the permutation table, I like this idea. It should (if my understanding of math is correct) yield 512! permutations, however I don't know how to shuffle an array reliably in a deterministic manner, I want the shuffle to be the same every time I use the same seed. so something like shuffle(perm, 12) would return the same every time the seed is 12 but something different when the seed is 22321.

So what I really wish to know is either how to shuffle the permutation table in a fast, reliable and deterministic manner using a seed or a better method for seeding simplex noise.

# Answer
> 1 votes
Here how I 've done it (c#)

```
        private static float[] grad = new float[256];
        private static int[] p = {151,160,137,91,90,15,
 131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23,
 190, 6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33,
 88,237,149,56,87,174,20,125,136,171,168, 68,175,74,165,71,134,139,48,27,166,
 77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244,
 102,143,54, 65,25,63,161, 1,216,80,73,209,76,132,187,208, 89,18,169,200,196,
 135,130,116,188,159,86,164,100,109,198,173,186, 3,64,52,217,226,250,124,123,
 5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42,
 223,183,170,213,119,248,152, 2,44,154,163, 70,221,153,101,155,167, 43,172,9,
 129,22,39,253, 19,98,108,110,79,113,224,232,178,185, 112,104,218,246,97,228,
 251,34,242,193,238,210,144,12,191,179,162,241, 81,51,145,235,249,14,239,107,
 49,192,214, 31,181,199,106,157,184, 84,204,176,115,121,50,45,127, 4,150,254,
 138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180};

```

when I change seed a redefine the the gradient array using the c# random class

```
    private static void InitPerlinPerm(uint seed)
    {
        Random r = new Random((int)seed);
        for (uint i = 0; i < grad.GetLength(0); i++)
        {
            grad[i] = (r.Next(0, 32000) / 32000f);
        }
    }

```

here where I generate values:

```
    private float pseudoRandomFromPerm(int x, int y, int z)
    {
        return grad[(x + p[y + p[z & 255] & 255]) % grad.GetLength(0)];
    }

```

try this without regenerate the grad array or shuffering the p array:

```
    private float pseudoRandomFromPerm(int x, int y, int z)
    {
        return grad[(SEED + x + p[y + p[z & 255] & 255]) % grad.GetLength(0)];
    }

```

---
Tags: c++, voxels, simplex-noise
---