# Question
Title: Turn-based board game server references?
Are there any good references/books to recommend about how to build a turn-base game server? It's something like a chess server for pairing chess players and keep game states. In the past, for example the IGS (for go, weiqi) is a socket based implementation. What are the available contemporary technologies to learn from? Thanks!

# Answer
I don't think there is a particular book about this, since the topic is kinda trivial.

Just imagine a mail-server where players can sent their actions via mail. The server has all the actions performed so far (as mails), which means you have the game state. If you want to reload the gamestate, just execute all the actions inside the mails chronologically. The only thing you have to do is to make sure whose turn it is ... but thats easy too (e.g. turn numbers). No need for contemporary technologies ... a modified mail server/client solution will do.

Pairing ppl can be done via Elo ... but i guess u knew that
> 5 votes

# Answer
If it were me, I'd build it from the ground up with sockets. The amount of data to send is very small, and the turn-based nature makes a little latency unnoticeable.

The real question, in my opinion, is what additional features you need on it. Are the game sessions persistent (can someone drop out and rejoin, can the game be saved, etc)? If you're doing a Civilization style save you probably want to push out the save data to all clients, or have the save done client side with a server-provided key embedded for verification.

Do you need any sort of between-turn reporting, e.g. "Player 2 is moving a unit" or "Your opponent may be AFK"? If so you may end up wanting to keep the socket connections open.

Generally speaking, unless there's some compelling reason to deviate, I'd keep the server as dumb and simple as possible. Leaves less to debug. I also kind of like using plain text protocols, as I can test my servers using telnet without an actual game client (which may be suspect in a given problem), but this does sort of encourage Wireshark manipulation of the data (which you probably will check for anyway).

Edit: If the game only supports 1-on-1 games, peer-to-peer connections may be worth looking at.
> 2 votes

# Answer
It's important not to overthink what a server is and what it's responsibilities are. In this case, you have a relatively slow acting game, so the server architecture won't be incredibly complicated (vs a faster paced game where you have dead reckoning, etc.). Your server should be listening on a TCP port (might as well skip UDP if you don't require speed anyway) for connected clients to send it packets of information. It accepts the packets, validates them based on the game rules, and sends back a response. In your specific case your server should know who's turn it currently is and reject any attempt by other players to perform actions until it's their turn.

I don't know what technology you had in mind but something this would be easy enough to do in Java with the Kyronet library. Simply send your game actions to the central server (could also be one of the two players), process it, and send back a game update to both players. I'm sure something similar exists for .NET.
> 1 votes

---
Tags: game-design, networking, server
---


# Question
Title: Type Object does not support slicing Unity3D
I am getting the following error in my code and I can't seem to understand why. Can anyone help me with it?

This is my current code. The line causing the error is marked in a comment near the end.

```
var rows : int = 4;
var cols : int = 4;
var totalCards : int = cols * rows;
var matchesNeedToWin : int = totalCards * 0.5;
var matchesMade : int = 0;

var cardW : int = 100;
var cardH : int = 100;

var aCards : Array;
var aGrid : Array;

// This Array will store the two cards that the player flipped
var aCardsFlipped : ArrayList;

// To prevent player from clicking buttons when we don't want him to
var playerCanClick : boolean;

var playerHasWon : boolean = false;

class Card extends System.Object {
var isFaceUp : boolean = false;
var isMatched : boolean = false;
var img : String;

    function Card () {
        img = "robot";
    }
}

function Start () {

    var i : int = 0;
    var j : int = 0;

    playerCanClick = true;
    aCards = new Array ();
    aGrid = new Array ();
    aCardsFlipped = new ArrayList ();

    for ( i = 0; i < rows; i++) {
        aGrid [i] = new Array ();

            for (j = 0; j < cols; cols++ ) {
            aGrid [i] [j] = new Card (); // <------ Error over here
        }
    }
}

function Update () {
    Debug.Log("Game Screen has loaded");
}

```

The error states as follows:

> **Error BCE0048: Type 'Object' does not support slicing. (BCE0048)** (Assembly-UnityScript)

# Answer
> 1 votes
Like Jonathan Hobbs said, I've made a few changes.
This is what I modified those code

```
var aCards:Array
var aGrid:Card[,]; //<-- change how you declare this variable to multidimensional arrays
var aCardsFlipped:ArrayList;

```

And change this in the Start function

```
function Start () {
    playerCanClick = true;
    aCards = new Array();
    aGrid = new Card[rows,cols]; //<-- I instantiate it as rows*cols array
    aCardsFlipped = new ArrayList();
    for (var i=0;i<rows;i++)
    {
        for (var j=0;j<cols;j++)
        {
            aGrid[i,j] = new Card(); //<-- Then assign the value like this
        }
    }
}

```

Hope this help

# Answer
> 4 votes
Javascript doesn't support multidimensional arrays well, so either switch to storing an array of objects or switch to C# in order to use multidimensional arrays.

This advice came up in answers to this Unity question. Meanwhile, according to this other question, you can declare them like this:

```
var a : float[,];

```

Or in your case, I'm guessing the syntax would be this (with or without the `new`, I'm not sure):

```
aGrid = new Card[,];

```

### So instead of your problematic line you'd have this:

```
aGrid[i,j] = new Card();

```

If you really do want to use a jagged array you need to use a workaround (according to that first link): use the `Array.Add()` method rather than directly setting the variable at each index.

---
Tags: unity
---


title: Using two joysticks in Cocos2D

text:
# Question
Title: Using two joysticks in Cocos2D
Here is what I am trying to do: With the left joystick the player can steer the figure and with the right joystick it can attack. Problem is that the left joystick seems to get all the input, the right one does not even register anything. I enabled multipletouch after the eagleView and gone thoroughly over the code. But I seem to miss something. I initiliaze both sticks and it shows me both of them in game, but like I said, only the left one works.

I initialize them both. From the h. file:

```
SneakyJoystick *joystick;
SneakyJoystick *joystickRight;

```

And in m.file I synthesize, deallocate and initialize them. In order to use one for controlling and the other for attacking I put this:

```
-(void)updateStateWithDeltaTime:(ccTime)deltaTime
andListOfGameObjects:(CCArray*)listOfGameObjects {

if ((self.characterState == kStateIdle) ||
    (self.characterState == kStateWalkingBack) ||
    (self.characterState == kStateWalkingLeft) ||
    (self.characterState == kStateWalkingRight)||
    (self.characterState == kStateWalkingFront) ||
    (self.characterState == kStateAttackingFront) ||
    (self.characterState == kStateAttackingBack)||
    (self.characterState == kStateAttackingRight)||
    (self.characterState == kStateAttackingLeft)) {

    if (joystick.degrees > 60 && joystick.degrees < 120) {
        if (self.characterState != kStateWalkingBack)
            [self changeState:kStateWalkingBack];

    }else if (joystick.degrees > 1 && joystick.degrees < 59) {
            if (self.characterState != kStateWalkingRight)
                [self changeState:kStateWalkingRight];

    } else if (joystick.degrees > 211 && joystick.degrees < 300) {
        if (self.characterState != kStateWalkingFront)
            [self changeState:kStateWalkingFront];

    } else if (joystick.degrees > 301 && joystick.degrees < 360){
    if (self.characterState != kStateWalkingRight)
            [self changeState:kStateWalkingRight];

    } else if (joystick.degrees > 121 && joystick.degrees < 210) {
        if (self.characterState != kStateWalkingLeft)
            [self changeState:kStateWalkingLeft];
    }

if (joystickRight.degrees > 60 && joystickRight.degrees < 120) {
    if (self.characterState != kStateAttackingBack)
        [self changeState:kStateAttackingBack];

}else if (joystickRight.degrees > 1 && joystickRight.degrees < 59) {
    if (self.characterState != kStateAttackingRight)
        [self changeState:kStateAttackingRight];

} else if (joystickRight.degrees > 211 && joystickRight.degrees < 300) {
    if (self.characterState != kStateAttackingFront)
        [self changeState:kStateAttackingFront];

} else if (joystickRight.degrees > 301 && joystickRight.degrees < 360){
    if (self.characterState != kStateAttackingRight)
        [self changeState:kStateAttackingRight];

} else if (joystickRight.degrees > 121 && joystickRight.degrees < 210) {
    if (self.characterState != kStateAttackingLeft)
        [self changeState:kStateAttackingLeft];
}
        [self applyJoystick:joystick
               forTimeDelta:deltaTime];
        [self applyJoystick:joystickRight
               forTimeDelta:deltaTime];
}

```

Maybe it has something to do with putting them both to time delta? I tried working around it, but it did not work. So I am thankful for any input you guys can give me :)

As per Request here is some more code: This is from the init of my gameplaylayer.

```
self.isTouchEnabled = YES;
[knight setJoystick:leftJoystick];
[knight setJoystickRight:attackButton];

```

And also from the gameplaylayer method:

```
-(void)initJoystickAndButtons {
CGSize screenSize = [CCDirector sharedDirector].winSize;
CGRect joystickBaseDimensions = CGRectMake(0, 0, 128.0f, 128.0f);
CGRect attackButtonDimensions = CGRectMake(0, 0, 128.0f, 128.0f);
CGPoint joystickBasePosition;
CGPoint attackButtonPosition;
joystickBasePosition = ccp(screenSize.width*0.10f,
                           screenSize.height*0.15f);
attackButtonPosition = ccp(screenSize.width*0.9f,
                          screenSize.height*0.15f);

SneakyJoystickSkinnedBase *joystickBase =
[[[SneakyJoystickSkinnedBase alloc] init] autorelease];
joystickBase.position = joystickBasePosition;
joystickBase.backgroundSprite =
[CCSprite spriteWithFile:@"dpadDown.png"];
joystickBase.thumbSprite =
[CCSprite spriteWithFile:@"joystickDown.png"];

joystickBase.joystick = [[SneakyJoystick alloc]
                         initWithRect:joystickBaseDimensions];
leftJoystick = [joystickBase.joystick retain];
[self addChild:joystickBase];

SneakyJoystickSkinnedBase *attackButtonBase = [[[SneakyJoystickSkinnedBase
                                               alloc] init] autorelease];
attackButtonBase.position = attackButtonPosition;
attackButtonBase.backgroundSprite = [CCSprite spriteWithFile:
                                  @"dpadDown.png"];
attackButtonBase.thumbSprite = [CCSprite
                                    spriteWithFile:@"joystickDown.png"];

attackButtonBase.joystick = [[SneakyJoystick alloc] initWithRect:
                           attackButtonDimensions];
attackButton = [joystickBase.joystick retain];
[self addChild:attackButtonBase];
}

```

And I added this in the appdelegate

```
glView.multipleTouchEnabled = YES;

```

# Answer
> 3 votes
I went over the whole code today, only to (after way too long) spot one mistake, that did it all.

```
leftJoystick = [joystickBase.joystick retain];
attackButton = [joystickBase.joystick retain];

```

It actually has to be

```
attackButton = [attackButtonBase.joystick retain];

```

and it works now. Always the little things that drive you crazy...

# Answer
> 2 votes
Putting them both to delta shouldn't matter, as you say one works already I take it you've enable touches in the init method.

Could you post your touch methods please? Not only you do you need to enable touch you should probably make sure you're using

```
-(void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;
-(void)ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event;
-(void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event;

```

Instead of cctouch. I think the problem may lie with how you handle the code in the above methods, if you edit your question with that code, then people maybe able to help you a little more.

Update:

I see you're using sneaky joystick. I think that this maybe outdated now, as it was last updated around 2010. Take a look at this repository its a lot cleaner and easier to implement, there will be no need for really long if statements as you can move your sprite using three joystick delegates:

```
-(void)joystickControlBegan;
-(void)joystickControlMoved;
-(void)joystickControlEnded;

```

https://github.com/zaldzbugz/zJoystick

EDIT:

Have you set multitouch available on EAGLView?

After you've initialized EAGLView add:

```
view.multipleTouchEnabled = YES;

```

---
Tags: cocos2d, input, joystick
---


title: Dynamic quadrees

text:
# Question
Title: Dynamic quadrees
Recently I started writing a Quadtree for creature culling in Opendungeons game.

Thing is these are moving points and the bounding hierarchy will quickly get lost if the quadtree is not rebuild very often.

I have several variants, first is to upgrade the leaf position every time creature move is requested. Note that I would need collision detection, so this might be necessary anyway.

Second would be making leafs large enough that the creatures would sure stay inside its bounding box (due to its speed limit). The partition of a plane in quadtree is always fixed (modulo the hierarchical unions of some parts). For creatures close to the center of the plane, there would be no way to do this except to keep it inside one big leaf. Besides, this brakes the invariant that each point can be put into any small area as desired. So on the second thought could I use several quadrees? Each would have its "coordinate axis XY" shifted?

Before I start playing with this maybe some other space diving structure would suit me better. Unfortunately, the wiki does not compare their execution time.

# Answer
> 2 votes
Without knowing the details of your game, I'd say: Keep It Simple. Updating the quadtree whenever something moves is a perfectly acceptable solution. I mention in my answer to a similar question that the simplest way to update the quadtree is to remove the item, then re-add it, but this can cause unnecessary overhead. The way I've done it in the past is like this:

```
If the object is still inside the same quad
    if the object fits into a child quad
        Add to child
Else
    move the object to the parent(s) until it fits, and optionally going back down into children

```

It also sounds like you're using points to represent your creatures. If your creatures actually take up space (WxH \> 1x1), I would recommend using the creature's bounding rectangle in the quadtree. This will allow you to do more meaningful lookups like collision detection and view culling.

---
Tags: 2d, tree, quadtree, space-partitioning
---


# Question
Title: How to structure game states in an entity/component-based system
I'm making a game designed with the entity-component paradigm that uses systems to communicate between components as explained here. I've reached the point in my development that I need to add game states (such as paused, playing, level start, round start, game over, etc.), but I'm not sure how to do it with my framework. I've looked at this code example on game states which everyone seems to reference, but I don't think it fits with my framework. It seems to have each state handling its own drawing and updating. My framework has a SystemManager that handles all the updating using systems. For example, here's my RenderingSystem class:

```
public class RenderingSystem extends GameSystem {

    private GameView gameView_;

    /**
     * Constructor
     * Creates a new RenderingSystem.
     * @param gameManager The game manager. Used to get the game components.
     */
    public RenderingSystem(GameManager gameManager) {
        super(gameManager);
    }

    /**
     * Method: registerGameView
     * Registers gameView into the RenderingSystem.
     * @param gameView The game view registered.
     */
    public void registerGameView(GameView gameView) {
        gameView_ = gameView;
    }

    /**
     * Method: triggerRender
     * Adds a repaint call to the event queue for the dirty rectangle.
     */
    public void triggerRender() {
        Rectangle dirtyRect = new Rectangle();

        for (GameObject object : getRenderableObjects()) {
            GraphicsComponent graphicsComponent =
                    object.getComponent(GraphicsComponent.class);
            dirtyRect.add(graphicsComponent.getDirtyRect());
        }

        gameView_.repaint(dirtyRect);
    }

    /**
     * Method: renderGameView
     * Renders the game objects onto the game view.
     * @param g The graphics object that draws the game objects.
     */
    public void renderGameView(Graphics g) {
        for (GameObject object : getRenderableObjects()) {
            GraphicsComponent graphicsComponent =
                    object.getComponent(GraphicsComponent.class);
            if (!graphicsComponent.isVisible()) continue;

            GraphicsComponent.Shape shape = graphicsComponent.getShape();
            BoundsComponent boundsComponent =
                    object.getComponent(BoundsComponent.class);
            Rectangle bounds = boundsComponent.getBounds();

            g.setColor(graphicsComponent.getColor());

            if (shape == GraphicsComponent.Shape.RECTANGULAR) {
                g.fill3DRect(bounds.x, bounds.y, bounds.width, bounds.height,
                        true);
            } else if (shape == GraphicsComponent.Shape.CIRCULAR) {
                g.fillOval(bounds.x, bounds.y, bounds.width, bounds.height);
            }
        }
    }

    /**
     * Method: getRenderableObjects
     * @return The renderable game objects.
     */
    private HashSet<GameObject> getRenderableObjects() {
        return gameManager.getGameObjectManager().getRelevantObjects(
                getClass());
    }

}

```

Also all the updating in my game is event-driven. I don't have a loop like theirs that simply updates everything at the same time.

I like my framework because it makes it easy to add new GameObjects, but doesn't have the problems some component-based designs encounter when communicating between components. I would hate to chuck it just to get pause to work. Is there a way I can add game states to my game without removing the entity-component design? Does the game state example actually fit my framework, and I'm just missing something?

**EDIT:** I might not have explained my framework well enough. My components are just data. If I was coding in C++, they'd probably be structs. Here's an example of one:

```
public class BoundsComponent implements GameComponent {

    /**
     * The position of the game object.
     */
    private Point pos_;

    /**
     * The size of the game object.
     */
    private Dimension size_;

    /**
     * Constructor
     * Creates a new BoundsComponent for a game object with initial position
     * initialPos and initial size initialSize. The position and size combine
     * to make up the bounds.
     * @param initialPos The initial position of the game object.
     * @param initialSize The initial size of the game object.
     */
    public BoundsComponent(Point initialPos, Dimension initialSize) {
        pos_ = initialPos;
        size_ = initialSize;
    }

    /**
     * Method: getBounds
     * @return The bounds of the game object.
     */
    public Rectangle getBounds() {
        return new Rectangle(pos_, size_);
    }

    /**
     * Method: setPos
     * Sets the position of the game object to newPos.
     * @param newPos The value to which the position of the game object is
     * set.
     */
    public void setPos(Point newPos) {
        pos_ = newPos;
    }

}

```

My components do not communicate with each other. Systems handle inter-component communication. My systems also do not communicate with each other. They have separate functionality and can easily be kept separate. The MovementSystem doesn't need to know what the RenderingSystem is rendering to move the game objects correctly; it just need to set the right values on the components, so that when the RenderingSystem renders the game objects, it has accurate data.

The game state could not be a system, because it needs to interact with the systems rather than the components. It's not setting data; it's determining which functions need to be called.

A GameStateComponent wouldn't make sense because all the game objects share one game state. Components are what make up objects and each one is different for each different object. For example, the game objects cannot have the same bounds. They can have overlapping bounds, but if they share a BoundsComponent, they're really the same object. Hopefully, this explanation makes my framework less confusing.

# Answer
> 4 votes
*I'll admit that I didn't read the link you posted. After your edit, and reading the link provided, my position has changed. The below reflects this.*

---

I don't know that you need to worry about game states in the traditional sense. Considering your approach to development, each system is so specific that they, in effect, *are* the game's state management.

In an entity system, the components are just data, right? So is a state. In its simplest form, it's just a flag. If you build your states into components, and allow your systems to consume those components' data and react to the states (flags) within them, you will be building your state management into each system itself.

It seems management systems such as the AppHub example do not apply very well to your development paradigm. Creating a super-system that encapsulates other systems seems to defeat the purpose of separating logic from data.

This might help you to understand what I mean about not having to explicitly handle game states:

http://paulgestwicki.blogspot.com/2012/03/components-and-systems-of-morgans-raid.html

# Answer
> 0 votes
State is a value that applies to an object. Game state, as the name suggests, would be the state of a 'Game' object. That Game object - or more likely, a specific component on it - would track the current state and create or destroy whatever objects are necessary to facilitate the current state. Since your components are just data you will need a new System to handle this, even though there may only ever be one instance of its associated component.

It's hard to comment on how you would implement pausing when it's not clear how you implement updating. The process that emits update events could elect not to do so, if the game object says the game is paused. How the game object communicates to the updating process is down to you; perhaps your `getRelevantObjects` call should allow the updater to find the Game object, or vice versa.

---
Tags: architecture, component-based, entity-system, state
---


# Question
Title: How to utilize miniMax algorithm in Checkers game
I am sorry...as there are too many articles about it.But I can't simple get this.

I am confused in the implementation of AI. I have generated all possible moves of computer's type pieces. Now I can't decide the flow. Whether I need to start a loop for the possible moves of each piece and assign score to it.... or something else is to be done.

Kindly tell me the proper flow/algorithm for this. Thanks

**UPDATE:**

MiniMax code

Now I coded the algorithm but not getting correct moves. Please help me find out the logical error.

# Answer
One useful thing to understand about minimax for a game like Checkers is that it's traditionally viewed (to first approximation) as *symmetric* \- this means that both players can share the same evaluation function, but simply with the signs flipped, or put another way that it's a zero-sum game: if you evaluate the position as being 4/10ths of a checker in your favor, you know that your opponent's evaluation will be -4/10ths of a checker. This means that you can use the *same* loop structure for both sides and simply multiply by a 'sign flip', rather than having to have different control structures for min and max (or switching within the loop). In simplest form, the minimax can be done as a classic recursive function, with a termination once you've reached your maximum depth:

```
float EvaluatePositionRecursive(int depth, Board curBoard, float signFactor)
{
  if ( depth >= MAX_DEPTH )
    return EvaluatePositionStatic(curBoard);
  MoveList moves = GenerateMoveList(curBoard);
  float posValue = -FLT_MAX;
  for (move in moves) do {
    Board newBoard = MakeMove(curBoard, move);
    float newValue = signFactor*EvaluatePositionRecursive(depth+1, newBoard, -signFactor);
    if ( newValue > posValue ) posValue = newValue;
  }
  return signFactor*posValue;
}

[...]

  val = EvaluatePositionRecursive(0, thisBoard, 1.0f);

```

This code has the property/requirement that the value returned from the EvaluatePosition functions will always be in terms of one side's evaluation - that is, a positive value of EvaluatePositionRecursive will always be better for (e.g.) black; this is why it (re-)multiplies by signFactor before returning its value.

Note that there's a *lot* that this (pseudo)code doesn't do: it doesn't do any alpha-beta pruning, it doesn't use transposition tables to cut down on re-evaluating the same position, and it doesn't do any sort of quiescence search or similar adaptive-depth techniques to avoid misevaluating positions where a forced-capture is on the horizon of your search. What's more, for practical considerations you might not want to use explicit recursion for the minimax, and instead maintain a stack yourself, and there are plenty of other object-management optimizations that you would want to make for a practical implementation of the algorithm (rather than a quick-and-dirty one). Still, this code should show the core of the algorithm: to evaluate a position, evaluate all of the subpositions from the current side's point of view, pick the 'best', and return that value.
> 7 votes

---
Tags: game-design, algorithm, ai
---


# Question
Title: Scrolling background stops after awhile?
Can anyone tell me where my maths is wrong please, it stops scrolling after awhile.

```
if (background.position.y < background2.position.y)
{
    background.position = ccp(background.contentSize.width / 2, background.position.y - 50 * delta);
    background2.position = ccp(background.contentSize.width / 2, background.position.y + background.contentSize.height);
}
else
{
    background.position = ccp(background2.contentSize.width / 2, background2.position.y - 50 * delta);
    background.position = ccp(background2.contentSize.width / 2, background2.position.y + background.contentSize.height);
}

//reset
if (background.position.y <-background.contentSize.height / 2)
{
    background.position = ccp(background.contentSize.width / 2 ,background2.position.y + background2.contentSize.height);
}
else if (background2.position.y < -background2.contentSize.height / 2)
{
    background2.position = ccp(background2.contentSize.width / 2, background.position.y + background.contentSize.height);
}

```

# Answer
Looks like you you have duplicated the background position twice in the else part. I've inserted the 2 below

```
else
{
    background.position = ccp(background2.contentSize.width / 2, background2.position.y - 50 * delta);
    background.position = ccp(background2.contentSize.width / 2, background2.position.y + background.contentSize.height);
}

```

Added: After the else statement you have background.position = .... in twice.

The first one needs to be background2.position
> 3 votes

---
Tags: parallax-scrolling
---


title: Physics from other games

text:
# Question
Title: Physics from other games
I'm making a platform engine with XNA Game Studio, and I've solved almost everything about colliding stuff. But now, I'm searching for good physics for the player, I'm trying to emulate characters from other games like Mario from Super Mario World, or MegaMan X... do you know a website or something, where the physics from that games are revealed? I remember seen a page with something like that.

Or what's the process you think is the best to emulate physics from other games? Just trial and error?

Thank you.

# Answer
> 2 votes
**Empirical testing.** The physics are revealed to you when you play the game, you just need to collect numbers for what you're seeing. For each game you want to emulate you need to collect:

* Pixel to meter ratio
* Gravity applied (can be tested by allowing the character to fall, you need to measure the change in velocity over time, I suggest video recording and frame by frame playback)
* Maximum jump height
* Maximum sprint speed
* Any number of other effects applied to the character (air drag, stamina constraints, time dilatation, etc.)

With all that information you can re-create the physics for a particular character. Sounds like a lot of work, but that's because it is. Good luck!

# Answer
> 0 votes
There is no way you can directly use another game's physics, unless they give a public API for that (for example: Super Smash Bros Brawl's Havok and Mirror's Edge's PhysX are free to use).

What you can do is try to reproduce its effects. In this case... well, it's a matter of trying. Check your numbers, test your algorithm, see if it's working.

I think older games didn't have a accelerated gravity, for example. The character was either going up of falling.

What I can suggest to you is start from some library as Box2D and go for trial-and-error on the numbers until you get some satisfactory result. The other option is make your own simple physics engine (which I recommend).

---
Tags: xna, physics, platform
---


# Question
Title: Physics engine that can handle multiple attractors?
I'm putting together a game that will be played mostly with three dimensional gravity.

By that I mean multiple planets/stars/moons behaving realistically, and path plotting and path prediction in the gravity field.

I have looked at a variety of physics engines, such as Bullet, tokamak or Newton, but none of them seem to be suitable, as I'd essentially have to re-write the gravity engine in their framework.

**Do you know of a physics engine that is capable of dealing with multiple bodies all attracted to one another?**

I don't need scenegraph management, or rendering, just core physics. (collision detection would be a bonus, as would rigid body dynamics).

---

My background is in physics, so I would be able to write an engine that uses Verlet integration or RK4 (or even Euler integration, if I had to) but I'd much rather adapt an off the shelf solution.

**\[edit\]:** There are some great resources for physics simulation of n-body problems online, and on stackoverflow

# Answer
I don't think that you are going to be able to use a conventional timeslice physics engine because of the three body problem is not going to allow for stable orbits.

You might be able to yank the physics engine out of Stellarium or some other astronomy package.

However, I think the best course of action is to simply bake in your planet's paths and pull them out of a table. Unless your player can actually affect the trajectory of planets by his actions there is no point doing a full simulation.
> 2 votes

# Answer
Is there any platform limitation? Because PhysX, from nVidia, has exactly what you are looking for, and more.
> 1 votes

---
Tags: physics, algorithm, physics-engine
---


# Question
Title: How are realistic 3D faces created and animated in video games?
I'm interested in being able to create realistic faces and facial expressions for the 3D characters of a game I'm working on. Think something similar to the dialog scenes in games like Mass Effect.

Unfortunately I'm not sure where to begin. I'm sure the faces/animations are created through 3D Modeling software, but otherwise I am lost.

Do facial animations use the same "bones" that normal body animation uses?

Is there any preferred 3D software for realistic faces and animations? Is there a preferred format to export these faces and animations in?

# Answer
> 5 votes
CobaltHex is correct, but I want to expand on his answer.

Most games using facial animation use something called morph targets. NVIDIA has a great implementation available on their website.

However, I would say *all* AAA-titles use motion-captured (mocap) actors for cutscenes. They are expensive to do, but cheaper than having an army of artists create facial animations by hand. Mocap also has the advantage of looking a lot more life-life, depending on the amount of control points on the actor's face.

If, however, you do not work for an AAA-studio and you want some simple facial animation for your characters, look into morph targets. Create a bunch of facial expression (one for each consonant, for instance) and blend them dynamically, based on the lines of dialog.

# Answer
> 4 votes
Since most of the answers so far have been focused on animation, I'd like to add as a sidenote that the shading model and materials used to render the face can also have a large impact on its realism.

In particular, realistic skin rendering is usually implemented using a subsurface scattering shader, otherwise it tends to look artificial. Reflectance is also important, as skin is slightly glossy and reflects a certain amount of light. Eyes and hair rendering are also important, and both subjects can get extremely complex when pursuing realism.

If possible, use a game engine that already supports these rendering techniques!

I'll just leave a few resources on these subjects below, for those that are interested, taken either from the Cryengine 3 documentation (amazing stuff), or from the free GPU Gems books.

**Skin**

> Skin's main look is the result of subsurface scattering (light bouncing inside the surface, exiting in a different location than where it entered). Without subsurface scattering skin appears hard like concrete. It's the most important visual cue for the look of skin

**Eyes**

> Eyes are very complex not only in shading but also in composition, therefore their shading/look cannot be achieved via regular shading methods.

**Hair**

# Answer
> 3 votes
Well faces are generally scanned in and then mapped to heads for 'realistic faces' and then for their facial expressions, they can either be mocapped or done by hand (which is not as pretty but cheaper). However, both take a fair amount of time and mocap costs a lot of money. Facial animations i think generally use more precise vertex based animation but you could probably rig the lips to bones if you don't care about being super accurate. I think there are some professional packages for face modeling, try googling around for your favorite 3d editor. Also, game engines sometimes have their own facial modeling software, for example, face poser in source games.

# Answer
> 3 votes
Facial expressions and mouth movements usually use a facial animation middleware of some sort. FaceFX is one (Mass Effect used it), and incidentally I used to work in the very same building as some of the guys from OC3 Entertainment, who put it out. I believe in many if not most cases these middlewares do processing on the voice file to generate most of the mouth animations to sync up, perhaps with cleanup by a human afterward. The expressions are most likely scripted, and perhaps blended with the mouth animations at render time (to avoid storing a million distinct animations to disk). I'm sure you can learn more by going on the FaceFX website.

If you want to get similar results yourself, you're probably in for an uphill climb. It's typically not something you do on your own if you have a large amount of animating to do (As Bioware did with the ME games). However, if you're closer to Call of Duty or some such where you have only a few minutes of dialogue which needs very realistic movements, hand animating might be cheaper or give a better result. Not sure.

# Answer
> 1 votes
There are tools these days for producing facial animations based on a few basic emotions and phonemes for spoken words. By blending from one to the next (eg. using morph targets as knight666 has said) you can create the appearance of fairly realistic conversation. (Sadly I'm a programmer rather than an artist so I forget the name of the plugin that I saw that does this.)

I doubt most games are using motion-captured faces except perhaps for very important scenes and extreme close-ups. Mocap is expensive and time-consuming to do and capturing every line of speech is likely to be impossible. Certainly you can see that most games just attempt morph the face based on the audio. It may be the case that a studio performs motion capture to collect the initial phonemic and emotion shapes to the face, but these are common across most cultures and therefore it makes more sense just to use pre-captured ones in a standard tool.

---
Tags: 3d, animation
---


# Question
Title: How can I go about learning to write a shader
So here's the background:

I'm writing a game, just for my own amusement and education really. I've already come to the conclusion that XNA was the way to go for graphics, I've bought a couple of books, I've gotten basic game graphics going, and that's great.

Now I'm starting to get a little in-depth and I'm starting to need to do stuff not covered in my (beginner) books. In particular, I need to display a sprite using a mask. Actually, what I need to do is display a generic sprite with a different color for each player. After banging around on the web, it seems the way to go is to have a color texture (one for each player) which I display using the mask, then display the generic part of the sprite. This has to be done dynamically, i.e. at runtime because there are too many sprites to keep in memory if I try to generate all the permutations at startup.

So, I need to use a shader. Fine. I've downloaded a sample shader program, and managed to hit it with a hammer until it does something close enough to what I want so that I know I'm on the right track. And here, we come to my problem... I have no friggin' clue what I'm doing. While there are a lot of samples and such about shaders, no one ever actually explains what's going on. For instance, I can't find any real docs on Tex2D. I feel like the guys in Zoolander poking at the computer. So, my question (yes, I have a question) -- where is a good URL or what is a good book to take me from dumskie to reasonably competent to write a basic shader?

# Answer
> 1 votes
If you want to learn about XNA shaders, this resource might help you out:

http://forums.create.msdn.com/forums/t/27849.aspx

However, there may be an easier way to do what you described. The SpriteBatch.Draw method takes in a Color parameter which can be used to tint the color of your sprite's Texture2D. If you pass Color.White, there will be no tinting. If you pass Color.Blue, your sprite will be tinted blue.

Keeping this in mind, if you need multiple sprites rendered with different colors depending on the player, you could assign a color to each player, and when rendering the player's sprite, tint it with the player's color. Something like this:

```
SpriteBatch.Draw( Player.Texture,   // a Texture2D object depicting the player
                  Player.Location,  // where the Texture should be drawn
                  Player.Color );   // the color the tint the player's sprite

```

If you use a texture that looks like this:

All the white parts would be tinted blue, while black would be left alone. The various shades of gray would be tinted a darker blue.

---
Tags: xna-4.0
---


# Question
Title: What is a good bytes per second sent/received rate?
I am working with XNA networking, on the XBOX.

I was wondering what is a safe number to stay under in the bytes sent and received when it comes to the xbox. Obviously various factors will effect the number, and you want as little packet data as possible to keep things smooth, but what is a good number for that?

(Using : networksession.bytespersecondsent and networksession.bytespersecondreceived to measure the number.)

# Answer
8 kilobytes per second is the number I have seen tossed around on the AppHub forums. There is a short description of how headers and voice affect this number on Shawn Hargreaves blog.
> 1 votes

---
Tags: xna, networking, xna-4.0, xbox
---


# Question
Title: Is it possible to construct a cube with fewer than 24 vertices
I have a cube-based world like Minecraft and I'm wondering if there's a way to construct a cube with fewer than 24 vertices so I can reduce memory usage.

It doesn't seem possible to me for 2 reasons: the normals wouldn't come out right and per-face textures wouldn't work.

Is this the case or am I wrong? Maybe there's some fancy new DX11 tech that can help?

Edit: Just to clarify, I have 2 requirements: I need surface normals for each cube face in order to do proper lighting and I need a way to address a different index in a texture array for each cube face

# Answer
If you only need per-face normals, and if your texcoords for a face are strictly 0/0, 0/1, 1/0, 1/1 (or similar to suit your layout) then you can construct a cube with 8 verts and either 30 (strip with restart) or 36 (list) indexes. Fetch the normals and texcoords using a constant array lookup based on SV\_VertexID in your vertex shader.

Doing this means that you don't even need to include texcoords or normals in your vertex buffer, which will give you even more of a memory saving.

Going further, you could still go all the way to 24 verts per cube but also use instancing. Each cube would be a fixed-size in your vertex buffer (1x1x1) and you'd have a scaling factor and position (assuming your cubes don't rotate, a matrix if they do) as per-instance data. In the non-rotating case you've a once-off cost of 24 verts, but then each cube just needs 6 floats to fully specify. In the rotating case you're looking at 16 floats, but even that is a substantial saving (you're more likely to bottleneck CPU-side on matrix transforms in this case - for the non-rotating case constructing a matrix on the fly in your vertex shader - even if it's done per-vertex, is so stupidly fast that you don't even need to worry about it).

For per-face textures, just use a texture array. You need to ensure that each such texture in the array is the same size, of course, and you'll still need to break your current batch if the array itself needs to change, but otherwise it'll do the job just fine. Add a third texcoord to your vertex definition which defines the array slice to use for each face.

You don't need a GS with this, and it should run faster than using one as having the geometry shader stage enabled will impose extra overhead of it's own.

I've benchmark code in my engine that just draws a bunch of cubes using this method, and I can easily chew through over 300,000 cubes while still clearing 60fps, on a relatively low-end GPU, and without doing anything else to optimize the process. Admittedly I'm neither lighting nor texturing them, but I do have alpha blending enabled, backface culling disabled, and overall it balances against my "not doing anything else to optimize" part, so it should give you a reasonable idea of the kind of ballpark you can hit with this method.
> 9 votes

# Answer
I think the main optimization you can make, is based on the fact that *not every cube will actually need all 24 vertices*. In fact, the only cubes that need 24 vertices are the ones that are floating in midair, which is probably a rare occurrence.

In general, *only generate quads for the faces that are in contact with air*. This means that if two cubes are touching each other, you don't need to generate any vertices for the face where they're touching.

The image below demonstrates this concept, but in 2D for easier comprehension. In the image there are 11 occupied blocks (represented by the filled gray circles), which would normally require 4 x 11 = 44 edges to represent (4 because it's a square, not a cube). But as you can see, you only really need to draw the edges when they're in contact with an empty square, which in this case, is only 8 edges.

If such a simple example in 2D managed to reduce 44 edges to 8 edges, imagine the gains in a large 3D world...

This is the approach described in **this article**, which I recommend you to read, despite being aimed at OpenGL. The concepts should be pretty universal though.

You could also probably use a **geometry shader** to generate the vertices on the fly on the GPU, eliminating the need to store them in memory, but I don't have experience with that, nor do I know how well it would perform for a large world.
> 15 votes

---
Tags: directx, directx11
---


# Question
Title: DX11 - Weird shader behavior with and without branching
I have found problem in my shader code, which I dont´t know how to solve.

I want to rewrite this code without "ifs"

```
tmp = evaluate and result is 0 or 1 (nothing else)
if (tmp == 1) val = X1;
if (tmp == 0) val = X2;

```

I rewite it this way, but this piece of code doesn ´t word correctly

```
tmp = evaluate and result is 0 or 1 (nothing else)
val = tmp * X1
val = !tmp * X2

```

However if I change it to:

```
tmp = evaluate and result is 0 or 1 (nothing else)
val = tmp * X1
if (!tmp) val = !tmp * X2

```

It works fine... but it is useless because of "if", which need to be eliminated

I honestly don´t understand it Posted Image . I tried compilation with NO and FULL optimalization, result is same

# Answer
> 4 votes
Your problem is: `!1 == -2`, not `!1 == 0`.

Try this instead:

```
val = tmp * X1;
val += (1 - tmp) * X2;

```

This works because:

```
1 * x = x

(1 - 1) * x =
   0    * x = 0

-----------

0 * x = 0

(1 - 0) * x =
   1    * x = x

```

As suggested by Nathan, to make the code more compact you can use `lerp`. The equation for `lerp` is `(a * (1 - c)) + (b * c)` which is identical to the equation you see above. Thus the code would become:

```
val = lerp(X2, X1, tmp);

```

# Answer
> 3 votes
I'd advise to just write it with regular branching in your shader code. The D3D shader compiler is *extremely* good at taking code like this and converting it to a non-branching equivalent in bytecode, and can also detect cases (they're rare but they do happen) where a branching solution is actually faster than a non-branching one. You definitely shouldn't assume that just because your HLSL code uses branching it means that the generated shader will also branch - have a look at the asm version of your shader in PIX and you may be in for an eye-opener - they can often be quite different.

It will also be much more maintainable going forward than if you do anything tricksy to avoid branches in HLSL code.

---
Tags: hlsl, directx11, behavior
---


title: What happened to .fx files in D3D11?

text:
# Question
Title: What happened to .fx files in D3D11?
It seems they *completely* ruined .fx file loading / parsing in D3D11.

In D3D9, loading an *entire* effect file was D3DXCreateEffectFromFile( .. ), and you got a `ID3DXEffect9`, which had great methods like `SetTechnique` and `BeginPass`, making it easy to load and execute a shader with multiple techniques.

Is this completely manual now in D3D11? The highest level functionality I can find is loading a SINGLE shader from an FX file using `D3DX11CompileFromFile`.

Does anyone know if there's an easier way to load FX files and choose a technique? With the level of functionality provided in D3D11 now, it seems like you're better off just writing .hlsl files and forgetting about the whole idea of Techniques.

# Answer
> 10 votes
The effect functionality was refactored. It's fundamentally the same set of operations, you just have more control over them -- similar to how the D3D10+ interface redesign does mostly the same stuff as the 9 API, but affords you a more direct model of the hardware or driver to work with. The cost of this change to you is more verbosity in your code; more steps you have to take (often with more parameters) to reach a similar result.

D3D11 no longer ships binaries for the Effect API; it was moved to separate library which is provided as source (in the SDK sample directory) and you must compile it yourself. This was done to help divorce the versioning of the effect API from the versioning of the D3D API itself, which is tied to the Windows SDK). It also lets interested parties optimize and customize the API for their needs, as appropriate.

The HLSL compiler is still part of the core API (d3dcompiler\_XX.dll) and can be used to turn .fx or HLSL source into compiled bytecode. That in-memory bytecode can, in turn, be used to produce an effect from the Effects11 API.

# Answer
> 1 votes
I found the ID3D10Effect interface, which does it.

Not at all easy to find, and the D3D10/11 sample packages seem to avoid using it!!

# Answer
> 1 votes
It's very much worth noting that using .fx files may cause much more harm than good in D3D10+ - which is possibly at least part of the reason why they seem to be moving to deprecation city.

In particular you need to be highly careful about how you manage constant buffer updates. .fx files hide this from you, and make it so easy to severely impact on your performance. You most definitely do need to arrange your cbuffers as if you weren't using .fx files at all, and at that point a rather large part of the reason for using Effects has gone away.

---
Tags: shaders, directx11
---


# Question
Title: How to move an object along a circumference of another object?
I am so out of math that it hurts, but for some of you this should be a piece of cake. I want to move an object around another along its ages or circumference on a simple circular path. At the moment my game algorithm knows how to move and position a sprite just at the edge of an obstacle and now it waits for the next point to move depending on various conditions.

So the mathematical problem here is how to get **(aX, aY)** and **(bX, bY)** positions, when I know the Centre **(cX, cY),** the object position **(oX, oY)** and the distance required to move **(d)**

# Answer
> 8 votes
(**CAVEAT:** I'm using two approximations here: the first takes d as an arc length, and the second takes it as an orthogonal length. Both of these approximations should be good for relatively small values of d, but they don't fulfill the precise question as clarified in comments.)

The math on this, fortunately, is relatively straightforward. First of all, we can find the relative vector from our center position to our current position:

```
deltaX = oX-cX;
deltaY = oY-cY;

```

And once we have this relative vector, then we can know the radius of the circle we're working on by finding the length of it:

```
radius = sqrt(deltaX*deltaX+deltaY*deltaY);

```

What's more, from our relative vector we can find the precise angle that the line from cX to oX is at:

```
curTheta = atan2(deltaX, deltaY);

```

Now things get a little bit trickier. First of all, understand that the circumference of a circle — that is, the 'arc length' of an arc with an angular measure of 2π — is 2πr. In general, the arc length of an arc with an angular measure of θ along a circle of radius r is just θr. If we were to use the d in your diagram as the arc length, and since we know the radius, we can find the change in theta to get us to the new position by just dividing out:

```
deltaTheta = d/radius; // treats d as a distance along the arc

```

For the case where d needs to be a linear distance, things are a little more complicated, but fortunately not much. There, d is one side of an isoceles triangle whose other two sides are the radius of the circle (from cX/cY to oX/oY and aX/aY respectively), and bisecting this isoceles triangle gives us two right triangles, each of which has d/2 as one side and radius as the hypotenuse; this means that the sine of half our angle is (d/2)/radius, and so the full angle is just twice this:

```
deltaTheta = 2*asin(d/(2*radius)); // treats d as a linear distance

```

Notice how if you took the asin out of this formula, and cancelled the 2s, this would be the same as the last formula; this is the same as saying that sin(x) is approximately x for small values of x, which is a useful approximation to know.

Now we can find the new angle by just adding or subtracting:

```
newTheta = curTheta+deltaTheta; // This will take you to aX, aY. For bX/bY, use curTheta-deltaTheta

```

Once we have the new angle, then we can use some basic trig to find our updated relative vector:

```
newDeltaX = radius*cos(newTheta);
newDeltaY = radius*sin(newTheta);

```

and from our center position and our relative vector we can (finally) find the target point:

```
aX = cX+newDeltaX;
aY = cY+newDeltaY;

```

Now, with all this, there are some *big* caveats to be aware of. For one, you'll notice that this math is mostly floating-point, and in fact it almost has to be; trying to use this method to update in a loop and rounding back to integer values at every step can do everything from making your circle not close (either spiralling inward or outward every time you go around the loop) to not getting it started in the first place! (If your d is too small, then you might discover that the rounded versions of aX/aY or bX/bY are exactly where your start position oX/oY was.) For another, this is very expensive, especially for what it's trying to do; in general, if you know your character is going to be moving in a circular arc, you should plan out the whole arc in advance and *not* tick it from frame to frame like this, since many of the most expensive calculations here can be front-loaded to cut down on costs. Another good way to trim back the costs, if you really want to update incrementally like this, is to not use trig in the first place; if d is small and you don't need it to be *exact* but just very close, then you can do a 'trick' by adding a vector of length d to oX/oY, orthogonal to the vector towards your center (note that a vector orthogonal to (dX, dY) is given by (-dY, dX) ), and then shrink it down to the right length. I won't explain this code quite so step-by-step, but hopefully it'll make sense given what you've seen so far. Note that we 'shrink down' the new delta vector implicitly in the last step, where we add it to our center to get the updated point:

```
deltaX = oX-cX; deltaY = oY-cY;
radius = sqrt(deltaX*deltaX+deltaY*deltaY);
orthoX = -deltaY*d/radius;
orthoY = deltaX*d/radius;
newDeltaX = deltaX+orthoX; newDeltaY = deltaY+orthoY;
newLength = sqrt(newDeltaX*newDeltaX+newDeltaY*newDeltaY);
aX = cX+newDeltaX*radius/newLength; aY = cY+newDeltaY*radius/newLength;

```

# Answer
> 9 votes
Form a triangle using the two sides you already have (one side is from 'c' to 'o', the other from 'o' to 'a'), and the third side goes from 'a' to 'c'. You don't know where 'a' is just yet, just imagine there is a point there for now. You'll need trigonometry to calculate the angle of the angle that is opposite to the side 'd'. You have the length of the sides c\<-\>o and c\<-\>a, because they're both the radius of the circle.

Now that you have the length of the three sides of this triangle you cannot yet see, you can determine the angle that is opposite to the 'd' side of the triangle. Here's the SSS (side-side-side) formula if you need: http://www.teacherschoice.com.au/maths\_library/trigonometry/solve\_trig\_sss.htm

Using the SSS formula you have the angle (which we'll call 'j') that is opposite to side 'd'. So, now we can calculate (aX, aY).

```
// This is the angle from 'c' to 'o'
float angle = Math.atan2(oY - cY, oX - cX)

// Add the angle we calculated earlier.
angle += j;

Vector2 a = new Vector2( radius * Math.cos(angle), radius * Math.sin(angle) );

```

Make sure the angles you're calculating are always in radians.

If you need to calculate the radius of the circle, you can use vector subtraction, subtract point 'c' from point 'o', then get the length of the resulting vector.

```
float lengthSquared = ( inVect.x * inVect.x
                      + inVect.y * inVect.y
                      + inVect.z * inVect.z );

float radius = Math.sqrt(lengthSquared);

```

Something like this should do, I believe. I do not know Java, so I guessed on the exact syntax.

Here's the image given by user `Byte56` to illustrate what this triangle might look like:

# Answer
> 3 votes
To make obj2 rotate around obj1 maybe try:

```
float angle = 0; //init angle

//call in an update
obj2.x = (obj1.x -= r*cos(angle));
obj2.y = (obj1.y += r*sin(angle));
angle-=0.5;

```

---
Tags: java, mathematics
---


# Question
Title: Does use of simple shaders improve performace/battery life?
I'm making OpenGL game for Android. Till now i've used only fixed function pipeline, but i'm rendering simple things.

Fixed function pipeline includes a lot of stuff i don't need. So i'm thinking about implementing shaders in my game to simplify OpenGL pipeline if it can make better performance.

Better performance = better battery life, unless fps is limited by software limit, not hardware power.

# Answer
There isn't actually a question here except in the subject, but improved performance and improved battery life could be totally different things. Also, improved compared to what? Compared to the fixed function pipeline? Compared to complex shaders?

Simple shaders should give a higher framerate (assuming your framerate is limited by gpu throughput rather than screen refresh rate) when compared to complex shaders, which you might consider better performance. That won't necessarily improve battery life though, you could still be using 100% gpu/cpu power, but you will have a higher frame rate because there is less to do each frame.

Compared to the fixed function pipeline... who knows? Many hardware vendors nowadays implement the fixed function pipeline in terms of shaders, so you're just comparing simple vs complex shaders again.
> 4 votes

# Answer
I don't have up-to-date figures of smartphone power consumption, but I think that CPU and GPU should be somewhere at the same level. Correct me, if I am wrong.

Generally, trying to optimize parts of your code that rely on performance is always a good thing, not only because you save battery life, but also because you can reach devices with less powerful hardware. I also always encourage people to use OpenGL ES 2.0 / OpenGL 3.0 for games, because the power of shaders is, like you said, to cut down the effort to a minimum and to provide much more flexibility.

But, based on the assumption you are rendering *some* 2D sprites, I'd say that the GPU is mostly in an idle state. That means that the CPU will possibly have more impact on battery life than the GPU, so you should not expect too positive results here. I'd recommend you try to improve your algorithms running on the CPU before you optimize the ones on the GPU, but I'd use shaders too for the sake of flexibility. At least if you can ignore the devices out there without support for OpenGL ES 2.0 (again, I don't have figures ^^).
> 1 votes

---
Tags: opengl, android, shaders, performance
---


# Question
Title: Transform 3D vectors between coordinate systems
I've got 6 points in 3D space: A,B,C,D,E,F, that represent 4 vectors. AB is perpendicular to AC and DE is perpendicular to DF.

I need to find a transformation matrix M, that transforms AB to DE and AC to DF. In other words: M⋅AB=DE, M⋅AC=DF

If no scaling was involved, this could be solved with a simple rotation matrix. But since the ratios |AB|/|DE|, |AC|/|DF| might be different, I'm not sure how to proceed.

# Answer
The result is given in the M matrix. Note that Trans\_DEF and Rot\_DEF are constructed in the same manner as ABC.
> 2 votes

---
Tags: 3d, mathematics, matrix, vector, transformation
---


# Question
Title: What techniques can I use to render very large numbers of objects more efficiently in OpenGL?
You can think of my application as drawing a very large ball-and-stick diagram (or graph). At times, this graph can get very large, where the number of elements even outnumbers the pixels on the screen. Currently I am simply passing all of my textures (as `GL_POINTS`) and lines to the graphics card using VBO's.

When the number of elements outnumbers the number of pixels, is this the most efficient way to do this? Or should I do some calculations on the CPU side before handing everything over to the GPU?

If it matters, I do use `GL_DEPTH_TEST` and `GL_ALPHA_TEST`. I do some alpha blending, but probably not enough to make a huge performance difference.

My scene can be static at times, but the user has control over a typical arc-ball camera and can pan, rotate, or zoom. It is during these operations that performance degradation is noticeable.

# Answer
If there is more than one element per pixel on the screen there is no point in rendering all of them. Try to find a way to cull elements that either aren't visible anymore or don't contribute to the final image.

It's also a good idea to consider using a dynamic level of detail reduction on your model to reduce the load.
> 1 votes

# Answer
Unfortunately to find the fastest solution you might need to implement and test several, because it can vary depending on your graphics card manufacturer, driver version, etc.

For example, rendering as points & lines might actually be slower than rendering them as textured quads (pairs of triangles) - triangle rendering is the most common use case, so manufacturers focus optimisations on this path. Some drivers may just implement points and lines as triangles anyway, so you may not notice any difference if you make the change.

If you have many similar sprites you should also look at instancing techniques, which will reduce the amount of data you need to send to the GPU and may improve performance.
> 1 votes

---
Tags: opengl, 3d, jogl, hardware-acceleration, scalability
---


# Question
Title: Complex shading using one single (small) texture
Recently I stumbled upon a demo reel in UDK about how one can attain beautiful results using just one (rather tiny) texture that's being sent to the shader pipeline. The famous link is this one.

Basically, the author states that they've used just one texture and give a snapshot of the technique here.

I see that every RGBA channel contains different grayscale information.. and that info could be used to inside a shader to obtain a colour blended output. The problem is that the reel displays a fairly complex scene. To top that, the author even makes use of a normal map. How did they manage to fit a normal map in an already cluttered texture? It makes sense to have a half-space normal map by using only RG from an RGB texture, but what about the rest of the information? Since it was proven to be possible, could someone please explain how it was done (the big picture, not the dirty details!)!?

Here's the texture being used. Click to see in full size.

# Answer
> 4 votes
Well to begin, it's actually two textures, but basically what he's done is cram lots of individual maps into separate channels of the textures. So in those two textures, you have specular, normal, masks, albedo etc.

Unfortunately, in order to extract all the separate bits of information and use them properly this means he has to have quite complex shaders and possibly multiple UV sets on his geometry as well. The trade-off here is saving texture memory (of which we have lots) by using more GPU cycles (of which we have relatively few) to do complex material processing.

If you want to know the specifics of that particular scene, you can download the package from the page you linked and view it in UDK yourself.

edit: In addition there is a lot of very fancy baked lighting in that scene, so really there are a lot more than two textures. :)

---
Tags: shaders, rendering, udk, normal-mapping
---


# Question
Title: What is the best practice for future proofing my editor enumerations?
I would like to know the best practices for handling the following situation:

---

Suppose the project you are working on is split in to two sub-projects; the game engine library, and the editor GUI.

You have the method `bool Method( const MethodParams &params )` that will be called during game-level initialization; it is a method that belongs to the game engine library. The parameters of this method, passed as a reference to the structure `MethodParams`, can be decided via the editor in the level design phase. The `MethodParams` structure is as follows:

```
enum Enum1
{
    E1_VAL1,
    E1_VAL2,
};

enum Enum2
{
    E2_VAL1,
    E2_VAL2,
    E2_VAL3,
};

struct MethodParams
{
    float   value;
    Enum1   e1;
    Enum2   e2;
    // some other members
}

```

The editor should present a dialog that will allow the user to set the values in the `MethodParams` structure. The editor needs to present a text box for `value`, and let the user set the fields `e1` and `e2` using a combo box, for example. Every enum option should be mapped to a string, so the user can make an informed selection (normally, the names used in the enum would be more meaningful). One could even want to map every enum to a more informative string (so, for example, `E1_VAL1` could map to "Image union algorithm", and `E1_VAL2` could map to "Image intersection algorithm").

---

The editor will include all the relevant game engine library files (.h, etc.), but this mapping is not automatic, and I am confused by how to handle it in a way that where code change will be minimal, if I add further enum options in the future.

# Answer
The absolute easiest way to map this is to use an `std::map`. That's what it's for.

```
std::map<Enum1, std::string> map_enum1;

map_enum1.insert<std::pair<Enum1, std::string>>(E1_VAL1, "Image union algorithm");
map_enum1.insert<std::pair<Enum1, std::string>>(E1_VAL2, "Image intersection algorithm");

```

This has several advantages:

* Uses tried-and-tested tools.
* No hacky precompiler trickery to map the values at compile-time.
* Able to change values at run-time.
* Easy to translate to other languages.

Adding new enums will continue to be difficult though, because it requires a recompile. However, if you step down from `enum`s to simple `int`'s, you can always add new values without requiring recompilation.
> 1 votes

# Answer
If you just need to map enumerations to strings, you can use the following question on SO: How to easily map c++ enums to strings.
> 0 votes

---
Tags: editors
---


title: Logic behind greedy Spider game?

text:
# Question
Title: Logic behind greedy Spider game?
What will be the best algorithm or logic that can be used for game like greedy spiders. As far as I can think it is based on A\* algorithm ? Where the shortest path has to be a search between the spider and the flies.

Is there any better logic to implement that game?

I would like to learn the concept behind it. How they will be managing nodes and edges concept?

# Answer
> 2 votes
It really depends on the accuracy you want the pathfinding to have and the amount of nodes you have. I would recommend the A\* search algorithm, and then you can experiment with the heuristics. By example the Manhattan heuristic is really fast but doesn't got the accuracy like the Euclidean heuristic.

For a game like Greedy Spiders I would go for an accurate heuristic since there aren't much nodes, the Euclidean heuristic will suffice here.

This is a really good tutorial I once used for a game which explains a lot about it: A\* Pathfinding for Beginners

---
Tags: game-design, game-mechanics
---


title: Looping 3D environment in shmups

text:
# Question
Title: Looping 3D environment in shmups
So I was watching Ikaruga:
http://www.youtube.com/watch?v=Aj23K8Ri68E

And then raystorm:
http://www.youtube.com/watch?v=TQ4V0G5ykAg

After looking at their 3D backgrounds for a little bit, it appears that they use a lot of repeated segments.

How would one start with the development with such systems? Would there be editors that can be used (or at least help) with creating the environments? Perhaps a 3D map with splines describing the path of the ship, as well as events on the splines?

# Answer
I can't say I've personally implemented this, but here is my suggestion: With a sufficiently large background "world" and a sufficiently narrow field of view on that world, you could implement a "inner ring" background world similar to the world in the Halo games. Put the background camera inside the ring, pointing "outward" towards your background world, and move it along the inner orbit. Render this to texture, and use that as your background.

Of course you could also put the ship, enemies, etc inside the ring itself to avoid the render to texture process, but assuming an Ikaruga-like game, having to account for the curve of the ring (i.e. a third dimension, and at least one constantly changing axis) might cost more than the RTT, and would certainly be harder from a coding standpoint.

With clever maths, you can probably turn a "ribbon" world of known dimensions into a ring to make level editing easier. Any moving items in the background will need extra attention though.

Note the caveats, though. Without a large enough ring or with too wide a camera FOV, things will probably look weird, although perhaps you could account for that with some other method, like fish-eye.

EDIT: Thinking about the particular case of repeated segments that eventually change, I think maybe two half-rings would be a better solution. A repeatable half-ring would be able to connect with itself seamlessly, and when you're done repeating, swap out the next half-ring for the next segment. This is a little more complicated than a single, giant ribbon that gets turned into a ring, but if you need to repeat on-the-fly instead of a pre-specified number of times, it's a potential solution.

EDIT 2: For situations where you need to be able to move and repeat on both axes, consider a similar approach but with a torus. Could be much more challenging to construct.
> 1 votes

---
Tags: 3d, graphics, level-design, shoot-em-up
---


# Question
Title: Can frequent state changes decrease rendering performance?
Can frequent texture and shader binding decrease rendering performance?

"Frequent" binding example:

```
for object
   for material in object
      render part of object using that material

```

"Low count" binding example:

```
for material
   for object in material
      render part of object using that material

```

I'm planning to use an octree later and with this "low count" method of rendering it can drastically increase memory consumption. So is it good idea?

# Answer
> 7 votes
State changes are, relatively speaking, an expensive operation and texture and shader state changes in particular can have the largest overhead. So yes, if you structure your render loop in such a way as to constantly change the shader and textures bound to the pipeline, that will have a negative impact on render performance. That impact may not be *noticeable* depending on the overall number of binds, however, it's still good to be aware of it.

Your second example will result in fewer state changes than your first example, and it is generally the way you want to go, especially for solid objects: essentially, sort what your going to render by shader and texture so that you can bind the appropriate combination and then render several objects using those resources. Transparent objects also need additional depth-based sorting or require you to use an order-independent transparency technique such as depth peeling.

An octree can be a useful optimization but it is intended as a means to cull out entire objects that are not visible or otherwise contributing to the scene. You should only have *one* octree, maintaining an octree-per-material is wasteful and doesn't provide you any real benefits.

# Answer
> 2 votes
Are your examples the right way round? If you sort by material, you bind once per material. If you sort by object, you might end up binding \[numObjects * numMaterials\] times.

To avoid those subloops, forget about the objects. You're not really rendering objects, you're rendering parts, so when you instantiate objects, add their parts to a render list. Then your two example loops would look like this:

```
for material
    bind material & render all parts

```

and

```
for part
    bind material & render

```

You would probably have more parts than materials, so you can see the first option would result in fewer bind calls.

---
Tags: opengl, graphics, rendering, performance
---


# Question
Title: Handling various frame layouts in Android
I am trying create a Contra or the old TMNT game (but a simple one) like game for Android. For the game I decided to divide my main screen in three parts - upper for stats, mid for the game and lower for controls.

My main.xml is

```
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<FrameLayout
    android:id="@+id/upper_bar"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_weight="1" >
</FrameLayout>

<FrameLayout
    android:id="@+id/fl"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_weight="0.5" >
</FrameLayout>

 <FrameLayout
    android:id="@+id/low_bar"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_weight="0.85" >
</FrameLayout>

</LinearLayout>

```

So I have created the `gameview` and `gameloopthread` classes for the mid surface(which is pretty standard). My problem is I don't know how to draw in the upper and lower frame layouts. Should I make new classes for view and thread for each layout, should I do all this in the `gameview` class itself or is there any better way to implement this?

# Answer
> 1 votes
You can now add the GUI and/or game components to the frames you've created. This can be done either from Java code or in your XML layout (recommended). For an example of both ways, please see this tutorial: http://mobile.tutsplus.com/tutorials/android/android-sdk\_frame-layout/

---
Tags: android, level-design, game-loop
---


title: Tic-Tac-Toe game AI

text:
# Question
Title: Tic-Tac-Toe game AI
I'm looking into creating a simple tic tac toe/noughts and crosses game in Actionscript3 and am trying to understand the ideas behind the AI used in a game like this.

I've seen some simplistic examples online but from what I've read a game tree or something like minimax is the best way to go about this. Can anyone help explain or reference any good examples of this?

I've seen that there is a library called as3ds - data structures for game developers which has a number of classes that might help tie this together?

Any info/examples or help is much appreciated.

# Answer
> 5 votes
If you implement the rules from Tic-tac-toe Wiki you can create the perfect AI that always wins, then you can decrease the difficulty by making the AI do random moves, and the frequency of random moves is the difficulty level. Here are the rules:

1. **Win:** If the player has two in a row, play the third to get three in a row.
2. **Block:** If the \[opponent\] has two in a row, play the third to block them.
3. **Fork:** Create an opportunity where you can win in two ways.
4. **Block opponent's Fork:**
    * Option 1: Create two in a row to force the opponent into defending, as long as it doesn't result in them creating a fork or winning. For example, if "X" has a corner, "O" has the center, and "X" has the opposite corner as well, "O" must not play a corner in order to win. (Playing a corner in this scenario creates a fork for "X" to win.)
    * Option 2: If there is a configuration where the opponent can fork, block that fork.
5. **Center:** Play the center. (If it is the first move of the game, playing on a corner gives "O" more opportunities to make a mistake and may therefore be the better choice; however, it makes no difference between perfect players.)
6. **Opposite corner:** If the opponent is in the corner, play the opposite corner.
7. **Empty corner:** Play in a corner square.
8. **Empty side:** Play in a middle square on any of the 4 sides.

---
Tags: ai, actionscript-3, data-structure, tree
---


title: Random map generation

text:
# Question
Title: Random map generation
I'm starting/started a 2D tilemap RPG game in Java and I want to implement random map generation. I have a list of different tiles, (dirt/sand/stone/grass/gravel etc) along with water tiles and path tiles, the problem I have is that I have no idea where to start on generating a map randomly.

It would need to have terrain sections (Like a part of it will be sand, part dirt, etc.) Similar to how Minecraft is where you have different biomes and they seamlessly transform into each other. Lastly I would also need to add random paths into this as well going in different directions all over the map.

I'm not asking anyone to write me all the code or anything, just piont me into the right direction please.

tl;dr - Generate a tile map with biomes, paths and make sure the biomes seamlessly go into each other.

# Answer
Among the many other related questions on the site, there's an often linked article for map generation: Polygonal Map Generation for Games you can glean some good strategies from that article, but it can't really be used as is.

While not a tutorial, there's an article on how Dwarf fortress world maps are generated. Basically you generate multiple layers of noise, for height, moisture, temperature, salinity. Then you'd use something like this:

Or this

to generate biomes based on the layers of noise you produced before. Typically this gives a fairly smooth transition between biomes and the transitions are logical. I also modify the moisture and temperature maps based on elevation. This naturally generates a "timber line" and produces rocky mountains with snowy caps.

I'm using this strategy my game and it produces maps like this very quickly:

Additionally, you can see me scroll through a few more maps at the beginning of this video.

And here's some more to get you started:

How can I create a random "world" in a tile engine?

How can I identify feature regions in a procedurally generated world?

How do I create tileable solid noise for map generation?
> 68 votes

# Answer
While the other answers here are really good for generating the kinds of static landscapes that would work for this specific need. There are other methods that people coming across this question might be looking for if they want to create landscapes that change over time or appear much more realistic you can follow this technique.

Unlike the other answers you begin this with an entirely empty map. Start with what you would consider to be sea level. Use Perlin Noise to add very slight variation, if you have 256 possible elevations, don't vary more than 3-5 in either direction. This builds the first few billion years of your landscape without having to actually run a simulation for that long.

### Plate Tectonics

Split the map along straight or curved lines to create plates, the more detailed the shapes of the plates the more interesting your landscape with be. Keep them large. Give each plate a direction, speed. Over a given timeframe move the plates in step-wise fashion around the map, dragging all tiles above them with them.

When two plates cross, make a choice of which will go over and which will go under, this choice can be random. Tiles on plates designated under are instantly reduced in height by 5 steps. Once a plate has been designated over or under, all future interactions with plates will follow these rules:

* Where a designated plate crosses an undesignated plate, the undesignated plate becomes the opposite type. (So UD plates becomes under when crossing an over.)
* Where an over plate sits over an under plate, all those tiles move up 0-1 elevation steps, and the tiles follow the path of the over plate.
* Where an over plate crosses an over plate, all those tiles move up 1-2 steps, and the tiles in the cross over region no-longer drift.
* Where an under plate crosses an under plate, any tiles in the area with elevation greater than the 66% mark for both plates in the cross over region move up 1-3 steps (as if by volcanic activity, this will produce islands over enough time) and tiles in this area stop drifting.

All plates that cross slow by 20% of their current speed each step. For added realism, add a random -10% to 10% change in direction of movement each step.

After performing the desired number of steps. Probably 5-10 are plenty. Any tiles where no plates are resident, should be dropped to the lowest existing level.

### Large or Small?

This map can be used as is, or be expanded to create a much larger map by breaking it into 4X4 tile(cell) chunks and expanding those sections based on their individual elevations. Treat each cell's elevation as a point, and create a smooth gradation in the larger map between those points. So, if the larger map is 40X40 instead of 4X4, and point (0,0) was 10 and point (0,1) was 1, the tiles on the larger map between them would be 10,9,8,7,6,5,4,3,2,1 in height. Further Perlin Noise can be added to de-smooth the slopes. Over all this scaling technique is similar to the Diamond Square algorithm.

### Water

To simulate rivers and lakes, oceans and water tables. I prefer to use cellular automata.

Heights become floats or expanded int ranges to allow for finer grained tracking. Water cells have saturation values, say in the range of 1-256. The maps should start evenly. You'll need to play with the numbers for your individual map sizes, however generally you will follow rules something like this:

* If a neighbor cell is more saturated, increase saturation and gain height.
* If a neighbor cell is less saturated, decrease saturation and lose height.

Make this check for every neighboring cell. Run through a sufficient number of steps. If you want, you can add temperature to this simulation by changing the amount of lost/gained saturation by that temperature. You also can change it based on elevation. Natural lakes and rivers should form. Some will fall into the ocean. (The ocean won't probably fill by any metric, but you'll designate anything under sea-level to be water filled at the end anyway.)

You can keep the temperature and saturation data to use, like in the other answers, to create biomes. They should be MUCH more accurate and interesting. With snowy biomes at the poles and hot ones in the middle (if you uses a smooth graduated list of temperatures.)

You can also simulate wind, and therefore temperature changes based on the elevations. You can step back and forth between running the temperature simulation and the water simulation if you want. However I haven't built anything using temperature changes so I won't comment on how to do that.

### Evolving Landscapes

If you keep the simulations for land, water, and heat around and dramatically reduce their effects and also stop the plates from moving, you can continue to change all of these metrics over time. I wouldn't run the calculations very often, but you can get a world map that responds to changes this way.

### Conclusion

While these kinds of techniques are way more involved, they produce a lot more realistic and evolving effects. Take it for what it is worth?
> 27 votes

# Answer
You can use Perlin Noise for the generation of the terrain, here is how the biomes in Minecraft work. As you can see he uses a heatmap in combination with a rainmap to create the biomes.
> 13 votes

---
Tags: tiles, maps, tilemap
---


# Question
Title: How do I create tileable solid noise for map generation?
Hey guys, I'm trying to figure out how to generate tileable fractals in code (for game maps, *but that's irrelevant*) I've been trying to modify the Solid Noise plug-in shipped with GIMP (with my extremely limited understanding of how the code works) but I cant get mine to work correctly.

My modified code so far (Java)

GIMP's solid noise module that I'm basing my code off of (C)

Here is what I'm trying to achieve but This is what I'm getting

So if anybody can see what I've done wrong, or has a suggestion how I could go about doing it differently, I'd greatly appreciate it. **Thanks in advance.** And if I'm asking way to much or if just a huge failure at life, I apologize.

# Answer
> 3 votes
It seems as though my original pastebin expired somehow, so I have no way to compare my nonworking code, but on my current game I went through and translated the GIMP code into java again and it seems to work fine now.

If anyone plans on using this code, I'd recommend modifying the constructor to modify the setting parameters (detail and size) so you can make it work how you'd like. **EDIT:** I realized my original question was about making it tileable, so remember to set tilable to true!

Code: http://pastebin.com/KsfZ99Xa

Example:

# Answer
> 4 votes
I don't follow your code exactly, but here is a simplified description of the algorithm that will roughly achieve the effect (based on the image you posted).

The following explanation is not the super optimised version, but is one that's conceptually clear (I hope). Once you have got it running, you can optimise it (quite drastically, in fact).

1. Generate n layers of uniform random noise (just random greyscale pixels).
2. Now sample each of these by sampling every, 1, 2, 4, 8, ... 2^(n-1) pixels, and interpolating the intermediate pixels. Each layer is smoother than the previous one.
3. Now scale of these with a factor of 1, 2, 4, 8, etc. Each layer is darker than the previous one.
4. Add all these together.
5. Normalise by dividing each pixel with (1 + 2 + 4 + 8 + ... 2^(n-1)).

The difficult step is the sampling and interpolation step. Suppose we are in the layer skipping sampling every m-th pixel. Here is the basic idea for m \> 1 (if m is 1, we use the image as is):

```
for each pixel x and y
   left_sample_coord = m *(x / m) //(integer division, automatically truncated)
   right_sample_coord = (left_sample_point + m) % image_width
   top_sample_point = m*(y / m)
   bottom_sample_coord = (top_sample_point + m) % image_height

   horizontal_weight = (x - left_sample_point) / (m - 1)
   vertical_weight = (y - top_sample_point) / (m - 1)

   sample_top_left = image(left_sample_coord, top_sample_point)
   //and the same for the other four corners

   //now combine the top two points
   top_interpolate = sample_top_left * horizontal_weight + sample_top_right * (1-horizontal_weight)

  //now combine the bottom two points
  bottom_interpolate = sample_bottom_left * horizontal_weight + sample_bottom_right * (1-horizontal_weight)

  //and combine these two last obtained values

  smooth_noise(x, y) = top_interpolate * vertical_weight  + bottom_interpolate * (1 - vertical_weight)

```

A few tips:

* The result of the algorithm above might seem a bit washed out. You can reduce this effect by using the same layer of noise for all layers, or be contrast enhancing the image afterwards.
* The algorithm above uses linear interpolation, but cosine interpolation (do a search) gives much better results.
* Make it possible to look at your layers separately during all parts of the algorithm. This will help you flush out bugs quickly.

# Answer
> 2 votes
Just skimmed through the Java and C versions and noticed a slight difference in the way you use the noise function. Here's yours:

```
int val = Math.abs((int) Math.floor(255.0 * noise(((double)col/(double)width), ((double)row/(double)height))));

```

C code:

```
val = (guchar) floor (255.0 * noise ((col - xoffset) / width,

                                           (row - yoffset) / height));

```

Why have you chosen not to subtract the offset? (col - xoffset) and (row - yoffset)

Just wondering. I don't have time to do a full analysis of the code.

Hope this helps.

# Answer
> 2 votes
I don't know if it could help but the following trick worked a treat for me :

http://www.gamedev.net/blog/33/entry-2138456-seamless-noise/

This fellow is using a 4d noise function and simply provide xy values of two circles as xyzw values for the 4d noise. The result is looping perfect.

Here is the idea(simplified) for a 1000\*1000 picture :

```
for(i = 0;i < 1000; i++){

  for(j = 0; j < 1000; j++){

    nx = cos((i/1000) * 2 * PI);
    ny = cos((j/1000) * 2 * PI);
    nz = sin((i/1000) * 2 * PI);
    nw = sin((j/1000) * 2 * PI);

    looped_noise = noise_4D( nx, ny, nz, nw, octaves, persistence, lacunarity, blah...);
    noise_buffer[(i*1000)+j] = looped_noise;

  }
}

```

# Answer
> 1 votes
I recommend you use the diamond-square algorithm, also known as plasma fractal or random mid-point displacement fractal. Using this algorithm it is very easy to constrain the edges to have the same values. When you generate a value for an edge, copy it to the corresponding edge on the other side. This yields a perfectly tiling map.

# Answer
> 0 votes
There's a great article about noise generation here. It's not Perlin noise as the article claims (it's pink noise actually), but it is still incredibly useful to understand how noise images are generated.

So, to actually answer your question: to make a tileable noise image, you just need to keep "tileability" throughout the generation. That is, when noise is smoothed, you smooth it as if it is repeated infinitely in all directions - tiled.

# Answer
> 0 votes
From the screenshot, my guess is that only the "big" layers are being generated, which is why the noise appears too regular and lacks detail.

This may sound stupid, but did you try increasing the "detail" variable (line 16)? In your code, it's set to 1, which means the algorithm will only generate two layers of detail before stopping. Try increasing it to something like 8.

# Answer
> 0 votes
You should also take a look at Simplex Noise, which was developed by Ken Perlin to fix some of Perlin noise's shortcomings.

I've been working on an implementation of Simplex Noise for a C++ game. It supports multi-octave 1D/2D/3D/4D noise. Right now, the only built-in texture is marble, but you could easily add more:

(http://code.google.com/p/battlestar-tux/source/browse/trunk/src/lib/procedural/)

---
Tags: java, procedural-generation, maps
---


# Question
Title: How many BasicEffects do you have in a Game? What is the best way to render multiple objects/shapes at once?
I'm trying to understand 3D rendering and it seems that everytime you render a new object (A 3D Cube or something) you need to have a new BasicEffect for each Box you render unless you want the exact same texture?

...so if I have over a hundred boxes with each different textures, I need at least as many BasicEffects? Will that not be "too much" for the CPU/GPU in the end or result in lagging? Is there any good way to render multiple objects (cubes or other shapes) at the same time?

I've tried changing the BasicEffect.Texture with each cube drawn, but it resulting in changing the first Cube's texture too.

Any suggestions would be really appreciated, I'm really new to 3D in XNA so I'm trying to wrap my head around the best methods for example render a Map with objects (of shapes).

Example: I create some Cube3D (by providing location and size) and it creates a list of Vertices.

I have to render it this way:

```
            gameEffect.TextureEnabled = true;
            gameEffect.Texture = gameTexture;
            gameEffect.EnableDefaultLighting();

            foreach (EffectPass pass in gameEffect.CurrentTechnique.Passes)
            {
                pass.Apply();
                foreach (Cube3D cube in gameCubes)
                {
                    cube.Render(GraphicsDevice);
                }
            }

```

...thereby having the same Texture on each Cube. Are there any other ways?

# Answer
> 2 votes
For drawing multiple objects in XNA you can have one or multiple effects.

If you have only one you must set all parameters (texture, light color, light direction...) for each object before drawing it. All common values for all objects (view and projection matrix for example) can be set once at the beginning of drawing.

If you have multiple effects. For each object exactly one instance. You must set only that parameters that are changing (view and projection matrix, etc..) each frame.

Definitely is not good to create new `BasicEffect` or load custom effects in Draw method. Create it in Load method.

There are also another method how to draw models in XNA. BasicEffect is actually a shader and you can write your own. Something more about shaders and how to use them you can read here: http://digitalerr0r.wordpress.com/tutorials/

# Answer
> 1 votes
Unless i am missing something i think that XNA approach is flawed. You shoud have something like this:

```
class Model
{
   public List<Material> Materials;
   public ModelMesh Mesh;
}

```

and Model should be created in game by new Model(Content.Load()) and not cached (or loaded by some alternative from xml). Materials should be collection of parameters that you pass to effects inside Mesh.MeshParts\[\].Effects (like texture)

# Answer
> 1 votes
It's actually simpler to embed the texture reference with the model itself. That way, when you load your model via the content pipeline, the texture is loaded with it automatically. This thread has some information on that:

http://www.dreamincode.net/forums/topic/227811-how-do-i-put-a-texture-to-a-3d-model/

Then when you draw your scene, you can loop through your models something like:

```
protected override void Draw(GameTime gameTime)
{
    graphics.GraphicsDevice.Clear(Color.CornflowerBlue);

    // Copy any parent transforms.
    Matrix[] transforms = new Matrix[myModel.Bones.Count];
    myModel.CopyAbsoluteBoneTransformsTo(transforms);

    // Draw the model. A model can have multiple meshes, so loop.
    foreach (ModelMesh mesh in myModel.Meshes)
    {
        // This is where the mesh orientation is set, as well
        // as our camera and projection.
        foreach (BasicEffect effect in mesh.Effects)
        {
            effect.EnableDefaultLighting();
            effect.World = transforms[mesh.ParentBone.Index] *
                Matrix.CreateRotationY(modelRotation)
                * Matrix.CreateTranslation(modelPosition);
            effect.View = Matrix.CreateLookAt(cameraPosition,
                Vector3.Zero, Vector3.Up);
            effect.Projection = Matrix.CreatePerspectiveFieldOfView(
                MathHelper.ToRadians(45.0f), aspectRatio,
                1.0f, 10000.0f);
        }
        // Draw the mesh, using the effects set above.
        mesh.Draw();
    }
    base.Draw(gameTime);
}

```

This tutorial might help you make sense of loading and drawing 3D models with XNA:

http://msdn.microsoft.com/en-us/library/bb197293(v=xnagamestudio.31).aspx

---

If you are going to render your own primitives in code, I don't know any other way to apply a texture than a `BasicEffect`. If Cube3D is your own class, I'd suggest adding a `BasicEffect` and a `Texture2D` to the class. That way, you can supply the texture to the Cube3D constructor and it setup the `BasicEffect` for you. If it's not, you could extend it.

```
class Cube3D {

    ...
    public BasicEffect Effect { get; set; }
    public Texture2D Texture {
        get { return Effect.Texture; }
        set { Effect.Texture = value; }
    }
    ...

    public Cube3D( Texture2D t ) {
        ...
        this.Texture = t;
    }

    ...
}

```

---

It seems as though you can also use the `Effect` class to apply a texture as well:

http://www.riemers.net/eng/Tutorials/XNA/Csharp/Series2/Textures.php

---
Tags: xna, c#, rendering, performance, graphic-effects
---