# Question
Title: Segmentation fault on reallocation of memory but why?
I have been learning to code in C from this amazing resource http://c.learncodethehardway.org/book/

I am on exercise 17. Basically creating your own simple database using Malloc. I modified the exercise to come up with my own arbitrary size database. So far I have been on the right track. But I have had to deal with this segmentation fault nightmare and I don't know where and why its happening in my code.

If some of you C geniuses could kindly look into my code and point out what I am doing wrong, it would be greatly appreciated!

Particularly in the function Database\_Set and Database\_ExpandSize. Inside Database\_Set, I keep track of rows count to see if it exceeds maxrows and call Database\_Expand to reallocate a new memory space of bigger size. Before this I shift everything from old address to a temporary address using memcpy.

Please look at my code below. The code is running fine till I set 8 rows but when I try to set a 9th row in my database. The size increases from 8 to 16 but and causes a "segmentation fault". I am definitely doing something absurd in Database\_Expand but I am don't know what. You can also try running the entire code in your C compiler. I am running it on my Mac Terminal by using Make.

Also after running the code through valgrind, showed me some memory leaks loss of some 16k bytes in Expand\_Size. How do I correctly free the old memory space while reallocating?

```
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

#define MAX_DATA 512
#define MAX_ROWS 2

struct Address
{
    int pid;
    int set;
    char name[MAX_DATA];
    char email[MAX_DATA];
};

struct Database
{
    //for arbitrary size database, we need to allocate it on the Heap'
    int maxrows;
    int rowCount;
    struct Address* addressRows;
};

struct Connection
{
    struct Database* db;
    FILE* file;
};

void Database_Load(struct Connection* conn)
{
    int rc = fread(conn->db,sizeof(struct Database),1,conn->file);
    if(rc!=1)printf(" could not load the database ");
}

// This is the first step. You first open the database by allocating space for connection and database structures
// Next you check for the mode type and open the file assigining it to connection
struct Connection* Database_Open(const char* filename)
{
    struct Connection* conn = malloc(sizeof(struct Connection));
    if(!conn)printf(" memory error ");

    conn->db = malloc(sizeof(struct Database));
    if(conn->db == NULL)printf(" mem error ");

    //setting up arbitrary size database
    conn->db->maxrows = MAX_ROWS;
    conn->db->rowCount = 0;
    conn->db->addressRows = malloc(sizeof(struct Address) * conn->db->maxrows);
    conn->file = fopen(filename,"w");
    /*else
    {
        conn->file = fopen(filename,"r+");

        if(conn->file)
            printf(" loading the database.. ");
            Database_Load(conn);
    }*/
    if(!conn->file)
    {
        printf(" failed to open the file ");
        return NULL;
    }
    return conn;
}

// Initialize all the pids of address structures in the database
void Database_Create(struct Connection* conn)
{
    int i = 0;
    for(i = 0; i < conn->db->maxrows; i++)
    {
        struct Address* addr = conn->db->addressRows + ( sizeof(struct Address) * i );
        addr->set = 0;
        addr->pid = i;
    }
}

int Database_ExpandSize(struct Database* db)
{
    /*
     allocate a temp address row stuct
     */
    struct Address* tempAddrRows = malloc(sizeof(struct Address) * db->maxrows);
    struct Address* startAddress = tempAddrRows;  //to bring back tempAddressRows back to the start, keep a track of its starting address
    struct Address* incrementalAddress = tempAddrRows;
    struct Address* dbAddrRowTemp = NULL;

    /*
     copy everything from original addressRows to temporary incremental address which points to tempAddressRows
     */
    int i = 0;
    for(i = 0; i < db->maxrows; i++)
    {
        dbAddrRowTemp = db->addressRows + (sizeof(struct Address) * i);
        memcpy(incrementalAddress,dbAddrRowTemp,sizeof(struct Address));
        incrementalAddress += sizeof(struct Address);
    }

    //sanity check, all looks fine
    for(i = 0; i < db->maxrows; i++)
    {
        struct Address* check = tempAddrRows + (sizeof(struct Address) * i);
        printf(" \n for temp addr row, pid, set, name, email %d %d %s %s \n ",check->pid,check->set,check->name,check->email);
    }

    //reallocate temp address to double size and bring it back to start address
    tempAddrRows = realloc(tempAddrRows,db->maxrows * 2 * sizeof(struct Address)); //realloc frees the previous memory block ie previous allocations of tempAddrRows is freed!
    tempAddrRows = startAddress;

    //make the max rows double the size and assigne dbAddressRows to point to newly allocated tempAddressRows
    db->maxrows *= 2;
    db->addressRows = tempAddrRows;
    return 1;
}

void Database_Write(struct Connection* conn)
{
    rewind(conn->file);
    int rc = fwrite(conn->db,sizeof(struct Database),1,conn->file);
    if(rc!=1)printf(" memory error in database write ");
    rc = fflush(conn->file);
    if(rc == -1)printf(" could not be flushed ");
}

void Database_Set(struct Connection* conn,int id,char* name,char* email)
{
    conn->db->rowCount++;
    if(conn->db->rowCount > conn->db->maxrows)
    {
        printf(" row increased max row size, expanding the array from %d to %d \n ",conn->db->maxrows,conn->db->maxrows*2);
        if(Database_ExpandSize(conn->db) == 0)
        {
            printf(" failed to resize the array ");
            return;
        }
    }

    struct Address* addr = conn->db->addressRows + ( sizeof(struct Address) * id );

    if(!addr)
    {
        printf(" addr is null in Set ");
        return;
    }

    if(addr->set == 1)
    {
        printf(" already set the id \n ");
        return;
    }

    addr->set = 1;
    addr->pid = id;

    printf(" setting for %s with address %p \n",name,(void*)addr);

    char* res = strncpy(addr->name,name,MAX_DATA);
    if(!res)printf(" could not set the name ");

    res = strncpy(addr->email,email,MAX_DATA);
    if(!res)printf(" could not set the email ");
}

void Database_Get(struct Connection* conn,int id)
{
    struct Address* addr = conn->db->addressRows + (sizeof(struct Address) * id );

    if(!addr)
    {
        printf(" addr is null in Get ");
        return;
    }
    printf(" for id %d ",id);
    printf(" \n name %s",addr->name);
    printf(" \n email %s",addr->email);
}

void Database_Delete(struct Connection* conn,int id)
{
    struct Address* addr = conn->db->addressRows + (sizeof(struct Address) * id );

    if(!addr)
    {
        printf(" addr is null in Get ");
        return;
    }
    addr->set = 0;
}

void Database_List(struct Connection* conn)
{
    int i =0;
    for(i = 0; i < conn->db->maxrows; i++)
    {
        struct Address* addr = conn->db->addressRows + (sizeof(struct Address) * i );
        printf(" \n inside list address for id %d -> %p, setId %d \n ",i,(void*)addr,addr->set);
        if(addr->set == 1)
        {
            printf(" id %d \n",addr->pid);
            printf(" name %s \n",addr->name);
            printf(" email %s \n",addr->email);
        }
    }
}

void Database_Close(struct Connection* conn)
{
    if(conn)
    {
        if(conn->file)fclose(conn->file);
        if(conn->db)free(conn->db);
        free(conn);
    }
}

int main(int argc, char *argv[])
{
    if(argc < 3) printf(" enter correct parameters in form ./HeapDatabase db.dat c ");

    char* filename = argv[1];
    struct Connection* conn = Database_Open(filename);
    Database_Create(conn);
    Database_Write(conn);

    Database_Set(conn,0,"j","b");
    Database_Set(conn,1,"p","k");
    Database_Set(conn,2,"fd","ewew");
    Database_Set(conn,3,"ew","as");
    Database_Set(conn,4,"ewq","ewe");
    Database_Set(conn,5,"bn","we");
    Database_Set(conn,6,"de","de");
    Database_Set(conn,7,"m","a");
    //Database_Set(conn,8,"wee","qweqwe");
    Database_List(conn);
    Database_Close(conn);
    return 0;
}

```

Thank you!

# Answer
In your `Database_ExpandSize()` function:

```
struct Address* startAddress = tempAddrRows;
...
//reallocate temp address to double size and bring it back to start address
tempAddrRows = realloc(tempAddrRows,db->maxrows * 2 * sizeof(struct Address));
tempAddrRows = startAddress;

```

You first reallocate your data with twice the size but then you overwrite the pointer it with the old (now invalid, because *realloc frees the previous memory block ie previous allocations of tempAddrRows is freed!*) pointer. This leaks the newly allocated block (as there is no pointer to it) and makes `tempAddrRows` a dangling pointer. Any access to the memory pointed to by it results in undefined behaviour.

To fix both issues remove the assignment `tempAddrRows = startAddress;`.

You should also check whether `realloc` returns `NULL` to handle any error during memory allocation. Note that when `realloc` indeed does return `NULL` the original memory block is **not** freed.
> 2 votes

---
Tags: c, memory-efficiency, memory
---


title: Unity Ui slider volume control

text:
# Question
Title: Unity Ui slider volume control
I have the ui slider to control my volume, I have my slider to control all the volume of the game. I have make it so when the main slider change value all the other slider change with it but when I try to use the other slider to change the volume of the game doesn't work, the audio only change when I use the main slider, I want that when you use the other slider it can control the volume of the game too but I don't know how. Can anyone help?

Code:

```
using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class MainAudio : MonoBehaviour {

public Slider slider;

void Awake()
{
    if(slider){
    GetComponent<AudioSource> ().volume = PlayerPrefs.GetFloat ("CurVol");
    slider.value = GetComponent<AudioSource>().volume;
}
}
public void VolumeControl(float volumeControl)
{
    GetComponent<AudioSource> ().volume = volumeControl;
    PlayerPrefs.SetFloat ("CurVol", GetComponent<AudioSource> ().volume);
    PlayerPrefs.Save ();
}
private void Update()
{
    VolumeControl(slider.value);
}
void OnApplicationQuit() {
    PlayerPrefs.Save();
}
}

```

# Answer
> 0 votes
I answered a question from you on this source code a few days ago and already saw that you dont really think about what you code.

At first -as I said you-, remove the PlayerPrefs lines from the `VolumeControl` method, this is producing unneeded overhead, because you update and save the "CurVol" value from the Registry in the `OnApplicationQuit` method.

```
private void OnApplicationQuit()
{
    PlayerPrefs.SetFloat("CurVol", GetComponent<AudioSource> ().volume);
    PlayerPrefs.Save();
}
public void VolumeControl(float volumeControl)
{
    GetComponent<AudioSource>().volume = volumeControl;
}

```

And i also cannot help you with your current problem because you did not update your source code to what you have or at least tried. There is no reference to other sliders and not even the slightest change from last time where I answered your question. Please try to put a little bit more effort into your problem description, and maybe another guy in the Internet had the same problem as you sometime before and gave an answer in a forum. Google could be a good start here.

---
Tags: unity, c#, unityscript, audio, ui-design
---


# Question
Title: What is the difference between games technology and games development?
I have firmly decided to be in the games industry. However, I have really hard time choosing a bachelor program because I can't understand what's the difference between games technology and games development. I've checked the unis prospectus and I find the two programs pretty much similar.

What is the difference between games technology and games development?

# Answer
I don't know if this terminology has the same meaning across countries, but the terms can definitely be used to describe distinct topics. Note that, related to the terms *game technology* and *game development*, there also exists the term *game design*.

---

# Game technology

***Game technology*** *refers to the development of supporting technologies for games, independant of a specific game design. It focusses on the design of high-performace algorithms of core game-related functionality.*

Think of it as low-level tech that belongs in your game engine. Topics you would label as game technology include: rendering algorithms, input polling from devices, collision checking and physics, audio processing, timing, file handling, memory handling and more.

Game technology expertise is important if you are developing a custom game engine or engine component, as well as low level mechanisms to support game development decisions. Additionally, you can pursue game tech as an academic career as constitutes a big body of academic research, being an optimization/ performance-related field. As user Stephan notes, you could see game technology as a form of high-performance computing, specialized in game-related algorithms.

---

# Game development

***Game development*** *refers to using game technology to build specific game designs. It is an intermediate inbetween game technology and game design, because its goal is to build functional game mechanics (conceptualized in the game design phase), making use of low-level game technologies.*

You can think of it as the answer to the following question: "How do I translate an idea for a game mechanic into a functional game/ algorithm?". For example you could design a game where you shoot birds at crates and pigs, with the goal of destroying as many of these objects as possible. The game development step is then to: 1. implement shooting of birds based on touch-screen input of the player, 2. implementing physics-based movement of the projectile-bird using a physics engine, 3. implementing destruction of scene elements by checking for collisions via your physics engine and spawning particles, 4. implementing the rendering of your objects and particles using a rendering system and more.

Game development expertise is important when you actually want to make a game. Note that algorithms created during game development are related to a specific game, whereas game technological algorithms are agnostic of a specific game. Because of this, acedemic research on game development is much more limited than research on game technology. On the flip-side, game technology expertise is less required in the industry, as you can rely on existing game engines that handle most low-level operations themselves. Game development-related studies aim at giving you an insight in how game technologies work from a high-level standpoint (without delving into the nitty-gritty optimization details) with the goal of allowing you to make use of them efficiently.

---

# Game design

***Game design*** *refers to the conceptualization of a game idea, independant of specific technologies. It emphasizes on coming up with novel gameplay mechanics, that would be fun to play for a user.*

Think of this as the artistic side of game design. Game design includes the design of a story for a game along with quests that can be situated in this story, the design of items, conceptualizing novel enemy behavior patterns and more. Game design focusses largely on creativity.
> 7 votes

---
Tags: game-industry
---


# Question
Title: Finding the "Important" nodes of a grid path
On a Navmesh Grid, all nodes are essentially vertices or turn-points so the returned path is efficient in that it only involves points where an entity must change its direction.

A grid path, however, involves nodes at every point along the path. For long paths, there could be hundreds of nodes contained even though most of those nodes just follow a line and don't change the direction of the path.

Note: Paths are lists of a GridNode object.

I haven't tested this hypothetical issue in application yet so my first question is: Is this even an issue? For a game that requires real-time pathfinding for roughly 200 entities on a grid of 4,096 nodes, will the returned paths consume too much memory and resources? My main concern is related to how entities will handle paths, which is to check for reaching the target node before moving on to the next one and calculating the new direction needed. With more spaced out nodes, entities might have more leeway with following their paths if pushed off of it.

Secondly, if it is a potential issue, how would I solve it and cull out the insignificant nodes of a path?

# Answer
At 4096 nodes, it's probably not an issue. The pathfinding should be fast, and the resulting paths will be pretty small.

The simplest approach to reduce the number of nodes on the paths is to first find the path on the grid, and then use "string pulling" to eliminate most of the nodes from the resulting path.

If you're working with a large grid you might want to reduce the graph to just the places where you need to turn. It's every grid node that's a "convex corner". Here's an example (interactive demo here):

You may be able to do this as part of your map editor or map generation algorithm, or you can write an algorithm to find these points and edges. I have an unfinished page here that runs a brute-force algorithm on Bioware maps. There are also much more clever algorithms; see one demo here (800x800 grid, ~1ms to find a path in javascript), or look at this paper from the grid-based pathfinding competition to learn about lots of other techniques that people use.
> 2 votes

---
Tags: path-finding, data-structure, grid
---


title: Run HLSL in C++ Basic Sample

text:
# Question
Title: Run HLSL in C++ Basic Sample
I'm considering the idea of taking shaders written in HLSL and running them in an AviSynth plugin to process videos. This would allow accessing various shaders, and also to have GPU acceleration. I'm a .NET programmer and have no experience with HLSL, Direct, C++ or AviSynth plugin development. It's a lot to learn at once. So before spending too much time into it, I have a few questions.

1. Can it easily be done to run a HLSL script in c++, copy the input frame data, and copy the output frame data back, doing a bridge between 2 interfaces?
2. On computers not supporting OpenCL, will the HLSL script still run on the CPU or refuse to run at all?
3. I haven't yet found any sample using HLSL that compiles. I can't use Windows Store Templaes on Windows 7 and ActiveX SDK samples run on outdated components that aren't compiling. Where can I find a good tutorial or sample to get started?

This right here seems to describe the basics of what needs to be done. Loading and using an HLSL shader?

# Answer
> 1 votes
HLSL is the High Level Shader Language used by Direct X. HLSL Shaders are run on the GPU at runtime and can only be run by the CPU in a special debug mode inside of Visual Studio. HLSL requires a Direct X pipeline to be setup in your application. Visual Studio can compile your shaders for you but you have to load them and feed them to your pipeline. You must then instruct Direct X to run your shader logic with given geometry. If you're doing video processing / playback this geometry is probably just a simple rectangular buffer.

Open CL is not Direct X and has no correlation to HLSL other than that they both run on the GPU. If a computer does not support Direct X you will have to detect that when you setup your Direct X pipeline and fall back to a different way to handle your graphics logic or just fail spectacularly (which is what I would recommend, screw CPU side graphics manipulation).

You should use C++ with Direct X as the .NET implementation (XNA Game framework) has been deprecated and while Monogame (the open source implementation of XNA) is excellent I don't think it would work very well with AviSynth. Also I believe XNA and Monogame use FX shaders which are pretty deprecated.

Learning C++ and Direct X is your best bet to get this done but it's no small task. Of course stack exchange is a good place to ask smaller questions if you run into more specific problems along the way :)

---
Tags: c++, shaders, directx, hlsl
---


title: Stencil based mask with alpha

text:
# Question
Title: Stencil based mask with alpha
I'm trying to create a fog effect like civ 5:

I tried creating a StencilSet shader that receives a mask and sets the stencil buffer to 1. I would render the following on every unexplored tile using this shader. White is full alpha, black is 0 alpha, gray is in between.

Then I created a StencilUse shader that would display the cloud as one big texture, but will test that stencil value is 1. This way the cloud will only be shown on top of the unexplored tiles (+ a bit of overlap outside the tile, per the mask sprite).

This is what I got:

The problem is that I can't produce the fading effects towards the end of the cloud. It's either fully visible or not visible at all. How would I be able to use the grey areas when determining the alpha value of the cloud?

Any ideas? (I'm using Unity)

# Answer
> 1 votes
Using only stencil will not help you if you want smooth fading of your clouds. Stencil (as the name suggests) is used to reject pixels which are masked out by it.

When you draw your b/w alpha tile you probably setup stencil test so that if alpha!=0 then stencil passes, otherwise - fails. So you get what you asked for.

When you later draw your clouds they will be hard-cutted according to the stencil mask.

I do not know all details of your code, but it could be easier to just draw alpha-transparent clouds only over unexplored tiles, but also multiply them by your b/w color tile. This way your unexplored tiles will have fading borders. Drawback is that there will be fading borders also between any 2 consequent unexplored tiles. To avoid this you can have several types of b/w textures (depending on type of neighbour tiles), but then you'll have to issue separate draw call for each tile (or unique configuration, if you sort them by b/w texture). I am not familiar with Unity, so unfortunately cannot say how to exactly do it there. But if you got the idea, then it should be easy.

More proper solution would be to generate distance field texture.

# Answer
> 0 votes
What you could do is to set the alpha by using a formula similar to this:

```
If(length(color) != 0)

Alpha = 1 - length(normalize(color));

Else

Alpha = 0

```

---
Tags: unity, shaders, stencil
---


# Question
Title: How can I implement a quaternion camera?
I am trying to implement a quaternion camera in OpenGL 3.3.

I have so far used these tutorials below however I have a bug which I cannot work out how to fix.

So as I understand it the camera defines it's own co-ordinate space with target, up and right vectors which are relative to the view. Using some matrix trickery these three vectors can be used to construct a matrix which transforms the vector positions to the correct place.

The second of the two tutorials linked above seems to use quaternions to rotate the up, left and target vectors although it renames them to view, up and axis.

On my vector class I have a rotate method which takes an axis and angle as a parameter and creates the rotation quaternion before applying it to the vector.

The problem I face is that as I rotate the camera around the y axis to face negative z, looking up or down (rotating around the camera's right vector) appears to tilt the camera around the global x axis in the opposite direction, rather than translating relative to the camera.

Also when facing in the negative Z direction rotation around the cameras right vector is completely inverted.

I am guessing that this is something to do with the way that quarternion rotation works and that when I face towards the negative z my camera's right vector's direction is inverted thereby inverting the rotation axis. I have tried to remedy this with a messy if statement but that seemed to clamp the camera in strange places and wasn't really effective.

Some help or guidance would be greatly appreciated.

```
// Quaternion Normalize Method.
Quaternion<TValue> normalize() const {
  TValue magnitude = getMagnitude();
  auto normalizedValues = array<TValue, 4>();
  for (int i = 0; i < 4; i++){
    normalizedValues[i] = m_values[i] / magnitude;
  }
  return Vector<dimensions, TValue>(normalizedValues);
}

// Quaternion multiplication method.
Quaternion<TValue>& operator*=(const Quaternion<TValue>& rhs) {
  float x, y, z, w;
  x = m_values[W] * rhs[X] + m_values[X] * rhs[W] + m_values[Y] * rhs[Z] - m_values[Z] * rhs[Y];
  y = m_values[W] * rhs[Y] - m_values[X] * rhs[Z] + m_values[Y] * rhs[W] + m_values[Z] * rhs[X];
  z = m_values[W] * rhs[Z] + m_values[X] * rhs[Y] - m_values[Y] * rhs[X] + m_values[Z] * rhs[W];
  w = m_values[W] * rhs[W] - m_values[X] * rhs[X] - m_values[Y] * rhs[Y] - m_values[Z] * rhs[Z];

  m_values[X] = x;
  m_values[Y] = y;
  m_values[Z] = z;
  m_values[W] = w;

  return *this;
};

Quaternion<TValue> conjugate() const{
  return Quaternion({ { -m_values[X], -m_values[Y], -m_values[Z], m_values[W] } });
};

// Quaternion rotation method
static Quaternion<TValue> rotation(Vector<3, TValue> axis, TValue angle){
  float x, y, z, w;
  TValue halfTheta = angle / 2.0f;
  TValue sinHalfTheta = sin(halfTheta);
  return Quaternion<TValue>({ {
    axis[X] * sinHalfTheta,
    axis[Y] * sinHalfTheta,
    axis[Z] * sinHalfTheta,
    cos(halfTheta) } });
};

// Vector rotate method
Vector<dimensions, TValue> rotate(const Vector<3, TValue> axis, float angle){
  Quaternion<TValue> R = Quaternion<TValue>::rotation(axis, angle);
  Quaternion<TValue> V = (*this);
  Vector<dimensions, TValue> result = R * V * R.conjugate();
  return result;
}

// Camera rotate method.
void Camera::rotate(Vector<3,float> axis, float angle){
  setLookAt(m_target.rotate(axis, angle), m_up.rotate(axis, angle));
}

// Camera setLookAt method.
void Camera::setLookAt(Vector<3, float> target, Vector<3, float> up){
  Vector<3, float> newUp = up.normalize();
  Vector<3, float> newTarget = target.normalize();
  if (newUp != m_up || newTarget != m_target){
    m_up = newUp;
    m_target = newTarget;

    m_right = (m_up * m_target).normalize();

    m_up = m_target * m_right;

    m_uvn = Matrix<4, float>::identity();

    m_uvn[0][0] = m_right[Dimensions::X];
    m_uvn[1][0] = m_right[Dimensions::Y];
    m_uvn[2][0] = m_right[Dimensions::Z];

    m_uvn[0][1] = m_up[Dimensions::X];
    m_uvn[1][1] = m_up[Dimensions::Y];
    m_uvn[2][1] = m_up[Dimensions::Z];

    m_uvn[0][2] = m_target[Dimensions::X];
    m_uvn[1][2] = m_target[Dimensions::Y];
    m_uvn[2][2] = m_target[Dimensions::Z];

    setViewMatrix(m_uvn * m_translation);
  }
};

// Taken from game update method.
Vector<2, double> offset = getMousePosition() - m_screenCentre;
if (offset.getMagnitudeSquared() > 0.00001){
  float dy = offset[Dimensions::X] * (3.1415),
  dx = offset[Dimensions::Y] * (3.1415);
  m_camera.rotate(Vector<3, float>({ { 0, -1, 0 } }), dy);
  m_camera.rotate(Vector<3, float>(m_camera.getXAxis()), dx);
  setMousePosition(m_screenCentre);
}

```

# Answer
> 3 votes
As someone who has implemented an entire Math library including Quaternions let me say that just following a tutorial will not get you anywhere with this. To iron out bugs like this you really need to understand how Quaternions work, what they are and how to use them. It's probably some of the most complicated math in Game development and I don't recommend trying to just wing it with an OpenGL camera to try to learn it all.

euclideanspace has a lot of really good resources but it's a terribly organized site so I can point you to a page to get you started (can't post more than 2 links right now).

http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/index.htm

It might be better to ask some more specific questions related to rotational mathematics and quaternions over a the math stack exchange as you learn about this concept. It might be better right now to just stick with an Euler angle camera with a matrix representation under the hood.

It's also worth noting that just having a quaternion implementation will not solve gimbal lock on its own (assuming that's your goal). https://mathoverflow.net/questions/95902/the-gimbal-lock-shows-up-in-my-quaternions

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


title: OpenTK Ray Picking

text:
# Question
Title: OpenTK Ray Picking
I just can't get ray picking to work (I need to drop old working faedback mode, and replace it with color pick, but because my scene can have up to 300K+ objects it is reasonable to filter (it's a hierarchy) visible objects by ray picking first to limit the number of drawn bounding boxes).

Here it goes. Why oh why this is failing me (I'm out of ideas, I don't see some obvious error...):

```
public class MouseRay
{
    private Vector3 _start;
    private Vector3 _end;

    public Vector3 Start { get { return _start; } }

    public Vector3 End { get { return _end; } }

    public MouseRay(Point mouse)
        : this(mouse.X, mouse.Y)
    {
    }

    public MouseRay(int x, int y)
    {
        int[] viewport = new int[4];
        Matrix4 modelMatrix, projMatrix;

        // get matrix and viewport:
        GL.GetFloat(GetPName.ModelviewMatrix, out modelMatrix);
        GL.GetFloat(GetPName.ProjectionMatrix, out projMatrix);
        GL.GetInteger(GetPName.Viewport, viewport);

        _start = new Vector3(0, 0, 0);
        _end = new Vector3(0, 0, 0);

        Glu.UnProject(new Vector3(x, y, 0.0f), modelMatrix, projMatrix, viewport, ref _start);
        Glu.UnProject(new Vector3(x, y, 1.0f), modelMatrix, projMatrix, viewport, ref _end);
    }

    public bool HitSphere(IDrawable drawable)
    {
        return HitSphereAt(drawable) != Vector3.Zero;
    }

    public Vector3 HitSphereAt(IDrawable drawable)
    {
        Vector3 pos = drawable.RealTranslation;
        float radius = drawable.BoundingRadius;

        Vector3 d = _end - _start;
        float a = Vector3.Dot(d, d);
        float b = 2.0f * Vector3.Dot(d, _start - pos);
        float c = 2.0f * Vector3.Dot(pos, pos) + Vector3.Dot(_start, _start) - 2.0f * Vector3.Dot(pos, _start) - radius * radius;

        float test = b * b - 4.0f * a * c;

        if (test >= 0.0)
        {
            // Hit (according to Treebeard, "a fine hit").
            float u = (-b - (float)Math.Sqrt(test)) / (2.0f * a);
            return _start + u * (_end - _start);
        }

        return Vector3.Zero;
    }
}

```

Here is unproject func (not my code, but I think I understand it):

```
public static class Glu
{
    //....

    public static int UnProject(Vector3 win, ref Vector3 obj)
    {
        Matrix4 modelMatrix;
        GL.GetFloat(GetPName.ModelviewMatrix, out modelMatrix);

        Matrix4 projMatrix;
        GL.GetFloat(GetPName.ProjectionMatrix, out projMatrix);

        int[] viewport = new int[4];
        GL.GetInteger(GetPName.Viewport, viewport);

        return UnProject(win, modelMatrix, projMatrix, viewport, ref obj);
    }

    public static int UnProject(Vector3 win, Matrix4 modelMatrix, Matrix4 projMatrix, int[] viewport, ref Vector3 obj)
    {
        return gluUnProject(win.X, win.Y, win.Z, modelMatrix, projMatrix, viewport, ref obj.X, ref obj.Y, ref obj.Z);
    }

    private static int gluUnProject(float winx, float winy, float winz, Matrix4 modelMatrix, Matrix4 projMatrix, int[] viewport, ref float objx, ref float objy, ref float objz)
    {
        Matrix4 finalMatrix;
        Vector4 _in;
        Vector4 _out;

        finalMatrix = Matrix4.Mult(modelMatrix, projMatrix);

        //if (!__gluInvertMatrixd(finalMatrix, finalMatrix)) return(GL_FALSE);
        finalMatrix.Invert();

        _in.X = winx;
        _in.Y = viewport[3] - winy;
        _in.Z = winz;
        _in.W = 1.0f;

        /* Map x and y from window coordinates */
        _in.X = (_in.X - viewport[0]) / viewport[2];
        _in.Y = (_in.Y - viewport[1]) / viewport[3];

        /* Map to range -1 to 1 */
        _in.X = _in.X * 2 - 1;
        _in.Y = _in.Y * 2 - 1;
        _in.Z = _in.Z * 2 - 1;

        //__gluMultMatrixVecd(finalMatrix, _in, _out);
        // check if this works:
        _out = Vector4.Transform(_in, finalMatrix);

        if (_out.W == 0.0)
            return (0);
        _out.X /= _out.W;
        _out.Y /= _out.W;
        _out.Z /= _out.W;
        objx = _out.X;
        objy = _out.Y;
        objz = _out.Z;
        return (1);
    }

    //....
}

```

# Answer
Solved it. Maybe this will be usable for someone:

```
public class MouseRay
{
    private Vector3 _start;
    private Vector3 _end;

    public Vector3 Start { get { return _start; } }

    public Vector3 End { get { return _end; } }

    public MouseRay(Point mouse)
        : this(mouse.X, mouse.Y)
    {
    }

    public MouseRay(int x, int y)
    {
        int[] viewport = new int[4];
        Matrix4 modelMatrix, projMatrix;

        GL.GetFloat(GetPName.ModelviewMatrix, out modelMatrix);
        GL.GetFloat(GetPName.ProjectionMatrix, out projMatrix);
        GL.GetInteger(GetPName.Viewport, viewport);

        _start = new Vector3(x, y, 0.0f).UnProject(projMatrix, modelMatrix, new Size(viewport[2], viewport[3]));
        _end = new Vector3(x, y, 1.0f).UnProject(projMatrix, modelMatrix, new Size(viewport[2], viewport[3]));
    }

    public bool HitSphere(IDrawable drawable)
    {
        return Vector3.Cross(Vector3.Subtract(drawable.RealTranslation, _start), Vector3.Subtract(drawable.RealTranslation, _end)).Length / Vector3.Subtract(_end, _start).Length < drawable.BoundingRadius;
    }
}

Extensions
{
    public static Vector3 UnProject(this Vector3 mouse, Matrix4 projection, Matrix4 view, Size viewport)
    {
        Vector4 vec;

        vec.X = 2.0f * mouse.X / (float)viewport.Width - 1;
        vec.Y = -(2.0f * mouse.Y / (float)viewport.Height - 1);
        vec.Z = mouse.Z;
        vec.W = 1.0f;

        Matrix4 viewInv = Matrix4.Invert(view);
        Matrix4 projInv = Matrix4.Invert(projection);

        Vector4.Transform(ref vec, ref projInv, out vec);
        Vector4.Transform(ref vec, ref viewInv, out vec);

        if (vec.W > 0.000001f || vec.W < -0.000001f)
        {
            vec.X /= vec.W;
            vec.Y /= vec.W;
            vec.Z /= vec.W;
        }

        return vec.Xyz;
    }
}

```
> 0 votes

---
Tags: c#, opengl, raycasting, opentk
---


title: How can I make a scrollable text view?

text:
# Question
Title: How can I make a scrollable text view?
I am trying to do an appication in monogame windows. I have a long text to be displayed on screen. I tried to render it on screen using spriteBatch.Drawstring, was succesful to an extent. But, the text did not fit into a required area. I had followed this tutorial. I need a vertical scroll to be implemented to have the entire text inside my desired area. Can anyone suggest some help. This is my current code :

```
protected override void LoadContent()
    {
        spriteBatch = new SpriteBatch(GraphicsDevice);
        _boxTexture = new SolidColorTexture(GraphicsDevice, Color.Red);
        _borderRectangle = new Rectangle(100, 100, 500, 500);
        _textboxRectangle = new Rectangle(105, 105, 490, 490);
        _font = Content.Load<SpriteFont>("Rockwell");
        _text = "He determined to drop his litigation with the monastry, and relinguish his claims to the wood-cuting and fishery rihgts at once. He was the more ready to do this becuase the rights had becom much less valuable, and he had indeed the vaguest idea where the wood and river in quedtion were.";

    }

private String parseText(String text)
{
String line = String.Empty;
String returnString = String.Empty;
String[] wordArray = text.Split(' ');

foreach (String word in wordArray)
{
    if (font.MeasureString(line + word).Length() > textBox.Width)
    {
        returnString = returnString + line + '\n';
        line = String.Empty;
    }

    line = line + word + ' ';
}

return returnString + line;
}

```

and inside draw function :

```
spriteBatch.DrawString(font, parseText(text), new Vector2(textBox.X, textBox.Y), Color.White);

```

# Answer
> 1 votes
I wrote something similar to this for the GUI library I made. It's hosted here and uses the MIT license so feel free to rip anything you want out of it.

This method draws the text to a render target as I found that provided significant performance gains compared to redrawing everything line by line. Simply replace the textureBaker bit with your SpriteBatch if you want to redraw normally.

For the scrolling bit simply use the clipping rectangle `GraphicsDevice.ScissorRectangle = node.Data.ClippingArea;` to limit what is drawn. If you want help on how to handle the scrolling as in the rendering of scrollbars and handling input I can show you how I accomplished that but it is fairly involved and would warrant a separate question. If you want to take a look here are the relevant bits: Handling Input, Layout and Logic.

```
    public void BakeText() {

        var textureBaker = new TextureBaker(
            RenderManager.GraphicsDevice,
            Area.Width,
            Area.Height,
            TextureBaker.RenderState.Fill);

        var start = 0;
        var height = 0.0f;

        while (true) {

            start = RenderLine(textureBaker, start, height);

            if (start >= Length) {
                RenderedText = textureBaker.GetTexture();
                return;
            }

            height += Font.LineSpacing;
        }
    }

    private int RenderLine(SpriteBatch textureBaker, int start, float height) {

        var breakLocation = start;
        var lineLength = 0.0f;
        var row = (byte)(height / Font.LineSpacing);
        string text = new string(_char), tempText;

        //Starting from end of last line loop though the characters
        for (var iCount = start; iCount < Length; iCount++) {

            //Calculate screen location of current character
            _charX[iCount] = (short)lineLength;
            _charY[iCount] = (short)height;
            _row[iCount] = row;

            //Calculate the width of the current line
            lineLength += _charWidth[iCount];

            //Current line is too long need to split it
            if (lineLength > Area.Width) {
                if (breakLocation == start) {
                    //Have to split a word
                    //Render line and return start of new line
                    tempText = text.Substring(start, iCount - start);
                    textureBaker.DrawString(Font, tempText, new Vector2(0.0f, height), TextRenderer.Color);
                    return iCount + 1;
                } else {
                    //Have a character we can split on
                    //Render line and return start of new line
                    tempText = text.Substring(start, breakLocation - start);
                    textureBaker.DrawString(Font, tempText, new Vector2(0.0f, height), TextRenderer.Color);
                    return breakLocation + 1;
                }
            }

            //Handle characters that force/allow for breaks
            switch (_char[iCount]) {
                //These characters force a line break
                case '\r':
                case '\n':
                    //Render line and return start of new line
                    tempText = text.Substring(start, iCount - start);
                    textureBaker.DrawString(Font, tempText, new Vector2(0.0f, height), TextRenderer.Color);
                    return iCount + 1;
                //These characters are good break locations
                case '-':
                case ' ':
                    breakLocation = iCount + 1;
                    break;
            }
        }

        //We hit the end of the text box render line and return
        //_textData.Length so RenderText knows to return
        tempText = text.Substring(start, Length - start);
        textureBaker.DrawString(Font, tempText, new Vector2(0.0f, height), TextRenderer.Color);
        return Length;
    }
}

```

---
Tags: c#, sprites, monogame, windows-8, scrolling
---


# Question
Title: How to manage state in a component-based game engine?
I'm working on a small, data-driven game engine with some friends.

We use GameObjects (a.k.a. Entities, Actors, or whatever it is called in your favorite engine) to represent every entity in the game. These GameObjects owns Components, who communicates via message passing. This is a very well-known pattern, and although implementations differ greatly, it seems to be what every commercial, modern game engine is doing.

Now we have one problem: managing state. Let's say we are creating some kind of platform game. The hero of this game should be able to stand still, jump, attack...

We created some Finite State Machines to hold the player's state. Now the state should, in turn, be consumed by the other components. Running should trigger an animation and modify the player's velocity, attacking should stop the player and spawn a bullet...

But this creates a lot of dependencies. The Sprite component now has to be aware of the State component, and listen to state changes. The Movable component should listen to state changes too, to be able to change the player's speed. Nearly every component depends on the State component. This sounds like a dependency hell.

I think it's a very common problem, but I can't find a good solution for it. Are there some design patterns for situations like this?

# Answer
> 5 votes
It's OK to have component dependencies. And the more explicit the dependency the better. There's nothing worse than dependencies hidden behind useless layers of indirections.

Your case doesn't look like a dependency hell to me. No circular dependency or unclear ownership of data: consider yourself lucky!

Now I still believe that you need to reverse your thinking a bit. Instead of having your Movable, Sprite, VFX etc. components reading the player's State, you should probably have the State request changes on the others. E.g. by posting messages (I want a speed of Xm/s, I want a running animation, and also some dust smoke, kthxbye), or via direct functions calls. The player controller is often the client of various subsystems, not the other way around.

# Answer
> 3 votes
In my experiences there aren't too many ways around the fact that, you're right, all your different game entities and their components need to be aware of the state of the game and their own state. It's a mess unless you design with state machines in mind.

The best way I've found to deal with it is to make sure that components are all doing small pieces of work and working together. Don't let components get out of control and handling all sorts of things that could be handled by separate components. Let the Sprite component just load images, check the Player's state and update with the right image. If you need Animation scrap the Sprite managing anything other than loading and Drawing and let the Animation query the Player's state and tell the sprite to play back certain images at a certain speed. This is a rough example but I think it highlights how to deal with components working together in one object.

Another practice that helps is having a GameManager entity that has a series of scripts for managing the game state of the scene. You don't necessarily want the GameManager to control much game logic as that should mostly be up to the components but it should act as a wingman for all of the components to let them know about the state of the game as a whole. Don't be afraid to have static data either. It's not awful to call something like `Enemy.GetEnemies()` or `GameManager.GetState()`

It's a good idea to check out some projects written in Unity or another engine to see how they're organized. I know you're dealing with the Engine not just the Game but I can link you to some projects of mine that I think are fairly well organized.

A game written in my engine: https://github.com/FlannelViolin/Checkers

A game written in Unity (links directly to scripts): https://github.com/Honeybunch/Ebolinator2014/tree/master/Assets/EbolinatorScripts

Polymorphism and Dependencies are your friends; very powerful friends. Design with them, not against them.

---
Tags: architecture, entity-system, component-based, data-driven
---


# Question
Title: How can I pass messages from multiple components to another?
I want to start with an (easy) Entity Component System. I have a question regarding the messaging between Components.

Let's say I have a `RenderComponent`. This component needs 2 integer values `x` and `y` and probably a Sprite to render. Now I have 3 other Components:

* `TransformComponent` with 5 doubles: `x`, `y`, `width`, `height` and `rotation`.
* `MovementComponent` with 2 doubles: `velX` and `velY`.
* `AnimationComponent` with an array of Sprites.

Now I want to render my Entity.

How do I collect the Data from the different Components to render my Sprite? All these informations have to enter the RenderingComponent at the same time. Does someone have an idea on how to accomplish an efficient ECS?

# Answer
Templating and metaprogramming are your friends here.

What I did for my engine was implement a method like Unity: `GameObjectInstance.GetComponent<ComponentType>()`. And make sure that every `Component` has access to the `GameObject` that it's attached to. This way you can easily say in `MovementComponent`

```
void Update()
{
    //Move game object
    transform = gameObject.GetComponent<TransformComponent>();
    transform.position += Vector(xVel, yVel);

    //Animate sprites
    animator = gameObject.GetComponent<AnimationComponent>();
    animator.AnimateMoving();
}

```

It's best to model a component system off of something like Unity or Unreal which is proven to work unless you have a reason for doing something experimental.
> 1 votes

# Answer
You could try creating a System architecture. Like components are added to entities and entities are added to an engine, the engine could also contain a collection of Systems.

A System would iterate through the entities in the engine and for each entity that contains a TransformComponent, MovementComponent and AnimationComponent, it gathers all necessary data needed to render your entity.

RenderSystem - on Update:

```
for (Entities in Engine) {
    if (Entity contains TransformComponent, MovementComponent, AnimationComponent) {
        // Render the entity
    }
}

```

This same pattern can be seen in entity frameworks such as Artemis and Ashley. With Ashley, you can create a system which only updates entities that contain specific components using Family. Here's an example (Java):

```
public class AnimationSystem extends IteratingSystem {

    public AnimationSystem() {
        super(Family.all(
                TransformComponent.class,
                MovementComponent.class,
                AnimationComponent.class
        ).get());
    }

    @Override
    protected void processEntity(Entity entity, float deltaTime) {
        TransformComponent transform = entity.getComponent(TransformComponent.class);
        MovementComponent movement = entity.getComponent(MovementComponent.class);
        AnimationComponent animation = entity.getComponent(AnimationComponent.class);

        animation.elapsedTime += deltaTime;

        someSpriteBatch.draw(animation.currentFrame, transform.x, transform.y);
    }
}

```

That being said, in terms of the component definitions you provided, logically the AnimationSystem would only require access to the TransformComponent and the AnimationComponent. If you want to manage entity movement, you could create a MovementSystem which requires access to the TransformComponent and the MovementComponent.
> 1 votes

# Answer
Start simple: x and y and are in the Transform component, so read them from here. Same for the sprite: read it from the component where it's stored.

You really don't need to make it more complicated than that.
> 0 votes

---
Tags: entity-component
---


title: DirectX map/unmap

text:
# Question
Title: DirectX map/unmap
In my 2d game i want to use dynamic buffers to render sprites. My question is, when should i map unmap buffer? The 2 possibilities are:

```
#1
//game logic
map()
    fill buffer
unmap()
render()

#2
//game logic
fill buffer
unmap()
render()
map()

```

The second is different because the resource stays mapped for a longer time(all the game logic of the next frame), while in the first option is mapped and soon after unmapped. I want to use the second, it's a good idea or are there cons (performance wise or others)?

# Answer
> -1 votes
Usually in DirectX you need 2 textures, one allocated on "dynamic" zone (hint during create resource). And one created in "static" zone, which you copy remotely using `CopyResource` from D3DContext. So you map/unmap the dynamic texture, then post a copy order, this way you limit the change of blocking the rendering.

# Answer
> -1 votes
If you have DYNAMIC buffer and map it with WRITE\_DISCARD then both ways are pretty much identical.

As soon as you issue map call, DirectX will provide you with brand new buffer, so there will be no CPU-GPU sync, that is the point. You cannot read data in this provided buffer, first because it is a completely new memory and does not contain your data, second - because returned memory is a writecombine memory and reading from it will cause big penalty.

While in your case this will not be a problem, but mapping buffer with discard causes runtime to search available piece of memory, which sometimes may lead to hitches. More robust way would be to have several buffers (or just one bigger buffer) and map it with MAP\_NO\_OVERWRITE (only available for index/vertex buffers unless you are running Direct3D 11.1 on Win8), but you need to ensure that memory to which you are writing is not anymore used by GPU. One way to ensure it is to have as many buffers as you maximum frame latency, or issue queries and check that they are ready.

You can read more about it here

Hope this helps.

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


title: Custom Coloring of Tileset Characters

text:
# Question
Title: Custom Coloring of Tileset Characters
Games like Dwarft Fortress and Dungeon Crawl Stone Soup are drawing their boards using tiles from a tileset image (I think?). I know you can do color keying and replace the background color with transparency or another color, but how are games like these drawing the text characters into different colors? Using the same method? I am trying to find the best way to use a tilesheet to draw ascii graphics and be able to choose what color the text is, and what color the background of the tile is separately.

Something similar to what is pictured here.

# Answer
If your "base" tile in a tile set is white (1.0, 1.0, 1.0), then you can simply take advantage of the multiplicative identity (one times a thing is that thing) to multiply in the color of your choice from whatever source you want at draw time. For example, you might pass the desired color as a vertex attribute or a shader uniform, and in the fragment shader output you sample the tile texture and multiply in your desired color (pseudocode):

```
float4 baseColor = sample(tileTexture);
return baseColor * desiredColor;

```

Depending on the values you put in the colors, you may need to further clamp/reassign the alpha component of the color because you normally won't want that modulated in this fashion. Although you can allow that if you like the effect/control it provides.

That's a simple approach.

A more complicated approach, for example if your base tile color is not white or is more than one color, is to look at either

* decomposing the tiles into one or more layers which can be tinted as above, or
* hue-shifting the tiles instead; this means converting the tile colors from RGB into the hue/saturation/value color space, and adjusting the hue to the desired value, and converting back.

You can combine the above two approaches, in fact: use one texture layer for the parts of the tile which would always remain their fixed, original color and another layer (or layers) containing the parts of the tile that can be color-shifted by some amount. This gives you quite a bit of flexibility and is very similar (if not exactly the same as) a common technique used to support "dye channels" in character's clothes or armor.
> 2 votes

---
Tags: libgdx, textures, graphics
---


# Question
Title: Dual Currency vs. One Currency in social games economics and monetization
Not a programming question but game development related.

I am creating an iPhone online game which I wish to be free-to-play where in-app purchase is used for monetization. The important point is to make sure that this does not break the game-play, my priority is gameplay first, monetization second.

One popular way of monetizing the player base is to sell your in-game currency, however there are 2 ways to go about this:

1. One Currency: This currency can buy anything within the game, it can be earned through normal play at a limited rate. Players can, however, choose to buy this currency directly to speed up the acquisition of the currency.
2. Dual Currency: One currency can be earned through normal play and it can be used to buy a limited set of items that is required for normal enjoyment of the game. The second currency is 'premium' and must be purchased using real world money. This second currency can be used to purchase 'premium items' that gives extra abilities such as increase EXP gain, etc. The 2 currencies can be traded between players to give non-paying players to exchange their time for the 'premium' currency.

Both methods do not break gameplay and allows players who does not wish to pay enjoy the entire contents of the game if they put in enough time and effort.

My question is, is there any reason why you would pick one over another? What are the pros and cons that I should pay attention to when implementing each alternative?

Thank you.

# Answer
Using one currency has the benefit of keeping things simple. You don't require dual prices for anything, and you don't require trading to give all players potential access to all content.

The psychology of the two approaches is complicated. I'm going to look at this from the commercial point of view. People fall into (at least) the following categories:

* "Paying players get an advantage? I'm not playing". (You can ignore these)
* I will pay a small amount to get things I would have got anyway as a money-time tradeoff. (Favour single currency)
* I won't pay, but I will only play single-currency games (time-money tradeoff). Whether you care about these players or not depends on your gameplay, and the nature of interaction between players.
* I will pay to get the best stuff and then lord it over the non-paying plebs. (Slightly favour dual-currency).
* I'll play for a bit before I make up my mind. These players don't have a fixed approach to money-time tradeoffs, so they could go either way.

I'm not sure what research has been done on the relevant sizes of the camps, and it may well depend on the genre.

Additional considerations:

1. Having two currencies makes it more complicated. Not only does it complicate the code, but it complicates the balancing, and keeping the economy balanced is a familiar problem to MMO designers.
2. There is actually a third way. I'm currently playing a game which has two currencies; one of them is for sale, but even non-paying players acquire it very slowly (one coin some of the time on level up). Some items are only for sale in the monetised currency; others have prices in both.
> 6 votes

# Answer
The best approach I've seen as of yet is that of **Spiral Knights**.

There are two currencies, and **they do completely different things**.

You cannot use a currency instead of the other to do something, and that's good because that would defeat the purpose of having two currencies in the first place!

You use **crowns** to buy stuff, you use **energy** to revive yourself and other people, and to go deeper in the dungeons, and you use **both** (not either! both!) to craft items.

Crowns are dropped by mobs, energy can be bought with real money, *and* every player has 100 "free" energy which automatically slowly recharges in 22h. Of course this free energy is spent before the other one. Many things cost more than 100 energy so in that case you have to use paid energy to do that.

Of course there's an exchange for the users to trade crowns for energy and vice-versa.
> 7 votes

# Answer
Having a single currency is not simple at all for monetization. This is because you would have to implement many efficient money sinks in the game to stop players from grinding their way to unlocking all content/items. Without good sinks, there is no incentive to buy IAPs. I suppose in terms of coding it might be slightly more complicated, but with a single-currency model you'll forever have to be hyper-alert to the in-game economy's fine-tuning to make any money, as well as be a whiz at implementing the right balance of currency source vs. sink. Remember, too effective a sink and players just avoid that feature of a game altogether. Basically, you'll have to be a godlike economist as well as a brilliant coder and game designer (or hire all three).

There is a good reason why all the top grossing F2P games currently - Supercell's games, Zynga's games, League of Legends, etc. - use a dual currency model. It's actually a lot simpler in the long run, and has some psychological benefits to boot (e.g. the sunk cost effect, where unused premium currency sits in your inventory, a constant reminder that you could use it if you bought a little more). You can allow people who like to grind, grind their hearts out on the soft currency. And you can keep the premium currency exclusive to payment. You can gift it slowly to reward loyalty and improve your KPIs (retention, re-engagement), but you control the flow of this currency tightly.

In the end, it does come down to the type of game you're making. Some games are more suited for a single currency, others require more (I've seen games with 5 currencies). However, you should probably default with dual currency model and have a damn good reason for not using it if you do otherwise. If you go with a single currency, there's a good chance you'll have a hard time making any revenue.

Strongly recommended reading: Mobile & Social Game Design: Monetization Methods and Mechanics, Second Edition By Tim Fields, Brandon Cotton

disclaimer: I've worked with game publishers and developers, and am currently a data analyst and monetization specialist for a company that does both.
> 6 votes

# Answer
Basically you should create a game play that any player can ***enjoy*** the most, either way the only people who has money and willing to spend it without much hesitation, will buy any thing from you and others will not that often.

And only from these people you will get your main portion of revenue, while from others you will get about 10-15% purely depending on your game. So you can implement either one it does not make any difference to the player or you.

The only problem you will face is how to implement any one in your game.

I have seen both kinds of game with nice game play get users to buy from the apples app store after playing the game.

Here is an example for both.

---

1.. Dual Currency :- You will find this game called ***steam birds*** one of the kind that implements dual money kind of a thing in the game. If can pay then you will be rewarded by some new planes which has got extra speed and power. It is also available on the iphone.

http://www.steambirds.com/
http://itunes.apple.com/us/app/steambirds-survival/id441192740?ls=1&mt=8

It has a simple but really awesome game play that makes the user to stick to the game day and night.

---

2.. One Type Currency :- If you ever owned an iphone or working on udk then you will know this game. Its called ***Infinity Blade***.

http://itunes.apple.com/app/infinity-blade/id387428400?mt=8

If you look at the above page then you will get an idea about how good and famous that game is. The link shows that the top in-app purchase is about $50, so can see how people spend there money if they like the game.

---

So in the end it comes down to how much work are you putting in the game for its look & feel, then you can get as many bucks as you want by implementing the anyone of the above 2 methods.

I hope this helps you even a bit for your game.
> 1 votes

---
Tags: game-design, monetization, economy
---


# Question
Title: Algorithm to fill a shape defined by 4 pixel points?
I'm developing an application in Unity3D where a user can define 4 pixel points on screen, and what I would like to do is fill this shape with pixels using Unity's SetPixel.

While I can do this easily for square or rectangular shapes, I was wondering if there is any efficient code or algorithm to do this for more irregular four-sided shapes, such as trapezoids etc.

Note : Filling the shape with a mesh is not an option.

So far the best option I can think of is to draw the outline, then draw a line from each pixel point of every outline, to every other outline point, but I'm not sure that's very efficient.

# Answer
You can use the even-odd algorithm. In summary it does the following.

1. Loop thru each scan line
2. Intersect the scan line with each polygon edge
3. Sort the intersection points by x value
4. Fill interior pixels between intersection points using the even-odd rule to determine interior points

Note, you have to guard against degenerate cases like intersecting with vertices and horizontal lines.
> 1 votes

---
Tags: unity, rasterization
---


# Question
Title: How can I find the difference between rotations represented as angles in [0, 360]?
What is the easiest way to find the difference between two 2D rotations/directions?

I want to test if one rotation is within 10° of another. I would just subtract, but there are some problems because I want to keep each rotation between 0 and 359. E.g. 0 is within 10° of 359, but simple subtraction would claim that they're 359 degrees apart.

# Answer
### This requires simple modulo arithmetic.

1. Find the difference between two angles `t1` and `t2`.
2. Fix any angle differences that are greater than one full rotation.
3. If angle exceeds 180 degrees, compare in the ***other*** direction.

### Pseudo Code:

```
d = mod (abs (t1 - t2), 360)

if (d > 180)
    d = 360 - d

if (d <= 10)
  "Hooray!!!"

```
> 2 votes

# Answer
One easy way is to check if the difference is greater than 180 or less than -180. If it is, you can add or subtract 360 to one of the values and then get your difference.

Example:

```
if(r1-r2 > 180) //r1 > r2
     r1 = r1-360;
else if(r1-r2 < -180) //r1 < r2
     r1 = r1+360;
//then check the difference
diff = r1-r2;

```
> 1 votes

# Answer
Note that above fails for `r1=720 and r2<=0`. I would like this...

```
d = mod (r1 - r2), 360)
if(d >= 180) //r1 > r2
 d = d-360;
else if(d < -180) //r1 < r2
 d = d+360;

```
> -1 votes

---
Tags: mathematics, rotation
---


# Question
Title: Using Farseer Physics, how can I get objects to bounce at the correct angle
I am using the Farseer Physics engine in my MonoGame project. I have static walls which have "body" friction 0 and "body" restitution 1. I have dynamic objects, which are circles, with "body" friction 0 and "body" restitution 1. There is no gravity.

When I launch a dynamic object at a wall, it does not bounce in the way I would expect for a perfectly elastic, frictionless collision. The angle it bounces at should be the reflection (through the wall's normal vector) of the angle it arrives at.

Instead, the dynamic objects often slide *along* the wall:

In the diagram, the black line is the wall; the blue line is the desired path of the dynamic object; and the orange line is the current path of the dynamic object.

How can I make my dynamic objects bounce properly?

# Answer
> 2 votes
It turns out that Farseer objects can have multiple restitution and friction settings: one set for the body and one set for each fixture.

I was only setting the body settings; adding settings for the fixtures solved the problem:

```
fixture.Restitution = 1f;
fixture.Friction = 0f;

```

---
Tags: physics, monogame, collision-resolution, farseer-physics-engine
---


# Question
Title: OpenGL How to render a voxel based world scene with many objects
I am working on a voxel game engine using OpenGL binding for JVM languages (scala is my case) - LWJGL 3 for OpenGL version 4.5 . Currently I'm stuck with chunk rendering (32\*32\*32 blocks). To render any object I firstly give it an unique ID, treating similar objects, like simple blocks, as one with different transformations, create one VAO data thing in initialization stage and after all preparation is done, I render a whole chunk looping through each block, passing its data to the shader and then calling drawElements with appropriate offset, taken from ID. This way fps drops from 3000(with 3 axis lines and a huge grid object rendered separately) to 1-2. So how should I correctly render a chunk ?

I used https://sites.google.com/site/letsmakeavoxelengine/home/basic-block-rendering tutorial as reference.

Fps dropping code:

```
def render(shader:Shader): Unit ={
   for(x <- 0 until SIZE) {
      for (y <- 0 until SIZE) {
         for (z <- 0 until SIZE) {
            val obj = blocks(x)(y)(z)
            if(obj != null){
               val M = obj.getTransformationMatrix() * Matrix4F.matrixTRANSLATION(obj.getPosition())
               shader.setUniformMat4f("M", M)
               shader.setUniformMat4f("MI", M.inverse())
               shader.setUniformBool("lightInteraction", obj.lightInteraction)
               shader.setUniform1f("smoothness", obj.smoothness)
               shader.setUniform3f("matD", obj.matDiffuse)
               shader.setUniform3f("matS", obj.matSpecular)
               GL13.glActiveTexture(GL13.GL_TEXTURE0); // Texture unit 0
               glBindTexture(GL_TEXTURE_2D, obj.getTextureID())
               Shader.full.setUniform1i("tex", 0)
               RenderRegistry.getRenderManager().render(obj.getID, obj.getRenderType())
            }
        }
     }
  }
}

```

EDIT: for those who are interested, instanced arrays helped me a lot ! Link for a tut: http://learnopengl.com/#!Advanced-OpenGL/Instancing

# Answer
The way you are rendering voxels is extremely ineffective. For each cube you have to do calculations, set uniforms, and worst of all bind textures(This is usually a very expensive operation)

Typically effective voxel rendering involves multiple techniques to speed up rendering:

* Rendering in chunks: You split your world into neatly sized proportions, which makes it easier to cull and to generate/regenerate.
* VBO: You render each chunk as a single VBO to utilize least possible API calls.
* You render only the blocks that are "facing air"(Don't render the blocks that are completely surrounded and have no visible faces.) to reduce polygon count. The most commonly used algorithm for this, is called "Marching cubes". wiki
* To further reduce rendered polygons, you could use frustum culling, so you would only render the chunks that are in your viewport.(Thanks to @Kaarez to pointing this out)
* Texture atlas: you don't bind a new texture for each cube, but create a huge texture which contains all of your voxel textures and just change the voxel texture coordinates to match the correct texture's location on the atlas.

The site you referenced also has these and other techniques in its tutorial section, so you should probably reduce your world size so you get a testable FPS and start implementing these optimizations.

Also you should measure performance not in FPS but in frame time: The time needed to rendered a single frame. FPS is not good, because it is not linear.
> 4 votes

---
Tags: opengl, lwjgl, voxels, vbo
---


# Question
Title: wheeled 2D character controller platform edges problem
I have built a little wheeled 2D character controller (a rectangle for the body and a circle for the legs with a motor joint). Everything is ok but the problem is that when the player reaches the edge of a platform it goes down a little because the the the legs part is a circle. How do you ussually fix this kind of behaviour?

This image shows the problem when the character walks close to the platform edge:

Cheers.

# Answer
> 0 votes
I'd limit the movement near the edge of the platform. So, when the wheel base is stopped near the edge make the character halt, and wobble, and only if the player keeps on pushing will they go off the edge. You can control the "dismount" animation, too.

Of course, if the player just pushes constantly off the edge you must honour their intent and just move them off the platform.

---
Tags: physics
---


title: Tiled tilemapper - isometric

text:
# Question
Title: Tiled tilemapper - isometric
I'm attempting to move from oblique mapping (45 degree angles) to isometric (30 degree angles) in Tiled.

I made a test tile in Photoshop:

Made an isometric map:

But my tile appears completely distorted, and the 'isometric' map just appears as a top-down grid rotated 45 degrees:

How do I create a proper isometric scene using tiled?

---

Hi, in your example (here), your Tiled grid is angled down. As you can see, mine appears Top down. How do I configure this?

# Answer
When creating your tileset, you need to set up your tileset parameters such that the whole column becomes a single tile. Once you have that working you can tweak the "tile width" and "tile height" properties of your map until your tiles align correctly on the grid.

Easiest is to enable a grid in your image editor so that you can experiment with the size and align the column properly. Then it's easy afterwards to fill in the right values in the New Tileset dialog.

There is a small HOWTO about creating an isometric map on the forums.
> 1 votes

---
Tags: tilemap, isometric, tiled
---


title: Ranking system for "offline" game?

text:
# Question
Title: Ranking system for "offline" game?
I'm currently developing a game where players will be able to battle each other, not in real time, but offline, in a way where both players doesn't have to be online. This might seem like a bad idea, but it makes sense in the context of the game.

Right now I'm trying to create some kind of ranking system, where the outcome of the match only affects the player who initiated the match, since I don't want players loosing rank when they're not playing.

A simple idea would be to award the player 2 points for winning and take away 1 for loosing.

I honestly have no idea if this design would work, so I come here to get some suggestions on how to design system like this. Thank you.

# Answer
> 1 votes
A good idea is to grant them points based on how much their opponent has.

Try something like this: https://en.wikipedia.org/wiki/Elo\_rating\_system

# Answer
> 0 votes
It all depends on the context of what you are doing but:

**FLAT :**

Designing it around flat values is viable if you don't wish the competitive factor to be heavy. = Win or lose vs anyone gets you the same result, no need to seek out better players to play againts.

**FLAT AND PERCENTILE:**

You can take percentages of existing points but then you have to work on engagement rules. Is a 0 hour noob going to be able to take a shot at someone with a lot of points. Games that open engagements fully mean that an observant but sneaky party can wait for stronger people to spend their forces fighting each other, to only sweep easy targets. No right or wrong - just choose if you want that kind of social dynamic or not. Either way you have to give flat points because 122142% of 0 is still 0.

**ALTERNATIVE:**

You can track all the points people ever had, or the largest amount of points people ever had. Then draw upon that source only or parallel to any other points you deal.

This way defeating prestigious players still nets a result even if they are now low on current points. Limiting the exploit-ability of afk/ish players is as simple as only draw points from record IF the provider of points has more than 0 current.

**..........**

In any event. A tool is complimentary to a goal. If you have a specific idea of what you want to achieve you will be much better suited to chasing down details. Even is said idea is as abstract as "I want the player to get points very hard, but lose them easily - so the ones with much points can feel way superior".

Otherwise you fall pray to the design loop of "we ought to have it because we think its probably popular/good to have it"... Instead of because we want to make something of it. Use it to fill a ... Make it feel like ...

Who are you going to buy? "I don't know, we saw that making TVs is trendy so we opened a factory" or ... "We felt we wanted to improve This and That, to make TVs better, so we went into the business..."

---
Tags: game-design, ranking
---


# Question
Title: How to create scrolling input text field using Unity UI
How to create scrolling input textfield using UI

in Unity 4.6.6

problems in my project are

1.Cursor is not masking

2.Scrollbar size is automatically become 0 to 1 size

3.Scrollbar is not working after assigning in "Scroll Rect".

Here is my sample project

Thanks in advance .

# Answer
I have not looked in your sample but you want to create panel within your canvas. I name mine ScrollView and attached is the Scroll Rect and mask. set the scroll rect to verticle, elasticity to .1 and sensitivity to around 25. It is important that the Content of scrollview is filled with the container panel that will be a child of the View panel. Also is important if you want a scrollbar that you place it as a child of the view panel then click the view panel and drag the bar to vertical scrollbar within the scroll rect

If you don't have a container panel as a child to the ScrollView create one and within the Container panel Add a grid layout group and set the start corner to upperleft the start axis to verticle the child alignment to uppercenter and constraint to fixed column count, set constraint count to 1.

Next add to the container panel a content size fitter and set verticle fit to min size and horizontal to uncontrained also the rect transform of the container panel set Pivot Y to 1 so it starts at the top of the list.

After this is all set up anything that is a child of the container panel(Multiple created text objects, input fields, images or even Instantiated panels) should scroll just fine and be fitted perfectly in the container.
> 2 votes

---
Tags: unity, input, ui-design, scrolling
---


# Question
Title: In MonoGame, how can I disable font anti-aliasing?
I am building a game with a "low resolution" aesthetic, so I would like to disable the default font anti-aliasing. The text is drawn using the built-in SpriteFont and SpriteBatch classes.

Here is what it currently looks like:

Here is what I would like it to look like:

(Please ignore the particles)

# Answer
To turn off antialiasing, all you have to do is change your sampler state to `SamplerState.PointClamp` in your `spriteBatch.Begin()` call. Here's a short code example:

```
spriteBatch.Begin(SpriteSortMode.Deferred,
      BlendState.AlphaBlend,
      SamplerState.PointClamp,
      null, null, null, null));

// Draw text here using DrawString

spriteBatch.End();

spriteBatch.Begin()

// Draw textures, etc

spriteBatch.End()

```

Alternatively to this, you can permanently set the `SamplerState` of the graphics device to `PointClamp` in your `Initialize()` method with the following code (this should work in any method that is only called once, maybe even the constructor):

`graphicsDevice.SamplerStates[0] = SamplerState.PointClamp;`

This way, you could use the normal `spriteBatch.Begin()` call with no parameters. Note that this method would apply SamplerState.PointClamp to everything that you draw, not just text

# References:

Here's the reference for XNA's SamplerState, which should be the same as MonoGame's: https://msdn.microsoft.com/en-us/library/microsoft.xna.framework.graphics.samplerstate\_fields%28v=xnagamestudio.40%29.aspx

Behind the scenes when actually drawing, SamplerState.PointClamp actually evaluates to:

```
Filter = TextureFilter.Point,

AddressU = TextureAddressMode.Clamp,
AddressV = TextureAddressMode.Clamp,
AddressW = TextureAddressMode.Clamp,

```

(according to the documentation)

# Notes:

Another possibility to disable antialiasing would be to change this graphics device setting:

```
Game1.GraphicsDevice.RenderState.MultiSampleAntiAlias = false;

```
> 4 votes

---
Tags: xna, monogame, text, antialiasing
---


# Question
Title: Player rotation issues (Player returns to default forward rotation after releasing keys)
So basically what is happening is that my player rotates and faces the direction that he is currently being steered toward (which is wonderful). But after I release, let's say the A key, meaning he is currently facing and moving to the left, he goes back to facing forward after the key is released.

Here is my code:

```
public class PlayerMovement : MonoBehaviour {
public bool isGrounded;
private float distToGround;
private Vector3 v;
private Vector3 h;
public float speed;

Rigidbody rb;
Collider col;

void Start() {
    rb = GetComponent<Rigidbody>();
    col = GetComponent<Collider>();
    distToGround = col.bounds.extents.y;
}

void Update() {
    if (Physics.Raycast (transform.position, -Vector3.up, distToGround + 0.1f)) isGrounded = true; else isGrounded = false;
    if (isGrounded) {
        v = new Vector3(0, 0, Input.GetAxis("Vertical")) * speed;
        h = new Vector3(Input.GetAxis("Horizontal"), 0, 0) * speed;
        rb.MovePosition(rb.position + v * Time.deltaTime);
        rb.MovePosition(rb.position + h * Time.deltaTime);

//This deals with all the rotation
        Vector3 direction = new Vector3( Input.GetAxis ("Horizontal"), 0, Input.GetAxis ("Vertical") );
        Quaternion rotation = Quaternion.LookRotation(direction, Vector3.up);
        transform.rotation = rotation;
    }
  }
}

```

I obviously know that the reason this is happening is because the rotation is being set to the axis currently being pressed, so when I release any key, the rotation goes back to the original position. I just can't quite figure out how to fix it...

# Answer
> 1 votes
I think the issue is that the input is being polled every frame as part of the Update().

~~I would suggest pulling the input from the Update() and using input callbacks instead. That way the input is only polled when fired, and not every frame. That should cause the direction to only update with input changes, and the Update() will continue to render the same direction until the value is changed the next time the callback fires.~~

Unity doesn't have callbacks, I forgot that I emulate them. This is going to take some more thought on my part. I will update soon.

If your game is a top down on an 8 point compass this gets a lot easier, but I'm trying to come up with a generalized solution.

# Answer
> 0 votes
Try adding an if statement saying if neither of the axis are equal to zero then change the rotation, this would eliminate facing forwards when there is 0 on each axis.

```
if(direction != Vector3.zero)
{Quaternion rotation = Quaternion.LookRotation(direction, Vector3.up);
    transform.rotation = rotation;
}

```

Hope this helped.

Here is another solution on Velocity;

```
    if (direction != Vector3.zero)
    {
        transform.rotation = Quaternion.LookRotation(direction);
    }

```

Hope this is better.

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


# Question
Title: Monogame - Not enough storage is available to complete this operation, on backgrounds
I am making a level selector, which works like a web slider. I am showing 12 levels per page, and I have a total number of 60, which means 5 pages of 12 levels.

Each level has his on background image, and I tried to load all the backgrounds into an Texture2D array. Since now I loaded only 12 backgrounds, because I had only them, everything worked perfectly. Now, I have more, about 40, and when I try to load them into the array I receive this error:

**Additional information: HRESULT: \[0x8007000E\], Module: \[General\], ApiCode: \[E\_OUTOFMEMORY/Out of memory\], Message: Not enough storage is available to complete this operation.**

Code line:

```
for (int i = 1; i <= 36; i++)
                LevelBackgroundTextures[i] = Resource.ContentManager.Load<Texture2D>("Levels/Backgrounds/bg_" + i);

```

If I understood correctly I receive this error because I do not have enough space (RAM) to load all the content once and I need to use multiple content processors, and here is the problem.

I do not know how can I use them to be effective, when to load/unload the content, etc. Or is there another way that I can fix this error?

Thanks.

# Answer
Yep, you're out of memory. Loading all of those textures (which I assume are going to be very large since they're backgrounds) is going to eat through your RAM pretty quickly. There are a couple different ways you could solve this.

1. Make sure no unnecessary values are floating around. It might just be that you have other data that you're not using that's in memory. This is less of a solution and more of a quick fix. You're still loading a lot of data into memory and if you move to a device with less memory you'll hit the same problem.
2. Load smaller backgrounds. It won't look as nice but if you stretch the textures a bit you'll save memory. This also doesn't perfectly solve the problem. If you want more backgrounds in the future you'll still probably run into the same problem again and then have to downgrade the quality further. That's a pain.
3. Don't load all of your backgrounds at once. When you move to the next page, add a transition like a fade where you, in a separate thread, load all of the background images. Then as you fade back in, unload the previous page's textures. That way you have 24 textures loaded at most.
4. Have fewer levels per page. This one may not be the most ideal but it will work. Heck if you lower it to like, 6 or 8 per page you can do something where you have the displayed page loaded, and the next and previous pages loaded as well. That's 18-24 textures loaded at once. Then when you move to the next page you don't have to load anything to display the page, but you can unload the page that's no longer 'adjacent' and load the next 'adjacent' page.

The solution that works best for you might be some combination of the solutions I've proposed, or even none of them! With problems like this there isn't always a #1 top solution so pick one that fits your project the best.
> 2 votes

---
Tags: c#, xna-4.0, monogame, windows-phone-8
---


title: Design Pattern for card game objects

text:
# Question
Title: Design Pattern for card game objects
In my game, I will have more than 100 types of cards,
and before the actual game, player can select 6 of them and will be shown as 6 buttons on the scene.
The card have its own ID, card name, and a 3D game Object prefab, and have a function call perfromCardAction which performs different actions.

```
public class cardA:cardInterface {
     private int ID;
     private string cardName;
     private Texture2D cardImage;
     private GameObject card3DObject;

     ...Constructor...

     private override void prefromCardAction(){
     ...do Card A action...
     }
}

```

A script cardManager should get the 6 object player selected and stored in an array.
And set the button's Image as card's 2D image.
when the button is click, that card's prefromCardAction should be called.

So my main quesstions are:
What pattern should I used so that easier manage my cards objects?
I believe I should use Factory so that I can do something like:

```
selectedCardArray[0]=CardFactory.createCard("CardA");

```

If yes, I would like to ask:
How should I code all my card class (cardA, cardB, cardC...)?
separate into different c# script and implement cardInterface and override the perfromCardAction?

# Answer
> 2 votes
I 'll try this aproach: I'm lazy so I included the factory inside the class card. I suggest using delegates to forge the behaviour of each card type, and a big and maybe brute, swith case inside the factory method (createCard).

```
public class card{
     private int ID;
     private string cardName;//getters setters?
     private Texture2D cardImage;//getters setters?
     private GameObject card3DObject;//getters setters?

     ...Constructor...

     public delegate void theFuncPrototype();
     private theFuncPrototype theFunc = {return;} ;  //initialize?
     public doAction()
     {
        this.theFunc();
     }

// define all actions
    private static actionCardA(){
    //...
    }
    private static actionCardB(){
    //...
    }
//...

     public static createCard(string cardType){
    switch (cardType)
    {
        case "CardA":
            card N = new card(....);
            N.theFunc = actionCardA;
            return N;
        case "CardB":
            card N = new card(....);
            N.theFunc = actionCardB;
        return N;
        //...
        default:
                        //... manage wrong cardType?
    }
     }

}

```

# Answer
> 2 votes
While the answer posted @dnk drone.vs.drones is technically exactly about what you asked for and a viable solution, here is another suggestion that goes a bit further, and is based on my comment on your question.

I'm assuming:

* the card effects are quite small and generic, and act on either the player or the opponent
* the game is played against an opponent, you chose the card and the effect is applied, either on yourself or on the opponent, depending on the card
* the card can be left on the table and be part of the game

The idea is to have data describe your cards, and have your code architecture read it.

The first part would be to split your actions into functions and have them mapped to a unique value.

*I'll use pseudo c++ because it's what I know, equivalents exist in c# I presume.*

```
void actionDestroyWeakestOpponentCard() {...}
void actionStrongestOpponentHalfHP() {...}
void actionHealAllMyUnitsOneHP() {...}
...

std::map<std::string, std::function<void()> > mNameToAction;

```

And the mapping:

```
void applyMappingNameToAction() {
  mNameToAction["DestroyWeakestOpponentCard"] = actionDestroyWeakestOpponentCard;
  mNameToAction["StrongestOpponentHalfHP"]    = actionStrongestOpponentHalfHP;
  mNameToAction["DestroyHealAllMyUnitsOneHP"] = actionHealAllMyUnitsOneHP;
  ...
}

```

The second part would require you to build the data file(s) required:

```
<cards>
  <card>
    <name>cardA</name>
    <graphic>images/cards/cardA.png</graphic>
    ...
    <effects>
      <action>DestroyWeakestOpponentCard</action>
    </effects>
  </card>
  <card>
    <name>cardB</name>
    <graphic>images/cards/cardB.png</graphic>
    ...
    <effects>
      <action>StrongestOpponentHalfHP</action>
    </effects>
  </card>
  <card>
    <name>cardC</name>
    <graphic>images/cards/cardC.png</graphic>
    ...
    <effects>
      <action>DestroyHealAllMyUnitsOneHP</action>
    </effects>
  </card>
</cards>

```

*Note that I use* file(**s**) *because you could have one card per file and you'd read all the files in a folder, for instance; this is for those who like to have many small files rather than one big file.*

Then you'd need to specify your card structure:

```
struct Card
{
  std::string mName;
  std::string mImagePath;
  std::vector< std::function<void()> > mActions;
  ...
  void performCardAction()
  {
    for( action in mActions )
      action(); // perform the action
  }
}

// and something to contain them:
std::map<std::string, Card> mAvailableCardsByName;

```

And then you load them:

```
for ( cardDataXml in read_cards_data_from_xml )
{
  Card newCard;
  newCard.mName = cardDataXml["name"],
  ...
  for ( cardDataXmlAction in cardDataXmlActions )
  {
    newCard.mActions.push_back( mAvailableCardsByName[cardDataXmlAction] );
  }
  ...
  mAvailableCardsByName[newCard.mName] = newCard;
}

```

This way of doing things allows you to combine small effects/actions into a card, which can offer a bit more flexibility in the design: you can create new cards by simply adding a chunk of xml.

---

You could push it a bit more by having your actions take paremeters

```
void actionHealUnitsParamDecode(
  XmlChunk aParameters,
  PlayerType& aPlayerType, // passing parameter by reference so the call gets modified
  int& aHealAmout)         // passing parameter by reference so the call gets modified
{
  if ( aParameters["target"] == "self" )
    aPlayerType = PlayerTypes::SELF;
  else if ( aParameters["target"] == "opponent" )
    aPlayerType = PlayerTypes::OPPONENT;

  if ( isPositiveInteger( aParameters["heal_amount"] )
    aHealAmout = toPositiveInteger( aParameters["heal_amount"] );
}

void actionHealUnits(Player aSelf, Player aOpponent, XmlChunk aParameters)
{
  PlayerType target = PlayerTypes::SELF;
  int        healAmount = 0;

  actionHealUnitsParamDecode( aParameters, target, healAmount );

  if ( target == PlayerTypes::SELF )
  {
    aSelf.heal( healAmount );
  }
  else
  {
    aOpponent.heal( healAmount );
  }
}

```

And with the (XML) data looking like this:

```
<effects>
  <action>
    <name>HealUnits</name>
    <params target="self" heal_amount="3" />
  </action>
</effects>

```

You need to modify your Card:

```
struct Card
{
  ...
  std::vector< std::function<void(Player, Player, XmlChunk)> > mActions;
  XmlChunk mXmlParams;

  void performCardAction( Player aSelf, Player aOpponent, XmlChunk aParameters )
  {
    for( action in mActions )
      action(aSelf, aOpponent, aParameters); // perform the action
  }
}

```

Now with this your get a whole lot of flexibility in the tweaking of your cards :) And you can add some without having to recompile, provided that all the effects are already programmed in the game.

---

This might be a bit more than you asked for :P

If it is, please use the answer already posted by @dnk drone.vs.drones as it is a more generic and flexible way to tackle it than using pure inheritance as you were suggesting.

---
Tags: c#, software-engineering, design-patterns, card-game
---


# Question
Title: How to reference a map position in code?
I'm coding a digital version of the Macao board game which has a flat map similar to below. Players have a "ship" which starts in the blue box and can follow the dashed lines in any direction/orientation. The larger rectangles represent city locations.

I'm stuck in the following issues.

1. How do I record the position of each ship? I'm thinking co-ordinates like X,Y but that doesn't tell me the segment its on
2. How do I construct the route paths as objects? Do I put them in an array?
3. Finally; in order to measure distance between 1 rectangle and another, it will need to count how many segments there are to ascertain the shortest distance. I believe this can be resolved via a simple path algorithm.

I've not created a map like this before in a project but would welcome any help on how to move this forward.

# Answer
I would suggest you start by building a node graph (a bunch of nodes and arcs (sometimes called edges)).

* The nodes are the cities and "dash" intersection
* The arcs link cities and "dash" intersection

Then all these nodes have info like their 'physical' location (x/y coordinates on the map).

To solve your issues:

1. you use the position that are set in the nodes to infer the location and the orientation.
2. this will depend on the implementation of your node graph.
3. use a path-finding algorithm like A\* to find the best route between your current location and the destination. Your graph, again, will be used for that.

This should help you to get started.

**Edit**

The produced node graph could look like this:

Of course, the arcs depicted in the picture would be the arcs linking the nodes in the graph.

Now, from the question it is not clear if the intersection nodes are spots where the ships could *stay*, but as it is designed as a board game, I assumed that if there is more than one dash between two cities, it is because it costs more to travel from one city to another (for instance you need a 2 on a dice instead of just 1). With this in mind, I assumed that a ship *could* stay on these spots (but not on arcs).

If it is not the case, however, the intersection nodes could still be used for navigation purpose between cities. This would give squarish ship tracks, however, so perhaps another approach should be taken for that. For instance: edges could contain data describing how they should be travelled (spline, series of dots, etc.).
> 8 votes

# Answer
Alexandre gave a good answer. I thought I'd take a stab at a concrete example.

The example is is C#, but hopefully it is general enough to be implemented in any language you choose to use.

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

public class SimpleGraph
{
    private int _numberOfCities;
    private int[] _paths;

    public SimpleGraph()
    {
        _numberOfCities = 9;
        _paths = new int[_numberOfCities * (_numberOfCities + 1) / 2];

        AddPath(0, 2, 1);
        AddPath(0, 3, 2);
        AddPath(3, 4, 2);
        AddPath(3, 5, 1);
        AddPath(3, 2, 1);
        AddPath(2, 1, 1);
        AddPath(2, 6, 1);
        AddPath(5, 6, 1);
        AddPath(6, 7, 1);
        AddPath(5, 7, 1);
        AddPath(6, 8, 5);
        AddPath(7, 8, 5);
        AddPath(1, 8, 6);
    }

    public void AddPath(int cityA, int cityB, int distance)
    {
        int pathIndex = getPathIndex(cityA, cityB);
        if (pathIndex < 0 || _paths.Length <= pathIndex) return;

        _paths[pathIndex] = distance;
    }

    public void RemovePath(int cityA, int cityB)
    {
        AddPath(cityA, cityB, 0);
    }

    public int GetPathDistance(int cityA, int cityB)
    {
        int pathIndex = getPathIndex(cityA, cityB);
        if (pathIndex < 0 || _paths.Length <= pathIndex) return 0;

        return _paths[pathIndex];
    }

    public bool HasPath(int cityA, int cityB)
    {
        return GetPathDistance(cityA, cityB) > 0;
    }

    public List<int> GetAvailableCities(int currentCity)
    {
        var result = new List<int>();

        for (int i = 0; i < _numberOfCities; i++)
        {
            if (HasPath(currentCity, i)) result.Add(i);
        }

        return result;
    }

    private int getPathIndex(int cityA, int cityB)
    {
        if (cityA == cityB) return -1;

        int small, big;

        if (cityA < cityB)
        {
            small = cityA;
            big = cityB;
        }
        else
        {
            small = cityB;
            big = cityA;
        }

        return (big * (big - 1) / 2) + small;
    }
}

```

This is a graph representation of your map if you number the cities in the following way:

Then, all you would need to do is keep track of an integer from 0 to 9 which is the current location of your ship and use the methods to find your way around.
> 1 votes

---
Tags: path-finding, maps, board-game
---


title: Tile map collision C++, SFML

text:
# Question
Title: Tile map collision C++, SFML
My problem with the collision here is more to do with how to decide which tile the player is in. Each quad of the map is 16 pixels squared (Vertex array), and the player moves in 1 pixel jumps. Because of this I cannot think of a way to decide which quad the player is in.

I am not sure if I am just missing something, but does anyone have an idea of how to do this?

# Answer
This is a classic collision detection problem. Thinking about it in pixels isn't the right way of going about it though.

What you need to do is have a geometric representation of your player and the boundaries of your tile map. This might be as simple as just having a bounding box on your player and on each tile.

When the player's bounding box intersects a tile's bounding box, the player is colliding with or "on" that tile. Depending on how you construct your movement the player could be "on" many tiles at the same time.

Checking the player's bounding box against every tile would also be pretty inefficient. You don't want to check the player's bounding box against tiles that it's nowhere near intersecting. This is solved with a Spatial Partitioning algorithm and for your needs it sounds like you'd want to implement a Quad Tree if you want the player to be able to be intersecting multiple tiles at once.

I hope that makes sense!
> 1 votes

---
Tags: c++, collision-detection, tilemap, sfml
---