# Question
Title: 2D tile-based collisions: using different methods by tile?
I'm trying to write a collision handling method that handles each of the 9 potentially colliding tiles (the player's and the 8 around him) differently according to a "CollisionType" value attached to each tile, the goal being a system that allows a player to walk on jagged slopes or objects smaller than a tile width, but only doing per-pixel checks on tiles that actually need it--plain, square tiles just get the bounding box treatment.

This is my first attempt at cobbling together a collision detection system that isn't a blatant clone of tutorial code. In fact, I've yet to find any code online that works like this, leading me to believe that it's probably a terrible idea--which is why I'm going to post the skeleton of what I'm working on here (thoroughly commented) and ask if the way I'm doing this makes any sense at all.

```
public void xHandleCollisions()
    {
        /*
         * Preparations. Find out where the entity is, what tiles are around
         * it, its collision box, and where it's trying to go.
         */
        //get the cell the entity is in
        Vector2 currentLoc = LevelManager.CurrentMap.GetCellByPixel(worldLocation);

        //from that, find the range of indexes to check for collision--
        //entity can't possibly touch anything it's not adjacent to,
        //unless it's moving more than one tile per frame, which I can deal with later
        //if it ever actually happens.
        int startX = (int)MathHelper.Clamp(currentLoc.X - 1, 0, LevelManager.CurrentMap.MapWidth);  //[o][o][o]-1
        int endX = (int)MathHelper.Clamp(currentLoc.X + 1, 0, LevelManager.CurrentMap.MapWidth);    //[o][x][o]
        int startY = (int)MathHelper.Clamp(currentLoc.Y - 1, 0, LevelManager.CurrentMap.MapHeight); //[o][o][o]+1
        int endY = (int)MathHelper.Clamp(currentLoc.Y + 1, 0, LevelManager.CurrentMap.MapHeight);    //-1    +1

        //now, create rectangles representing the entity's current collision box
        //and its desired new position.
        Rectangle oldPosition = CollisionRectangle; //<--Thus far, any attempt at
                                                    //changing this from being just
                                                    //the sprite's frame has ended
                                                    //with bizarre errors.
        Rectangle newPosition = CollisionRectangle;
        newPosition.Offset((int)velocity.X, (int)velocity.Y);

        //don't need these anymore this frame, zero them out for next frame
        velocity.X = 0;
        velocity.Y = 0;

        //if there's no difference, just return
        if (oldPosition.Equals(newPosition)) return;

        //for each of the rectangles, get four vectors for per-pixel terrain collisions
        //   ___x___    <--Head, for colliding with tiles above
        //  |       |
        //  |       |
        //  x       x   <--for determining horizontal collisions and
        //  |___x___|       how steep a slope can be climbed
        //      ^--for determining collisions with ground

        //old
        Vector2 oldHead = oldPosition.GetTopCenter();
        Vector2 oldFeet = oldPosition.GetBottomCenter();
        Vector2 oldLeft = new Vector2(
            oldPosition.GetBottomCenter().X - (oldPosition.Width / 2),
            oldPosition.GetBottomCenter().Y - (oldPosition.Height / 10));
        Vector2 oldRight = new Vector2(
            oldPosition.GetBottomCenter().X + (oldPosition.Width / 2),
            oldPosition.GetBottomCenter().Y + (oldPosition.Height / 10));

        //new
        Vector2 newHead = newPosition.GetTopCenter();
        Vector2 newFeet = newPosition.GetBottomCenter();
        Vector2 newLeft = new Vector2(
            newPosition.GetBottomCenter().X - (newPosition.Width / 2),
            newPosition.GetBottomCenter().Y - (newPosition.Height / 10));
        Vector2 newRight = new Vector2(
            newPosition.GetBottomCenter().X + (newPosition.Width / 2),
            newPosition.GetBottomCenter().Y + (newPosition.Height / 10));

        /*
         * Now, the actual collision detection. Calculated differently for each tile
         * depending upon what collision type the tile has, but each resulting in an
         * adjustment (or no adjustment) to the newPos rectangle.
         */
        Tile.CollisionType cType;
        //Check horizontal collisions with all tiles,
        //adjusting newPosition as little as possible.
        for (int x = startX; x <= endX; x++)
        {
            for (int y = startY; y <= endY; y++)
            {
                cType = LevelManager.CurrentMap.GetTileAtCell(x, y).GetCollisionType;//<---

                switch (cType)
                {
                    case Tile.CollisionType.None:
                        //do nothing
                        break;
                    case Tile.CollisionType.Solid:
                        //adjust x movement to not enter this tile.
                        //first, get the collision depth between the tile and newPosition.
                        Vector2 collisionDepth =
                            RectangleExtensions.GetIntersectionDepth(newPosition, LevelManager.CurrentMap.CellWorldRectangle(x, y));
                        //if its x is zero, we can skip it--there's no collision with this tile.
                        if ((int)collisionDepth.X != 0)
                        {
                            //if there's a collision, adjust newPos so there isn't,
                            //but only in the x direction for now
                            newPosition.Offset((int)collisionDepth.X, 0);
                        }
                        break;
                    case Tile.CollisionType.Platform:
                        //x dimension, so do nothing
                        break;
                    case Tile.CollisionType.PerPixel:
                        //do per pixel collision detection, checking
                        //points against tile collision layer so player
                        //can move on uneven terrain or stand on objects
                        //smaller than a full tile width

                        break;
                }

            }
        }

        //Check vertical collisions with all tiles, adjusting newPosition as little as possible.
        // Treat Platforms as impassable if they're located below oldFeet, otherwise passable.
        for (int x = startX; x <= endX; x++)
        {
            for (int y = startY; y <= endY; y++)
            {
                cType = LevelManager.CurrentMap.GetTileAtCell(x, y).GetCollisionType;

                switch (cType)
                {
                    case Tile.CollisionType.None:
                        //do nothing
                        break;
                    case Tile.CollisionType.Solid:
                        //adjust y movement to not enter this tile
                        //first, get the collision depth between the tile and newPosition.
                        Vector2 collisionDepth =
                            RectangleExtensions.GetIntersectionDepth(newPosition, LevelManager.CurrentMap.CellWorldRectangle(x, y));
                        //if its y is zero, we can skip it--there's no collision with this tile.
                        if ((int)collisionDepth.Y != 0)
                        {
                            //if there's a collision, adjust newPos so there isn't,
                            //but only in the y direction
                            newPosition.Offset(0, (int)collisionDepth.Y);
                        }
                        break;
                    case Tile.CollisionType.Platform:
                        //if oldFeet.y >= platform height, treat as solid
                        //else, do nothing

                        break;
                    case Tile.CollisionType.PerPixel:
                        //do per pixel collision detection, checking
                        //points against tile collision layer

                        break;
                }

            }
        }

        //At this point, newPosition should be the best valid movement. Adjust worldLocation
        //to match the coordinates of newPosition's origin.
        worldLocation.X = newPosition.X;
        worldLocation.Y = newPosition.Y;
        //done?
    }

```

So...

**Question:** Logically speaking, is this feasible? Or is there some massive flaw in the process that I've so far been unable to see?

**Second Question:** If this approach is too terrible to save, is there another, better way to accomplish the same thing? I don't want to limit the game to a few predetermined slope angles, and I'd like the character to be able to stand on an object that's far less than the full width of a tile (and not float in the air next to it, either).

I'm aware that some of the stored vectors are currently pointless (most of the old\* ones other than oldFeet, for instance); I'll cull them out later if I don't find a use for them. And yes, I know the code for solid tiles is wrong already--the character falls from his spawn location, lands on the ground correctly, but then can't move at all.

# Answer
> 1 votes
There doesn't seem to be anything inherently wrong with the method of your collision detection code here.

It really depends on how you are going to do to check the Tile.CollisionType.PerPixel collision type, as this will really want to be high performance.

The fact that you are trying to be as simple as possible in only checking the most basic collision type you can is a good thing. The same thing happens in 3D:

Bounding Sphere =\> Smaller Spheres within =\> Face Collision checks

To possibly make the code more future proof, and maybe a more readable (smaller methods are nicer), you could have each tile as an interface with a collision method.

class ITile { bool CheckCollision(...); };

class PerPixelTile : ITile { bool CheckCollision(...) { // check pixel collision here... } };

---
Tags: xna, 2d, collision-detection, collision-resolution
---


# Question
Title: which courses in Computer Science are really needed for game development?
I would like to know what courses that somebody interested in game development, should take in a Computer Science Career?

I suppose that are necessary for example:

```
- Discrete Mathematics
- Computer Graphics
- some programming language courses, for example C++ or C#
- AI
- Web programming

```

what else does anybody involved in this field could recommend me? I got a group of universities that I would like to apply, but their computer science curricula are not the same for every case.

This question is not for generating a debate about which career to follow. I think the natural way will be to follow CS, but here the question is what model would be more suitable according to the standard curricula?

Somebody from mathematics would lack the background in CS, and also that problem comes with people from arts.

Any advice?

# Answer
> 3 votes
## TLDR

* Talk to current CS students and recent CS alumni of the colleges you're interested in. Be aware that they will be biased toward speaking highly of their school, so ask for more advice about specific classes that they thought did or did not benefit them greatly
* A class about language syntax is a gigantic waste of your time and tuition
* CS degrees are about getting foundational knowledge not easily self-taught
* Attend every single one of your Linear Algebra lectures

Also (added because of Panda Pajama's comment), take history and art and music and literature classes.

## Foreword to a lengthy answer

The honest truth is that no CS curriculum can prepare you for ***game development***, but every single course in a respectable CS curriculum will benefit you in some way if you are interested in contributing to the process of game development as a ***game programmer***. That's what my answer caters to.

How useful my answer is to you will change as you go through school and work on more of your own game projects and understand better what roles you want to fill. You will probably leave school as a fairly different person from the one you entered as. Your desire to work on games may not change, but how you see yourself going about doing that likely will.

## A lengthy answer

I'm going to have to disagree with Josiah Hester and recommend that you not take a C++ course, because it is very likely that the course will be either too out-of-date (using bad inheritance) or too up-to-date (too much standard library), and almost certainly inadequate for working with C++ on the level that you'd be expected to at a game company. You can only get to that level by working with the language on your own time with your own projects, which is time you'd have to spend on top of a C++ class anyway. Save your classroom time for concepts that aren't as easily (or in this case, optimally) self-taught.

Take instead a class that requires that you use C (not C++) to implement low level OS features like a shell, a memory allocator, or a scheduler. "Operating Systems" is the typical name for the upper level version of this course (intro courses may be called Systems or Architecture or something similar).

In fact, don't take any classes named after a specific language. And avoid colleges that have a list of programming languages as their course sequence. If you happen to learn a language while learning about some other topic (hard to learn systems/architecture without learning assembly and C), that's great. *But a class about language syntax is a gigantic waste of your time and tuition.*

Don't take any class called "Web Programming" unless it's a fun elective type thing and you're looking to fill credits with something that is new material but isn't essential to get into your brain. Same goes for anything about trendy platforms, like "iPhone Programming." Just go watch the Stanford videos on iTunes and make an app on your own. It'll look more impressive if you're applying to be an iOS game programmer somewhere.

University classes can't possibly keep up with what's current in industry, so you have to use them for what they're good for: foundational knowledge not easily self-taught.

If at all possible, your best source of information on the usefulness of any given course will be current students and recent alumni.

### Sampling of standard courses you should expect to take

* Data Structures
* Algorithms
* Operating Systems
* Discrete Math
* Linear Algebra

### Useful higher-level elective classes

(Note, don't take *all* of these, you might go crazy. Let your developing interests guide you.)

* Artificial Intelligence (teaches you academic AI, which isn't directly useful for games, but being exposed to it is helpful)
* Sometimes a course in Graphics can be helpful, research the professors that teach it
* Machine Learning
* Heuristics
* Compilers
* Networks and distributed systems (again, less practical game programming knowledge, but the value is in the little things you learn along the way)
* Some deep thinking class on math and computation, usually named something like Theory of Computation, Numerical Computing, or Numerical Analysis

Be wary of classes that are purely about making a project, as game studios will be more interested in projects you worked on outside of class, and will specifically ask you (it was specifically asked of me), "This game project on your resume, did you make that in class or in your spare time?"

This isn't an absolute thing of course, but keep this in the back of your mind as you choose classes. If the professor is really good and you'd really like to allocate part of your semester toward dedicated work on a project, then you've already convinced yourself you should take it.

Note again that the classes I've listed aren't "Making a Flash Game 101." I've beaten this dead horse many times in this answer, but classes like that just aren't worth the cost of a college degree. Even if you get a free ride via scholarship or other means, it will have been a waste of that scholarship/means.

Maybe this is a super US-centric or spoiled attitude about things, but think of it like this: *You* are the customer at your university. Ensure you receive a product of a certain quality, and do all that is necessary in order to ensure its safe delivery.

# Answer
> 1 votes
It depends.

If you want to work on game *design*, CS is actually not the best way to go. Game Design is more straight math, art, and Communications. Knowing CS is good for implementing prototypes, but the heavy lifting should be done by someone else if you are serious about seeing your vision through.

"Game Development" is fairly broad, you could argue that concept artists "develops" games (which actually happens far more often than you would believe, Ed McMillen of Super Meat Boy and Binding of Isaac fame spends most of his time on Art and Design, he has others do the technical bits for him), so pick an aspect (art, sound, programming, whatever) and push it as *hard as you can*. Being really good at one thing makes you far more attractive in most cases than being "eh" at most of them.

So lets assume you are set to make a game from start to finish, by yourself. In that case, CS definitely can't hurt. You will be able to make game engines do things they weren't quite built for, you'll understand why a computer is freaking out the way it is, and best of all, you'll know how to at least figure out how to fix it. It is a commitment, and far worth it if you put time in it. You will also find the truth in the saying "Those who make games, don't play games." It takes time.

If you are just in this to "make games", there is no faster way to discourage yourself than learning C++/C. I'm sorry, it is the ***worst*** starting point. If it is your first time programming, learn Python, Java, or Game-Maker script, or heck, C#. **Only learn C++ if you are willing to commit to the time and effort to master it.** You will spend most of your time with C++ *LEARNING C++, not making games.* You have been warned.

Also be aware, CS itself splits into a lot of sub-fields that may or may not deal with games. Off the top of my head, there are:

* Algorithms
* Networking
* Graphics (shaders)
* Graphics (hardware)
* HCI
* AI
* UI/GUI
* Image Processing
* Database design

...among others. Getting as CS degree is akin to getting a "Teaching" degree. A person who knows better may squint and ask you what your specialty is. Always be asking yourself what you want to do, and do it on your own. Because above all, Computer Science education is based off of methodology more than technology. You "learn to learn". You may learn Java in school, but who knows how long that will be around. Your employer won't teach you the latest and greatest, and your time at work will be spent working on what they give you. Know what you are paying for if you decide to go this path in higher education.

If you are already down the CS path, C++ then conversely becomes a **good** choice, as it basically has very core concepts built right in, such a memory management, algorithm design, and on top of that, you will need to do things akin to how the computer would do it. A lot of these things are lost on more powerful languages. Take a class on that or C, either will be good foundations. If the starter language is Java (like my school), consider taking an ECE class with assembler or micro-controllers, so you get hands on with lower level languages.

You will want to avoid "pop" classes, as the technology you learn there will already be on its way out when you get out. Conceptual classes are better. Math classes may seem pointless in the moment, but it all comes around when you are trying to maximize processes or transform 3D imagery. Algorithm analysis is good, Statistics is a must. Linear algebra is basically all of Graphics. Software Engineering is learning how to program as a team. Human Computer Interfaces teaches how to program a app for an actual person, not just your (tech-savy, command line master) self.

# Answer
> 0 votes
Aside from object-oriented design, I would highly recommend Machine Learning and Artificial Intelligence be thrown into your docket. Additionally, project-based systems classes are great because they tend to be crash courses in handling a large modular project on a team (which is important for game development).

Learn C. Even if you end up working in C++ or C#, learning C99 is a great trial by fire for a developer, and will give you the familiarity with how computers work to handle a variety of challenges you may encounter down the road.

You'll also want to look at their math departments. If you're serious about graphics, then some linear algebra will help. Also, graph theory can be a powerful tool, and can also inspire some fun game mechanics.

Source: I'm an undergraduate Mathematics student, working as a developer at a gaming company.

# Answer
> 0 votes
None.

You can make games without a Computer Science degree.

---
Tags: career
---


# Question
Title: limiting jump forces to achieve a maximum jump height
A player and the world are modeled using a physics engine. Jumping is modeled by applying a vertical upward force to the player's physics body when the jump button is pressed.

The upward force is being applied every update tick that the button is held. This makes the player accelerate upward so long as the button is held, potentially forever, rather than limiting the jump to a predetermined maximum jump height

How can this be fixed so that pressing the jump button allows a limited jump height, even if the button is held down indefinitely?

# Answer
Jumping is usually just one impulse, rather than a continuous force. Many games don't allow influencing this force and just allow moving sideways. (Or not even that.)

```
if(onGround && jumpKeyPressed)
{
  yDir -= 90;
  onGround = false;
}
if(!onGround)
{
  yDir += gravity * dTime;
  /* Check for collisions on y-Direction */
}

```

If you really want to make it possible to the player to influence the jump height, you can use a initial impulse and make the influence on it less than gravity.

```
jumpInfluence = gravity / 2;
[...]
if(!onGround)
{
  if(jumpKeyPressed)
    yDir -= jumpInfluence * dTime;
  [...]
}

```

If you really want the player to influence the jump even more you'll need to decrease the influence over time.

```
[...]
if(jumpKeyPressed)
  yDir -= (jumpInfluence / (1.f+timeSinceJump)) * dTime;
[...]

```

In this case after a second the influence is halved, after 2 seconds it's a third etc.
> 1 votes

# Answer
One simple solution is to keep a timer and a boolean. When the button is first pressed, if the boolean is false and the player is on the ground, apply the force and start set thee timer to some specific and set the boolean to true. When the button is released, set the boolean to false. If the boolean is true, decrement the timer by the time delta. Keep applying the force each frame so long as the boolean is true and the timer hasn't expired.

```
bool is_jumping = false
float jump_timer = 0.0

jump_pressed () {
  if (!is_jumping && is_on_ground())) {
    is_jumping = true
    jump_timer = 0.5
  }
}

jump_released () {
  is_jumping = false
}

update (float time_delta) {
  if (is_jumping) {
    jump_timer = max(0.0, jump_timer - time_delta)
    if (jump_timer > 0.0)
      apply_jump_force()
  }
}

```

Finding the ideal timer length and force will take some tweaking. You could with some work derive the right values to get a particular jump height, but I would play with the values until you get something that feels right.

The advantages of this approach are that pressing the button for longer results in a higher jump, which is what you want if you want your platformer to feel "right" (like Mario).

If you want stiffer controls, you could allow a fixed jump velocity. Just set that boolean when the player jumps, and reset it when the player lands.

```
 bool is_jumping = false

 jump_pressed () {
   if (!is_jumping && is_on_ground())
     is_jumping = true
     apply_jump_force()
   }
 }

 update () {
   if (is_on_ground())
     is_jumping = false
 }

```

Be mindful that will require a little more work if update is called *after* `jump_pressed` is called but before physics updates and the jump force is applied. You might need an extra bool or check to avoid resetting `is_jumping` on that first frame.

More advanced versions can start the jump after the button is released (measuring how long the button was held) or after a timer expired (it should be a pretty short timer).

You can with this method also use fixed gradiations of jump height, e.g. a short jump if the button time is 0 - 0.05 seconds and a high jump if button time is 0.05 - 0.1 seconds. All that needs to change there is the amount of force applied for a decent effect.

Even with variable jump height, you might want a stable upward velocity, up to a point, rather than the high initial jump velocity and steady gravity acceleration. in this case, you need to each frame during jump ascent (measured again with a timer) calculate the necessary force to apply to achieve the desired velocity. This requires some knowledge of physics formulas and how your physics library updates, but is otherwise pretty simple.
> 0 votes

---
Tags: physics, physics-engine, jumping
---


# Question
Title: Collision detection - Smooth wall sliding, no bounce effect
I'm working on a basic collision detection system that provides point - OBB collision detection. I have around 200 cubes in my environment and I check (for now) each of them in turn and see if it collides. If it does I return the colliding face's normal, save the old player position and do some trigonometry to return a new player position for my wall sliding.

**edit**
I'll define my meaning of wall sliding: If a player walks in a vertical slope and has a slight horizontal rotation to the left or the right and keeps walking forward in the wall the player should slide a little to the right/left while continually walking towards the wall till he left the wall. Thus, sliding along the wall.

Everything works fine and with multiple objects as well but I still have one problem I can't seem to figure out: **smooth wall sliding**. In my current implementation sliding along the walls make my player bounce like a mad man (especially noticable with gravity on and moving forward).

I have a velocity/direction vector, a normal vector from the collided plane and an old and new player position. First I negate the normal vector and get my new velocity vector by substracting the inverted normal from my direction vector (which is the vector to slide along the wall) and I add this vector to my new Player position and recalculate the direction vector (in case I have multiple collisions).

I know I am missing some step but I can't seem to figure it out.

Here is my code for the collision detection (run every frame):

```
Vector direction;
Vector newPos(camera.GetOriginX(), camera.GetOriginY(), camera.GetOriginZ());
direction = newPos - oldPos; // Direction vector
// Check for collision with new position
for(int i = 0; i < NUM_OBJECTS; i++)
{
    Vector normal = objects[i].CheckCollision(newPos.x, newPos.y, newPos.z, direction.x, direction.y, direction.z);
    if(normal != Vector::NullVector())
    {
        // Get inverse normal (direction STRAIGHT INTO wall)
        Vector invNormal = normal.Negative();
        Vector wallDir = direction - invNormal; // We know INTO wall, and DIRECTION to wall. Substract these and you got slide WALL direction
        newPos = oldPos + wallDir;
        direction = newPos - oldPos;
    }
}

```

Any help would be greatly appreciated!

---

**FIX** I eventually got things up and running how they should thanks to Krazy, I'll post the updated code listing in case someone else comes upon this problem!
```
for(int i = 0; i < NUM_OBJECTS; i++)
{
    Vector normal = objects[i].CheckCollision(newPos.x, newPos.y, newPos.z, direction.x, direction.y, direction.z);
    if(normal != Vector::NullVector())
    {
        Vector invNormal = normal.Negative();
        invNormal = invNormal * (direction * normal).Length(); // Change normal to direction's length and normal's axis
        Vector wallDir = direction - invNormal;
        newPos = oldPos + wallDir;
        direction = newPos - oldPos;
    }
}

```

# Answer
I think you need to multiply invNormal by the length of direction before making the subtraction.

```
Vector invNormal = normal.Negative();
invNormal *= direction.length
Vector wallDir = direction - invNormal;

```
> 6 votes

# Answer
You want to lose all the velocity in the direction of the normal of the wall. To do this, project the current direction onto the wall normal to get the wall part of the velocity/direction.

```
projected = normal * dot(direction, normal);
direction = direction - projected

```

Last line might have to have the sign flipped depending on the normals direction (in or out of the wall).
> 5 votes

---
Tags: c++, 3d, collision-detection
---


title: Storing a hex grid

text:
# Question
Title: Storing a hex grid
I've been creating a small hex grid framework for Unity3D and have come to the following dilemma. This is my coordinate system (taken from here):

It all works pretty nicely except for the fact I have no idea how to store it. I originally intended to store this in a 2D array and use images to generate my maps.

One problem was that it had negative values (this was easily fixed by offsetting the coordinates a bit).

However, due to this coordinate system, such an image or bitmap would have to be diamond shaped - and since these structures are square shaped, this would cause a lot of headaches even if I hack something together. Is there anything I'm missing that could fix this? I recall seeing a forum post regarding this in the unity forums but I can no longer find the link.

Is writing a set of coordinate translators the best solution here?

If you guys think it would be helpful, I can post code and images of my problem.

# Answer
> 9 votes
The parallelogram coordinates you're using are easier to work with, but they do have the drawback of being weird for rectangular maps. One approach is to store it with the offset coordinates but actually use parallelogram coordinates in your game logic.

Observation: in each row of the map, the grid data is contiguous. All the wasted space is on the left and right.

Solution: within that row, store data starting at the leftmost column instead of the column marked 0. Calculate the first column of the rectangular map in *your coordinate system*, then subtract that from the column coordinate to determine where in the array it goes. This works for negative column coordinates too.

Perform the conversion in the getter and setter for the map, with something like this:

```
inline function get(q, r) {
    first_column_in_this_row = -floor(q/2);
    return array[r][q - first_column_in_this_row];
}

```

You'll have to modify this to work with your choice of coordinates and map (pay attention to off by one differences). In some layouts you'll want to offset the columns by the row instead of vice versa.

You can use the same trick to make maps of other shapes; it's not limited to rectangles.

If you're using C or C++ you can use pointer arithmetic to make this faster. Instead of storing an array of pointers to arrays, store an array of pointers that have been adjusted by `first_column_in_row`. (This may not be portable)

# Answer
> 6 votes
*Personally, I would prefer simplicity over saving memory. Don't optimize until needed!*

If you're still bent on saving a few bytes, here's how you can do it:

1. Slice the parallelogram in half to form two right triangles
2. Rearrange the two triangles to form a rectangle.
3. *(Note I added the green buffer strip so the math works out nicely.)*

Python code to map rectangle coordinates to parallelogram coordinates and back:

```
# Height of rectangle
H = 15

def r2p(x, y):
"rectangle to parallelogram"
if y < -x/2 + H:
    y = y + H
return (x - 1, y)

def p2r(x,y):
"parallelogram to rectangle"
if y >= H:
    y = y - H
return (x + 1, y)

```

# Answer
> 1 votes
It's not necessary to distort your map, as conversion between rectangular and "canonical" coordinates is quick and easy. Here is a link to an intro on how to do it:

Converting between Rectangular and Canonical hex coordinates

This technique combines lazy evalutation with caching of calculated conversions.

---
Tags: image, grid, hexagonal-grid, storage
---


title: Path finding between multiple maps

text:
# Question
Title: Path finding between multiple maps
I'm interested in path finding between multiple maps - could be indoor/outdoor maps, different levels in a building etc but the main restraint is that there are one (or more) ingress/egress points between the different maps. I've looked and couldn't find any good solutions, yet I'm aware of several games which use similar systems.

I've found this paper - Hierarchical Shortest Path Finding Applied to Route-Planning for Wheelchair Users which seems to address a similar issue, but it is purely theoretical.

Anyone done similar with some experience they could share, or some tips?

# Answer
I did something similiar several years ago for a mockup demo of cyberpunk-themed "Jagged Alliance" clone which was supposed to have large maps filled with skyscrapers. It was a stupid idea, apparently maps for tactical combat should be tidy and easily understandable :)

In order to have a quicker pathfinding one global map was divided into several discrete square-shaped areas. Once we have a criteria for areas, it's time to find possible "entrances" between each pair of adjacent areas. "Entrance" is a transition point which shows that this agent can enter this area at this point.

In your example with building of several floors, each floor would be an area with borders defined by floor, ceiling and outer walls; and varius holes in wall or floor, or ladders would be entrances, there could be a lot of them. So entrances basically link path nodes from one area to path nodes in the other area.

Once you identified entrances, you'll need to find all possible ways to traverse each area resulting in a "map of area entrances to adjacent area entrances" with edges between entrances showing length of this path through area.

If everything went right, your agent standing on the 1-st floor will be able to find its way to that special box on the 4-th floor quickly. Maybe something similiar could be used in your problem of multiple maps, so hope it helps.
> 5 votes

# Answer
I believe you are looking for Hierarchical Path-Finding A-star such as described here:

HPA-\*
> 1 votes

---
Tags: path-finding
---


# Question
Title: How to finish a sprite animation before going back to default animation?
I want to run a animation until it has gone through all the frames, even when the activation key is no longer held. After the animation is completely finished, it goes back to walking state. I also want to force the animation to finish first before the player can trigger the new animation.

```
     if (mCurrentState == State.Walking)
        {
            action = "stand";
            Update_Stand(gameTime);

            if (aCurrentKeyboardState.IsKeyDown(Keys.Left) == true)
            {
                action = "run";
                feetPosition.X += MOVE_LEFT;
                effect = SpriteEffects.None;

                Update_Run(gameTime);

            }
            else if (aCurrentKeyboardState.IsKeyDown(Keys.Right) == true)
            {
                action = "run";
                feetPosition.X += MOVE_RIGHT;
                effect = SpriteEffects.FlipHorizontally;

                Update_Run(gameTime);
            }

            if (aCurrentKeyboardState.IsKeyDown(Keys.Z) == true)
            {
                mCurrentState = State.Hitting;
            }
        }

        if (mCurrentState == State.Hitting)
        {
            action = "hit";

            Update_Hit(gameTime);

            mCurrentState = State.Walking;
        }

```

My Update\_Hit(GameTime gameTime) method is something like that.

```
// Amount of time between frames
TimeSpan frameInterval_Hit;
// Time passed since last frame
TimeSpan nextFrame_Hit;

 public void Update_Hit(GameTime gameTime)
    {
        // Check if it is a time to progress to the next frame
        if (nextFrame_Hit >= frameInterval_Hit)
        {
            // Progress to the next frame in the row
            currentFrame_Hit.X++;

            // If reached end of the row advance to the next row, reset to the first frame
            if (currentFrame_Hit.X >= sheetSize_Hit.X)
            {
                currentFrame_Hit.X = 0;
                currentFrame_Hit.Y++;
            }

            // If reached last row in the frame sheet, jump to the first row again
            if (currentFrame_Hit.Y >= sheetSize_Hit.Y)
                currentFrame_Hit.Y = 0;

            // Reset time interval for next frame
            nextFrame_Hit = TimeSpan.Zero;
        }
        else
        {
            // Wait for the next frame
            nextFrame_Hit += gameTime.ElapsedGameTime;
        }
    }

```

# Answer
A simple generic approach should work. You should really consider making your animations more generic by making them objects, instead of all that hard coding you're doing now. Once you do, add an attribute to your animations and some simple code for handling animations.

Each animation should have a boolean flag indicating if it requires finishing, like your punching animation. Then when a new animation is requested, you can do a simple check:

```
public void changeAnimation(Animation next) {
    if(currentAnimation.IsPlaying() && currentAnimation.RequiresFinish())
       nextAnimation = next;
    else
       currentAnimation = next;
}

```

Then, have some code that handles the transition.

```
private void onAnimationEnd() {
    if(nextAnimation != null) {
        currentAnimation = nextAnimation;
        nextAnimation = null;
    } else {
        currentAnimation = getIdleAnimation();
    }
}

```

Where `currentAnimation` and `nextAnimation` are instances of a animation class. Something like:

```
class Animation {
    // Amount of time between frames
    TimeSpan frameInterval;
    // Time passed since last frame
    TimeSpan nextFrameInterval;
    Vec2 currentFrame;
    Vec2 sheetSize;

    public Animation (Vec2 currentFrame, Vec2 sheetSize) {
        this.currentFrame = currentFrame;
        this.sheetSize = sheetSize;
        this.frameInterval = new TimeSpan();
        this.nextFrameInterval = new TimeSpan();
    }

    public void update(GameTime gameTime) {
        // Check if it is a time to progress to the next frame
        if (nextFrameInterval>= frameInterval)
        {
            // Progress to the next frame in the row
            currentFrame.X++;

            if (currentFrame.X >= sheetSize_Hit.X)
            {
                currentFrame.X = 0;
                currentFrame.Y++;
            }

            // If reached last row in the frame sheet, jump to the first row again
            if (currentFrame.Y >= sheetSize.Y)
                currentFrame.Y = 0;

            // Reset time interval for next frame
            nextFrameInterval = TimeSpan.Zero;
        }
        else
        {
            // Wait for the next frame
            nextFrameInterval+= gameTime.ElapsedGameTime;
        }
    }
}

```

Using an object like this makes it reusable for other animations, instead of just being used for the hit animation. Now when you want to change animations, you can easily just set the `currentAnimation` to whatever animation object you want, and use all the same code for updating the animation.
> 2 votes

# Answer
You could create a bool variable like so

```
 bool isPunching = false;

```

then wrap a an if loop around Update\_Hit(gameTime);, and a if not loop around your mCurrentState = "walking";

```
  if (mCurrentState == State.Hitting)
    {
        action = "hit";
        isPunching = true;

        if (isPunching)
        {
            Update_Hit(gameTime);
        }

        if (!isPunching)
        {
            mCurrentState = State.Walking;
        }
    }

```

now in your Update\_Hit() method, at the end of the loop add a

```
 isPunching = false;

```

Hope this helped.
> 1 votes

---
Tags: xna, xna-4.0
---


title: how to run game server

text:
# Question
Title: how to run game server
I'm creating a game on UDK and i have some questons about the server. my game is a 3d mmorpg simliar to dayz/warz. I have some questions

Each map will consist of 30-60 players similar to dayz/ warz. should i use cloud servers or should i go for dedicated server?

should I get a server that can hold hundreds of players or should I host multiple servers for each instances(map)?

also what should the specs be for the server if I'am looking to host 200 players per server? how do other games make a profit from server hosting.. from what i know it would cost me around £80/month to host a server for 200 players. my game cost $20/£15 so 200 x £15 equals 3000. 3000- (80 x 12 months) equals 3000 - 960 which is 2040. does that mean if you buy my game I can only host for a year. how does minecraft,warz manage to keep their servers running without additional income for years?

# Answer
> 3 votes
If your game has high demands for server hardware/bandwidth you have a few options:

* Require players to pay to use your servers, either via monthly fees or a pay as you go system.
* Run the servers at a loss, if enough people continue to buy the game you can continue to run the servers.
* Run the servers with some form of advertising to offset the costs.
* Allow players to create their own servers.
* Some combination of the above.

Companies that run servers are not doing so "without additional income for years". Once the money stops, the servers stop too. Consider a server option that allows you to scale your needs, like Amazon Cloud services. The requirements of your server will depend entirely on the requirements of your game, the number of users connecting and the quality of connection you desire.

---
Tags: c++, udk, server
---


title: XNA .fbx model imported sideways

text:
# Question
Title: XNA .fbx model imported sideways
Using Blender 2.6. My model has its location and rotation zeroed out, scale set at 1.0, and generally conforms to every guideline detailed on this site and misc google results. When exporting it, I check 'XNA Strict Options'. Y up and -Z forward seems right.

However, it still ends up sideways. I found that a possible fix was to just set the X Axis Rotation in the Content Processor properties to -90, but that ended up being worthless when I started checking out collision spheres and realized that they lay in that skewed orientation.

What could I be missing?

**Edit:** Drawing code:

```
Matrix[] bones = animPlayer.GetSkinTransforms();
foreach (ModelMesh mesh in model.Meshes)
{
    foreach (SkinnedEffect fx in mesh.Effects)
    {
        fx.SetBoneTransforms(bones);
        fx.View = camera.viewMatrix;
        fx.Projection = camera.projectionMatrix;
        fx.EnableDefaultLighting();
        fx.World = worldMatrix;
    }
    mesh.Draw();
}

```

Where

```
worldMatrix = rotMatrix * moveMatrix;
camera.viewMatrix = Matrix.CreateLookAt(camPosition, target+camTargetOffset, camUp);
camera.projectionMatrix = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, (float)game.Window.ClientBounds.Width / (float)game.Window.ClientBounds.Height, 1, 100);

```

# Answer
> 0 votes
I also used that blog link for reference on importing models. I had a similar problem with importing animated models for this reason.

Some models came out sideways in the game, they will animate properly but turned sideways. For instance the Dude model would appear correct using the default import setting for the pipeline, but then I made a custom animation in Blender from a mesh I downloaded elsewhere and on export was turned 90 degrees to one side. Applying rotation in Blender's export settings didn't work either because the bones will be misaligned and animations will look all wrong.

I managed to solve the problem by making a modification to the content importer and applying the custom rotation during that step. That part of the article with the RotateAll function, I made the parameters editable in the Properties window.

The code isn't much, here's what I added to the model prep code in the model processor class:

```
    [DisplayName("Mesh animation rotation")]
    [Description("Rotates 3D models while they are loaded, including rotating their animations.")]
    public Vector3 NodeRotation
    {
        get { return nodeRotation; }
        set { nodeRotation = value; }
    }
    private Vector3 nodeRotation;

```

This makes the NodeRotation editable in the Properties window, so now you can set the rotation (in degrees) on a per-model basis.

# Answer
> 0 votes
if you right click your model in the solution explorer and choose 'Properties', then in the properties section, expand content processor, then set -90 in the x axis rotation field, it will apply the rotation to all vertices and transforms during build so all the bounding spheres will line up.

---
Tags: xna-4.0, blender, fbx
---


title: Saving model image

text:
# Question
Title: Saving model image
How can I get a top-down,side view of the model imported into XNA and then save that view as an image, that can be used later in the program?

Thank you for your time

# Answer
> 3 votes
Set a RenderTarget on your application; this will set the scene for saving and loading that texture data later in the application life cycle.

You're going to want to render your model and scene exactly as you want to on the default RenderTarget and then make sure nothing else is rendered on that RenderTarget. After this is done for a single pose you can call SaveAsPNG from Texture2D (RenderTarget is inherited from this). After this is done, just load up the image into a Texture or alternatively just cache that Texture2D somewhere for later use instead of saving it.

Hope this helps!

---
Tags: xna, c#, xna-4.0
---


title: UV Mapping Problems

text:
# Question
Title: UV Mapping Problems
I'm creating an alien in blender, doing my best to base it on the guys from toy story. When I create the UV Map and colour it, import it back in then take a look at it in a seperate window there is alot of black segments on it. Ive tried the whole SMART UV PROJECT option aswell but I still get the same thing. What have I done wrong here?

Update: Followed advice below and can now colour without the black segments seen in the first pic, however I am now seeing lines on my alien, is this because of GIMP? (Im using GIMP to colour my guy)

# Answer
> 3 votes
First off, make sure you're adding a material on your mesh, then add the texture, set it as "image or movie", and chose "Coordinates: UV":

---
Tags: 3d, blender, uv-mapping
---


# Question
Title: Is a 10 meg 2048x2048 bitmap too big a size texture to use in an OpenGL game?
This is a speed question, I have a texture, which is 2048 per 2048, the texture is designed to run in big resolutions (1920x1080 for example).

The problem is, that the texture have a size of 10MB in bitmap, is too heavy, I don't know if that's a good size for load it in gl and use it in a game...

Is there any problem to use a 10MB texture in an OpenGL Game?

# Answer
First off, don't measure the amount of video memory used by the image by the disk size of the file. There's a similar question here which covers the topic and I've linked to a very good answer that will cover most ground on how you should measure VRAM usage accurately. As a quick guideline though, it depends on the size and amount of colours in the image and how the image is saved and packed.

With this in mind, the image might be a lot smaller than you anticipated or bigger - it would be up to you to check this out. At any rate however, as long as you're not loading a bunch of those textures into memory you would probably be okay but it's a game specific thing. With todays video cards having 1GB + of VRAM, it's trivial to load a few of those textures into memory if that's what you need. It also depends on your target audience and what kind of hardware you expect them to run this on.

So in short: **Run with it if you think you need; optimize it later if you need.**
> 8 votes

---
Tags: c++, opengl, textures
---


title: How much to modify yaw? XNA 4.0

text:
# Question
Title: How much to modify yaw? XNA 4.0
Heres a picture that explains better than my words can

For rotating an object I'm using quaternions. CreateFromAxisAngle(vector3.Right,yaw)

Maybe this isn't how I should be doing it but I also keep my yaw as radians that are always between 0 and 360;more or less than 0 or 360 puts it at 0 or 360 respectively.

(object is build up of vertices and indices)

I can rotate it no problem. Move it all about. But what I really want to do is to find how much I should alter the yaw so that the my models right vector will sync up with the line I can draw between the objects center and the camera's position(y is always 0).

Which I guess is the problem now, but long term I am trying to find how I modify the yaw to match any direction.

Say I am travelling Left, I may want to rotate my yaw so that my objects forward is also left.

I have been researching here and elsewhere and there seem to be solutions, I just can't wrap my head around any. Maybe someone could help shed some light?

# Answer
XNA makes this surprisingly easy with Matrix.CreateBillboard and Matrix.CreateConstrainedBillboard. The first method returns a matrix with the orientation determined by the input vector you choose, which is where you use the camera's lookAt vector. Simple enough. The second method returns a matrix with a constrained orientation- that is, it's limited to one of three axes (it can be an arbitrary axis, not limited to the orthogonal directions).

You probably want to use the latter. The Rotate axis should be Vector3.Up for yaw. The resulting matrix can be applied directly to your object's transformation.
> 1 votes

# Answer
I'm not really sure I understand your question. But maybe what you're trying to do is billboarding?

If so, the only thing you have to do is make sure each sprite points to the camera. If both your camera and the sprites use the same coordinate system, the Y rotation for your object can either be the inverse of the Y rotation for your camera (for planar billboarding), or the angle between the camera and the object, whose cosine is the dot product between the normalized vector between the camera and the object, and the normalized vector of the camera's forward vector (for cylindrical billboarding)
> 0 votes

# Answer
If you normalize the vector that represent Right(Rn) and you normalize the vector resulting from the subtraction of the objects position from the camera position(Cn) then you can use the dot product to determine the angle that you want to apply to your Yaw.

Rn . Cn = |Rn|x|Cn| cos a

Since Rn and Cn are normalized |Rn|x|Cn| = 1 and this reduces to Rn.Cn = cos a

so (Rn.X)(Cn.X) + (Rn.Y)(Cn.Y) + (Rn.Z)(Cn.Z) = cos a

The only gotcha with this approach is that there are two possibilities that you have to be able to identify and handle due to the fact that cosine is defined between 0 and 180(0 and Pi). In order to handle this you have to take the crossproduct of the two vectors and check the results Y component to determine if you should use a negative 'a' or a positive 'a' in your yaw.
> 0 votes

# Answer
You should use

```
Matrix.CreateWorld(Position, Forward, Up) to create the right matrix...

```

where forward is the vector you want to face...

http://msdn.microsoft.com/en-us/library/bb975261.aspx

I think you don't need it, but if you want to get the yaw from that matrix...

you can use the matrix method

```
transform.Decompose(out scale, out rotation, out translation)...

```

and then you can get the axis rotation values from the quaternion you can extract it with this function

```
public static Vector3 QuaternionToEulerAngleVector3( this Quaternion rotation )
    {
        Vector3 rotationaxes = new Vector3( );
        Vector3 forward = Vector3.Transform( Vector3.Forward, rotation );
        Vector3 up = Vector3.Transform( Vector3.Up, rotation );

        rotationaxes = AngleTo( new Vector3( ), forward );

        if ( rotationaxes.X == MathHelper.PiOver2 )
        {
            rotationaxes.Y = ( float ) Math.Atan2( ( double ) up.X, ( double ) up.Z );
            rotationaxes.Z = 0;
        }
        else if ( rotationaxes.X == -MathHelper.PiOver2 )
        {
            rotationaxes.Y = ( float ) Math.Atan2( ( double ) -up.X, ( double ) -up.Z );
            rotationaxes.Z = 0;
        }
        else
        {
            up = Vector3.Transform( up, Matrix.CreateRotationY( -rotationaxes.Y ) );
            up = Vector3.Transform( up, Matrix.CreateRotationX( -rotationaxes.X ) );

            rotationaxes.Z = ( float ) Math.Atan2( ( double ) -up.Z, ( double ) up.Y );
        }

        return rotationaxes;
    }

```
> 0 votes

---
Tags: xna, vector, quaternion
---


# Question
Title: Drawing Sprites in Android OpenGL efficiently?
I want to basically give myself some sprite drawing functions (making use of openGL) such as;

```
draw(Texture,x,y)

```

I want to do this using OpenGL-ES 2.0 on Android. Since the textures can be varying sizes, I was thinking I would save the vertices along with the textures and pass them to the shaders every draw call using "glVertexAttribPointer". Is there a better(performance) way of doing this?

I would also make use of a model matrix to translate/rotate the sprites. Is this a normal thing to do for 2d rendering?

# Answer
> 4 votes
You'll want to look at `SpriteBatch` then which basically involves deferring any actual GPU draw calls until all the drawing has been completed and ready to be flushed to the GPU bugger. This is a very common approach to draw 100s or even 1000s of sprites on a screen at once without negative implications on the frame rate. There's a lot of different ways to implement SpriteBatching so I'll leave the exact implementation in OpenGL to you, but in a lot of implementations I've seen (MonoGame, Direct X Toolkit) the `Begin` function of the `SpriteBatch` will take a transform view matrix (which will translate, rotate and scale the sprites). I suggest you look at the implementations I've linked to and derive your own. MonoGame has OpenGL components which will probably be of use to you.

---
Tags: opengl, 2d, android, sprites
---


# Question
Title: Why is forward=down mouse orientation commonly called "inverted"?
If you look at 3D games that allow you to control the camera using the mouse--most notably first-person and third-person shooter style games--you'll usually find two specific details:

* By default, pushing the mouse forward makes the camera look up, and pulling back looks down.
* The option to reverse this (forward=down) is called "invert Y axis" or something similar.

I've never understood that, and it's always seemed backwards to me, to the point where I get wildly disoriented in any game with default settings on. It seems intuitively obvious that the mouse (or, even more so, a thumbstick, which even looks kind of like a head sitting atop a neck) is modeling the perspective character's head. Move left, you look left. Move right, you look right. Push forward, *the head pushes forward, and you look down...* right?

In fact, this orientation was the default in a lot of early 3D games, such as flight simulators, MechWarrior 2, etc. But at some point it changed, and people started calling the intuitive orientation "inverted" and disabling it by default.

Are there any historical reasons behind this reversal of the default camera control orientation? Any articles, perhaps, on the rationale behind changing it, or studies showing why it was a desirable change to make?

# Answer
> It seems intuitively obvious that the mouse (or, even more so, a thumbstick, which even looks kind of like a head sitting atop a neck) is modeling the perspective character's head.

Maybe this seems intuitively obvious to you, but not to everyone. To some it would seem intuitively obvious that moving the mouse "up" should move your view "up." I'm not suggesting either side is more correct--they both have their followers obviously--but they're certainly both within the realm of reasonable possible interpretations of what the mouse should do. Apparently you're in the minority, since your inclination received the "inverted" naming, but somebody had to.

You requested some history. There's this from Wikipedia:

> After id Software's Doom, the game that popularized FPS games but which did not support vertical aiming with a mouse (the y-axis served for forward/backward movement), competitor 3D Realms' Duke Nukem 3D became one of the first games that supported using the mouse to aim up and down. This and other games using the Build engine had an option to invert the Y-axis. The "invert" feature actually made the mouse behave in a manner that users now regard as non-inverted (by default, moving mouse forward resulted in looking down). Soon after, id Software released Quake, which introduced the invert feature as users now know it. Other games using the Quake engine have come on the market following this standard, likely due to the overall popularity of Quake.

And here's a fun video of someone who agrees with you.
> 6 votes

# Answer
If you stop calling it "pushing forward" on the joystick/mouse, and start calling it "pushing up" (which is the way that most players think of it -- particularly the ones who don't play flight simulators), then the "invert Y axis" name makes complete sense, since pushing up causes the player to look down.

**Edit:**

The fundamental issue here is people's mental models about what a game's controls do.

One group of people have this mental model: **"if I press up, I should see more upward"**. That is, the controls are wired to the view, and what I do with the controls should have the same effect on the view.

Another group of people have this mental model: **"If I press up, I'm swinging the *camera* upward, so I see more downward"**; that is, the controls are wired to *an object in the world*, and the rendered view is merely a side-effect of the motion of these controlled objects in the world.

Neither viewpoint is 'right'. Lots of games have been made using each approach, and these days they mostly give you the option to switch it if you don't like the default. Mostly people have settled on "up means the view moves up" as "normal" and "up means the view moves down" as "inverted", but there have been plenty of games which named them in the reverse direction.

Incidentally, the same issue exists for left and right, for games which have a third-person camera. Some people think that pushing left means they should see more to the left, others think that pushing left means that the camera should swing to the left, and thus they should see more to the right. Some even feel differently about the two axes.

The important point is that options are presented to players, which lets everyone play according to their own preferred mental model, rather than obsessing over which approach is the **correct** one.
> 16 votes

# Answer
I believe the most likely explanation is that it's an artefact of the original Quake, which defaulted it's mouselooking to forward = up, and had a menu item explicitly called "invert mouse" for forward = down. See e.g. http://en.m.wikipedia.org/wiki/Mouse\_(computing)#section\_11

Also interesting to note that for standard GUI usage moving the mouse forward will move the pointer up on-screen, although I don't know how related that may or may not be.

At the time, true 3D was something new and strange and the best control schemes were still being worked out, so it shouldn't be surprising that the default used was the reverse of what many, if not most, now consider normal.
> 4 votes

---
Tags: input, control, ui-design
---


title: Simple 2D hair simulation/manipulation

text:
# Question
Title: Simple 2D hair simulation/manipulation
I would like to simulate *very* simple hair in a 2D environment, and will need to be able to "brush" the hair.

What I want to do: A 2D character is facing squarely towards the player. The player can then brush the character's hair. Think of a little girl brushing her doll's hair into different styles.

In my preliminary Google searches, I found many 3D, super-optimized hair simulations for tens of thousands of hairs, which are far more complicated than I need. I only need 100-500 hairs, and they only need to react to "brushing" by the player.

How might I do this?

# Answer
> 12 votes
I tried it.

Brown is **generated hair**. The red circle is the **hairbrush**. The hairstyles were achieved by brushing the hair with the hairbrush.

Here's how that works:

# The Hair

Hairs are like this:

* *Bendy*. Like a bezier curve. Quadratic ones are pretty simple.
* *Finite*. They start and end somewhere. They also have some fixed length.
* *Coloured*. They've got some RGB to them, usually pretty heavy in the R and G.
* (*Weighty*.) Let's ignore gravity to keep things simple -- and to allow awesome hairstyles.

This is roughly how you might translate that into a program:

```
oneHair = {
    start = vector(100,100),
    controlPoint = vector(120,70), -- For the bezier
    end = vector(100,200),
    length = 100,
    update = function(self)
        -- Make sure the END is within LENGTH of START
        -- (This isn't actually quite right, since beziers aren't lines,
        --  but it's a pretty good approximation...)
    end,
    draw = function(self)
        -- Make a bezier curve using START, CONTROL and END.
        -- Sample it at intervals. Draw lines between samples.
    end
}

```

And then you just create really many. (There are 1200 in each of the pictures.)

It's useful to create them *on* or *within* some circle describing the shape of the head or the line of the fringe. (I used a filled half-circle for the bulk of the hair an edge of a different half-circle for the fringe.)

You can also vary the lengths of hairs. (I find bangs running down both sides of the face attractive, so I approximated hair length with this quadratic function (picture just below), using the horizontal distance from the centre of the aforementioned guide circle as input.)

I recommend a similar approach, obviously keeping the desired style in mind.

# The Brush

The brushing mechanic is based on these (idealised) observations:

* Hair that touches the brush moves in the direction the brush is moved in, except slower.
* Brushing *along* hair straightens the hairs.
* Brushing *across* hair bends the hairs.

So my brushing code does essentially this:

1. Find hairs that touch brush (using their bezier curves)
2. For each hair:
    * Move the endpoint of the hair by some fraction of the pointer movement vector.
    * Project the movement vector of the pointer onto the perpendicular of the hair's direction. This gives a vector describing the brush motion in relation to the hair.
    * If the brush motion in relation to the hair is *more along than across* the hair, move the control point some fraction of the way toward the midpoint of the hair. This smooths the hair.
    * Else (if the brush motion is *more across than along*, move the control point some fraction of the pointer's movement vector.

# The Code

I made it with LÖVE in Lua. Here's my `main.lua`, if you just want to read:

```
local v = require "vector"
local graphics = love.graphics
local mouse = love.mouse
graphics.setBackgroundColor(255,255,255) --> white background

-- A function that makes bezier functions
-- Beziers have start point     p0
--              control point   p1
--              end point       p2
local function makeBezierFunction(p0,p1,p2)
    return function (t)
        local pow = math.pow
        return pow( (1-t),2 ) * p0
               + 2 * (1-t) * t * p1
               + pow(t,2) * p2
    end
end

-- Hair class
-- Encapsulates all that needs to be known to create, draw or update a hair.
local hair = {}
function hair.draw(self)
    -- Make a bezier function describing the shape of the hair
    local shape = makeBezierFunction(
        self.from,
        self.mid,
        self.to
    )
    -- This is the increment for one segment of a hair's bezier function
    local segIncr = 1/self.resolution
    for n=0,1-segIncr,segIncr do
        -- This and next sample point
        local x1,y1 = shape(n):unpack()
        local x2,y2 = shape(n + segIncr):unpack()

        graphics.setColor(unpack(self.col))
        graphics.line(x1,y1, x2,y2)
    end
end
function hair.update(self)

    -- Beziers can be longer than lines. This is an approximation to save us
    -- from some complicated maths.
    local vectorAlongLength = self.to - self.from
    -- Move endpoint to within the length of the hair of the start point.
    if vectorAlongLength:len() > self.length then
        self.to = self.from + vectorAlongLength:normalized() * self.length
    end

end
function hair.new(from, to, verticalBend, col) -- Create a new hair object
    return setmetatable({
        length = (from - to):len(),
        from = from,
        to   = to,
        mid  = from + v(0,verticalBend),
        verticalBend = verticalBend,
        resolution = 5,
        col = col,
    }, {
        __index = hair
    })
end
setmetatable(hair, {
    __call = function(_,...) return hair.new(...) end
})

local hairs = {}                -- all hairs stored here
local selectorSize = 30         -- radius of brush
local fringeOrigin = v(325,260) -- origin of the fringe guideline circle
local fringeRadius = 90         -- radius of the fringe guideline circle

-- Terrible drawing of a bald person, happy to soon receive lots of hair.
local portrait = graphics.newImage "portrait.png"

function love.load()

    ---[[ Bulk of hair, at the back
    local numHairs = 1000
    for _=1,numHairs do
        -- Get a random angle within 180 degrees
        local randomAngle = math.random() * math.pi + math.pi/2
        -- Find random point within circle (though offset somewhat)
        local point = fringeOrigin + v(0,-30) + v(math.sin(randomAngle), math.cos(randomAngle)) * (fringeRadius - 20 + math.random(50))
        -- Fairly dark brown
        local randomValue = math.random(50)
        local randomCol = {randomValue+50, randomValue+30, randomValue}
        local length = 30+math.random(50 * (math.pow(2*(point.x - fringeOrigin.x)/fringeRadius, 2)))
        local horizontalBend = -15 + math.random(30)
        local verticalBend = math.random(length)
        local newHair = hair(v(point.x, point.y), v(point.x+horizontalBend, point.y+length), verticalBend, randomCol)
        table.insert(hairs, newHair)
    end
    --]]
    ---[[ Fringe
    local numHairs = 200
    -- get random points on fringe circle arc
    for _=1,numHairs do
        -- Get a random angle within 180 degrees
        local randomAngle = math.random() * math.pi + math.pi/2
        -- Find random point somewhere ON (NOT WITHIN) the fringe arc
        local point = fringeOrigin + v(math.sin(randomAngle), math.cos(randomAngle)) * fringeRadius
        local randomValue = math.random(100)
        local randomCol = {randomValue+50, randomValue+30, randomValue}
        local length = 50+math.random(50 * (math.pow(2*(point.x - fringeOrigin.x)/fringeRadius, 2)))
        local horizontalBend = -15 + math.random(30)
        local verticalBend = math.random(length)
        local newHair = hair(v(point.x, point.y), v(point.x+horizontalBend, point.y+length), verticalBend, randomCol)
        table.insert(hairs, newHair)
    end
    --]]
end

lastMousePos = v()
mousePos = v()
mouseMovement = v() -- Movement vector of the mouse this step
function love.update()

    mousePos = v(mouse.getPosition())
    mouseMovement = mousePos - lastMousePos

    if mouse.isDown "l" then -- Left mouse button pressed

        -- Find all hairs with ends nearby the cursor
        local nearbyHairs = {}
        for _,hair in ipairs(hairs) do
            -- Create a function describing the shape of the bezier
            local shape = makeBezierFunction(
                hair.from,
                hair.from + v(0,hair.verticalBend),
                hair.to
            )
            -- This is the increment for one segment of a hair's bezier function
            local segIncr = 1/hair.resolution
            for n=0,1,segIncr do
                local pointOnShape = v(shape(n):unpack())
                -- If it's close enough to the mouse
                if (pointOnShape - mousePos):len() < selectorSize then
                    -- Select it
                    table.insert(nearbyHairs, hair)
                end
            end

        end

        -- Apply transforms to each hair
        for _,hair in ipairs(nearbyHairs) do

            -- Move endpoint along with movement vector
            hair.to = hair.to + 0.5 * mouseMovement

            -- Find movement in relation to hair
            local movementAcross = mouseMovement:projectOn((hair.to - hair.from):perpendicular())

            -- If the movement was ALONG the hair
            if math.abs(movementAcross.x) < 10 then
                -- Smooth the hair by moving control point closer to midpoint
                local midPoint = (hair.to + hair.from) /2
                hair.mid = 0.85 * hair.mid + midPoint * 0.15
            else -- Movement was ACROSS the hair
                -- Move the control point along with the movement vector
                hair.mid.x = hair.mid.x + 0.25 * mouseMovement.x
            end
        end

    end

    -- Update hairs to make sure their lengths stay the same
    for _,hair in ipairs(hairs) do hair:update() end

    lastMousePos = mousePos
end

function love.draw(dt)
    -- Draw the bald portrait image
    graphics.draw(portrait, 200, 100)
    -- This is a nice cheat for making less hair look like it has more volume
    graphics.setLineWidth(2)

    for _,hair in ipairs(hairs) do
        hair:draw(dt)
    end

    -- Draw brush pointer
    graphics.setColor(255,0,0)
    graphics.circle("line", mousePos.x, mousePos.y, selectorSize)

    -- The fringe line
    --graphics.arc("line", fringeOrigin.x, fringeOrigin.y, fringeRadius, -math.pi, 0)
end

```

If you want to have a play with it, get LÖVE (any OS is OK) and open my love file with it.

If you want to see the source code in its entirety, just change the `.love` extension to `.zip` and unpack.

---
Tags: physics, simulations, character
---


# Question
Title: Sprite Animation in Android with OpenGL ES
How to do a sprite animation in android using OpenGL ES?

*What i have done :*

Now I am able to draw a rectangle and apply my texture(Spritesheet) to it

*What I need to know :*

Now the rectangle shows the whole sprite sheet as a whole How to **show a single action from sprite sheet at a time and make the animation**

It will be very help full if anyone can share any idea's , links to tutorials and suggestions.

Advanced Thanks to All

# Answer
> 1 votes
AndEngine provides a good way to draw animated sprites. It has a class `AnimatedSprite` which will do a lot of work for you. Here are the steps :

1. Get the `BitMapTextureAtlas`

`bitmapTextureAtlas = new BuildableBitmapTextureAtlas(getTextureManager(), 480, 200, TextureOptions.NEAREST);`

2.Get the `TiledTextureRegion` for your spirtesheet

`yourTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(bitmapTextureAtlas, context, "yourspritesheet.png", /*sprite rows*/, /*sprite columns*/);`

3.Finally create the `AnimatedSprite` and attach it to the scene

`AnimatedSprite yourSprite = new AnimatedSprite(40, 40, yourTextureRegion, this.getVertexBufferObjectManager());
yourSprite.animate(100);
yourScene.attachChild(yourSprite); /**attach this spirte to the scene**/`

For further reference look : https://github.com/nicolasgramlich/AndEngineExamples

# Answer
> 1 votes
The optimized way would be to have one texture with all the steps in your animation, like movie frames. As it is a texture, each frames has initial coordinates and a common frame width and height. Draw one quad and change the uv coordinates of the quad to match the frame you want to draw in the texture. Marco Martilleni pointed to a good tutorial.

# Answer
> 1 votes
You need to adjust your uv coordinates. You want the top left uv to correspond with the location on the sprite sheet. Say your sprite sheet is 256x256 pixels and the frame you want starts at (32, 32).

You can think of the uv's as a percentage of the image. The horizontal percentage is 32/256. (12.5% of the sheet) so the u for the left vertices should be 0.125.

The u for the right vertices depends on how large each frame is. Lets say 16x16. Then the two right vertices' u's would be (32+16)/256 or 0.1875 of the sheet.

now for the v's. 0 is at the bottom, and the frame position is defined from the top. 32/256 would give us a percentage from the bottom of the image. What we need is (256-32)/256 to get the percentage from the bottom of the sheet to the top of the image - 0.875 (yay!)

The bottom vertices are an additional distance from the top of frame size. So (256-32-16)/256 or 0.8125.

So to recap, the uv coords for each vertex is:

```
top left : (frame.x / sheet.w , (sheet.h - frame.y) / sheet.h)
bottom left:(frame.x / sheet.w , (sheet.h - frame.y - frame.h) / sheet.h)
top right: ((frame.x + frame.w) / sheet.w , (sheet.h - frame.y) / sheet.h)
bottom right: ((frame.x + frame.w) / sheet.w , (sheet.h - frame.y - frame.h) / sheet.h)

```

where x = x position, y = y position, w = width, h = height all in pixels

If you see a mistake anywhere, please point it out. I'm actually about to implement this for my engine and explaining it helped me figure it out.

With this information you should be able to create a render function that takes some of these parameters and draws a subsection of the image. Then, you can just change the frame positions every animation step to animate the image.

# Answer
> 0 votes
You need to do the right UV mapping to be able to see only one frame of your sprite sheet.

For the animation the trick is to use

```
glMatrixMode(GL_TEXTURE);
glTranslatef(u, v, 0);

```

where u and v are the coordinates of the current frame in UV space.

You can find more info here: sprite animation in openGL

---
Tags: android, animation, opengl-es, spritesheet
---


# Question
Title: glsl 150 struct in uniform buffer object
Can I do this in opengl 3.2 / glsl 150?

glsl shader:

```
struct LightSource {
    vec4 ambient;
    vec4 diffuse;
    vec4 specular;
    vec4 position;
    vec4 direction;
};
...
layout(std140) uniform LightSources {
    LightSource lightSources[ 1 ];
};
...

```

And if so, how do I actually bind the data (using c++)?

I've got data binding working for this uniform:

```
layout(std140) uniform LightSources {
    vec4 ambient;
    vec4 diffuse;
    vec4 specular;
    vec4 position;
    vec4 direction;
};

```

I'm just not sure how to extend it to use an array of `struct`s instead of binding 5 `vec4`s.

# Answer
This is explained at http://ogldev.atspace.co.uk/www/tutorial20/tutorial20.html about halfway down the page.

I would've done a comment, but not enough rep :(

Edit: In order to make up for my bad answer, I have found the pertinent sections of the OpenGL 3.2 specification. I hope this helps.

When using the std140 storage layout, structures will be laid out in buffer storage with its members stored in monotonically increasing order based on their location in the declaration. A structure and each structure member have a base offset and a base alignment, from which an aligned offset is computed by rounding the base offset up to a multiple of the base alignment. The base offset of the ﬁrst member of a structure is taken from the aligned offset of the structure itself. The base offset of all other structure members is derived by taking the offset of the last basic machine unit consumed by the previous member and adding one. Each structure member is stored in memory at its aligned offset. The members of a toplevel uniform block are laid out in buffer storage by treating the uniform block as a structure with a base offset of zero.

If the member is a structure, the base alignment of the structure is N, where N is the largest base alignment value of any of its members, and rounded up to the base alignment of a vec4. The individual members of this substructure are then assigned offsets by applying this set of rules recursively, where the base offset of the ﬁrst member of the sub-structure is equal to the aligned offset of the structure. The structure may have padding at the end; the base offset of the member following the sub-structure is rounded up to the next multiple of the base alignment of the structure.

If the member is an array of S structures, the S elements of the array are laid out in order, according to rule (9) (the last paragraph).

Edit 2: It seems from the specification that arrays of structs are lined up directly next to each other in the buffer. So if you had 2 lights, the buffer data would just be the 20 floats defining that light, followed by the 20 floats defining the next light.

The reason it is that simple is because all of your struct members are the same type. If you had a vec2 in there, you would have to skip 2 floats in the buffer.

Edit 3: Sorry for all of these edits. I tested what I said in edit 2, and it indeed worked. I created a similar structure to yours in my shaders, but I used 3 vec4's for simplicity. I had an interface uniform containing an array of 2 of those structs. In my uniform buffer object I just placed 24 floats (4 floats per vec4 * 3 vec4 per struct * 2 structs) After binding the object I was able to read the correct values in the shader.
> 3 votes

---
Tags: c++, opengl, glsl
---


# Question
Title: Unity3d select empty gameobjects in scene
I have a pathing system that I am creating in Unity. When you add nodes to denote the path, I create a empty GameObject and render it in OnGUI as a square. The problem that I have is clicking on the object in the scene view. I am trying to figure out what would be the best way to click the Node, so that I can move and rotate the Node.

I had some ideas, like:

1. Creating a Cube or some other GameObject with a mesh, and change the layer to Node. Then make the camera cull out the Node layer.
2. Only in editor mode, create a temp asset and delete it before runtime.
3. Do a raycast and see what objects are near the click, then pick the closest one.

I have a feeling that I am putting to much thought into it, and suggestions would be greatly appreciated!!

# Answer
> 2 votes
It sounds like you want to extend the Unity editor. Looks like you can use the Handles class to create custom handles for your objects too.

---
Tags: unity, selection, gameobject
---


title: Using depth buffer on a sprite

text:
# Question
Title: Using depth buffer on a sprite
I am following this guide:

http://www.cocos2d-iphone.org/wiki/doku.php/prog\_guide:tiled\_maps

Trying to create a tiled map that also supports multiple layers. The guide says that a way is to use depth buffer, and says to:

1) Create the z-buffer and a 2D projection; 2) For every layer in the tiled map, set the cc\_vertexz attribute; 3) Enable alpha test and set the sprite alpha func.

The first question is: if I use a tiled maps with multiple layers, are also the point 1 and 3 needed?

I am fine with the first two points, but as for the third point I don't know how to do that. I should subclass CCSprite and override the draw method, but the problem is that when I create a tiled map there are already sprites on it, so the instances don't belong to the subclass I created. How I go around this?

# Answer
> 1 votes
There are 2 methods described in the guide, `Using multiple TMX Layers and z-order` and `Using Depth Buffer`. It would be better to use `Using multiple TMX Layers and z-order` as it is easier to use and it uses cocos2d's drawing and z-order structure.

1) is not needed as every tile in CCTMXTiledMap is a CCSprite, where the order of rendering depends on the z-order of CCSprite. `Using multiple TMX Layers and z-order` has described how it works.

2) cc\_vertexz is the value of a z axis value of a vertex in a 3d space. If you are using z-order you don't need to set cc\_vertexz at all. You should not set cc\_vertexz if you are using cocos2d v2.0. An exception would raise if you use it as it is no longer support.

3) Again, the alpha test is not needed if you are using z-order. CCTMXLayer has already enabled it by default.

If you insist on using `Using Depth Buffer`, 1) 2) and 3) are required. You can override CCTMXLayer/CCSpriteBatchNode's draw to enable the alpha test before \[textureAtlas\_ drawQuads\];, instead of every CCSprite. The order of CCSprite is not important because z-buffer is enabled.

---
Tags: sprites, cocos2d-iphone, objective-c, depth-buffer
---


# Question
Title: Does my 2D OpenGL renderer need optimized?
I've started a game engine for learning purposes. I have successfully gotten an opengl renderer working and I can draw textures of varying sizes to the screen. The way I have done this is by creating a hard coded array of vertices that are just a box.

```
float Renderer2D::vertices[30] = {
        0.f,  1.f, 0.0f, 0.0f, 0.0f, // Top-left
        0.f, 0.f, 0.0f, 0.0f, 1.0f,  // Bottom-left
        1.f, 1.f, 0.0f, 1.0f, 0.0f, // Top-right
        1.f, 1.f, 0.0f, 1.0f, 0.0f, // Top-right
        0.f, 0.f, 0.0f, 0.0f, 1.0f,  // Bottom-left
        1.f, 0.f, 0.0f, 1.0f, 1.0f // Bottom-right
};

```

(The first three are xyz - The fourth and fifth floats are texture coords)

I send this to the GPU at the beginning of my program. For every sprite I draw, I create a transformation matrix like this:

```
void Renderer2D::draw(int x, int y, int w, int h)
{
    float posX = 2.0f * x / m_screenWidth - 1.0f;
    float posY = 1.0f - 2.0f * y / m_screenHeight - 2.0f*h/m_screenHeight;

    glm::mat4 translation, scale;
    translation = glm::translate(glm::mat4(1.0f), glm::vec3(posX, posY, 0));

    scale = glm::scale(glm::mat4(1.0f), glm::vec3(2.0f * w /   m_screenWidth,2.0f*h/m_screenHeight, 1.f));
    transformation = translation * scale;
    glUniformMatrix4fv(m_shaderProgram.getMVPLocation(), 1, GL_FALSE, &transformation[0][0]);
    glUniform1i(m_shaderProgram.getSamplerLocation(), 0);

    m_shaderProgram.enableVertexAttribArray();

    glActiveTexture(GL_TEXTURE0);
    glDrawArrays(GL_TRIANGLES, 0, 6);

    m_shaderProgram.disableVertexAttribArray();
}

```

I started looking up other questions on here about sprite batches, so I could optimize my draw calls. But in all of these questions it was suggested that a vertex array should be built up, with vertex's for every sprite.

In my code, I send vertices to the gpu once, and call glDrawArrays for every sprite. If I built the vertex array every frame, I'd send the vertices every frame (not every sprite) and call glDrawArrays once per frame. I would still have to calculate the matrices for every sprite.

Is glDrawArrays much more computationally expensive than sending a vertex buffer? Does this definitely need fixing?

If I build a vertex buffer dynamically, how could I allocate the space if I don't know how many sprites are going to be drawn? Do you just put a hard limit on it?

# Answer
> 4 votes
As your sprite count increases, you will notice that glDrawArrays is relatively slow. Luckily, the GPUs happen to have a huge bandwidth. That's why huge amounts can be uploaded on every frame. When creating your vertex buffer you can even give it GL\_DYNAMIC\_DRAW or GL\_STREAM\_DRAW as usage parameter to suggest that the data will be updated all the time. This way the GPU will try to have it in the fastest part of the memory (if possible). Uploading a lot on every frame and making as few calls as possible is the way GPUs are designed to work.

If you don't know how many vertices you're going to have, just allocate as much as you think you'll need. If you exceed the cap, you can always create an even bigger one and copy the old data to the new one.

One problem with having all the quads in vertex buffer is the textures. All the textures needed by the quads in one vertex buffer have to be in the same texture atlas. If you can't fit all textures in one texture atlas you have to divide the quad batch into multiple batches.

# Answer
> -1 votes
I'm being picky, but there are some simple math operations which can be optimized by computing them only when they need it. For instance:

```
float posX = 2.0f * x / m_screenWidth - 1.0f;
float posY = 1.0f - 2.0f * y / m_screenHeight - 2.0f*h/m_screenHeight;

```

These values are only going to change when sprite moves, rather than each frame, so it makes sense to only compute them at those moments.

You will not see any FPS increases by this specific example, but the general principle is a good one to keep in mind.

---
Tags: opengl, 2d, graphics-programming, spritebatch
---


title: 3d objects in binary files

text:
# Question
Title: 3d objects in binary files
Currently I have 11 3d spheres created at runtime in my application. The application runs well as it is, but I'm anticipating some garbage collection hiccups due to camera panning. Would performance increase if the objects were written, then read the objects from a binary file?

# Answer
If you're concerned about performance, there's no reason to add additional operations to your setup. Especially operations containing hard disk read/writes as those are some of the slowest operations you can perform.

Additionally, since it's running fine now, there's nothing to fix yet. You should start worrying about performance, when there's a performance issue. Situations like this can easily be retrofitted later; there's no major code overhaul involved. Though, if performance does become an issue with this scenario in the future, I'd expect other optimizations to be more effective than reading from a binary file.

However, the best answer you can get for this, is the one you provide yourself. Profile both scenarios, and with empirical evidence you can prove to yourself which one is faster.
> 2 votes

---
Tags: java, 3d, file, jogl, binary
---


# Question
Title: Calculate new coords of camera after a 90 degree rotation in an isometric 2D projection
I made a 2D isometric renderer. It works fine but now I want to show my scene from 4 different points of view (NE NW SE SW) but, **on a 90° rotation, my camera cannot keep the center of my scene on screen.**

*What's working :*

* I calculate new projection of scene to match the new viewport (x y z in my world).
* I reorganise part of my scene(chunk) to draw them in a correct order
* I reorganise 'tiles' of 'chunks' to draw them in a correct order
* I can keep the correct center with a 180 degrees rotation.

*What's do not working :*

* I cannot find a correct translation to apply to my camera after a 90 degrees rotation.

*What I know :*

* To keep the same center on a 180° rotation with my camera I have to do this :

`camera.Position -= new Vector2(2 * camera.Position.X + camera.Width, 2 * camera.Position.Y + camera.Height);`

Illustation of the problem :

# Answer
> 0 votes
I resolved my issue by calculating tile elligeable to be the center of the screen. Then, I pick up the nearest one of the camera and, after a rotation, I put it back to the middle of the screen. It's a quite easy like this but finally I have to calculate the tile in the center of my screen (because Z axis).

# Answer
> 0 votes
How about putting your camera in the center of what you want to render, set the near plane behind the camera and the far plane in front of it?

If you do this, you don't have to move your camera when you rotate.

---
Tags: camera, isometric, projection
---


# Question
Title: Applying an outline effect to primitives
I am trying to draw an outline on a collection of quads in Direct3D. I have three intersecting quads on the same plane in the following configuration:

(The different colors here are just to visually break out the quads). Using two pixel shaders, one for the longer segments and another for their intersection (the purple quad), I am rendering this as a single color:

I would like to outline this shape, something like the following (please excuse my Paint skills):

My first approach was to write a pixel shader that would calculate the distance along the y-axis (before the transform) from the center of the quad and colorize based on that. However, when I render this, there is a problem where the quads overlap:

What is the best way to achieve my desired result? Is this possible with a texture and a clever use of blending, perhaps? What about somehow stenciling the non-outline areas?

I should mention that my outlines need to be thicker than one pixel, and that I'm working in DirectX 9 with shader model 4 level 9.1, and C++.

# Answer
An ideal way to do this would probably involve changing your geometry such that, instead of three overlapping primitives, you have one continuous primitive -- your two primary line segments, which are quads (of two triangles) and then use "miter" triangles to join them and provide the smooth, thick joints. Using geometry for the edges in this fashion can simplify their rendering when they are thick, which you mention is a requirement, and also allows you to pack in additional data with them which you can use to help determine if the edge should be culled or not.

This technique illustrated in a paper from 2004 on hardware feature edge detection (which covers, in general, the topic you're asking about and is fairly straightforward to implement; it's worth a read even if you cannot alter your geometry).

The fundamental approach taken by the paper is to pack information about edges (not actual vertices) into some vertex data, such that each vertex in the vertex shader now has access to information about the 3D positions of the endpoints, which type of edge this is (a contour edge, a crease edge, or a hand-marked edge), and so on. This information is then used to transform irrelevant edges beyond the clip plane, which will cull them, and allow appropriate edges to be rendered.

It's very possible this technique could be updated to use a geometry shader and thus be simplified, although I haven't tried doing so myself.

Also of note, while I was looking up the URL to that paper I came across this reference to a nVidia extension for NV\_path\_rendering (with a more detailed guide here), which may be relevant to your interests.
> 1 votes

---
Tags: directx, rendering, hlsl
---


# Question
Title: How can I have parent-child transform in a component system?
Before when using inheritance, I could draw all my objects using this recursive function:

```
void Object::innerDraw(sf::RenderTarget& target, sf::RenderStates states)
{
    states.transform *= Object::getTransform(); //translate by this object's position
    this->Draw(target, states); //draw this object
    for (Object *child : m_children)
    {
        if(child->isVisible)
            child->innerDraw(target, states); //draw all children
    }
}

```

However, I am now looking at a component design where the graphics component pushes it's sprite to the renderer `Renderer::toDraw.push_back(&sprite);`

The renderer then draws all the sprites in it's container

```
for (sf::Drawable *Entity : toDraw)
{
    target.draw(*Entity, state); // (state isn't doing any transforming here)
}

```

How can I be able to draw things relative to parents position?

# Answer
> 2 votes
Component-based entity systems are often about removing inheritance of type (and providing a nice means to drive things from data, although that aspect of things is not particularly relevant to this question).

That is, not having a very deep class hierarchy where everything in your game (tanks, bullets, space ships, whatever) exist in one large "family tree" of classes. It does not mean you need to remove logical parent/child relationships from your game.

In this case, you can implement the kind of hierarchical transformation approach in exactly the same way, either by having the renderable components have a transformation hierarchy themselves or simply having the renderable components contain a reference to a sprite which uses the existing transform hierarchy you outlined in your question -- this, in fact, would let you keep the bulk processing logic for those components in your renderer itself, where is could be in general more localized/cache-coherent and potentially better for parallelization (unlikely with rendering, but usually true for other subsystems or the subsystems themselves). See also the outboard component architectural approach.

# Answer
> 1 votes
You most probably need a complex transform state tree/cache system. You can start by adding a "parent" member to the transform object. Implementation pretty much depends on what you already have there so there's not much I can help with.

OR

You could go back to a system where you know how it's done (at least to that part of it). Why did you move away from it?

# Answer
> 1 votes
The easiest and most obvious way will work well enough:

Make a "parent relationship" component and attach it to your entities. Then in the transform calculation step, recursively calculate the parent transform.

If you want to improve efficiency, save a time stamp or frame counter with the parent entity so that you don't need to compute the parent transform more than once per frame.

# Answer
> 0 votes
I've got the feeling you might be misinterpreting what a component-system is about.

Here is an excellent article about this.

An ECM-system is meant to avoid the child-parent spaghetti between *code-objects that inherit from each other*, not between *game-objects*.

This has nothing to do with transforms. If you have a character and you want to move his head in relation to the body, you still need some form of parent/child relationship between them and a scene-graph or transform-stack that couples their position and orientation together.

For your example you could rewrite your renderer to apply the transforms itself and call \*push\_back\* like this

```
void Object::innerDraw(sf::RenderTarget& target, Transform & parentTransform)
{
    Transform myTransform = parentTransform * Object::getTransform();
    Renderer::toDraw.push_back(&sprite, myTransform);
    for (Object *child : m_children)
    {
        if(child->isVisible)
            child->innerDraw(target, myTransform); //draw all children
    }
}

```

But I would probably prefer to keep it as it is and not.

(Note, that *Transform* is just a guess, I don't know how they're actually called in SFML)

---
Tags: component-based, sfml, heirarchy
---


# Question
Title: Choose your own adventure console program
I'm new to programming and am writing a choose your own adventure game in C++ and am having trouble with exiting the program.

The way I have it set up is I am using functions as the different pages. So the program jumps around alot say from main to choice 1 to choice 2 to choice 5 to choice 3 and so on. It runs well aslong as I dont choose to go back. I have an int GameOver() function that displays if you die but after that message ends it will jump to another function.

I feel like I am doing this wrong but from all of my searches I can't find the right way to do this.

I have looked at the exit function but I am not sure if that is the right way to go about ending the program so abruptly or if I should end the program so abruptly.

I can post all of my code but really its just a lot of cout's and either a switch statement or if/if else/else loops.

Should my setup be dif.? Should I not jump from functions without returning to main?

# Answer
If you never return from functions, you may risk running out of stack space, but practically speaking it sounds like your case may be subject to tail call optimization. It's not an optimization I'd rely on, though; you may want to consider passing some concept of "current state" around or storing it, and letting a "main loop" (literally a loop in your main() function or some other early method) dispatch to other functions based on this state -- it can be a big `switch` block, or a data structure that relates states to function pointers, or something else.

Those functions can then run, possibly set state, and return to `main()`.

One of your states can therefore trigger an "exit main loop" via `break` or the like.

A quick sketch of a very simple "state machine" pattern:

```
int main() {
    bool isRunning = true;
    int nextGameState = GAME_START;
    while ( isRunning ) {
        switch ( nextGameState ) {
            case GAME_START: nextGameState = doGameStart(); break;
            // other states here, following the above pattern
            case EXIT_GAME: isRunning = false; break;
            default: /* error handling here */; break;
        }
    }
    return 0;
}

```

Another quick possibility would be something like:

```
extern bool g_isRunning = true; // global (yuck?)

typedef unsigned (*GameStateFunctionPointer)();

static const GameStateFunctionPointer s_gameStateTable[] =
{
    doGameStart, // index = 0 entry
    // TODO other state functions here
    doGameEnd // index = n entry
};
static const unsigned NUM_GAME_STATES = sizeof( s_gameStateTable ) /
                                        sizeof( s_gameStateTable[0] );

int main() {
    unsigned nextGameState = GAME_START;
    while ( g_isRunning ) {
        if ( nextGameState >= NUM_GAME_STATES ) {
            // bad state
            abort(); // or other error handling
        }

        // call through function pointer to function that
        // does the work of the this state, then determines next state
        nextGameState = s_gameStateTable[ nextGameState ]();
    }

    return 0;
}

```

Re "going back", you may be able to keep a state history -- a list of prior game states -- rather than just a single `nextGameState` as above. You can then "go back" trivially by popping a state off this container.

(You may want to look at Deterministic Finite Automata / Nondeterministic Finite Automata -- sometimes more colloquially referred to as "state machines", although there are some non-overlapping bits -- for ideas of how you might design this. I'd *strongly* advise diagramming your state machine on "paper" if possible!)

(You may also just want to look around for other "game loop" examples, especially for text adventures.)

There are various advantages and disadvantages to both of the above very simple examples. If you're getting into more complicated state machines you might want to look into existing libraries for state machine / DFA / NFA representation.

By the way: `exit(0)` in and of itself isn't that evil. The OS will clean up after you. The disadvantage is you can't run all your shutdown code, and it makes things like leak tracking or taking other actions on normal shutdown (save game, update high scores, or any number of other things) more difficult.
> 8 votes

---
Tags: c++, text-based
---