# Question
Title: Java - Adjusting the speed of an object during movement
I am trying to get an object to move (on java canvas) in the same angle but at different speed within the X and Y axis. Below you can see how i have implemented the movement of the object.

```
xPosition += xSpeed;
yPosition += ySpeed;

```

I want the object to be moving at the same angle. But speed change randomly throughout movement across the canvas.

How can I go about dealing with this?

I've tried changing the speed, such as;

```
  xSpeed -= 10;
  ySpeed += 10;

```

Any help would be greatly appreciated.

# Answer
If you want to change magnitude of a vector without altering its direction (its speed without its direction, in your case), you just have to multiply each of its contained number (x and y, in your case) by the same number.

So, once you have defined a precise `xSpeed` and `ySpeed` in your code, you just have to multiply them by the same number:

```
// Will move the object
xPosition += xSpeed;
yPosition += ySpeed;

// Half speed by 2
xSpeed /= 2;
ySpeed /= 2;

// Will move the object on the same direction, but two times less far away.
xPosition += xSpeed;
yPosition += ySpeed;

```

Now it is still up to you to know how you want to "randomize" this speed. One solution could be to store somewhere your original movement on X and Y axis, and a speed factor that you could change from time to time. The code would looks like this in the initialization part:

```
xMovemeent = /* Your original movement on X axis */;
yMovemeent = /* Your original movement on Y axis */;
speed = 1.0; // original speed

```

And then, on the looped part:

```
xPosition += xMovement * speed;
yPosition += yMovement * speed;

```

You will just have to change `speed` value in order to change your object speed.
> 1 votes

---
Tags: java, 2d, javascript, graphics, cocos2d
---


title: How to flick gameObject using Touch?

text:
# Question
Title: How to flick gameObject using Touch?
I've been searching for a solution for my problem for a while on the web, but i didn't find anything that work properly

**What i want to do**

I have a bouncing ball and I want to let the user flick it with his finger (using a swipe gesture or whatever). The ball shouldn't start moving unless the player flick touch the ball. I don't want the ball to move if the player flicks anywhere on the screen, ***only if the flick touch the ball***

**What i've done so far :**

I've tried to write a script which would detect the touch starting position and the touch end position, and check if the end position is the same as the ball position to make sure that the flick touch the ball. Then the script calculate the direction vector by substrating the start position from the end position. After that i use the `AddForce` methode and give it the direction vector as a parameter.

Here's my code, (it's better than 1000 words ) :

```
using UnityEngine;
using System.Collections;

public class Movement : MonoBehaviour
{
    public Vector2 start;
    public Vector2 end;
    public Vector2 direction;
    public Vector2 ballPos;
    public float Flicktime;
    void Start(){
        }
    void Update(){
        ballPos = new Vector2(transform.position.x,transform.position.y);
        if (Input.touchCount > 0)
        {
            Touch t = Input.touches[0];
            if (t.phase == TouchPhase.Began)
            {
                start = Camera.main.ScreenToWorldPoint(new Vector3(t.position.x,t.position.y,0));
            }

            if (t.phase == TouchPhase.Ended || t.phase == TouchPhase.Canceled)
            {
                end = Camera.main.ScreenToWorldPoint(new Vector3(t.position.x,t.position.y,0));
                direction = end-start ;
                if(t.position == ballPos){

                    rigidbody2D.velocity = direction * 2 ;
                }
            }
        }
    }

}

```

**What's the problem ?**

The problem is that the code doesn't work.

When i launch the game in the Unity Remote 4 app in my android device and try to flick the ball it doesn't move, the inspector shows that the the scripte is calculating the start & end positions and the direction vector, but the ball doesn't move, it stays in the same position even when the flick touch the ball.

So what's the problem ? is there a better way to do it ?

Since the ball have a circle collider how to make it detect collision with the player swipe ?

Thank's and have a nice weekend !

# Answer
`t.position == ballPos` is causing all your issue. You are comparing 2 vectors which will never be the same. The player will never tap exactly where the ball is. You should either do a `HitTest` or a `Physics2D.OverlapPoint`
> 2 votes

# Answer
Since you want the ball to only do something on touch I would remove all that and put your movement code in a OnMouseDown() it will still react to a tap. Depending on how you have it set up and if that works for you it might be a better way to accomplish your task.

The reason your code is not working is because the position you tap is not == to the balls position.
> 0 votes

# Answer
Try replacing these lines:

```
if (Input.touchCount > 0)
    {
        Touch t = Input.touches[0];
        if (t.phase == TouchPhase.Began)
        {
            start = Camera.main.ScreenToWorldPoint(new Vector3(t.position.x,t.position.y,0));
        }

        if (t.phase == TouchPhase.Ended || t.phase == TouchPhase.Canceled)
        {
            end = Camera.main.ScreenToWorldPoint(new Vector3(t.position.x,t.position.y,0));
            direction = end-start ;
            if(t.position == ballPos){

                rigidbody2D.velocity = direction * 2 ;
            }
        }
    }

```

You can use Touch.deltaPosition to find the swipe distance and direction. Also check a HitTest with the ball texture to know whether we're touching the ball.

```
Vector2 swipeDistance;
Texture ballTexture;

if (Input.touchCount > 0)
{
    Touch t = Input.touches[0];

    if (t.phase == TouchPhase.Ended || t.phase == TouchPhase.Canceled)
    {
        swipeDistance = t.deltaPosition;

        if(myTexture.HitTest(t.position))
            rigidbody2D.velocity = direction * 2 ;
    }
}

```
> 0 votes

---
Tags: unity, collision-detection, touch
---


# Question
Title: What are projection independent ways of determining whether a normal is facing the viewer?
A position `v` and normal `n` are given in world coordinates. Also there is a view matrix `V` for world-eye coordinate transition and a projection matrix `P` for eye-ndc transition. I would like to determine, whether the normal is facing the viewer.

If we assume that `P` is a perspective matrix, we can compare the normal direction with the direction to the viewer, both in eye-space. Note that the approach won't work for an orthographic projection, because there is no well defined eye position. But if `P` is orthographic, we only need to check the Z coordinate of `n` in eye space. Nevertheless, I'm seeking a solution that does not make assumption about what projection type we're using.

One way of achieving this is to compute the inverse `P'` of `P` and retrieve the viewing direction as a vector spanned between `P' [u.x, u.y, -1]` and `P' [u.x, u.y, 1]`, where `u` is `v` transformed to ndc. The drawback here is that it requires inverting a matrix and in my case also passing it to the shader.

Another solution would be to construct a small triangle around `v` within the normal plane of `n`, and check what's its winding direction in the ndc. The problem with this approach is that it's computationally heavy and it's still seems to me more like a hack than a proper solution.

I am not very satisfied with these two solutions. Do you have any other ideas? Am I missing something very simple?

**EDIT:** Since it seems unclear why the `dot(v - eye, n) < 0` is not satisfactory in my case, I post an exaple showing the difference between perspective and ortho projection for this particular problem.

As you can see, the vector is facing slightly away in the perspective projection, but clearly towards in the orthographic projection. More specifically, a face having that particular normal would be culled in perspective, but not in ortho.

# Answer
> 1 votes
You can get the position of the eye and test `dot(eye-v, n)>0`.

This checks that the angel between the viewing vector (from v to the eye) and the normal is less than 90°.

---
Tags: matrix, linear-algebra, normals, projection-matrix
---


title: Optimization of Cube-based World

text:
# Question
Title: Optimization of Cube-based World
I'm currently working on taking an idea I've been toying with in C++ and bringing it into Unity, but I'm struggling to figure out how to make it performant and how to do things the "Unity way".

My world is made up of cubes and cube shaped tiles viewed from a fixed angle (à la Monument Valley). I've watched their behind the scenes video and seen that they have a step in their workflow that removes the unused faces from their cubes and combines them into quads. I want to achieve something similar.

Ideally I want to build up my world using a bunch of prefab cube objects (with different textures and components) and then run some kind of process over my scenes before I export/play to optimize them (otherwise I'm going to be doing potentially thousands of draw calls that I don't need to do and have lots of colliders I don't need).

My questions are as follows:

* What hooks does Unity provide to do this sort of processing? Should I be using PostProcessSceneAttribute for this?
* I understand that I can use Mesh.CombineMeshes to combine my cubes, but what about for their colliders?
* How can I determine groups of cubes that are touching (for removing faces and combining colliders)? In my C++ project I keep all of the blocks in a 3D array and use that, but using the Unity editor to place the blocks means I don't have this available. Is there a way I could easily build one from my scene, or is there a more "Unity" way of doing this?
* Is my approach sensible? Or should I drop the idea of placing individual cubes in the editor and take a different approach?

# Answer
> 1 votes
One of the biggest overheads for Unity in regards to CubeWorlds is that *every single one of those cubes is an instance of something.* Whereas Minecraft has a single class instance for every Block and Item and merely references them to figure out what they do (there are a few exceptions, but those are handled with TileEntities, which if you have enough of them, the overhead starts to lag the game). Minecraft constructs the level geometry manually by iterating over the chunk and figuring out which sides need to be drawn and with what texture, etc. and storing the result until something changes.

`Mesh.CombineMeshes` will sort of do this for you, but be aware that:

* It ***does not*** cull hidden faces (that is, two cubes in adjacent positions will still use 24 triangles).
* It has a vertex limit of 65535
* Is treated as one object for the purposes of lights (only so many dynamic lights are rendered, depending on quality settings).

It will, however, maintain colliders. I forget if this is due to simply disabling the rendering of the original objects or by copying the colliders onto itself (it has been a few months since I last messed with this). For point 1, I created a custom cube object that would figure out if a given side needed to be rendered and disable it prior to being rendered.

# Answer
> 0 votes
I would highly recommend this tutorial series by *12pt* on the Unity forums, which details how to do procedural voxel mesh generation in Unity.

I've used his tutorial to create my own voxel world for an isometric city simulator (series). In the first video of the series you can see that I quickly dropped using Cube prefabs, as viewing my 160x160 world from the max distance resulted in ~10fps. Once I'd swapped to procedural mesh generation (using chunks) I returned to ~1,300fps.

Obviously it's not quite what you're looking for, but it wouldn't be too hard to make a terrain editor script that allowed you to increase/decrease the high of any tile, and set the texture of said tile. Once that's complete you'd have to Serialize that data to load it again at a later date for editing (episode 2 of my series).

An alternative approach would be to use a height map, and pass this to a terrain GameObject. Hope this helped.

---
Tags: unity, optimization
---


# Question
Title: Efficiently detect shoot direction with gravity playing a role?
How could I efficiently calculate shoot direction for enemy AI in order for it to hit the player?

Things I know:

player position, player velocity, gravity, bullet spawn position, bullet initial speed(not direction, gravity is also applied for it)

Bullets are slow and don't hit instantly.

# Answer
I spent weeks on a very similar problem. With the help of DMGregory, I finally solved it!

First you find the spawn position for the bullet (wherever you want). Then you find the destination for the bullet (calculate where the player will be...let me know if you need help with this part).

Then you cheer DMGregory's name for his insanely awesome awesomeness. Read How can I launch a GameObject at a target if I am given everything except for its launch angle?, DMGregory's answer, and the answer linked in his answer.

I know you are in Java, but you can take a look at my C# version for reference. A simpler version is also my answer to my question linked in your question above. If you have any questions on moving this to Java, lemme know.

The math is crazy here. Good luck!
> 1 votes

---
Tags: ai, aiming, movement-prediction
---


# Question
Title: How to assign game object references to a class instance created at runtime?
I'm creating a game where I have an Entity class that contains basic entity info (pos, health,..) and some functions. Enemies and Player later on inherit from this class.

```
Public class Entity {

public Vector2 position;
public float health;
,...

```

Lets say that I have a function like this inside the Entity class:

```
public GameObject movingIntoEnemy(Vector2 movingToPoint)
{
    foreach (GameObject go in GameObject.Find("GameMap").GetComponent<GameMap>().enemyList)
    {
        if (go.GetComponent<EnemyScript>().enemy.position == movingToPoint)
        {
            return go;
        }
    }
    return null;
}

```

This function looks for a GameObject called "GameMap" and then cycles through enemies in its list. If an enemy is found, it returns its GameObject. Using GameObject.Find() is pretty ineffective, so what would be a better approach to this? I mean, I can't just easily use

```
public GameObject GameMap;

```

since the code is in a class, and this class needs to be instantiated first in my player/enemy scripts.

My question is - how do I attach GameObjects to this class before it is even created? What is the appropriate approach to this? I guess that I might pass these GameObjects to the class through its constructor, but it would make things much more complicated.

# Answer
Obviously we can't do anything to a class instance that hasn't yet been instantiated, because by definition it *doesn't exist yet*.

**The real question here is "how can a class instance *created at runtime* get access to its dependencies, in Unity specifically?"**

There are a couple of general approaches to this:

1. Make the `GameMap` globally accessible so each Entity instance can reach out and find it. (You're already doing a flavour of this)
2. Provide a `GameMap` instance to each Entity when it's spawned. (This is called dependency injection)

For 1, we have options like...

**a) Each instance searches for its dependencies**, using `GameObject.Find()` as you're doing now, or FindAnyObjectByType() to shortcut straight to grabbing the component you want like so:

```
GameMap map = FindAnyObjectByType<GameMap>();

```

As you point out, this isn't ideal, but it's also not a grave sin as long as you cache the reference for reuse via a member variable, so you're not searching for it every frame/every event.

**b) Implement the Singleton Pattern.** There are many ways to skin this cat, but a common theme is a static method to get an instance (and possibly construct it on-demand if it's absent from the project):

```
public class GameMap : Monobehaviour
{
     private static GameMap _instance;
     public static GameMap GetInstance()
     {
         return _instance;
     }

     void Awake()
     {
        _instance = this;
     }

     //...

```

Now any code elsewhere in your scene can call:

```
var map = GameMap.GetInstance();

```

to get an instance to the one GameMap quite cheaply.

Where Singletons tend to start running into trouble is...

* When you change scenes and your singleton is deleted (fix with DontDestroyOnLoad)
* When you change scenes with `DontDestroyOnLoad` and there's already a singleton in the new scene, so now you have two (fix by self-destructing in `Awake()` if `_instance != null`)
* When you try to use the singleton in a scene without one, or before it's Awake (fix by constructing on demand, or using script execution order to ensure the singleton initializes first)
* When you want to extend your game so there can be multiple `GameMap`s at once (may require substantial refactoring - this applies to any of the "global access" strategies)

None of this is insurmountable, you just need to be on the lookout for it. But if we're using static members anyway, we could sidestep some of the complexity and just...

**c) Make the shared dependency itself static.** You lose the ability to put it in the hierarchy or manipulate it in the inspector, but if you so choose you can farm these responsibilities out to auxiliary objects that are either constructed by the `GameMap` as needed, or already exist in the scene and register themselves with the `GameMap` on start.

---

**On to #2, dependency injection...**

When you create your `Entity` instances, tell them which `GameMap` they should use.

If you're not using a `Monobehaviour`, this is as straightforward as passing an argument to their constructor, as you describe in the question:

```
var myEntity = new Entity(myGameMap);

```

If you are inheriting from `Monobehaviour`, then you wouldn't use a constructor, but instead a setter after instantiating the object or attaching the component:

```
// Make sure your prefab variable is of the type you want to use.
public Entity myEntityPrefab;

// ...then, when you want to spawn it:
var myEntity = Instantiate(myEntityPrefab);

myEntity.SetGameMap(myMap);

```

Either way, the `Entity` caches the map it's passed, and any code that runs after \[construction / Awake()\] will know which map to use.

This approach scales to uses where you might eventually introduce multiple `GameMap`s, so the Entity objects don't need to know how to request the right one - it's pushed in from whatever higher-level system created them (which usually has more knowledge of the context in which it's creating the Entity).
> 2 votes

---
Tags: unity, c#, gameobject, dependency-injection
---


# Question
Title: How do I generate random mountains in a sidescroller?
So I'm trying to make a simplified Terraria style world using Perlin noise. I got that working and the terrain is randomized. However the terrain always looks like like a weird cosines curve. Hills and bottoms with different heights repeating. The effect I want to achieve is something similar to this:

Where the terrain is mostly flat looking and sometimes a large mountain will appear.

Is there an algorithm or "noise" that could achieve this effect or what other things do I need to do?

# Answer
You want to mix different wave lengths with different levels of intensity.

E.G. Have one long wave, that has a high intensity, and a short wave with low intensity.

Now add the two(or more) waves together.  Black line being long waves and high intensity.

Red line being short waves with low intensity.

Green being the final result.

```
float getHeight(float x) {
    float longWave = getNoise(x / 100) * 20;
    float shortWave = getNoise(x);

    return longWave + shortWave;
}

```

Eventually add more waves, maybe using different noise algorithms. Play around with the values. To get more interesting results you could also try to multiply different wave lengths, make them exponential etc...
> 14 votes

---
Tags: algorithm, procedural-generation, terrain, perlin-noise
---


# Question
Title: How can I describe a square in OpenGL ES 2.0?
I need to draw a Tic-Tac-Toe board in Xcode using OpenGL ES 2.0. I am new to graphics programming and can't find good information on drawing a square in opengl es in iOS. I looked at Ray's tutorials, which are good, however he covers drawing a rotating cube. All I want is a square; how can I describe a square for OpenGL?

# Answer
This tutorial from Ray covers preparation of the OpenGL render pipeline and the setup required to describe a square. It's about halfway down.

Specifically, to draw a square you'll want to draw two triangles. Ray's code organizes them like this:

That's four vertices and six indices (two sets of three):

```
Vector2 vertices[] = {
  Vector2(1, -1), Vector2(1, 1), Vector2(-1, 1), Vector2(-1, -1)
};

short indices[] = {
  0, 1, 2,
  2, 3, 0
};

```

(Ray's tutorial uses 3D positions and also provides color information, which I'm excluding for brevity.)

Store this data into the appropriate buffers using `glBufferData` (assuming you've previously created both buffers):

```
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
glBufferData(GL_ARRAY_BUFFER, 4 * sizeof(Vector2), vertices, GL_STATIC_DRAW);

glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, 6 * sizeof(short), indices, GL_STATIC_DRAW);

```

Then use `glDrawElements` to submit the draw command to the card.

Note that you'll likely need to adjust the coordinates of the vertices depending on your current projection matrix (et cetera); the provided coordinates will fill the screen when the transformation pipeline is configured with a series of identity matrices, but is only really suitable for initially bootstrapping rendering.
> 1 votes

---
Tags: ios, opengl-es2, objective-c
---


# Question
Title: How to fix my tile-based game's tile movement code ? (like a CandyCrush Style)
I'm currently creating a tile-based game like a CandyCrush style direction movement (no problem on only down movement) trying to smooth, not laggy tile movement with a board piece, and I'm writing a report about it now.

However, I found it hard to properly describe it. I am having some weird issues with my tile movement code. I am trying to make it so it is a smoothly, in order, and tileses not sorted, buggy, bla bla. Need more optimization...

# Update:

-I removed DiagonallyMover on code, now It's simply. -But, Vector3 fallDestination is always get lastest null piece. Not sorted.

# Update2:

-I added my movement codes here. -When moveDirection's x and y not 0, It's moving transversely.

My code working like this ;

What I wan't ;

Can someone fix this code, please ? :(

My Movement Code :

```
public bool UpdateTilePhysics(DestructionBoardPiece curPiece) {
    this.UpdateFallingTilePosition(curPiece);
    bool hasTileReachedFallDestination = this.HasTileReachedFallDestination(ref this.fallDestination);
    if (!hasTileReachedFallDestination) {
        this.moveVelocity = Mathf.Min(this.moveVelocity + this.acceleration * Time.smoothDeltaTime, this.maxVelocity);
    } else {
        if (this.isSpawnedFromBehindMask) {
            this.distanceSinceSpawned = Mathf.Max(1f, this.distanceSinceSpawned);
            this.CheckDistanceSinceSpawnedTriggers();
        }
        base.LocalPosition = this.fallDestination;
    }
    return hasTileReachedFallDestination;
}

protected void UpdateFallingTilePosition(DestructionBoardPiece curPiece) {
    if (this.isSpawnedFromBehindMask) {
        Vector3 a = this.fallDestination;
        a.z = base.LocalPosition.z;
        this.moveDirection = (a - base.LocalPosition).normalized;
        base.LocalPosition += this.moveDirection * this.moveVelocity * Time.deltaTime;
        this.distanceSinceSpawned += this.moveVelocity * Time.deltaTime;
        this.CheckDistanceSinceSpawnedTriggers();
        return;
    }

    this.moveDirection = (this.fallDestination - base.LocalPosition).normalized;
    base.LocalPosition += this.moveDirection * this.moveVelocity * Time.deltaTime;
}

```

My Gravity Code :

```
protected IEnumerator ActiveGravityChecker() {
    DestructionBoardPiece destructionBoardPiece = null;
    DestructionBoardPiece destructionBoardPiece2 = null;
    DestructionBoardPiece destructionBoardPiece3 = null;
    while (this.GravityUpdateEnabled) {
        if (!base.enabled || !this.GravityEnabled || base.BoardPiece == null) {
            yield return null;
        } else {
            this.debugActiveGravity = true;
            destructionBoardPiece = (base.BoardPiece as DestructionBoardPiece);
            if (destructionBoardPiece3 == null) destructionBoardPiece3 = destructionBoardPiece;
            this.fallDestination = destructionBoardPiece.LocalPosition;
            bool canMoveDown = false;
            if (destructionBoardPiece.LockCount <= 0 && destructionBoardPiece.BottomLink != null && !destructionBoardPiece.BottomLink.IsBlocked && ((this.tileMovedDiagonally && this.HasReachedBoardPieceArea()) || !this.tileMovedDiagonally)) {
                if (destructionBoardPiece.BottomLink.Tile == null) {
                    destructionBoardPiece2 = destructionBoardPiece.BottomLink;
                    canMoveDown = true;
                    this.tileMovedDiagonally = false;
                } else if (destructionBoardPiece.BottomLink.Tile.IsMoving && this.HasTileInArea(destructionBoardPiece.BottomLink.Tile as DestructionTile)) {
                    this.moveVelocity = (destructionBoardPiece.BottomLink.Tile as DestructionTile).moveVelocity;
                }
            }
            if (destructionBoardPiece.LockCount <= 0 && !canMoveDown && this.HasReachedBoardPieceArea()) {

              //Removed DiagonallyMover Code
            }
            if (canMoveDown) {
                this.fallDestination = destructionBoardPiece2.LocalPosition;
                if (destructionBoardPiece.Tile == this) {
                    destructionBoardPiece.MoveTileTo(destructionBoardPiece2);
                }
                destructionBoardPiece.UpdateOrphanState();
            }
            if (!canMoveDown && this.UpdateTilePhysics(destructionBoardPiece) && (destructionBoardPiece2 == null || (destructionBoardPiece2.Tile != null && !destructionBoardPiece2.Tile.IsMoving) || destructionBoardPiece == destructionBoardPiece2 || destructionBoardPiece.LockCount > 0)) {
                destructionBoardPiece.Tile = this;
                destructionBoardPiece.ResetTilePosition();
                this.TileStoppedMoving(ref destructionBoardPiece3);
                base.IsMoving = false;
                this.RaiseEventTileFinishedActiveGravity(destructionBoardPiece3);
                this.moveVelocity = 0f;
                break;
            }
            yield return null;
        }
    }
    this.debugActiveGravity = false;
    yield break;
}

```

# Answer
*I did not look at your code.*

What you're trying to reproduce seems to have two "tracks" that the candies follow. They seem to only advance if there is room available in front of them *on their own track*.

Your implementation seems to make the candies go directly where they should be at, which makes them go out of *their own track*. Also, some of your candies look like they change track.

*I lied, I took a look at your code.*

You code looks very *very* complex, and debugging it looks hard.

I would suggest you implement a simple 'track' system that the candies would follow. You *fake* the gravity over the track. Or, if we look at it in another way, it would be the same behaviour as what we see on a busy street a Monday morning: cars in a heavy traffic.

Your first tracks should probably be as set of straight lines, then you could add curves.
> 2 votes

# Answer
It looks like you've wandered down a path I once did when working on a similar movement system for tiles a few years ago. I ended up taking a similar route as was taken in Candy Crush.

The first thing to consider is that in your example, you remove tiles while other tiles are still moving. Candy Crush does not do that. You swap two pieces and then the game reacts, clearing those tiles, and moving everything around. It then allows you to interact again.

The advantage of this is it creates distinct points in your logic where you calculate where pieces move to in the tile system and then it animates to those points.

Beyond that, look to Alexandre's advice, as a path system for movement is much more suited for this application. This removes all ambiguity in which direction pieces should flow around the board and removes a lot of the complexity in your system.
> 1 votes

---
Tags: unity, c#, 2d, physics, optimization
---


# Question
Title: How can I generate a (relatively) linear dungeon path?
We developing a concept for an action side-scroller. What we need is a way to generate a (relatively) straight map. By this I mean something like...

It's clear to see that this map follows one simple route, even if it deviates a bit. With that, we're also going to implement straying pathways -- shortcuts, or secret passages. So that, perhaps, to get from the third circled area to the fourth, you'd have the main path, and a secret passageway that's filled with stronger enemies, but is faster and has higher rewards.

Here we've reached an impasse. We're exploring a few options but haven't really made any progress. What approach could we use to generate this kind of path We're not bound by programming languages, as so far we've experimented with Java, C# and C++. Similarly, we don't have any current dependencies on specific game engines.

# Answer
**Requirements**

1. You want multiple paths from A to B.
2. You want to work in grid space, presumably this is tile space for your side-scroller.
3. You don't want paths to cross, or it will spoil game progression.
4. You want the paths to look reasonably organic.

**Voronoi Diagrams**

Voronoi Diagrams are space-filling, planar graphs:

One nice thing about them is how you can use them to create organic paths. If you draw a straight line from centre to centre you will get quite an unpredictable (read: non-ortholinear) path.

**How to create a Voronoi Diagram for use with a tile-based system**

Create a map of some reasonable size, say 128x128. Generate `n` random grid coordinates (x,y) in the map and populate each with a unique id / colour. Create a list for that colour, and add that starting cell to it; do this for each colour.

Now you have these uniquely colour points floating in a void, but you need to create whole islands of colour around them, with end result looking so:

To do that we need to see which colour owns each cell in the map (cell = pixel in the image above). We run through every cell in the map, checking which of our `n` starting colour points is closest to it (via pythagoras). That cell goes into the list associated with that unique id / colour... hereafter referred to as *islands* AKA Voronoi cells (in above diagram, groups of pixels with same colour).

You should now have a quantised Voronoi diagram. The next step is to analyse the adjacency of each island to other islands. Set up a simple node and edge struct so you can store a graph (node is just the id, the list for that id, and an empty list of edges; edge is just the start and end node). For each uniquely id'ed island, create a node, and add edges to link it to each island it is adjacent to.

Once you have the complete diagram (graph), you get to the fun part - use the graph to find chains of islands, and by making all the cells in each island in the chain have the same ID, you're carving out one of your paths. Let's say an island with all cells having ID 503 is sitting next an island with id 657. You can replace all 503 cells with a 657 ID, thus creating one larger island of adjacent 657s.

For example - red is path 1, blue is path 2, magenta is both:

You can use any existing graph algorithms (A\* included) to generate the paths from start to finish. Getting a meandering path is a case of not always using the optimal step toward the goal island.

Lastly, it is trivial to shrink the islands if you want narrower paths, or to use a larger map with many more islands in order to get finer resolution.

**An optional, final step, for pathfinding**

Either you can use the high-level graph you built in conjunction with the underlying cells / tiles to do runtime A\*, OR you can do Hill climbing on the underlying cells / tiles for better motion:

At the centre (or any) coordinate of your goal island, you can place an influence cell. This influence can pump out "scent" as in Collaborative Diffusion. This scent will spread all the way down the path back to what was the start island, getting weaker and weaker as it goes. Now for an entity at the start, we simply climb from a lower-scented cell to higher-scented one, each time bringing you closer to the goal - the same way a dog operates. Each path being roughly linear, this allows you to avoid using A\* at runtime. Or you can do the same with the graph of islands, but that way is a bit more complex because you'll probably want to navigate your entities at the tile level. So the first way is perhaps better. Either way will allow you to navigate to the goal at low processing cost.
> 15 votes

---
Tags: path-finding, procedural-generation, maps, heightmap
---


# Question
Title: Vertically mirroring the screen in LibGDX
I'm developing a game in which the screen layout is different for right and lefty players, so i'll put a button in it to mirror the screen vertically.

For displaying textures and fonts, i use a single scene2D stage with actors and labels. The stage's viewport type is FitViewport.

How can i swap between the right and left layouts? Is there something already done to do it on the viewport-side?

Is it only a matter of switching coordinates from bottom-left to bottom-right? I can do that on the viewport camera, but what about all the textures? How can i change an actor's coordinate system?

Thank you all

# Answer
> 1 votes
Render your part of scene to frame buffer object, than draw frame buffer textureRegion flipped where you want (buffer.getColorBufferTexture())

---
Tags: libgdx, camera, coordinates, screen, viewport
---


# Question
Title: Passing strings padded with white space into a byte[]
I am using Google Play services for a real time multiplayer game in Unity 3d. When sending the data in a byte\[\] in the multiplayer update I have to pad certain entries going into the byte\[\] with white space so all entries are a certain length. I am having a problem where they don't have the white spaces anymore when I get the strings back from the byte\[\].

For example I have a string called username that is set to "test name " with 6 white spaces on the end in order to take up 15 bytes.

I add the string to the byte\[\] like so:

```
updateMessage.AddRange(System.Text.Encoding.ASCII.GetBytes(username));

```

Then to get the part back out I use this code:

```
string username = System.Text.Encoding.ASCII.GetString(data, 38, 15);

```

38 is the index where the username string should start and it should be 15 bytes long. It actually ends up going into the next string I have stored because it doesn't have the white spaces anymore.

Is there a way to make sure the white spaces stay in the string so that I keep the padding after pulling it from the byte\[\]?

# Answer
Immibis wants you to inspect the actual byte-array created by `System.Text.Encoding.ASCII.GetBytes(username)`

because your input:

```
{ t,e,s,t, ,n,a,m,e, , , , , , }

```

has probably become:

```
{ t,e,s,t, ,n,a,m,e,0,0,0,0,0,0} //null-terminated
{ t,e,s,t, ,n,a,m,e,0, , , , , } //also null-terminated

```

because of the underlying "friendliness" of C# strings.

---

You may be able to use the non-breaking space - " " (alt + 0160 on numpad), which is character 255, to pad your strings and circumvent the trimming behavior. However, byte values beyond 127 are not representable with ASCII encoding (7-bit) and fallback to "?" so you'll need to use UTF-8, which is a super-set of ASCII.

```
//C# strings and documents support full unicode (UTF-16)
//swap " " (space) for " " (non-breaking space) when uploading
updateMessage.AddRange(System.Text.Encoding.UTF8.GetBytes(username.replace(" ", " ")));
//any characters that don't fit into ---------^ will be a "?"

```
> 1 votes

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


# Question
Title: One framebuffer for each light vs unique framebuffer per light
Currently I have two ideas how to implement my lighting system:

1) Use one framebuffer per light source

* no need to switch texture attachments of framebuffer
* may be faster
* bigger memory usage

2) Use one framebuffer for every light source

* some time may be wasted on attaching new textures to framebuffer
* less memory usage

So could you please tell me which way is better and why? Or I'm totally wrong on my thoughts and there is no difference at all?

# Answer
> 1 votes
I know it's not the answer you're looking for, but you just need to pick one and implement it, because "it depends". Better answers will suggest that you optimize **after** the (working) code begins to create performance problems, by profiling both methods. Profiling is the only way to non-subjectively answer which is "better" and precisely how/why. Your game may already run at 1200 FPS using either method. You might also find that by moving a single `Map(...)` call down a few lines, the bottleneck is diminished or eliminated.

As an example, the memory footprint, alone, of 1000 lights using method 1 may be astronomical, impractical and, not to mention, impossible. So, if you plan to implement 1000's of lights, the design requirements may have already chosen "NOT method 1" for you. Since we don't currently know the limits of what you *might* implement in the finished product, we can't say which will *definitely* be better.

Don't Repeat Yourself (DRY) tells me not to create a ton of identical buffers so I, personally, would almost always opt for method 2.

---
Tags: opengl
---


# Question
Title: Does the Facebook app need to be installed to use Facebook for Game Developers?
I just learned about Facebook for Game Developers. I would like to know if I need to have the Facebook app installed in my phone to use Facebook for Game Developers (like I need to install Google play games services in android).

# Answer
> 1 votes
1. The game can use the Facebook APIs without facebook installed on the player's device.
2. I haven't used Google Play, but Facebook is unable to query the information of any friend that's not also using the game. Requesting the friend list will return an empty list, for instance, until another friend installs the game. There is an API for inviting friends to install the game, but I don't know how effective that is in the real world. (I've never accepted an invitation to play a game with a friend.) If you call the API that purports to send messages and requests to the user's friends (assuming the friends have not yet installed the game), the messages will show an invitation to install/play instead of the actual content.

---
Tags: facebook
---


# Question
Title: Collision between UI element and GameObject
When I first started to develop in Unity I followed the Unity Tutorial for the Space Shooter 2D game and used the knowledge from that to create something myself. Looking at it now it may not have been the best idea.

Currently my game is 2D but in a 3D environment where the camera is top down and I am trying to figure out how I can detect a collision between a UI Image and my Player GameObject.

Any help will be extremely appreciated!

# Answer
> 1 votes
Two ways to go about this:

1. Use regular (3D) colliders for everything.
2. Use 2D colliders for everything.

It doesn't particularly matter which you pick, although working with 2D colliders will create fewer potential problems if you don't plan to use that extra axis of movement. Your main problem right now seems to be picking one or the other physics model.

Generally, if you're using an image as a game element it isn't part of the UI. You would normally use a sprite instead. But, if your heart is set on using a UI image, you could match a collider's position and shape to it in the place where it appears to be. Or, you could move the world in line with the UI (assuming you're using the new Unity UI, not the old IMHUI). Really though, it will make more sense to use a sprite.

---
Tags: unity, collision-detection, gui, gameobject
---


# Question
Title: Calculate Position on Tile Map by single Index
I stumble about a Math Problem for calculating a Position on a dynamic tile-map.

So i got a List of Tile Entities. Every Tile got his one unique Index Value and i have to set the parameters for Map Height and Width.

**Example A** Map X = 3 Y = 4

**Example B** Map X = 4 Y = 3

To get the X Position Value of Tile **E6** i know i have to use `Map.X % 6`. But i'm not sure how to get the Y Position of the Tile by his Index. `%` in this case stands for the modulo operation (c#).

Is there a name for such an calculation? Does somebody already know the answer?

# Answer
> 4 votes
How to get X and Y coordinates in a 2d array from a single index? You use the *modulo* (`%`) for the `x` coordinate and you use the *integer division* (`/`) for the `y` coordinate:

```
array< array< object, mCanvasWidth >, mCanvasHeight > mDirtMap;
int totalSize = mCanvasHeight * mCanvasWidth;

for ( int i = 0; i < totalSize; ++i )
{
  int xIndex = i % mCanvasWidth;
  int yIndex = i / mCanvasWidth;
  mDirtMap[yIndex][xIndex].doWhateverToObject();
}

```

Alternatively, what if you're stuck with a one dimension array that represent 2-dimension data? Here is how to get the index based on a set of `x, y` coordinates:

```
array<object, mCanvasHeight * mCanvasWidth> mDirtMap;

for ( int y = 0; y < mCanvasHeight; ++y )
{
  for ( int x = 0; x < mCanvasWidth; ++x )
  {
    int index = y * mCanvasWidth + x;
    mDirtMap[index].doWhateverToObject();
  }
}

```

# Answer
> 0 votes
How to get X and Y coordinates in a 2d array from a single index?

-You can use simple index with width & height. Here a example :

```
int width = 4;
int height = 3;

//E6 index = 6

public int getTileIndexFromArray(int x, int y)
{

    for ( int y = 0; y < height; y++)
    {
      for ( int x = 0; x < width; x++ )
      {
        int index = x + y * w;

        //For Example
        Tile t = getTile(index);
        if(t.Name != "E6") continue;

        return tiles[index];
      }
    }
    return tiles[0];
}

public Tile getTile(int x, int y) {
    if (x < 0 || y < 0 || x >= width || y >= height) return Tile.air;
    return Tile.tiles[tiles[x + y * width]];
}

public Tile getTile(int index) {
    return Tile.tiles[tiles[index]];
}

public void setTile(int x, int y, Tile t) {
    if (x < 0 || y < 0 || x >= width || y >= height) return;
    tiles[x + y * width] = t.id;
}

```

---
Tags: c#, mathematics, tilemap
---


# Question
Title: GLSL Shader not compiling (Android & LibGDX) and no log available
I'm trying to get a "ripple"-shader working for OpenGL ES 2.0+ (using LibGDX).

However, I can't get it to compile, and for some reason `ShaderProgram.getLog()` returns an empty string even though the Shader didn't compile.

I am 100% confident that the vertex shader is correct.. here's the fragment shader (not written by me, but I modified it a bit long time ago.. when I had a desktop project - and it worked back then):

```
                #version 120
                precision mediump float;
                varying vec2 v_texCoords;
                uniform float time;
                uniform float alpha;
                uniform float waveLengthMultiplier;
                uniform sampler2D u_texture;
                void main()
                {
                    vec2 center = vec2(0.5, 0.5);
                    vec2 tc = v_texCoords.xy;
                    vec2 p = -1.0 + 2.0 * (tc - offset);
                    float len = length(p) * waveLengthMultiplier;
                    vec2 uv = tc + (p / len) * cos(len * 12.0 - time * 4.0) * 0.03;
                    vec3 col = texture2D(u_texture, uv).xyz;
                    gl_FragColor = vec4(col, alpha);
                }

```

I'm still not very well-versed with shaders, as I've used them only a little.. Like I said, `getLog()` returns an empty string, so I'm hoping someone spots an error in the code.

# Answer
> 1 votes
"offset" is not declared. Not sure why it would compile anywhere else, I doubt it.

---
Tags: android, libgdx, shaders, glsl
---


# Question
Title: LibGdx: search through text file without lots of String garbage
I'm reading a text file from `Gdx.files.internal` in LibGdx. This is essentially streaming a file from a compressed Jar file so random access is not possible.

I want to search through the text file line by line until I get to the bit I want. That's easy enough, but I want to do it without generating loads of Strings and leaving lots for the GC to clean up.

Whats the best way of scanning through the file without creating object garbage?

# Answer
It sounds like you don't want to create a whole bunch of `String` instances for the GC to clean up, so how about using one or more `char[]` to hold the text file data?
> 1 votes

---
Tags: java, libgdx, file
---


# Question
Title: How to deal with collision in a networked game?
In my game, my own character is extrapolated with client side prediction for smooth input response and all the other objects are interpolated. So Let's say I was at (20, 10) according to server and a bullet hits me at that position. But my client displayed rendered myself at predicted position (23, 10), which leads to a discrepancy - I got hit by the bullet even though it looked like I wasn't hit. How can I deal with this problem?

# Answer
> 2 votes
It boils down to a choice: do you want a sniper that aimed perfectly to miss because the target actually moved? On the sniper's screen he got the shot.

The alternative is better: creating the possibility that you will get shot slightly *after* moving behind cover.

All FPS games have some form of this problem. Typically, shooter wins (because his aim was right for him), dodger loses (even though he swears he got shot *after* moving behind cover).

If the server "believes" the shooter, then it needs to be very careful, it needs to make sure that it was actually possible for that player to have gotten the shot. The problem exists for the victim as well, you don't want hacks to make you impossible to hit.

Generally, the server keeps track of the position and movement of a player, and can check whether it is feasible for the player to have gotten that shot within the last several game ticks.

# Answer
> 1 votes
For networking issues, you generally need to disguise the lag as much as possible. How you do this depends quite a bit on the type of game you're making. The situation where the lag occurs also should affect your approach.

If you had asked about shooting a bullet, the answer would be easy: use a brief firing animation on the client (but not on the server), so that the client's animation delay balances out with the networking delay, thus eliminating the appearance of lag. Getting hit by a bullet is a harder scenario though. Nonetheless, there is a solution: **you not only need to predict the character's movement, you need to predict bullet movement as well** (at least for bullets near the character). If you're predicting where both the character and the bullet will be 100 milliseconds after where they actually are on the server, they'll be in sync. This wouldn't work if bullets move at a very fast speed, such as if you're making a realistic FPS game, because the bullet speed would be even faster than the ping delay. If bullets move slowly enough, that's all the solution you'll need. If they move lightning fast, try predicting bullet movement before the bullet is even fired. That way, there will be enough delay to keep the character and the bullet in sync.

It isn't a perfect science, and "hiding the lag" is highly situational. Don't be afraid to alter gameplay mechanics a bit in order to make the networking work properly, because a game that feels out of sync just isn't fun to play.

---
Tags: networking
---


# Question
Title: Can I create a Sprite Asset using a downloaded Texture at runtime?
I know that Asset Bundles exist, and I'm already taking a look at them. But I'm still interested in this particular approach:

---

I am interested in downloading a .png image from the Web, and then "consolidate" it as a Sprite asset. After doing so, I can display this sprite in my game in the future without ever downloading that image again.

I was able to download the image and use its texture to create a `Sprite` object and use it for my `SpriteRenderer`:

```
        WWW request = new WWW("www.example.com/image.png");
        yield return request;
        if (request.isDone) {
            ((SpriteRenderer)renderer).sprite = Sprite.Create(request.texture, new Rect(0,0,request.texture.width,request.texture.height), new Vector2(0.5f,0.5f));
        }

```

Is it possible to grab this texture and generate a Sprite asset? With all the properties like pivot, pixels per unit, packing tag, etc?

---

**UPDATE**

Alright, so turns out that `Sprite.Create` let's me set the pivot and pixels to units properties. No packing tag, though, but I guess that makes sense since packing should be done during development and not during runtime.

Given this, I suppose one could serialize the generated Sprite class.

# Answer
> 2 votes
I wrote some code to handling this in my current project

```
public IEnumerator getImageFromWS(string fileName, Action<Texture2D> result = null){
    var path = Application.persistentDataPath+"/"+PathToFile+"filename"+".png";

    var f = new FileInfo(path);
    if(f.Exists)
    {
        var retVal = new Texture2D(0,0, TextureFormat.RGBA32, false);
        retVal.LoadImage(File.ReadAllBytes(path));
        if(result != null)
            result(retVal);
    }else{
        var WWW = new WWW("www.example.com/image.png");
        if (!www.isDone || !string.IsNullOrEmpty (www.error)) {
            Debug.LogError ("Load fail : " + url);
            if (result != null)
                result (null);
            yield break;
        }

        Save (www.texture.EncodeToPNG (), path);

        if (result != null)
            result (www.texture);
    }
}

```

The `Save` method refer to this :

```
public static void Save (byte[] data, string path)
{
    var file = new FileInfo (path);
    file.Directory.Create ();

    File.WriteAllBytes (path, data);

    data = null;
}

```

With an extending method that take a Texture2D and return a Sprite

```
public static Sprite ToSprite (this Texture2D t, Vector2? v = null)
{
    var vector = v ?? new Vector2(.5f, .5f);
    return Sprite.Create(t, new Rect(0, 0, t.width, t.height), vector);
}

```

And you can call this like :

```
StartCoroutine (getImageFromWS ("image",
        texture => SpriteToLoad.GetComponent<Image> ().sprite = texture.ToSprite ()));

```

Hoping that this will be useful

# Answer
> 1 votes
You could do something like this:

```
public GameObject Gameobj;

Gameobj.GetComponent<SpriteRenderer>().sprite =
  Sprite.Create(
    www.texture,
    new Rect( 0, 0, www.texture.width, www.texture.height ),
    new Vector2( 0.5f, 0.5f ) );

```

# Answer
> 0 votes
The way you are doing it is more or less the only way you can do it without sticking it into your build or into an asset bundle. There is a call for WWW that will auto-cache it for you, WWW.LoadFromCacheOrDownload, but it only works with asset bundles, so you could make a single texture asset bundle and cache it that way. If that's not an option, you'll have to create your own caching mechanism

---
Tags: unity, asset-creation
---


# Question
Title: Should enemies still attack if they cannot see the player?
This may seem like a silly question, but let me explain this further.

Consider a common stealth situation where the player is hidden from the enemy AI. The AI has vision and hearing and if they either see or hear the player they will move towards the player's last known position. However if the player is behind cover (therefore the enemy cannot see them) and they attack with a silent weapon (therefore the enemy cannot hear them either), how should the enemy react?

Realistically, the enemy should have an idea of the direction from which the attack struck them and therefore start moving in that direction. But I am wondering if this then would be detrimental to taking a stealth as oppose to offensive approach. If the enemy turns around when hit irrespective of whether they were hit with a loud or silent weapon, there is little benefit to using a silent weapon, since the loud ones will have more power anyway. On the other hand, if the enemy simply stands their while being hit several times by a silent pistol, it may make the AI seem a little stupid.

I suppose it comes down to balancing between rewarding stealth gameplay in a stealth game, but not making the AI seem silly at the same time. What should I do to balance this?

# Answer
> 4 votes
They solved this problem quite easily in the latest iterations of the Far Cry series:

If you can one-shot an enemy with a silent weapon, you succeeded at a stealth-kill (head-shot with a silenced gun, bow), and no one will know where you are. If you aim badly (e.g. the chest or lower body), or the enemy has too much defense (aim for the head with a silenced small gun on a heavily armoured guy) and you're not able to one-shot him, he'll know for sure where you are and come hunt you (with his friends).

Not knowing what is exactly right for you and your game, I suggest to list all the options available, architect your game code around the fact that you'll have to try all those different things, and then test the many things that could make the game fun.

---
Tags: ai
---


# Question
Title: How to scale objects and tiles without doubling view port in gamemaker
How do I scale up tiles and sprites without acully making the view port larger than the acual view? I know that I can just scale up the images and the tileset but there must better alternative right? The reason why I dont want to make the port bigger is because then I get this kind of "pixel perfect" behaviour so 1 pixel on the image is one pixel on the screen (So it looks kind of choppy). I'm thinking I can use the draw event if there's no other alternative but how would I do that with the tileset?

# Answer
> 0 votes
Depends how you want to scale them up. You can scale objects when you're placing them in Rooms by just dragging out their corners (and maybe holding Shift to keep them evenly scaled). You *might* be able to do the same with tiles.

Otherwise, if you're looking to scale sprites in real time in the game, you can use the function draw\_sprite\_ext, and to scale tiles you can use tile\_set\_scale.

---
Tags: game-maker
---


# Question
Title: Unity3D mesh showing only black triangles
My mesh in the unity editor won't show the correct texture. Instead I get to see loads of black triangles. Anyone know what's wrong?

thanks :)

# Answer
> 1 votes
It looks like half of the tris are flipped the wrong direction. Triangles have a winding order and a normal, and if they face the wrong way they will be treated as backfaces and culled from the render. The other half could be one of a number of things:

1. Mismapped UV coordinates.
2. Incorrect image import settings.
3. An image format Unity doesn't recognize.
4. Something else I haven't thought of.

It's probably the first of those. It looks like you're attempting to procedurally generate it, so you'll want to check on how you're ordering your vertices in the triangle list and how you're coming up with UV values.

# Answer
> 0 votes
You can also try, in your 3D mesh editor, to "unify normals", which is what it's called in 3ds Max under the Normals or Edit Normals modifiers. I don't know what this command is called or how to access it in other 3d packages, though.

---
Tags: unity, mesh
---


# Question
Title: How can I check on a large number of points to see if they're inside the camera's frustum?
I have a locally stored database on my Android project, it is a database of approx 100,000 Point3D(double,double,double). I need to check if each of these points are inside of the camera's frustum in unity. Will I most likely be running into performance issues querying the database and feeding all live Point3D's to unity per frame? What would be the best way to go about this if I am approaching this from the wrong direction?

# Answer
One of the approaches you could take:

If you could organize your points into 'objects' or logical group of some kind, you could then compute each object's bounding volume (either an axis-aligned-bounding-box (*AABB*) or a bounding-sphere), and with that, do a quick rejection based on the frustum of the camera and the bounds you've calculated.

This strategy will leave you with *some* points that will not be in the frustum of the camera (because their friends are).

Now it's not clear why you need to know if the point is in the frustum of the camera. If it's to reduce the load of things sent to the camera/rendering pipeline or to reduce the load of work to do on theses points, it could give you a sufficient boost that the extra work done on the points that are not seen but are not culled could be negligible.

If you really need to remove all of these not visible points, you could do a second pass to see if the bounding-volumes are not completely inside the frustum (or even flag it during the first pass); if they are not completely in the frustum, then check specifically each of the 3d points to see if they're in the frustum.
> 1 votes

---
Tags: unity, android
---


# Question
Title: How to find the participation id corresponding to a sender id
I am creating a real time multiplayer game in unity 3d using Google Play Game Services. In my function where I deal with the positioning of players based on information that is sent from other players, I get a sender id. The sender id is a long string of characters that does not match any participation ids. My participation ids are just strings such as "Player 1234." I keep the participation ids in an array so I can reference them and compare them to the sender of the information that I am receiving so I know which player it is from.

If the sender id and participation id are two different things, how do I make the connection between the two?

Here is a link to the tutorial I have been following for Google play services in unity: https://www.raywenderlich.com/87042/creating-cross-platform-multi-player-game-unity-part-2

# Answer
> 0 votes
The senderId is the player's participationId. I had been using the username that Google Play Services gives for a player on accident.

---
Tags: unity, c#, multiplayer, realtime
---


# Question
Title: Why does PIX crash while creating render target views in my D3D11 application?
I'm trying to use PIX to debug my Direct3D11 application. PIX crashes and gives the following stack trace:

```
Frame 000001 ........PRE: <this=0x054338e0>IDXGISwapChain::GetBuffer(0, IID_ID3D11Texture2D, 0x00B3E0F0)
Frame 000001 ........POST: <S_OK><this=0x054338e0> IDXGISwapChain::GetBuffer(0, IID_ID3D11Texture2D, 0x00B3E0F0)
Frame 000001 ........PRE: <this=0x05433978>ID3D10Texture2D::Map(11788512, Unknown D3D10_MAP, 1843764804, 0x00B3EA08)
Frame 000001 ........POST: <E_INVALIDARG><this=0x05433978> ID3D10Texture2D::Map(11788512, Unknown D3D10_MAP, 1843764804, 0x00B3EA08)
Frame 000001 ........PRE: <this=0x054b70d0>ID3D11Device::CreateRenderTargetView(0x05433978, NULL, 0x00B3E0F4)
Frame 000001 ........POST: <E_INVALIDARG><this=0x054b70d0> ID3D11Device::CreateRenderTargetView(0x05433978, NULL, 0x00B3E0F4)

```

What can I do to get around this problem so that I can debug my application?

# Answer
> 2 votes
The PIX for Windows tool in the legacy DirectX SDK is not compatible with the DirectX 11.1 or later runtime. This means it will crash if you attempt to debug a Direct3D 11 application on Windows 8, Windows 8.1, Windows 10, or Windows 7 SP1 with KB 2670838 installed with this old tool. Direct3D 9 debugging will work on Windows 7, but that's about it.

Take a look at Visual Studio's Graphics Diagnostics or one of the profiling tools from one of the GPU vendors.

See DirectX 11.1 and Windows 7 and DirectX 11.1 and Windows 7 Update

---
Tags: directx11, slimdx, pix
---


# Question
Title: Where does event-based audio fit in a component-based entity system?
Assuming the underlying low level audio logic is encapsulated in some outside class... what is the best way to add audio effects to a component-based entity framework?

I am taking the approach that entities are just IDs and a type of database is used to associate components with entity IDs. The I can create masks for the systems to query particular types from the database.

So for example for components I might have:

* `PositionComponent`.
* `PhysicsComponent`.
* `VisualComponent`.

And the corresponding systems:

* `VisualSystem`, which processes visual components, hands off to outside renderer.
* `PhysicsSystem`, which processes physics, updates position vectors.

So the question is, how best to add audio to this system... or should I even bother? The problem I am having is mapping sounds to actions and when to play sounds.

Here are some approaches I've thought of::

1. Force `PhysicsComponent`s to have a some collision sound field and when a collision occurs, play the sound within the physics system.
2. Same as 1 but instead when a collision is detected add a `SoundComponent(sound)` to the entity and lets the `SoundSystem` see that and consume it (so the sound plays once for example). This still means `PhysicsComponent` would have a sound field. So really this just shifts the playing of audio into a system.

I don't like either of those approaches. They are not very suitable to expanding the game either. Now I would need a field for every possible sound a unit could generate.

Really I think individual entities should dictate which sound to play based on some component attached to them I would assume. The question then becomes how to know when to play that sound.

Sorry if this is all very vague. Any tips appreciated.

# Answer
You are teetering on the brink of the pit that is "putting everything in the entity system." *Not everything needs to be a component*, and indeed, many things *should not* be.

You should strive for separation of concerns where possible: a physics system should not know about the sound system at all. This includes avoiding a "sound to play on collision" field for objects.

Instead, build your physics system such that it exposes callbacks for collisions; a callback can be as simple as a function that has references to the two colliding rigid bodies to as complex as you need.

There is a system in your game that knows about both physics and sound: the "game" class itself, the thing that holds both the "sound system" and the "physics system." Have this game class wire up callbacks from the physics into the game logic, which can understand what sounds to play when two things collide, and play them. Since the game already knows about both systems out of necessity, you introduce no additional coupling. This works perfectly fine in an entity/component system because physics components typically correspond to rigid bodies.

If you need to put SoundComponents in your game, use them for things like controlling whether the entity plays a periodic sound or emits an audio effect (like local sound damping).

Most of the time, component-based entity systems work best when paired with some form of scripting language or other way to drive behavior without recompilation of code. If you have such a thing, I'd recommend giving your "script components" access to at least of subset of the audio API, so that they can request that sounds be played when they determine it's warranted (for example: a script component representing enemy AI that "detects" a player may want to issue a warning growl).

Generally, I find that sounds work best when they are just a service that appropriate components or other systems can access as needed. There's room for things like `SoundComponent` for limited, simple use cases (like periodic sounds, as mentioned). But if you try to shoehorn all sound activity into components I've found that you often end up with a complex mess of components that's hard to balance for good audio mixing.

Also remember: an entity system is a high level concept. It's *higher level* than sound or physics, so the components should usually be built on top of the underlaying system and not the other way around (by which I mean it should be theoretically possible to use your physics or audio system *without* components if you wanted to).
> 9 votes

# Answer
This is just an idea, as I didn't try it out in practice.

What if you use empty components to indicate state, such as `IsColliding`, `IsFired`, etc.

In this case, you could have a SoundSystem configured with a map, so that it triggers a sound for each state. Such as:

```
{(RedBullet, IsFired): "red_fire.wav",
 (BlueBullet, IsFired): "blue_fire.wav",
 (Player, IsCollidingWithPathBlocker): "thump.wav",
 (Player, IsCollidingWithEnemyBullet): "ouch.wav"}

```
> 0 votes

# Answer
Actually that is easy to achieve.

If you have a collision, create a new entity with position component (for positional sound) and a collision component (maybe with the force as data). Now write a CollisionSoundSystem which deals with that new entity.

And I suggest a decay component and a decay system to get rid of the collision entity in under a second. Maybe you have an EffectSystem as well for some nice hit effects.

I would not mix it too much with traditional OO practices, at least not on the same abstraction level.

In ES, you have to solve things in a different way than in traditional way of programming. Think in therms of an ES.
> 0 votes

---
Tags: entity-system, audio
---


title: 360 degree quaternion interpolation?

text:
# Question
Title: 360 degree quaternion interpolation?
I am in the process of implementing interpolation into a simple game loop I am playing with after reading the infamous "fix your timestep" article (which is amazing by the way). I have the position interpolation working correctly from what I can tell, however when attempting to implement interpolation for rotation using three.js's slerp method of the quaternion object I am experiencing strange behavior. What is happening is that whenever you attempt to rotate full 360 degrees you are stopped at the 180 degree range.

Looking at the output from the console logs it appears that it is trying to rotate past this point but then it is being re-set. It seems strange, but perhaps there is something that I am doing that is weird?

**UPDATE:** A working example of this scenario can be found here: https://stashcube.com/stackexamples/quaternion-interpolation/

```
// Run the main game loop as fast as we can
    setInterval(function(){

        var newTime = (+new Date()) / 1000.0;
        world.renderDeltaTime = (newTime - world.currentTime);
        world.totalRenderRunTime += world.renderDeltaTime;
        // Increment world.physicsAccumulator by world.renderDeltaTime. If it takes longer than
        // a quarter of a second for a frame to render then increment by max frame time of .25.
        // This prevents spiral of death issue.
        world.physicsAccumulator += (world.renderDeltaTime > 0.25) ? 0.25 : world.renderDeltaTime;
        world.currentTime = newTime;

        // Physics/Game logic
        while(world.physicsAccumulator >= world.physicsDeltaTime){

            world.processServerUpdates(client);

            client.previous_state = client.current_state.clone();

            client.processInputs(socket, world.physicsDeltaTime);
            world.animatePeers(client);

            world.totalPhysicsRunTime += world.physicsDeltaTime;
            world.physicsAccumulator -= world.physicsDeltaTime;

        }

        // Interpolate client object to remove the stuttering caused by unpredictable number
        // of physics loops
        var alpha = world.physicsAccumulator / world.physicsDeltaTime;
        var client_physics_state = new THREE.Object3D();
        client_physics_state = client.current_state.clone();
        client.current_state.position.lerpVectors(client.previous_state.position, client.current_state.position, alpha);
        var testQuat = new THREE.Quaternion();
        THREE.Quaternion.slerp(client.previous_state.quaternion, client.current_state.quaternion, testQuat, alpha);
        client.current_state.quaternion.copy(testQuat);

        // Render world
        world.render();
        client.current_state.position.copy(client_physics_state.position);
        client.current_state.quaternion.copy(client_physics_state.quaternion);

    }, 0);

Client.prototype.processInputs = function(socket, delta){

    var input = new Object;
    input.input_sequence_number = this.input_sequence_number++;
    input.id = this.id;

    if(this.key_up){
        input.key_up = true;
    } else {
        input.key_up = false;
    }

    if(this.key_down){
        input.key_down = true;
    } else {
        input.key_down = false;
    }

    if(this.key_left){
        input.key_left = true;
    } else {
        input.key_left = false;
    }

    if(this.key_right){
        input.key_right = true;
    } else {
        input.key_right = false;
    }

    if(this.jump && this.velocity.y === 0){
        input.jump = true;
    } else {
        input.jump = false;
    }

    input.quat = {
        x:this.current_state.quaternion.x,
        y:this.current_state.quaternion.y,
        z:this.current_state.quaternion.z,
        w:this.current_state.quaternion.w
    };

    // Send this input to the server for processing
    socket.emit('client_input', input);

    // Do client-side prediction.
    this.applyInput(input, delta);

    // Save this input for later reconciliation.
    this.pending_inputs.push(input);

};

Client.prototype.applyInput = function(input, delta){

    if(input.jump){
        this.velocity.y += 350;
        this.jump = false;
    }

    this.velocity.x -= this.velocity.x * 10.0 * delta;
    this.velocity.z -= this.velocity.z * 10.0 * delta;
    this.velocity.y -= 9.8 * 100.0 * delta; // 100.0 = mass

    if ( input.key_up ) this.velocity.z -= 400.0 * delta;
    if ( input.key_down ) this.velocity.z += 400.0 * delta;
    if ( input.key_left ) this.velocity.x -= 400.0 * delta;
    if ( input.key_right ) this.velocity.x += 400.0 * delta;

    this.current_state.translateX( this.velocity.x * delta );
    this.current_state.translateY( this.velocity.y * delta );
    this.current_state.translateZ( this.velocity.z * delta );

    if ( this.current_state.position.y < 10 ) {
        this.velocity.y = 0;
        this.current_state.position.y = 10;
    }

};

```

**\*EDIT** It might be worth mentioning that if I remove the lines:

```
var testQuat = new THREE.Quaternion();
THREE.Quaternion.slerp(client.previous_state.quaternion, client.current_state.quaternion, testQuat, alpha);
client.current_state.quaternion.copy(testQuat);

```

and

```
client.current_state.quaternion.copy(client_physics_state.quaternion);

```

Which are the lines that I am expecting to interpolate the rotation and then reset the rotation back to it's current position after render, that everything works fine. It's only when I am attempting to interpolate rotation with this method that I am experiencing this strange behavior.

Also, client.current\_state is a reference to the yawObject of this THREE.PointerLockControls type (rotation is happening via mouse input):

```
THREE.PointerLockControls = function ( camera ) {

    var scope = this;

    camera.rotation.set( 0, 0, 0 );

    var pitchObject = new THREE.Object3D();
    pitchObject.add( camera );

    var yawObject = new THREE.Object3D();
    yawObject.position.y = 10;
    yawObject.add( pitchObject );

    var PI_2 = Math.PI / 2;

    var onMouseMove = function ( event ) {

        if ( scope.enabled === false ) return;

        var movementX = event.movementX || event.mozMovementX || event.webkitMovementX || 0;
        var movementY = event.movementY || event.mozMovementY || event.webkitMovementY || 0;

        yawObject.rotation.y -= movementX * 0.002;
        pitchObject.rotation.x -= movementY * 0.002;

        pitchObject.rotation.x = Math.max( - PI_2, Math.min( PI_2, pitchObject.rotation.x ) );

    };

    this.dispose = function() {

        document.removeEventListener( 'mousemove', onMouseMove, false );

    };

    document.addEventListener( 'mousemove', onMouseMove, false );

    this.enabled = false;

    this.getObject = function () {

        return yawObject;

    };

    this.getDirection = function() {

        // assumes the camera itself is not rotated

        var direction = new THREE.Vector3( 0, 0, - 1 );
        var rotation = new THREE.Euler( 0, 0, 0, "YXZ" );

        return function(  ) {

                        var v = new THREE.Vector3();

            rotation.set( pitchObject.rotation.x, yawObject.rotation.y, 0 );

            v.copy( direction ).applyEuler( rotation );

            return v;

        };

    }();

};

```

# Answer
> 1 votes
The problem lies here:

```
  yawObject.rotation.y -= movementX * 0.002;

```

There is no guarantee that this will rotate in the expected direction. You were safe while you were not modifying `rotation` elsewhere, but changing `client.current_state.quaternion` in the main loop forces `rotation` to be recomputed from the quaternion you just assigned. Unfortunately the Euler angles (or at least the ones with the convention used here) wrap around when `y` reaches 90 degrees, and all sorts of weird things happen.

Here is a quick hack to fix your problem:

```
  yawObject.rotation.y -= movementX *
               (Math.abs(yawObject.rotation.x) < PI_2 ? 0.002 : -0.002);

```

But a more robust solution would be to never modify `yawObject` or `pitchObject` outside of `PointerLockControls`.

---
Tags: rotation, quaternion, interpolation, three.js
---


# Question
Title: Depth Peeling implementation problem: How to render the next layer? (OpenGL)
I try to implement order-independet transparency sticking to the pseudo code in the linked paper (page 4). I can't figure out how they are able to do this in OpenGL.

I am rendering the scene two times in two different framebuffers and then want to blend the two. The first rendering uses the normal depth test GL\_LESS. So I receive the nearest fragments in the first framebuffer.

I want to render the second nearest fragments in the second framebuffer. In the pseudo code they use the depth test GL\_GREATER for this. But this would result in having the "farest" fragments in the second framebuffer, right?

So how can I render the "second nearest" pixels to a framebuffer? Which depth test would be right and how to apply it in OpenGL?

# Answer
> 4 votes
You should perform the depth test in the fragment shader "manually". OpenGL doesn't support multiple depth tests, and that its just what you need to render the second nearest pixels, because:

* You need the second **front** pixels (`GL_LESS` over the actual depth buffer)
* You need the **second** front pixels (`GL_GREATER` over the depth buffer of the first framebuffer).

This can't be done without the help of a shader, as you can only choose one of those two depth tests to be performed at once.

So:

You will need to read from the depth buffer of the first framebuffer. This can be done "making" the first framebuffer use a texture as a depth buffer and reading values from it later using texture(). You can assign a texture as depth buffer to a framebuffer using:

```
//I'm using Java and LWJGL in the example, C++ implementation should be pretty similar.
int texture = glGenTextures();
//Set active texture, bind it, etc.
glTexImage2D(GL_TEXTURE_2D, 0,GL_DEPTH_COMPONENT24, X_RES, Y_RES, 0,GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, (FloatBuffer)null);
//Hey you active framebuffer, use this texture as your depth buffer from now on
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, texture, 0);

```

Set the depth test to `GL_LEQUAL` or `GL_LESS` (the default depth test). Draw the scene again into the second framebuffer, but performing a second depth test over the first framebuffer depth texture in the fragment shader, like so:

```
uniform sampler2D depthTexture;

//current projected position, being z the depth.
//Assuming x and y coordinates normalized, in [0..1] range.
//To transform from standard [-1..1] coordinates to [0..1]
//coordinates, you can do (pos.x+1)/2, for example.

in vec3 pos;

void main()
{
    if (pos.z <= texture(depthTexture, vec2(pos.x, pos.y)))
        discard; //Manually performing the GL_GREATER depth test for each pixel

    //Rest of your shader code, if needed
}

```

Done!

---
Tags: opengl, depth-buffer, transparency, post-processing
---


# Question
Title: Orion Leap Motion`Hand' does not exist in the type `Leap.Leap' - Compile error for core assets
I was playing with the example scenes provided by the Core Assets pack. Everything was working perfectly in Unity 5.3.2f1 until I opened the PinchingSandbox scene and added two script components to the HandControllerSandbox. I added Hand Cycler and Recording Controls. These scripts were available from the add component drop-down list. Naturally I planned to add my own code, but I first wanted to see if the scene would still run.

Instead of running I suddenly get hundreds of AABB aabb errors which by the look of things is still an unresolved Unity issue. So, I remove the two script components but this doesn't resolve the issue. Perplexed, given that the PinchingSandbox scene worked fine just before I added those two scripts, I waste no time deleting the project and starting afresh.

I imported the unity core assets from the unity asset store like before and now I am very perplexed that I get the following error messages (I have tried reimporting the assets):

I am using Orion, and am not using VR just yet

## Related (here for reference)

# Answer
> 1 votes
As pointed out to me by Joe\_Ward:

> Orion is not compatible with any earlier asset packages. You can use one or the other, but you cannot combine them.

And sure enough, I had tried importing both the Leap Motion Core Assets and the Leap Motion Orion assets which I had assumed were identical. Once I imported only one or the other the issue vanished. Consequentially, I can now add scripts and modify my virtual hand's behaviour with reckless abandon.

---
Tags: unity, assets, scripting
---


# Question
Title: dual contouring concept and term translations
I am working on a 3D sandbox mmo with destructible terrain, using Java and LWJGL. I looked at most options to achieve this and found that dual contouring would probably be the best option for me. I've read about every paper i could find on the internet about how to implement such a thing and, since i have a very basic experience in game/3d/complex programming, I've had quite a hard time. but I think I've found the solution i was looking for and would like to check with some more experienced programmer if my solution seems right and if I really successfully wrapped my mind around some of those pesky terms that were haunting my nights for the last few months;

**Edit: I will try and add some more precise detail as to what i already do here in bold**

so, first of all, I've created an object called voxel **when I say object, i refer the the user side's way of handling the data received from the server. I already compress the data as to have it fit a byte or a short and use bitwise operations. Voxels are loaded once from the server then stored to memory unless the server returns a change to that voxel (not sending entire chunks for a small change)**, a voxel knows it's type and it's "integrity" (in this case, how much that stone voxel has been mined for example. I think it refers the the volume i often read about?). Those voxels "will" be created from a pre generated world map for a persistent world. **Yes, the world will have overhangs and most of all, tunnels players can mine.**

then i got a chunk, composed of at most 32x32x32 voxels. A chunk knows it's world position and has a 3D array of voxels passed from the server **when first loaded to memory, then the client/server only updates the voxels that have changed since the last update**. A chunk also knows it's neighbors (if such neighbors have been loaded into memory, or creates a default chunk of 32x32x32 air voxels)

**To find the surface, inside a chunk, i check every voxel from the bottom,left,near (I think it is the right order to fit with the way OpenGL read it's coordinates?) to the top,right,far. each time, i take the current voxels and all it's 7 neighbors in a cube shape and check whether their is a type change from solid to air in any of them, indicating a surface running through that cube. If there's a type change, i compare every edges to see if there's a type change and if so, place the entersection of that edge using and average of both corners integrity. doing so for all 12 edges allows me to average all the planes to a single point inside that cube and create a vertex and store it in an array.**

The point where I'm confused is this: what should i do next? I think I should check along one edge **that displays a type change** to find the 3 other cubes that has the same edge and find their vertices. Since i know what direction the ground is (comparing the type change along the edge axis) I can deduce the front and back of the quad. taking 3 of those 4 vertices should allow me to get a normal from their dot product and from there, go around that normal CCW and send those vertices to the GPU for the rendering phase. **I guess the real question here is: How do I get the right order of vertices to form triangles that OpenGL can draw correctly from that large collection of vertices generated while finding the surface?**

In theory, in my mind, it makes sense! but I find it so much simpler than all those papers I've found, that i fear I've missed the boat completely! I get lost when it comes to Isosurface **(I guess here, the formula they're talking about would be the average of integrity along any type change?)** and hermite data **(here, should i read voxel collection instead?)** and most maths are slightly beyond my understanding yet (working on it tho and I progressed quite a bit) please, can you help me out here and guide me a bit?

# Answer
> 1 votes
0) The size of a chunk doesn't necessarily have to be a power-of-two (e.g. VoxelFarm uses 40^3 - still allows to use 16-bit indices). Speed gains associated with turning multiplication into shifts are negligible compared to choosing optimal chunk granularity for streaming/updates.

Since I didn't understand your question, I'll describe how my voxel engine currently works.

I populate chunks from Signed Distance Fields.

Each chunk contains raw voxel data (8-bit material IDs) and active (or intersecting the surface, zero-crossing) edges (Hermite data - see "Fast and Adaptive Polygon Conversion By Means Of Sparse Volumes"(2011)). An active edge exists only where a material transition takes place.

For each cell in a chunk (cell grid is dual to the voxel grid, i.e. cell corners are voxel centers and vice versa - for a nice pic, see page 7 in "A real-time virtual sculpting application by using an optimized hash-based octree"(2014)) I store up to 3 intersection points with normals on active edges (Hermite data).

As the cubic cell sweeps along the grid, only 3 edges need to be examined.

I calculate the voxel material at the current point (the maximal corner of the cell) and compare it to the previously computed neighbors (along axes X,Y and Z). It's better to explain with a picture, but I'll just dump the code:

```
    // Calculates the so-called 'Hermite data':
    // intersection points together with their normals
    // (where the surface crosses with the edges of the dual grid).
    // NOTE: as the cube sweeps along the grid, only 3 edges need to be examined.

    const V3F voxelCenter = GetVoxelCenter( it.x, it.y, it.z ) + chunkOffset;

    const SDF::Sample sample = _SDF->SampleAt( voxelCenter ); // sample the distance field

    const MaterialID voxelMaterial = GetMaterialAt( sample, _settings );
    volume->Set( it.x, it.y, it.z, voxelMaterial ); // store this voxel

    // Examine previously computed neighbors and calculate intersections on zero-crossing edges.
    if( volume->Get( it.x-1, it.y, it.z ) != voxelMaterial )
    {
        activeEdges.Add( ComputeIntersection( _SDF, voxelCenter, AXIS_X_ ) );
    }
    if( volume->Get( it.x, it.y-1, it.z ) != voxelMaterial )
    {
        activeEdges.Add( ComputeIntersection( _SDF, voxelCenter, AXIS_Y_ ) );
    }
    if( volume->Get( it.x, it.y, it.z-1 ) != voxelMaterial )
    {
        activeEdges.Add( ComputeIntersection( _SDF, voxelCenter, AXIS_Z_ ) );
    }

```

Decompression is symmetric and can be performed simultaneously with countouring:

```
/// Experiments show that 3-byte normals don't have enough precision.
/// 8 bytes - GOOD
class GridEdge
{
    UShort4 packed;
public:
    GridEdge()
    {
        packed.v = 0;   // initialize with invalid values
    }
    bool HasIntersection() const {
        return !!packed.v;
    }
    void Encode( const V3F& normal, const float f01 )
    {
        mxASSERT(V3_IsNormalized(normal));
        mxASSERT(f01 >= 0.0f && f01 <= 1.0f);
        packed.x = TQuantize<16>::EncodeSNorm( normal.x );
        packed.y = TQuantize<16>::EncodeSNorm( normal.y );
        packed.z = TQuantize<16>::EncodeSNorm( normal.z );
        packed.w = TQuantize<16>::EncodeUNorm( f01 );
    }
    const NormalDistance Decode() const
    {
        NormalDistance result;
        result.N.x = TQuantize<16>::DecodeSNorm( packed.x );
        result.N.y = TQuantize<16>::DecodeSNorm( packed.y );
        result.N.z = TQuantize<16>::DecodeSNorm( packed.z );
        result.d = TQuantize<16>::DecodeUNorm( packed.w );
        //NOTE: normalization is necessary,
        //otherwise the extracted surface will look noisy and perturbed (e.g. annoying notches)
        float length;
        result.N = V3_Normalized( result.N, length );
        return result;
    }
};

/// exact intersection points with normals (on zero-crossing edges only)
typedef DynamicArray< GridEdge >    HermiteDataT;

/// DC cell grid is dual to the voxel grid (its corners are voxel centers)
struct DualCell {
    EdgeIndex   edges[NUM_AXES_];   //!< indices into Hermite data; -1 == no intersection
    VertexIndex vertexId;
public:
    DualCell() {
        for( int i = 0; i < mxCOUNT_OF(edges); i++ ) {
            edges[i] = NO_INTERSECTION;
        }
        vertexId = NO_VERTEX;
    }
};

for( int iVoxelZ = StartZ; iVoxelZ <= MaxZ; iVoxelZ++ )
    {
        for( int iVoxelY = StartY; iVoxelY <= MaxY; iVoxelY++ )
        {
            for( int iVoxelX = StartX; iVoxelX <= MaxX; iVoxelX++ )
            {
                const Int3 it = { iVoxelX, iVoxelY, iVoxelZ };
                const V3F voxelCenter = GetVoxelCenter( it.x, it.y, it.z );

                const MaterialID voxelMaterial = volume.Get( it.x, it.y, it.z );
                const AABB24 cellAabb = { voxelCenter - VOXEL_SIZE, voxelCenter };

                // compute a vertex position for the current cell
                // and emit quads for the previously visited cell
                QEF_Solver::Input solverInput;
                solverInput.bounds = cellAabb;

    //  Cube edge enumeration (edges are split into 3 groups by axes X,Y,Z, numbered using right-hand rule):
    //  NOTE: voxel centers are at cube corners:
    //                    \WE'RE HERE!
    //         ______2_____\|/
    //        /|           /|         Corner vertices are numbered as follows:
    //       5 |11        6 |               6___________7
    //      /  |         /  |10            /|           /             Z
    //     |------3-----|   |             / |          /|             |  Y
    //     |   |_____1__|___|            /  |         / |             | /
    //     |   /        |   /           4------------5  |             |/
    //    8|  4        9|  7            |   2________|__3             O-------X
    //     | /          | /             |   /        |  /
    //     |/___________|/              |  /         | /
    //            0                     | /          |/
    //                                  0/___________1
    //
                DualCell & cell = dualCellGrid.Get( it.x, it.y, it.z );
                // Edge 2:
                if( volume.Get( it.x-1, it.y, it.z ) != voxelMaterial )
                {
                    UnpackActiveEdge_And_AddIntersectionIfExists( voxelCenter, cell, AXIS_X_, hermiteData, solverInput );
                }
                // Edge 6:
                if( volume.Get( it.x, it.y-1, it.z ) != voxelMaterial )
                {
                    UnpackActiveEdge_And_AddIntersectionIfExists( voxelCenter, cell, AXIS_Y_, hermiteData, solverInput );
                }
                // Edge 10:
                if( volume.Get( it.x, it.y, it.z-1 ) != voxelMaterial )
                {
                    UnpackActiveEdge_And_AddIntersectionIfExists( voxelCenter, cell, AXIS_Z_, hermiteData, solverInput );
                }
                // Edges 1 and 7:
                {
                    const DualCell& lowerCell = dualCellGrid.Get( it.x, it.y, it.z-1 );
                    const V3F lowerCellCenter = GetVoxelCenter( it.x, it.y, it.z-1 );
                    // 1
                    AddIntersectionIfExists( lowerCellCenter, lowerCell, AXIS_X_, hermiteData(), solverInput );
                    // 7
                    AddIntersectionIfExists( lowerCellCenter, lowerCell, AXIS_Y_, hermiteData(), solverInput );
                }
                // Edges 3 and 9:
                {
                    const DualCell& frontCell = dualCellGrid.Get( it.x, it.y-1, it.z );
                    const V3F frontCellCenter = GetVoxelCenter( it.x, it.y-1, it.z );
                    // 3
                    AddIntersectionIfExists( frontCellCenter, frontCell, AXIS_X_, hermiteData(), solverInput );
                    // 9
                    AddIntersectionIfExists( frontCellCenter, frontCell, AXIS_Z_, hermiteData(), solverInput );
                }
                // Edges 5 and 11:
                {
                    const DualCell& leftCell = dualCellGrid.Get( it.x-1, it.y, it.z );
                    const V3F leftCellCenter = GetVoxelCenter( it.x-1, it.y, it.z );
                    // 5
                    AddIntersectionIfExists( leftCellCenter, leftCell, AXIS_Y_, hermiteData(), solverInput );
                    // 11
                    AddIntersectionIfExists( leftCellCenter, leftCell, AXIS_Z_, hermiteData(), solverInput );
                }
                // Edge 8:
                {
                    const DualCell& neighbor = dualCellGrid.Get( it.x-1, it.y-1, it.z );
                    const V3F neighborCenter = GetVoxelCenter( it.x-1, it.y-1, it.z );
                    // 8
                    AddIntersectionIfExists( neighborCenter, neighbor, AXIS_Z_, hermiteData(), solverInput );
                }
                // Edge 4:
                {
                    const DualCell& neighbor = dualCellGrid.Get( it.x-1, it.y, it.z-1 );
                    const V3F neighborCenter = GetVoxelCenter( it.x-1, it.y, it.z-1 );
                    // 4
                    AddIntersectionIfExists( neighborCenter, neighbor, AXIS_Y_, hermiteData(), solverInput );
                }
                // Edge 0:
                {
                    const DualCell& neighbor = dualCellGrid.Get( it.x, it.y-1, it.z-1 );
                    const V3F neighborCenter = GetVoxelCenter( it.x, it.y-1, it.z-1 );
                    // 0
                    AddIntersectionIfExists( neighborCenter, neighbor, AXIS_X_, hermiteData(), solverInput );
                }

                if( solverInput.numPoints > 0 )
                {
                    QEF_Solver::Output solverOutput;
                    solver.Solve( solverInput, solverOutput );

                    cell.vertexId = mesh.AddVertex( solverOutput.position );
                }//if( solverInput.numPoints > 0 )

                // Emit quads for each intersecting edge.
                const MaterialID v000 = volume.Get( it.x-1, it.y-1, it.z-1 );
                const MaterialID v100 = volume.Get( it.x,   it.y-1, it.z-1 );
                const MaterialID v010 = volume.Get( it.x-1, it.y,   it.z-1 );
                const MaterialID v001 = volume.Get( it.x-1, it.y-1, it.z   );

                const bool originInside = (v000 != EMPTY_SPACE); // if the voxel material is not AIR

                if( v000 != v100 )
                {
                    //  Connect the 4 cells sharing the edge along the X axis:
                    //
                    //         .-----.    Z
                    //        /  0  /|    |  Y
                    //       /-----/0|    | /
                    //      /  1  /|/|    |/
                    //     .-----|1|3|    O-------X*
                    //     |  1  |/|/
                    //     |-----|2/
                    //     |  2  |/
                    //     .-----.
                    //
                    const DualCell& cell1 = dualCellGrid.Get( it.x, it.y-1, it.z   );
                    const DualCell& cell2 = dualCellGrid.Get( it.x, it.y-1, it.z-1 );
                    const DualCell& cell3 = dualCellGrid.Get( it.x, it.y,   it.z-1 );

                    if( originInside && CCW_FrontFacing ) {
                        CreateQuad( mesh, cell.vertexId, cell1.vertexId, cell2.vertexId, cell3.vertexId );
                    } else {
                        CreateQuad( mesh, cell3.vertexId, cell2.vertexId, cell1.vertexId, cell.vertexId );
                    }
                }
                if( v000 != v010 )
                {
                    //  Connect the 4 cells sharing the edge along the Y axis:
                    //
                    //       .-----.-----.     Z
                    //      /  3  /  0  /|     |  Y*
                    //     .-----+-----|0|     | /
                    //     |  3  |  0  |/|     |/
                    //     |-----X-----|1/     O-------X
                    //     |  2  |  1  |/
                    //     .-----.-----.
                    //
                    const DualCell& cell1 = dualCellGrid.Get( it.x,   it.y, it.z-1 );
                    const DualCell& cell2 = dualCellGrid.Get( it.x-1, it.y, it.z-1 );
                    const DualCell& cell3 = dualCellGrid.Get( it.x-1, it.y, it.z   );

                    if( originInside && CCW_FrontFacing ) {
                        CreateQuad( mesh, cell.vertexId, cell1.vertexId, cell2.vertexId, cell3.vertexId );
                    } else {
                        CreateQuad( mesh, cell3.vertexId, cell2.vertexId, cell1.vertexId, cell.vertexId );
                    }
                }
                if( v000 != v001 )
                {
                    //  Connect the 4 cells sharing the edge along the Z axis:
                    //
                    //                           Z*
                    //         .-----.-----.     |  Y
                    //        /  1  /  0  /|     | /
                    //       .-----.-----.0|     |/
                    //      /  2  /  3  /|/      O-------X
                    //     .-----+-----|3/
                    //     |  2  |  3  |/
                    //     .-----.-----.
                    const DualCell& cell1 = dualCellGrid.Get( it.x-1, it.y,   it.z );
                    const DualCell& cell2 = dualCellGrid.Get( it.x-1, it.y-1, it.z );
                    const DualCell& cell3 = dualCellGrid.Get( it.x,   it.y-1, it.z );

                    if( originInside && CCW_FrontFacing ) {
                        CreateQuad( mesh, cell.vertexId, cell1.vertexId, cell2.vertexId, cell3.vertexId );
                    } else {
                        CreateQuad( mesh, cell3.vertexId, cell2.vertexId, cell1.vertexId, cell.vertexId );
                    }
                }
            }//X
        }//Y
    }//Z

```

**How do I get the right order of vertices to form triangles that OpenGL can draw correctly from that large collection of vertices generated while finding the surface?**

You simply create a quad for each active edge, connecting the four cells which share this edge (read Surface Nets / Dual Contouring). The orientation of the quad is easily derived from the active edge. Then you split each quad to generate triangles for rendering:

```
    void AddQuad(
        const VertexIndex vertex0,
        const VertexIndex vertex1,
        const VertexIndex vertex2,
        const VertexIndex vertex3
        )
    {
        mxASSERT(vertex0 != NO_VERTEX);
        mxASSERT(vertex1 != NO_VERTEX);
        mxASSERT(vertex2 != NO_VERTEX);
        mxASSERT(vertex3 != NO_VERTEX);
#if 0
        const MeshTriangle tri1 = { vertex0, vertex1, vertex2 };
        this->triangles.Add( tri1 );
        const MeshTriangle tri2 = { vertex0, vertex2, vertex3 };
        this->triangles.Add( tri2 );
#else
// Better results are obtained if we triangulate each quad by splitting it along the shortest diagonal.
// https://en.wikipedia.org/wiki/Distance_geometry_problem#Cayley.E2.80.93Menger_determinants
        const float diagonal02 = DistanceBetween( vertices[vertex0].xyz, vertices[vertex2].xyz );
        const float diagonal13 = DistanceBetween( vertices[vertex1].xyz, vertices[vertex3].xyz );
        if( diagonal02 < diagonal13 ) {
            const MeshTriangle tri1 = { vertex0, vertex1, vertex2 };
            this->triangles.Add( tri1 );
            const MeshTriangle tri2 = { vertex0, vertex2, vertex3 };
            this->triangles.Add( tri2 );
        } else {
            const MeshTriangle tri1 = { vertex1, vertex3, vertex0 };
            this->triangles.Add( tri1 );
            const MeshTriangle tri2 = { vertex1, vertex2, vertex3 };
            this->triangles.Add( tri2 );
        }
#endif
    }

```

HTH. And what the hell is "the average of integrity along any type change"?

---
Tags: java, lwjgl, voxels
---