# Question
Title: Bullet physics debug drawing not working
## Background

I am following on from this question, which isn't answered yet. Basically I have a cube and a UVSphere in my scene, with UVSphere on the top of the cube without touching the cube. Both exported from blender.

When I run the app The UVSphere does circle around the cube for 3 or 4 times and jump out of the scene. What I actually expect was the sphere to fall on top of the cube.

## What this question about

From the comment to the linked question, I got to know about bullet debug drawing, which helps in debugging by drawing outline of physics bodies which are normally invisible. I did some research on that and came up with the code given below. From whatever I have read, below code should work, but it doesn't.

## My Code

My bullet initialization code.

```
-(void) initializeScene {
    /*Setup physics world*/
    _physicsWorld = [[CC3PhysicsWorld alloc] init];
    [_physicsWorld setGravity:0 y:-9.8 z:0];

    /*Setting up debug draw*/
    MyDebugDraw *draw   =   new MyDebugDraw;
    draw->setDebugMode(draw->getDebugMode()
                      | btIDebugDraw::DBG_DrawWireframe );
    _physicsWorld._discreteDynamicsWorld->setDebugDrawer(draw);

    /*Setup camera and lamb*/
    …………..

    //This simpleCube.pod contains the cube
    [self addContentFromPODFile: @"simpleCube.pod"];
    //This file contains sphere
    [self addContentFromPODFile: @"SimpleSphere.pod"];

    [self createGLBuffers];

    CC3MeshNode* cubeNode   = (CC3MeshNode*)[self getNodeNamed:@"Cube"];
    CC3MeshNode* sphereNode = (CC3MeshNode*)[self getNodeNamed:@"Sphere"];
    // both cubeNode and sphereNode are not nil from this point

    float *cVertexData  = (float*)((CC3VertexArrayMesh*)cubeNode.mesh)
                               .vertexLocations.vertices;
    int cVertexCount    = ((CC3VertexArrayMesh*)cubeNode.mesh)
                               .vertexLocations.vertexCount;

    btTriangleMesh* cTriangleMesh  = new btTriangleMesh();

    int offset = 0;
    for (int i = 0; i < (cVertexCount / 3); i++)
    {
        unsigned int index1 = offset;
        unsigned int index2 = offset+6;
        unsigned int index3 = offset+12;
        cTriangleMesh->addTriangle(
          btVector3(cVertexData[index1], cVertexData[index1+1], cVertexData[index1+2]),
          btVector3(cVertexData[index2], cVertexData[index2+1], cVertexData[index2+2]),
          btVector3(cVertexData[index3], cVertexData[index3+1], cVertexData[index3+2]));
        offset += 18;
    }

    [self releaseRedundantData];

    /*Create a triangle mesh from the vertices*/
    btBvhTriangleMeshShape* cTriMeshShape
                       = new btBvhTriangleMeshShape(cTriangleMesh,true);
    btCollisionShape *sphereShape = new btSphereShape(1);

    gTriMeshObject =   [_physicsWorld createPhysicsObjectTrimesh:cubeNode
                            shape:cTriMeshShape
                            mass:0
                            restitution:1.0
                            position:cubeNode.location];
    sphereObject   =   [_physicsWorld createPhysicsObject:sphereNode
                            shape:sphereShape
                            mass:1
                            restitution:0.1
                            position:sphereNode.location];
    sphereObject.rigidBody->setDamping(0.1,0.8);

    /*Enable debug drawing*/
    _physicsWorld._discreteDynamicsWorld->debugDrawWorld();
}

```

And My btIDebugDraw implementation (MyDebugDraw.h)

```
//MyDebugDraw.h
class MyDebugDraw: public btIDebugDraw{
    int m_debugMode;

public:

    virtual void drawLine(const btVector3& from,const btVector3& to
              ,const btVector3& color);

    virtual void   drawContactPoint(const btVector3& PointOnB
             ,const btVector3& normalOnB,btScalar distance
              ,int lifeTime,const btVector3& color);

    virtual void   reportErrorWarning(const char* warningString);

    virtual void   draw3dText(const btVector3& location
                             ,const char* textString);

    virtual void   setDebugMode(int debugMode);

    virtual int      getDebugMode() const;
};

void MyDebugDraw::drawLine(const btVector3& from,const btVector3& to
                              ,const btVector3& color){
    LogInfo(@"Works!!");
    glPushMatrix();
    glColor4f(color.getX(), color.getY(), color.getZ(), 1.0);

    const GLfloat line[] = {
        from.getX()*1, from.getY()*1, from.getZ()*1, //point A
        to.getX()*1, to.getY()*1,to.getZ()*1 //point B
    };
    glVertexPointer( 3,
                    GL_FLOAT,
                    0,
                    &line );
    glPointSize( 5.0f );
    glDrawArrays( GL_POINTS, 0, 2 );
    glDrawArrays( GL_LINES, 0, 2 );
    glPopMatrix();
}

void MyDebugDraw::drawContactPoint(const btVector3 &PointOnB
         ,const btVector3 &normalOnB, btScalar distance
         ,int lifeTime, const btVector3 &color){
}

void MyDebugDraw::reportErrorWarning(const char *warningString){
}

void MyDebugDraw::draw3dText(const btVector3 &location
                                , const char *textString){
}

void MyDebugDraw::setDebugMode(int debugMode){
}

int MyDebugDraw::getDebugMode() const{
    return DBG_DrawWireframe;
}

```

## My Problem

The `drawLine` method is getting called. I can see the cube and sphere in place. Sphere again does some circling around the cube before jumping off.

No debug lines are getting drawn.

# Answer
Okay I got it working. For everyone who faces this in the future..

> Note : I use Cocos3D (2D) functions to draw the line. So this is not a generic solution.

This is how I done it.

## 1) Create a RuleSet objective C class

**RuleSet.h**

```
#import "CC3Scene.h"

@interface RuleSet : NSObject{
}
@property(strong, nonatomic) CC3Scene *currentScene;
@property (strong, nonatomic) NSMutableArray *lines;
+(id)sharedRuleSet;
-(void) debugLineFromX:(float)fromX fromY:(float)fromY
      fromZ:(float)fromZ toX:(float)toX toY:(float)toY toZ:(float)toZ;
@end

```

**RuleSet.m**

```
#import "RuleSet.h"
#import "CC3MeshNode.h"

@implementation RuleSet
+(id)sharedRuleSet{
    static RuleSet *sharedRuleSet = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedRuleSet = [[self alloc] init];
    });
    return sharedRuleSet;
}

-(void) debugLineFromX:(float)fromX fromY:(float)fromY fromZ:(float)fromZ
           toX:(float)toX toY:(float)toY toZ:(float)toZ {
    if (!self.lines) {
        self.lines        =   [NSMutableArray array];
    }
    float arr_location[] = {fromX,fromY,fromZ, toX,toY, toZ };
    CC3LineNode* lineNode = [CC3LineNode nodeWithName: @"Line test"];
    [lineNode populateAsLineStripWith: 2
                             vertices: arr_location
                            andRetain: YES];
    lineNode.color = ccRED;

    [self.lines addObject:lineNode];
    [self.currentScene addChild:lineNode];
}
@end

```

## 2) Create a custom btDebugDraw implementation

**MyDebugDraw.h**

```
#include <iostream>
#include "btIDebugDraw.h"
#import "RuleSet.h"

class MyDebugDraw: public btIDebugDraw{
    int m_debugMode;

public:
    virtual void drawLine(const btVector3& from,const btVector3& to
                    ,const btVector3& color);
    virtual void drawContactPoint(const btVector3& PointOnB
                       ,const btVector3& normalOnB,btScalar distance
                       ,int lifeTime,const btVector3& color);
    virtual void reportErrorWarning(const char* warningString);
    virtual void draw3dText(const btVector3& location,const char* textString);
    virtual void setDebugMode(int debugMode);
    virtual int  getDebugMode() const;
};

void MyDebugDraw::drawLine(const btVector3& from,const btVector3& to
                                ,const btVector3& color)
{
    RuleSet *rule = [RuleSet sharedToolSet];
    [rule debugLineFromX:from.x() fromY:from.y() fromZ:from.z()
                    toX:to.x() toY:to.y() toZ:to.z()];
}

void MyDebugDraw::drawContactPoint(const btVector3 &PointOnB
            , const btVector3 &normalOnB, btScalar distance
            , int lifeTime, const btVector3 &color){}

void MyDebugDraw::reportErrorWarning(const char *warningString){}

void MyDebugDraw::draw3dText(const btVector3 &location
                , const char *textString){}

void MyDebugDraw::setDebugMode(int debugMode){}

int MyDebugDraw::getDebugMode() const{
    return DBG_DrawWireframe;
}

```

## 3) During physics world initialization

**YourScene.m**

```
......
#import "RuleSet.h"
#import "MyDebugDraw.h"
.......

-(void) initializeScene {
    RuleSet *rule       =   [RuleSet sharedToolSet];
    rule.currentScene   =   self;

    //Create physics world
    btBroadphaseInterface* broadphase = new btDbvtBroadphase();
    btDefaultCollisionConfiguration* collisionConfiguration
                  = new btDefaultCollisionConfiguration();
    btCollisionDispatcher* dispatcher
           = new btCollisionDispatcher(collisionConfiguration);
    btSequentialImpulseConstraintSolver* solver
           = new btSequentialImpulseConstraintSolver();
    dynamicsWorld = new btDiscreteDynamicsWorld(dispatcher
              ,broadphase,solver,collisionConfiguration);
    dynamicsWorld->setGravity(btVector3(0,-10.0,0));

    /*Create custom debug drawer*/
    MyDebugDraw *draw   =   new MyDebugDraw;
    draw->setDebugMode( draw->getDebugMode()
          | btIDebugDraw::DBG_DrawWireframe );
    dynamicsWorld->setDebugDrawer(draw);

    /*Add rigid bodies and collision objects to physics world*/
    .....
    .....

    /*At the end of initializeScene function
        , after adding physics bodies*/
    dynamicsWorld->debugDrawWorld();
}

```

And credit goes here. This is not my code.
> 2 votes

---
Tags: bullet-physics, debugging, cocos3d
---


# Question
Title: How to bind std::map to Lua with LuaBind
Is this possible in lua to achieve?

```
player.scripts["movement"].properties["stat"] = "stand"
print (player.scripts["movement"].properties["stat"])

```

I've done getter method in c++ with this approach:

```
luabind::object FakeScript::getProp()
{
    luabind::object obj = luabind::newtable(L);

    for(auto i = this->properties.begin(); i != this->properties.end(); i++)
    {
        obj[i->first] = i->second;
    }

    return obj;
}

```

But I'm stuck with setter. The first line in lua code which I'm trying to set value "stand" for key "stat" is not going to work and it keep redirecting me to the getter method. Setter method only works when I drop `["stat"]` from `properties`.

I can do something like this for setter in my script:

```
player.scripts["movement"].properties = {stat = "stand"}

```

But this isn't what I want because I have to go through my real keys in c++ to determine which key is placed in setter argument table value.

This is my map in class:

```
std::map<std::string, std::string> properties;

```

# Answer
One way to do this is to maintain the table entirely in C++. You wouldn't have any actual properties in the Lua table at all; you'd just have a placeholder table with its `__index` and `__newindex` metamethods mapped to C++ functions that get and set properties from the underlying `std::map`. I'm not familiar enough with LuaBind to show you the exact code to make this happen, but it shouldn't be hard to do.
> 1 votes

# Answer
I think Lua can access and create objects on tables with array-like syntax. If it doesnt, Squirrel (which is based on Lua, and have much more OOP sugars) can, here it is: http://squirrel-lang.org/doc/squirrel3.html

Your script would be looking like this:

```
player.scripts["movement"] <- new PlayerClass()
player.scripts["movement"].properties["stat"] = "stand"
print (player.scripts["movement"].properties["stat"])

```
> 1 votes

---
Tags: c++, lua
---


# Question
Title: 2D Destructible Terrain with Box2D / Cocos2D -> Image Tracing
Bear with me as this will be a rather lengthy post. For the last month I have been working on an open source Cocos2D, Box2D Destructible Terrain Engine. I have some questions regarding its implementation.

TLDR-\> When tracing images, how can I account for a divided image where there is a column or row of alpha separating the sprite? How can I leverage a dynamic programming (or something else) type approach to make this algorithm efficient.

Some Context: In the engine, destructible terrain sprites are created with MutableTextures which allow for direct manipulation of pixel values. An alpha value of zero is considered to be destroyed or non existent terrain.

Now in order to use these mutable texture sprites with Box2D, I need an efficient algorithm to trace the image and create a set of vertices which can be used to define the terrain border. From research, there where two ways I could go about this. I could create many, composite polygons (avoid concave angles) to fill the terrain or just trace the border with EdgeShapes. I opted for EdgeShapes.

```
-(void)makePhysicsObject:(b2World *)theWorld {
self.physicsObject = YES;
self->world = theWorld;
[self generatePhysicsPoints];

if (body) {
    world->DestroyBody(self->body);
} // end if

b2BodyDef tDef;

tDef.position.Set(0, 0);
self->body = world->CreateBody(&tDef);
gameObjectType = kGroundTypeDynamic;
self->body->SetUserData((__bridge void *) self);

b2EdgeShape shape;

CCLOG(@"Size of simplified before adding verts is %d", imageBorderPointsSimplified.count);
    for (int i =1; i < imageBorderPointsSimplified.count; i++) {
    NSValue * val = [imageBorderPointsSimplified objectAtIndex:i];
    CGPoint endPt = val.CGPointValue;
    NSValue * val2 = [imageBorderPointsSimplified objectAtIndex:i-1];
    CGPoint startPt = val2.CGPointValue;

    b2Vec2 startVert = b2Vec2(startPt.x/PTM_RATIO, startPt.y/PTM_RATIO);
    b2Vec2 endVert = b2Vec2(endPt.x/PTM_RATIO, endPt.y/PTM_RATIO);
    shape.Set(startVert, endVert);
    self->body->CreateFixture(&shape,0);

    if (i == imageBorderPointsSimplified.count - 1) {
        // Connect the end verts
        val = [imageBorderPointsSimplified objectAtIndex:i];
        endPt = val.CGPointValue;
        val2 = [imageBorderPointsSimplified objectAtIndex:0];
        startPt = val2.CGPointValue;
        b2Vec2 startVert = b2Vec2(startPt.x/PTM_RATIO, startPt.y/PTM_RATIO);
        b2Vec2 endVert = b2Vec2(endPt.x/PTM_RATIO, endPt.y/PTM_RATIO);
        shape.Set(startVert, endVert);
        self->body->CreateFixture(&shape,0);

    } // end inner if
} // end for
} // MakePhysics

```

This turned out to work fairly well and didn't kill the fps. However, what is hurting from a performance and algorithmic perspective, is retracing the image.

The algorithm for tracing the image is posted below where the final array called ImageBorderPointsSimplified contains a set of vertices which can be given to box2d to trace the sprite. On average it contains 15-25 points for a medium sized 800x800 terrain sprite.

```
-(BOOL)isBoundaryPoint:(CGPoint)pt {
BOOL isBoundary = NO; // assumption

// Is trans... so not boundary
if ([self pixelAt:pt].a == 0) {
    return isBoundary;
}

for (int i = -1; i < 2; i++) {
    for (int j = -1; j < 2; j++) {
        if ([self pixelAt:ccp(pt.x + i, pt.y + j)].a == 0) {
            isBoundary = YES;
            return isBoundary;
        }
    }
}
return isBoundary;
} // end isBoundaryPoint

```

isBoundaryPoint traverses pixels around a given pixel to see if there is a pixel with alpha = 0. If a pixel has an alpha of 0, then it must be a boundary pixel.

```
-(void)traceImage {
    // List of visited pixels
    imageBorderPoints = [[NSMutableSet alloc] init];
    // ALL Border points
    imageBorderPointsOrdered = [[NSMutableArray alloc] init];
    // Smoothed with averages
    imageBorderPointsSmoothed = [[NSMutableArray alloc] init];
    // Simplified based on curvature
    imageBorderPointsSimplified = [[NSMutableArray alloc] init];

static int avgCons = 4;
float originX = self.position.x - self.contentSize.width/2;
float originY = self.position.y - self.contentSize.height/2;
float endX = originX + self.contentSize.width;
float endY = originY + self.contentSize.height;
for (int x = originX; x < endX; x++) {
    for (int y = originY; y < endY; y++) {
        if ([self isBoundaryPoint:ccp(x,y)]) {
            CCLOG(@"First boundary point found at %d, %d", x,y);
            [self traverseBoundaryPoints:ccp(x,y)];
            if (imageBorderPointsOrdered.count > 19) {
                // Smooth the points
                for (int i = avgCons; i < imageBorderPointsOrdered.count; i = i + avgCons) {
                    NSMutableArray * tempStore = [[NSMutableArray alloc] init];
                    for (int x = i; x > i - avgCons; x--) {
                        [tempStore addObject:[imageBorderPointsOrdered objectAtIndex:x]];
                    }
                    NSValue * avgVal = [self averageVertices:tempStore];
                    //CCLOG(@"Adding %f, %f to averageArray", avgVal.CGPointValue.x, avgVal.CGPointValue.y);
                    [imageBorderPointsSmoothed addObject:avgVal];
                } // end for to pop avg
                [self simplifyVertices];
            } // end if
            return;
        } // end if
    } // end inner for
} // end outer for
CCLOG(@"MUTTEXTURE :: No boundary points found");
} // end traceImage

-(void)traverseBoundaryPoints:(CGPoint)startPt {

NSValue * startVal = [NSValue valueWithCGPoint:startPt];
[imageBorderPoints addObject:startVal];
NSValue * nextVal = [NSValue valueWithCGPoint:startVal.CGPointValue];
while (true) {

    nextVal = [self findNextBoundaryPixel:nextVal.CGPointValue];
    if (nextVal == nil) {
        CCLOG(@"nextVal is nil... returning");
        return;
    }

    if (CGPointEqualToPoint(startVal.CGPointValue, nextVal.CGPointValue)) {
        CCLOG(@"Start Point equals end point.. Exiting traverseBoundaryPoints");
        return;
    } else {
        [imageBorderPoints addObject:nextVal];
        [imageBorderPointsOrdered addObject:nextVal];
    }

}
}

```

traverseBoundary points (along with findNextBoundaryPixel) navigates itself around the image pixel by pixel. It stores the visited pixels in a set, and uses the set to check if it has visited there before. It will continue traversing until the start point equals the end point or there are no more pixels left to traverse. This algorithm is the issue tbh... It breaks apart when an image is split in two or there is a linear line of pixels. I could use some suggestions here.

```
-(NSValue *)findNextBoundaryPixel:(CGPoint)pt {

for (int i = -1; i < 2; i++) {
    for (int j = -1; j < 2; j++) {
        CGPoint ptToCheck = ccp(pt.x + i, pt.y + j);
        if ([self isBoundaryPoint:ptToCheck]) {
            NSValue * val = [NSValue valueWithCGPoint:ptToCheck];
            if ([imageBorderPoints containsObject:val]) {
                // CCLOG(@"imageBorderPoints already contains the border point");
            } else {
                //CCLOG(@"Next boundary found %f, %f", ptToCheck.x, ptToCheck.y);
                return val;
            } // end inner if
        } else {
            //CCLOG(@"Point is not a boundary point %f, %f", ptToCheck.x, ptToCheck.y);
        }
    }
}

return nil;
}

-(NSValue *)averageVertices:(NSMutableArray *)vertices {

CGPoint averagePt = ccp(0,0);
for (NSValue * val in vertices) {
    CGPoint pt = val.CGPointValue;
    averagePt = ccp(averagePt.x + pt.x, averagePt.y + pt.y);
}
averagePt = ccp(averagePt.x/vertices.count, averagePt.y/vertices.count);
NSValue * valToReturn = [NSValue valueWithCGPoint:averagePt];
return valToReturn;
}

```

findCurvature locates the midpoint between 2 points and compares that midpoint to a point in-between the two outer points. The distance between the midpoint and the middle point gives a measure of curvature. If there is high curvature, more vertices are needed to trace the image accurately. Simplify vertices reduces the amount of points needed to trace the image by looking at the curvature of a set of points. When the total curvature breaks the arbitrary threshhold, it will use the given point for the final trace.

```
-(float)findCurvature:(CGPoint)pt1 pt2:(CGPoint)pt2 pt3:(CGPoint)pt3 {
// If curv is high, then there is high curvature
// If it is low then there is low curvature
CGPoint mid = ccpMidpoint(pt3, pt1);
return ccpDistance(pt2, mid);
} // end findcurvature

-(void)simplifyVertices {
float lim = 0.5;
float curvature = 0;
float curvatureTotal = 0;
for (int i = 2; i < self->imageBorderPointsSmoothed.count; i++) {
    NSValue * v1 = [imageBorderPointsSmoothed objectAtIndex:i];
    CGPoint pt1 = v1.CGPointValue;
    NSValue * v2 = [imageBorderPointsSmoothed objectAtIndex:i-1];
    CGPoint pt2 = v2.CGPointValue;
    NSValue * v3 = [imageBorderPointsSmoothed objectAtIndex:i-2];
    CGPoint pt3 = v3.CGPointValue;

    curvature = [self findCurvature:pt1 pt2:pt2 pt3:pt3];
    curvatureTotal += curvature;

    if (curvatureTotal > lim) {
        curvatureTotal = 0;
        [imageBorderPointsSimplified addObject:[imageBorderPointsSmoothed objectAtIndex:i-2]];
    }
}

}

```

In general this is what is happening: Starting from a corner, it traverses the sprite's texture until it finds a non alpha pixel. It then will 'climb' around all the border pixels caching their location until it reaches the same point again. The array of pixels found are then smoothed (averaged) and reduced based on curvature. However, I am running into problems where if a player destroys the terrain to where it is split in half, only half of the image is traced. I can't think of a way to account for this and am asking for help here.

Also the other issue with my current algorithm, is it will become 'stuck' when there is a straight line of pixels as it won't visit already visited pixels again. When this happens the tracing is incomplete (albeit this is a rare edge case)

Lastly, performance... When a player destroys the terrain, I know exactly which columns of the texture are modified. What I would like to figure out is a way I can avoid retracing the unaffected columns and just retrace the altered columns.

Thanks for reading this long post. Any help would be very welcomed

**EDIT** Here is a video demonstrating the algorithms in action. At the end it of the video it incorrectly draws the edge of the terrain. This is one of the edge cases described above where there is a linear line of pixels. http://www.youtube.com/watch?v=IUsgjYLr6e0&feature=youtu.be

# Answer
I'd probably try to do something like the following:

* Store all your vertices as well as the edges connecting them.
* When an explosion happens, do the following:

+ Remove all vertices within the explosion radius.
    + Remove all edges within the explosion radius.
    + Flag all vertices with removed edges as "dirty".
* After an explosion, iterate over all "dirty" vertices and use them as starting points to find shapes/borders till you return to your starting point or you're able to connect it to an existing open edge nearby.
> 1 votes

---
Tags: box2d, cocos2d-iphone, physics, objective-c
---


title: Great realtime shader tool?

text:
# Question
Title: Great realtime shader tool?
I often develop 2D games. I would like to know if there's a program like EvalDraw out there, that makes it easy to quickly make (for example) a square, out of a black quad, and then write some shader code, and see how that shader code modifies the square in realtime.

That would be really great for my future development processes.

**Edit:** The shader tool must work with HLSL.

# Answer
> 8 votes
Try these online shaders editors:
https://www.shadertoy.com/
https://shaderoo.org/
http://glslsandbox.com/
http://pixelshaders.com/editor/
http://shdr.bkcore.com/

# Answer
> 6 votes
RenderMonkey and FX Composer were both tools like this, although they've been relatively abandoned recently. 3D modelling tools like Max or Maya often usually have shader/effect/material pipelines built in, but they are probably prohibitively expensive.

# Answer
> 0 votes
Insprired by shadertoy and glsl-sandbox, I make a hlsl version of them. https://github.com/vinjn/HlslShaderToy

There is no live coding support for the moment, you can use your favorite editor to write the shader. If the content is changed, HlslShaderToy detects it, and reload the shader automatically. So you can pretend that it's a realtime shader tool.

There is also some fancy features:
\- loads local image as a texture
\- loads internet image as a texture

---
Tags: tools
---


title: Procedural World Generation

text:
# Question
Title: Procedural World Generation
How does Minecraft generate it's texture (ex. which block is grass and which one is stone)?

# Answer
It's a texture atlas. Each block has a particular type. The code then takes the type, the face index (top, side, etc.) and finds an index into a texture atlas (which is basically just the theme file).

The triangles are then generated using the UVs from that atlas. For instance, if grass is at `(128,64)` in a texture sized `(256,256)` then the UV coordinate is `(0.5,0.25)`. This coordinate and the per-tile size `(0.25,0.25)` in that made-up example are used to texture the four corners of that face of the block. The face's vertices are generated relative to the block's location, the UVs are slapped on, normals are output, and the vertices are stuffed into a cached mesh for later rendering.

Similar techniques are used in 2D, both for tiled and non-tiled games, and to some extent in more traditional 3D engines.
> 2 votes

# Answer
The simple answer is : with more perlin noise maps.

First, there are the biome maps. These maps are 2D, and if my memory serves me correct, they represent heat and humidity. Together with the height map, they divide the world in "Biomes"

For instance, areas that are "wet", "low" and "teppid" are swamps,

areas that are "dry", "hot" and "high" are mountains,

areas that are "moist", "hot" and "average" are jungle, etc.

Based on the biomes, minecraft uses a different set of rules for generating its surface world (which trees grow there, etc) and uses a different set of blocks and texture color filter.

Then, there is a 3D noise map built on top of the 2d noise map that determines where the rock starts, and where to spawn ore veins (and of which kind those veins are).

You can read up on an old post Notch made on his blog.

By now, the world generation code of minecraft has changed a lot, and a bunch of it probably no longer applies though.
> 1 votes

---
Tags: textures, minecraft-modding, terrain-rendering
---


# Question
Title: Odd blending result (semi-transparent 2d quad over 3D scene)
I'm working on a GUI library for my game, and I'm having problems with my blending.

I have a 3D scene, which I render with glDrawArrays. In the fragment shader the alpha color is hardcoded 1.0f (gl\_FragColor).

When I render a 2D quad on my screen with 1.0f in the alpha channel, my quad is semi-transparent, while it should be completely opaque.

I render the quad with the basic glBegin(GL\_QUADS) and glColor4f(0.0f, 0.0f, 1.0f, 1.0f).

I enabled blending with the function:

```
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

```

What am I doing wrong? Why is my quad semi-transparent?

Screenshot:

Fragment shader:

```
#version 130
varying vec2 texture_coordinate;
uniform sampler2D texture;

void main()
{
    vec3 textureColor = texture2D(texture, texture_coordinate).rgb;
    gl_FragColor = vec4(textureColor, 1.0f);
}

```

Quad render code:

```
glBegin(GL_QUADS);
        glColor4f(0.0f, 0.0f, 0.7f, 1.0f);
        glVertex2f(position.x, position.y + size.y);
        glVertex2f(position.x + size.x, position.y + size.y);
        glVertex2f(position.x + size.x, position.y);
        glVertex2f(position.x, position.y);
    glEnd();

```

Thanks in advance.

# Answer
> 2 votes
After a long debugging session with Basaa, we discovered that the problem was that texturing was still enabled. We just had to add:

```
glDisable(GL_TEXTURE_2D)

```

---
Tags: opengl, shaders, lwjgl, transparency, alpha
---


title: Where is the XACT documentation?

text:
# Question
Title: Where is the XACT documentation?
All the links here are broken:

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

# Answer
XACT can be found here

Hope it helps
> 6 votes

# Answer
The links are not broken, or are not any longer anyway - they redirect to the *Where is the DirectX SDK?* page which tells us that the XACT Authoring Tool is no longer supported, that's why that part of the documentation is removed.

http://msdn.microsoft.com/en-US/library/ee663275.aspx

> Where is the DirectX SDK?
>
> The Xbox Audio Cross Platform Tool (XACT) is no longer supported for use on Windows.

As AbstractChaos answered, the XACT API reference is still there though but that in turn links to the removed documentation for the tool that is posted in the question. Hence, it's removed.

> For detailed information about how to author audio using the XACT tool, including information about categories, variables, and other advanced features, see **(redirected to discontinued support statement)**.
> 5 votes

# Answer
The wayback machine appears to have preserved a copy of at least some of the documentation:

http://web.archive.org/web/20080514084356/http://msdn.microsoft.com/en-us/library/bb172314.aspx
> 5 votes

# Answer
You can download full MSDN Library for Visual Studio from the Microsoft website. But I think you need the same version of Visual Studio as is the version of the downloadable MSDN to be able to view it. **Here is a link to download page of MSDN Library for Microsoft Visual Studio 2008 SP1**, that should contain the information you are looking for. Unfortunately I don't own the MS Visual Studio 2008, so I can't make sure.
> 1 votes

---
Tags: xna
---


# Question
Title: How do these Direct3D 11 components work together?
I am having a really hard time to understand how the following Direct3D components play together and what they do (or exist for) while creating a scene on the screen.

* render target view
* render target
* viewport
* back buffer target
* back buffer texture (this is `ID3D11Texture2D` which is used as buffer target I guess)
* buffer (front buffer and back buffer)

I am currently reading a book about Direct3D 11 but the explanation does not match my brain model. Can someone explain in detail how it works (is there a diagram of it somewhere)?

# Answer
In the D3D11 parlance

* A buffer is a type of resource that contains data in various formats. Buffers are used to create textures (a buffer of texel data), meshes (buffers of vertex data with corresponding buffers of index data) and so on.
* A view an interpretation of some resource or buffer. Buffers are stored in generalized memory formats to facilitate their use in various stages of the internal pipeline, a view provides your code a way to access resource data in a defined format. It is similar to casting a `void *` to a known complete type.
* A render target is a conceptual thing that refers to the resource that is going to receive the result of all your draw operations; in other words, the canvas upon which you'll be painting.
* The viewport is a representation of where the scene rendering to the back buffer will appear within a window. It's a 2D region where your 3D scene will be projected, essentially. This documentation is for D3D9, but the concept hasn't changed much (and it has a better diagram than the D3D11 documentation).

D3D11 (and 10 before it) tries to follow a much more regimented format with the terminology it uses. Consequently, you can derive the definitions of the other terms from the previous definitions, because they are just combinations of terms. That should also tell you where they fit within the pipeline:

* A render target view is a way to interpret the data of the resource that is your render target. It's typically a view created for a texture resource that is going to hold your completed scene (your back buffer, see below).
* The back buffer is a texture-style buffer where rendering takes place "off screen" before it is conceptually flipped to the front buffer (which is the screen the user sees). This implements double buffering.
* The back buffer target is a render target used to direct operations to that back buffer texture (as opposed to some other render target).

They all fit together in your use of the D3D11 API to create graphics:

1. Early on in your program, you create *buffers* to hold your geometry and index data, textures, and so on. A buffer is also created to act as your *back buffer*, where your scene will be presented.
2. You create *views* of those buffer resources in order to fill them with useful data, or manipulate them in other fashions. You also use those views to bind interpretations of that data to shaders.
3. You create a window where all your rendering will appear to the user, and define a *viewport* within that window where your 3D scene will appear.
4. You issue draw calls to send geometry through the graphics pipeline, where it undergoes transformation and shading and ultimately is rasterized to your *back buffer texture*.
5. That back buffer is conceptually "flipped" to the front, which causes it to appear within the viewport you defined in your window.

If you still need clarification, I would recommend the MSDN documentation for Direct3D.
> 10 votes

---
Tags: directx11
---


title: How to do gpu batching?

text:
# Question
Title: How to do gpu batching?
I need to render two shapes with opengl (let's say a cube and a triangular prism) and one of them has texture and the other one has lightning fx. **The thing I want to do is first draw texture and lightning and then render the shapes.** I made a research, the only thing I could find is this is called gpu batching. Do you have any ideas or any tutorials etc. about this subject? How can I do this?

Edit: This video explains what I want to do: Crysis 2 - Rendering Pipeline

Edit: **I heard that it is not possible for gpu to render different fxs for different geometries back to back. So I need to group geometries by fxs.(Cube has texture put it in the texture array, prism has lightning put it in the lightning array...then loop these arrays and render the scene)** My aim is to first render fxs and then render geometries to render the whole scene.

# Answer
> 3 votes
You are looking for a technique called deferred shading. The basic premise is to reduce the number of lighting calculations done on a render while avoiding the expensive sorting used in the reverse painter's algorithm. The complexity of the whole procedure is `O(number of objects + number of light sources)`. It takes `(n+1)` steps, where `n` is the number of light sources.

The first step renders each object to an intermediate buffer called the *g-buffer*. This wide buffer stores the depth, world-space normals, albedo (color), and other material parameters; all per-pixel. It is a quite cheap shader because it really just does vertex transformation and texture reads.

The second step runs once per light source and adds to a buffer called the *la-buffer* (light accumulation). The shader reads in the data for each pixel from the g-buffer and performs lighting calculations for the corresponding pixel in the la-buffer. The la-buffer is then either used directly as the output or run through a post-processing step. This step can be rendered with light geometry (sphere for point light, cone for spotlight, full-screen for ambient light) to avoid doing unnecessary light calculations.

The advantages of deferred rendering are that it scales much better to scenes with many dynamic light sources and that it only needs to do at worst one light calculation per pixel per light. However, it uses up a lot of memory for the g-buffer and is dependent on the fill rate of the GPU. The good news is that this problem will disappear as hardware gets faster and has more memory. It is also more difficult to implement transparency, but there is a method published to work around that problem. It also constrains you to essentially one lighting equation per light source, but this is generally a non-issue.

Here is an image describing the basic pipeline.

---
Tags: opengl, gpu
---


title: Candy crush saga popup-like messages

text:
# Question
Title: Candy crush saga popup-like messages
I was wondering how could I make in Android something like the popup messages seen in Candy Crush Saga, those messages like "Delicious!", "Tasty!" or similar:

As well as the score of each movement, they will pop up at first and then vanish:

How could I implement something like that in Android?

# Answer
Toast message might be the thing, that you are looking for. If you are not familiar with toast messages, i suggest that you take a look at this document page, about Toast messages:

Toast message

And then you should take a look at custom toast view document:

CustomToastView

---

Here's how to do it. First, create XML layout file and name it "cust\_toast\_layout.xml" and define the below layout.

**cust\_toast\_layout.xml**

```
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/relativeLayout1"
    android:background="@android:color/white">

<TextView
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:id="@+id/textView1" android:layout_height="wrap_content"
    android:layout_width="fill_parent"
    android:text="Paresh N. Mayani"
    android:gravity="center"
    android:textColor="@android:color/black">
</TextView>

<ImageView
    android:layout_height="wrap_content"
    android:layout_width="fill_parent"
    android:src="@drawable/new_logo"
    android:layout_below="@+id/textView1"
    android:layout_margin="5dip"
    android:id="@+id/imageView1">
</ImageView>

<TextView
    android:id="@+id/textView2"
    android:layout_height="wrap_content"
    android:layout_width="fill_parent"
    android:text="This is the demo of Custom Toast Notification"
    android:gravity="center"
    android:layout_below="@+id/imageView1"
    android:textColor="@android:color/black">
</TextView>

</RelativeLayout>

```

And Now inflate the above layout to create/show custom Toast notification:

**CustomToastDemoActivity.java**

```
LayoutInflater inflater = getLayoutInflater();
    View view = inflater.inflate(R.layout.cust_toast_layout,
                                   (ViewGroup) findViewById(R.id.relativeLayout1));

    Toast toast = new Toast(this);
    toast.setView(view);
    toast.show();

```

(same answer can be found from here, thanks to Paresh Mayani) Adding image to toast
> 3 votes

---
Tags: android, gui, user-experience
---


title: Direct3D reducing DrawIndexed CPU usage

text:
# Question
Title: Direct3D reducing DrawIndexed CPU usage
I am trying to optimise some of my rendering to get is useable on lower end machines (in my case a 2GHz i5 laptop with a GT 520M).

A quick investigation showed that the GPU isnt actually getting to 100%, but both CPU cores are. While most of this is non-rendering stuff (which I can likely make faster), I was surprised to find the piece of code below is apparently using 10% (20% of a core).

```
void RenderStaticTerrain()
    SetShadersInputLayoutConstantsEtc();
    for region in regionsInView: //about 20
        region->SetVertexAndIndexBuffer()
        for texture in regoin->UsedTextures(): //around 100
            d3dContext->SetAsShaderResource(texture);
            d3dContext->DrawIndexed(...);

```

I used the Windows Performance Analyzer sample based profiling and that points at some AMD or Nvidia DLL's as being where the CPU spends its time, largely I believe within the DrawIndexed (found via QueryPerformanceCounter. The sampling results seemed to dump the dll time just in RenderStaticTerrain itself).

The textures, buffers, etc are all immutable usage so don't see anything obvious to consume CPU there like moving vertices about or anything like that.

Two idea I have which (both of which look like some work) is texture arrays and using a few very large textures containing the others. However I am not sure how viable either of those are, and if it would actually make any performance difference.

For texture arrays it seems I can have upto 2048 which is plenty. However I am not sure if the GPU is going happy with what seems to me like effectively random access via a vertex buffer field. The major problem however is it appears all the textures need to have the same size, while most of mine are in the 32x32 to 128x128 range, with some even larger ones.

Another idea was to pack them into some really big textures, but this always seems to cause problems with mip-mapping and texture filtering, since even if I repeat each textures border pixel a few times, a few mip levels down and I have one pixel in the small texture being made from pixels of unrelated textures.

Not sure what other options there are. I am still not really sure why that loop uses much CPU at all.

The current code is only D3D11 targeting D3D11 hardware, but I do plan to support older hardware and OpenGL.

# Answer
You've about 2,000 draw calls in there, but draw call overhead is much reduced in D3D11 (by comparison to 9) - they're still not free, of course, but the old days of horror stories from excessive draw calls are definitely over and any reasonable setup from the past 6 or so years should be able to handle this kind of count with ease (yes, I've profiled this; it's not that big a problem).

A bigger problem is the way you're traversing and sorting your scene. Having a separate vertex/index buffer pair for each region in your scene means that you're getting a LOT of state changes - when taken together with textures you're also looking at about 2,000 state changes per frame. Now *that's* going to hurt you somewhat more.

The first solution I'd recommend is that instead of separate vertex/index buffers per region, you just put everything into a single big vertex/index buffer pair. Then use the StartIndexLocation parameter of DrawIndexed to specify which subset to draw. That will get rid of those state changes and give you a single ISSetVertexBuffers/IASetIndexBuffer pair per frame.

From there you can look at sorting your entire scene by texture. So instead of drawing immediately as you traverse a region, you instead store the information you need to draw (i.e. a pointer to your texture and your DrawIndexed parameters) in a container of some sort, then sort the resulting list by texture. Finally walk through the list and issue texture changes as required followed by groups of draw calls per-texture.

The resulting pseudo-code might be structured something like this:

```
void RenderStaticTerrain()
    ClearListOfDrawCalls();
    for region in regionsInView: //about 20
        for texture in region->UsedTextures(): //around 100
            AddTextureAndDrawCallParamsToList();

    SetShadersInputLayoutConstantsEtc();
    SetVertexAndIndexBuffer();

    for texture in ListOfStuff
        d3dContext->SetAsShaderResource(texture.texture);
        for drawCall in texture.drawCalls
            d3dContext->DrawIndexed(drawCall.indexCount, drawCall.startIndex, 0);

```

That should get your state change overhead down to an absolute minimum, and allow the D3D runtime and driver to better optimize multiple successive draw calls that share the same state (which it can't do in your current setup).

If you still have performance problems after making these changes then is time to start looking at some more complex batching.
> 4 votes

---
Tags: directx, directx11
---


title: UV mapping width and height

text:
# Question
Title: UV mapping width and height
I am looking at the following C# code on howto construct a cube. It draws a cube using one texture on everyface.

```
 private void ConstructCube()
    {
        _vertices = new VertexPositionNormalTexture[NUM_VERTICES];

        // Calculate the position of the vertices on the top face.
        Vector3 topLeftFront = Position + new Vector3(-1.0f, 1.0f, -1.0f) * Size;
        Vector3 topLeftBack = Position + new Vector3(-1.0f, 1.0f, 1.0f) * Size;
        Vector3 topRightFront = Position + new Vector3(1.0f, 1.0f, -1.0f) * Size;
        Vector3 topRightBack = Position + new Vector3(1.0f, 1.0f, 1.0f) * Size;

        // Calculate the position of the vertices on the bottom face.
        Vector3 btmLeftFront = Position + new Vector3(-1.0f, -1.0f, -1.0f) * Size;
        Vector3 btmLeftBack = Position + new Vector3(-1.0f, -1.0f, 1.0f) * Size;
        Vector3 btmRightFront = Position + new Vector3(1.0f, -1.0f, -1.0f) * Size;
        Vector3 btmRightBack = Position + new Vector3(1.0f, -1.0f, 1.0f) * Size;

        // Normal vectors for each face (needed for lighting / display)
        Vector3 normalFront = new Vector3(0.0f, 0.0f, 1.0f) * Size;
        Vector3 normalBack = new Vector3(0.0f, 0.0f, -1.0f) * Size;
        Vector3 normalTop = new Vector3(0.0f, 1.0f, 0.0f) * Size;
        Vector3 normalBottom = new Vector3(0.0f, -1.0f, 0.0f) * Size;
        Vector3 normalLeft = new Vector3(-1.0f, 0.0f, 0.0f) * Size;
        Vector3 normalRight = new Vector3(1.0f, 0.0f, 0.0f) * Size;

        // UV texture coordinates
        Vector2 textureTopLeft = new Vector2(1.0f * Size.X, 0.0f * Size.Y);
        Vector2 textureTopRight = new Vector2(0.0f * Size.X, 0.0f * Size.Y);
        Vector2 textureBottomLeft = new Vector2(1.0f * Size.X, 1.0f * Size.Y);
        Vector2 textureBottomRight = new Vector2(0.0f * Size.X, 1.0f * Size.Y);

        // Add the vertices for the FRONT face.
        _vertices[0] = new VertexPositionNormalTexture(topLeftFront, normalFront, textureTopLeft);
        _vertices[1] = new VertexPositionNormalTexture(btmLeftFront, normalFront, textureBottomLeft);
        _vertices[2] = new VertexPositionNormalTexture(topRightFront, normalFront, textureTopRight);
        _vertices[3] = new VertexPositionNormalTexture(btmLeftFront, normalFront, textureBottomLeft);
        _vertices[4] = new VertexPositionNormalTexture(btmRightFront, normalFront, textureBottomRight);
        _vertices[5] = new VertexPositionNormalTexture(topRightFront, normalFront, textureTopRight);

        // Add the vertices for the BACK face.
        _vertices[6] = new VertexPositionNormalTexture(topLeftBack, normalBack, textureTopRight);
        _vertices[7] = new VertexPositionNormalTexture(topRightBack, normalBack, textureTopLeft);
        _vertices[8] = new VertexPositionNormalTexture(btmLeftBack, normalBack, textureBottomRight);
        _vertices[9] = new VertexPositionNormalTexture(btmLeftBack, normalBack, textureBottomRight);
        _vertices[10] = new VertexPositionNormalTexture(topRightBack, normalBack, textureTopLeft);
        _vertices[11] = new VertexPositionNormalTexture(btmRightBack, normalBack, textureBottomLeft);

        // Add the vertices for the TOP face.
        _vertices[12] = new VertexPositionNormalTexture(topLeftFront, normalTop, textureBottomLeft);
        _vertices[13] = new VertexPositionNormalTexture(topRightBack, normalTop, textureTopRight);
        _vertices[14] = new VertexPositionNormalTexture(topLeftBack, normalTop, textureTopLeft);
        _vertices[15] = new VertexPositionNormalTexture(topLeftFront, normalTop, textureBottomLeft);
        _vertices[16] = new VertexPositionNormalTexture(topRightFront, normalTop, textureBottomRight);
        _vertices[17] = new VertexPositionNormalTexture(topRightBack, normalTop, textureTopRight);

        // Add the vertices for the BOTTOM face.
        _vertices[18] = new VertexPositionNormalTexture(btmLeftFront, normalBottom, textureTopLeft);
        _vertices[19] = new VertexPositionNormalTexture(btmLeftBack, normalBottom, textureBottomLeft);
        _vertices[20] = new VertexPositionNormalTexture(btmRightBack, normalBottom, textureBottomRight);
        _vertices[21] = new VertexPositionNormalTexture(btmLeftFront, normalBottom, textureTopLeft);
        _vertices[22] = new VertexPositionNormalTexture(btmRightBack, normalBottom, textureBottomRight);
        _vertices[23] = new VertexPositionNormalTexture(btmRightFront, normalBottom, textureTopRight);

        // Add the vertices for the LEFT face.
        _vertices[24] = new VertexPositionNormalTexture(topLeftFront, normalLeft, textureTopRight);
        _vertices[25] = new VertexPositionNormalTexture(btmLeftBack, normalLeft, textureBottomLeft);
        _vertices[26] = new VertexPositionNormalTexture(btmLeftFront, normalLeft, textureBottomRight);
        _vertices[27] = new VertexPositionNormalTexture(topLeftBack, normalLeft, textureTopLeft);
        _vertices[28] = new VertexPositionNormalTexture(btmLeftBack, normalLeft, textureBottomLeft);
        _vertices[29] = new VertexPositionNormalTexture(topLeftFront, normalLeft, textureTopRight);

        // Add the vertices for the RIGHT face.
        _vertices[30] = new VertexPositionNormalTexture(topRightFront, normalRight, textureTopLeft);
        _vertices[31] = new VertexPositionNormalTexture(btmRightFront, normalRight, textureBottomLeft);
        _vertices[32] = new VertexPositionNormalTexture(btmRightBack, normalRight, textureBottomRight);
        _vertices[33] = new VertexPositionNormalTexture(topRightBack, normalRight, textureTopRight);
        _vertices[34] = new VertexPositionNormalTexture(topRightFront, normalRight, textureTopLeft);
        _vertices[35] = new VertexPositionNormalTexture(btmRightBack, normalRight, textureBottomRight);

        _isConstructed = true;
    }

```

Now, all of the UV coordinates are represented as a fraction out of 1, 1 being the total size of the texture. So, how on earth could I map only one size of a texture to my cube??? For example, have a texture with 6 squares and have each square be one case. I know how to map the coordinates, but even if I map the right coordinates, it will still draw everything that is to the right of the Y coordinates, and under the X coordinate.

# Answer
UV coordinates act as a normalized representation of a texel to sample at the particular x/y location within that texture. Whenever a vertex is passed through the shading pipeline, a portion of the pipeline will appropriately interpolate the UV coordinates for each pixel. Here is a good description of UV mapping in the context of directx http://msdn.microsoft.com/en-us/library/windows/desktop/bb219690(v=vs.85).aspx
> 2 votes

# Answer
So, it depends on how the pixel shader is written, but assuming it's completely generic (pass through the UV coordinates to the texture sampler), then the UV coordinates specify a location on the texture you're sampling. (0,0) is the upper left corner, and (1,1) is the bottom right corner. Ordinarily, anyway. I'm a little unclear why (0,0) is the upper right texture coordinate, and further why the elements of the UV vector are being multiplied by Size.x and Size.y, but the concept I want to explain is more general than that, so I suppose it doesn't matter in this case.

It sounds like you want to use your texture as a Texture Dictionary, where subtextures are sampled from the Texture Dictionary, rather than taking the whole texture and using that. This has a number of advantages, like being able to batch together multiple render calls and reducing congestion, but that's not what you asked.

First, you need a method of identifying where, within the texture, each subtexture lies. If you had a 64x64px texture, and it held 4 32x32px subtextures, then you'd have:

```
texture 1 at (0,0) with size (32,32)
texture 2 at (0,31) with size (32,32)
texture 3 at (31,0) with size (32,32)
texture 4 at (31,31) with size (32,32)

```

in terms of UV coordinates, that corresponds to

```
texture 1 UL (0,0)                 BR (32.0/64.0,32.0/64.0)
texture 2 UL (0,32.0/64.0)         BR (32.0/64.0,1.0)
texture 3 UL (32.0/64.0,0)         BR (1.0,32.0/64.0)
texture 4 UL (32.0/64.0,32.0/64.0) BR (1.0,1.0)

```

From those UpperLeft and BottomRight positions you can generate the four corners of each texture necessary to specify the face of each cube. Then, you simply pass it to the appropriate cube face.

So, that's the standard mapping which you said you understood. Now, onto some suspicions why, if you did that, it didn't work:

Notice that the code you provided is multiplying your UV coordinates by Size. It could be your shaders are doing something funky, like dividing by Size again, putting it back in the 0-\>1 range before texture sampling. If that is what's happening, and you do a mapping that doesn't multiply by Size, then your biggest value will be 1/Size, which might all end up inside the same subtexture, or at the very least offset. So, check out the PS if you can, and if you can't then just play around with that. If you have more specific questions, or if this didn't actually address your actual question, let me know and I can take another crack at it.
> 2 votes

---
Tags: xna, c#, .net
---


title: AI and rendering to screen

text:
# Question
Title: AI and rendering to screen
I'm using LWJGL, however I'm a bit confused on what to do.

I'm trying to write an AI simulation, however I'm stuck at this problem. I have one camera, and I plan to move the camera to the mob position and then save it to the screen, then I will then use that to input into the neural network, then it does its action, then I move onto the next mob and repeat. Then, finally I move the camera to the player position so I can see what is happening.

The problem is that I just want to see out of the player eyes and not the mob eyes. However, I'm confused on how to do it. http://www.lwjgl.org/wiki/index.php?title=Taking\_Screen\_Shots the only way I can think of getting the information for what the mobs see is to take a screen shot if I render it to the screen. But, then if I do this all I will see is everything jump around a lot.

The code will look something like this

```
public class Game() {
  public Game() {
      camera = new Camera();
      player = new Player();
      ArrayList<Mobs> mobs = new ArrayList<Mobs>();
  }

  public void update() {
  player.update();
    for(int i=0; i<mobs.length; i++) {
      camera.setPos(mobs.get(i).getPos();
      mobs.get(i).render;
      saveScreen();
      mobs.get(i).logic();
    }
  }

   public void render() {
     player.render();
   }
}

```

There must be a better way. For example, maybe it possible to not render to the screen to input the data into the mob. Or maybe, I don't need to save it to say .png to then put into the neural network.

# Answer
> 3 votes
Just render to an offscreen buffer for each mob. This is an FBO in OpenGL or a RenderTarget in D3D. In OpenGL, if no FBO is bound, everything is rendered to the screen. Just create and bind an FBO and then the mob's "view" will be rendered into a texture of your choosing for processing (and you aren't required to draw it to the screen, ever).

Note that you probably don't actually want to render the mob's vision. I'm not sure what AI you're trying to do, but odds are you're trying to do things a little too "realistic" and not faking things enough. Remember, in AI, the goal of computer vision is to take an image and then break it down into some semantic representation; with a game, you're starting with the semantic representation and then drawing it, just to try to convert it back (which is hard). Even if you think you need to really "see" you can usually fake this with ray casts and other scene metadata in a significantly faster and easier way than trying to do any sort of image processing on a rendered scene.

---
Tags: java, ai, lwjgl, simulations
---


# Question
Title: When should I represent points and sizes as structures?
As part of my simple Ruby 2D game development framework, my game objects have position (x and y values) and size (width and height).

```
class MyGameObject
  attr_accessor :x
  attr_accessor :y
  attr_accessor :width
  attr_accessor :height
  ...

```

Another approach I've seen was treating the position as a `Point` structure, and the size as a `Size` structure:

```
Point = Struct.new(:x, :y)
Size = Struct.new(:width,:height)

class MyGameObject
  attr_accessor :position   # Point instance
  attr_accessor :size       # Size instance
  ...

```

Some frameworks use the former (I think GDX, Gosu...). Others use the latter (cocos2d-iphone). The problem is, it isn't entirely clear to me the advantages and disadvantages of both behaviors (in game development) - I don't know why some frameworks chose one and not the other.

Are there significant differences I should consider?

# Answer
Some even use the `Rectangle` class:

```
class Rectangle
{
    float x, y, w, h;
}
class GameObject
{
    Rectangle dimensions;
}

```

It's just a choice of design, it doesn't really matter. If you're doing your own code, make what you feel more confortable. If you're using some API, framework or engine, or editing/modding a game, try to be consistently with the rest of the code and do just like is in nearby code.

I would say to go with two separate vectors, like this:

```
class Vector2
{
    float x, y;
    //helper functions like operator overload, dot, length, distance, etc.
}

class GameObject
{
    Vector2 position;
    Vector2 size;
    Vector2 direction;
}

```

This way you can handle things like angle between objects easier, like so:

```
GameObject foe;
GameObject player;
Vector2 dist = player.position - foe.position;
dist.normalize();
float angleBetween = acos(dist.dot(foe.direction));

```

instead of having to extract the vectors from rectangles, or create them from plain floats.
> 8 votes

# Answer
In general, always use a separate data structure. It makes your code significantly easier to use, read, and maintain. How often do you need `x` separate from `y` vs how often do you need to calculate a vector offset, length, dot product, etc.? Aim for the common case; make the code you write repeatedly easier to work with, which for points and vectors, is typically going to be operations on the entire "object" rather than operations on individual components.

The only exception I would make is, after *properly profiling*, you find the separate structure is too slow. Languages like Ruby do not make simple user-defined "by-value" possible and, in my experience, having points and vectors be "by-reference" types is both a pain at times and can be a massive slowdown without careful attention to temporaries. It can be advantageous, for instance, to have two arrays of ints, one for `x` and one for `y`, then to have a single array of `Point` objects; it's much more of a pain to work with though so only do that split *if* you have valid performance metrics to indicate it's worthwhile!
> 2 votes

---
Tags: 2d, data-structure, ruby
---


# Question
Title: XNA 4.0 Multiple Textures on same Vertexbuffer
I have been messing around with XNA for a long while now, but have never really done much more than just copy/pasting tutorials and editing those. Since a bit I have been trying to really start to learn XNA but encountered a problem (or challenge, I suppose) that I can't seem to find any information on anywhere (or its there but I just don't see it).

So my question is.. Is there any way to draw multiple (different) textures on a Vertex Buffer?

I make one large Vertex Buffer out of an array of cubes to make sure no cube-sides are drawn when they aren't visible as well as not having to call the drawing device a million times if I would want to draw a million cubes.

Example, having two cubes in a row would be:

```
 _ _
|_|_|

```

But obviously, the middle will never be seen (left cube's right side and right cube's left side) so they are not added to the Vertex Buffer.

So my question is, how do I get a different texture on both of these cubes even though they are part of the same Vertex Buffer?

A cube side is constructed like this, but will obviously have to have something in it that lets the buffer know this part will need this texture (instead of simply a color):

```
vertices.Add(new VertexPositionColor(new Vector3(x, y + 1, z + 1), Color.Purple));
vertices.Add(new VertexPositionColor(new Vector3(x, y, z + 1), Color.Purple));
vertices.Add(new VertexPositionColor(new Vector3(x, y, z), Color.Purple));
vertices.Add(new VertexPositionColor(new Vector3(x, y, z), Color.Purple));
vertices.Add(new VertexPositionColor(new Vector3(x, y + 1, z), Color.Purple));
vertices.Add(new VertexPositionColor(new Vector3(x, y + 1, z + 1), Color.Purple));

```

And the Vertex Buffer is filled like this:

```
if (vertices.Count > 0)
{
    chunkVertexBuffer = new VertexBuffer(device, VertexPositionColor.VertexDeclaration, vertices.Count, BufferUsage.WriteOnly);
    chunkVertexBuffer.SetData<VertexPositionColor>(vertices.ToArray());
}

```

Pretty standard stuff I believe, but I can't seem to work it out with textures as VertexPositionTexture will only let you add the texture when you assign the effect.. for the entire Vertex Buffer.

# Answer
> 4 votes
While XNA does support multitexturing, what you're trying to accomplish could easily be accomplished with a single texture.

**UV Coordinates** \- A Vertex has a Position in 3D space (X,Y,Z) . If it is part of a textured mesh, it also has a Position on the 2D texture (U,V). U,V are coordinates that go from (0,0) in the upper-left of the texture to (1,1) in the bottom right of the texture.

The Point of the VertexPositionTexture struct is that the TextureCoordinate is a UV-coordinate on the texture. For example, if you look at minecraft terrain packs, you'll see that all blocks are stored on the same texture. Then for each face each vertex will choose its UV coordinates based on which block texture you want to display. This is why you only need one texture.

---
Tags: 3d, xna, textures
---


# Question
Title: Any possibility to render XNA scene via POV-Ray
We are creating special purpose application. Its not game but its 3d Application that functions like game. We require app to have different places and we want to allow user to roam inside such places and take photographs of views.

Here is what we are doing

1. We are creating a model of a place (e.g. Room Interior) in 3Ds Max
2. We are exporting FBX file
3. We are importing FBX file in XNA. Adding lights , placing camera.
4. Application lets user rotate and move camera in any direction. Just as if you are moving character in FPS game.

Goal:

We want to capture high quality screenshot from the camera view point. We require hyper-realistic looking image.

What we do :

To achieve this we are capturing screenshot by storing screen pixels in an Image.

Problem :

Its pathetic quality image. As it is just a frame of run-time 3d render.

======

A. I heard POV ray is programmable renderer that can be helpful . But I dont know how will it fit in our current setup.

B. Is there any other approach which I can take to render high quality by looking at our current setup.

C: If I wish to entirely start from scratch , how should I code this application.

NOTE : I am just product manager for this app. I am not actual developer. But I have been web developer myself. I never did 3D programming though. But I know basics of all these.

# Answer
> 3 votes
POVRay is a raytracer with a custom file format (POV). As far as I can tell, the POV format is not very supported very well by third-party converters, although it is an ASCII format and you could write your own conversion. It runs on the command-line, so it is not technically an issue. However, the license requires you to obtain written permission from the POVRay authors before distributing it with your program.

In the open source category, You could also consider alternatives such as Yafaray (open source),which uses its own XML format, or LuxRender (unbiased, open source). Generally you will need to export the camera and lights and scene out to a file and invoke the raytracer. If you have the luxury of being able to wait a few hours for a render, the unbiased results of LuxRender make for some high-quality architectural shots. The Yafaray render should take seconds to minutes.

Generally, what distinguishes high-quality architectural renders is how well the light propagation is done. "Radiosity" or "Global Illumination" would be the keywords to search for here. There are ways to do these calculations in your XNA application as well. For example, with an artistic eye you can fake radiosity by adding extra lights to the scene, or you could implement a full-blown per-vertex iterative radiosity solver

---
Tags: xna, c++, directx, rendering
---


# Question
Title: Would A* or Dijkstra be more proper for a grid-based tactics game?
In a grid-based tactical game (think Fire Emblem), would A\* or Dijkstra be more proper for finding a path to use for enemy AI to determine the best place to move?

A\* has a better performance that Dijkstra, however Dijkstra may offer me better/smarter looking results for an AI.

If possible, I'd like to have the answer for both a hexagon based grid, and a rectangle based grid, if it'll make a difference.

# Answer
A\* is just Dijkstra's with a heuristic to speed up pathfinding. Both find an optimal path; neither generates "more realistic" paths than the other. They can both be tuned to prefer straight lines or zig-zags, as you prefer.

If you have a decent heuristic *(which you will for grid and hexagonal graphs)*, there's no reason *not* to choose A\*. It should perform faster on average than Dijkstra's, and (despite your claim) their final results will be similar or the same.
> 13 votes

# Answer
If you can tolerate a little pre-processing, consider ALT with the 4 map corners as landmarks. Use Dijkstra from the 4 corners to generate landmark distances at every hex. When I implemented this on my 760 x 420 map Bidirectional ALT ran 80 * faster than Bidirectional A\*.

Here is an Open Source implementation: Hexgrid Utilities for Board Games
> 1 votes

# Answer
Its subjective which *feels* better. You're the best judge of that; implement them both, and switch between them. And from then on only revisit the code with an eye to optimisation if its 'hot' in profiling!

If you are making a game with a large number of moving units then the speedup of Jump-Point-Search can be well worth it (empirical anecdotes from games like MegaGlest and 0ad).

Another key optimisation in my own hobby games has been to also have a 'reroute' function - when a unit hits an obstacle (e.g. a moving unit or a newly-placed building) it works out how to most efficiently rejoin its existing route rather than create a new route to the destination. There are nodes in the existing path just a cell or two away, typically.
> -1 votes

---
Tags: path-finding
---


title: How are boss battles important?

text:
# Question
Title: How are boss battles important?
What are the point of boss battles in the current form? For most games, a boss encounter is usually:

* A puzzle of sorts, where you have to figure out when the boss' weak point is exposed.
* An enemy with just more health and can hit harder, or maybe having a special attack.
* A scripted fight where you have to push the correct buttons at the right time.
* A test to see how well you've learned what the stage was trying to teach you. (IE an ability.) etc.
* An enemy that will become common at a later time.

In which they're mostly just a longer fight than normal. Some games have interesting bosses that are actually meaningful to the story, but are still nothing really substantial.

Why are boss fights so prevalent in games? Is there any research that shows the importance of boss fights? What function do they fulfil in a game, from a design perspective?

# Answer
> 19 votes
Boss battles, both metaphorical and literal, serve a number of important purposes. Not every boss has to do all of these, and even two bosses in the same game may have different purposes. There may be accidents where what is supposed to be a climactic boss battle is quickly forgotten as too easy, with no real story ties. Some may not fit totally into any category, but instead may be a foggy mix.

## Story Climax

He's killed your family, along with countless others. He's taken power of the country for his own selfish purposes, and plans on summoning an unstoppable demon. Worse, he's been mocking you the entire time you've been chasing him. But now he's standing directly across from you, sword in hand, smug grin on his face. Now you can end it...

Or, maybe you don't want to fight them. In fact, there may not be anything fundamentally wrong about their position. But for one reason or another, you clash, and regardless of who wins, no one is happy about it.

In fact, you may not even be fighting another individual...

If the battle exists only for the character, and not the player, it is not counted as a boss battle, as the player is not being tested even slightly.

**Examples:** Kefka from *Final Fantasy VI*, Gunther Hermann from *Deus Ex*, the Princess level from *Braid*.

## Aside: Not Story-Related

Not all boss battles need to be story-related. Some games have no story, so such a battle is obviously not story-related. But even when a story exists, some bosses are just irrelevant to it, and simply happen.

They can be a welcome surprise, or blatantly telegraphed from a mile away. In any case, they can perform any function any other boss battle can.

**Examples:** Master Hand from *Super Smash Bros.*, secret super-bosses in the *Final Fantasy* series, challenge dungeons in the *Zelda* series.

## Gameplay Climax/Test

All those skills you've gathered and refined over your journey? Let's see just how well you know how to use them. You are presented with a challenge, more difficult than before (probably), and/or uses all the elements you have learned throughout the journey together in a way you may or may not have even seen before.

Perhaps, it's just a bigger and tougher enemy with more health. Not exactly that satisfying for some gamers, but others will love it as a resource management challenge.

Perhaps it's a situation you have come across before, but in a new and dangerous setting, such as over lava, in a strange gravity field, or under a time-limit.

**Examples:** GLaDOS from *Portal*, the last level in *Mirror's Edge*, almost every second encounter in *Bayonetta*, final levels in the *Advance Wars* series.

## Puzzle Battle/Out-Of-Nowhere Gameplay

Ok, so, we know it's been a sidescrolling beat-em-up this whole time, but we've decided to give you a gun, and turn it into a third-person space shooter, just for the last boss. Or, maybe we've simply introduced a new game mechanic, and want to put you under pressure to learn it *quickly*. In it's simplest form, everything is as normal, gameplay-wise, but the enemy has some trick to them that you have to discover and exploit. In any case, you probably didn't have time to prepare.

Why is this useful, and not a dick move? Honestly, it sometimes *is* a bit of a dick move. But any other kind of boss battle can be that, too. It can be used to great effect if done well. If you want to put the player under a lot of pressure, make them have to learn something quickly to survive.

**Examples:** 02 from *Kirby 64*, Ozzie from *Chrono Trigger*, the Spider from *Limbo*.

## Aside: Metaphor

Not all boss battles have to be a battle, or even against an intelligent individual. In fact, even a single decision, made difficult enough, can be considered a boss battle, if you want to stretch the definition to breaking-point. As long as it can be a story climax, gameplay test, or have some kind of intensity that separates it from the rest of the game, it can be considered a boss battle. Well, in game design terms, at least.

**Examples:** Manfred von Karma from *Phoenix Wright*, final levels of puzzle games like *Super Monkey Ball* or of music games like *Elite Beat Agents*. If you want to stretch the definition, you can even count the question of which of your companions do you save when you can only save one in *Mass Effect* as a boss battle. As long as you actually care about them both, that is.

## No Boss Battle

Some games just don't need boss battles, or would actively be made worse by them. They might break the flow, or perhaps the game itself is already an increasingly difficult test. Maybe they just don't make sense.

**Examples:** *Tetris*, *Animal Crossing*, *Mario Kart*.

## Conclusion

I'd say the most important aspect of a "boss battle" is that it feels like a separate part of the game that has more tension and difficulty, in story and/or gameplay, than the rest. It is a climax, or otherwise a rise in intensity, that tests the player, and sometimes also the character. It is different from a purely story climax, because the player *must* be tested in one form or another. They're not used, or even useful, in every game. As with anything else in game design, use it if it makes sense to use it, otherwise don't.

# Answer
> 19 votes
Actually I'm glad you brought this up.

I think the purpose of boss battles is to give some sort of "epicness" to the conclusion of a section. I have seen this done very successfully, most notably for me in the Megaman series, where every level concludes with a tough boss battle, and you are awarded with a new weapon afterward.

I think boss battles emerge in the design as ways to "punctuate" sections of the game. Even RPGs use them to mark the end of quests.

That said, boss battles can be overstated, where the boss is too hard.

# Answer
> 5 votes
Well, I think it all comes down to one question:

Are they fun and/or interesting to fight? If yes, add them in, if not, leave them out. Personally, I hate bosses that are really just the same as every other enemy only with larger health bars. But if the boss fights are interesting or unique, they can really add a whole lot to the game, both to gameplay and atmosphere. Shadow Of The Collossus made a whole game about it, and in my opinion it worked really well. Boss battles in the Metal Gear series also tend to have some kind of spin to them - some are better than others, but they certainly are memorable and the games wouldn't be the same without them. Nobody forgets the first time they had to fight Psycho Mantis in MGS1 or The End in MGS3.

That said, badly done bossfights can also have a negative impact on your game, if they are boring, unfair or just plain don't fit the game they're in (like popular opinion on Deus Ex: Human Revolution says). Long story short: if you can make them entertaining and memorable and make certain that they add something to the game on the whole, do them. If not, nobody will complain about missing bossfights - better no bossfights than bad bossfights. Well, *somebody will* complain. This is the internet after all. But you get what I mean.

# Answer
> 4 votes
As a player progresses through a game, they expect something more than just the same boring level over and over again. Not only do games generally get harder, they throw new scenarios at the player as they go along. According to Extra Credits, both a difficulty change (difference in scale) and new scenarios (differences in kind) are necessary to make a good game.

Let's analyze the usual components of a boss fight:

* Difficult obstacle or foe (*Bigger scale*)
* Some weak point or strategy to win (*Difference in kind*)
* Cinematics, cut scenes, big animations (*Emphasizes this particular conflict*)
* Rewards the player with loot / items / cut scenes (*Sense of accomplishment*)

Boss fights satisfy the player's need for both differences in scale and differences in kind, and reward the player with a sense of epic accomplishment. Provided some important antagonist is not expected to fight the player in a boss battle, any scenario that satisfies these qualities for the player would be just as effective as a boss battle scenario. **Boss fights are not necessary to make a great game, but are a great tool to bring the game to a climax point.**

# Answer
> 3 votes
Well, i think you should find out what makes humans happy.

As far as I've discovered:

* prove own knowledge, skill and ethics
* collect things (more varied the better)
* listen to stories
* be creative
* be social
* gain fame (especially, liked from people you know)
* change, variation (even a little worse change is good)
* be bad (tease your friends and foes is funny)
* do things in rhythm (music-games or precise routine-movement mostly in fps)
* have a advantage (be good in something or know something your enemy don't know, hiding games)
* look at arts

typical single-player boss-fights ends up in a prove of skill and some knowledge, collecting treasure, sometimes a continuation of a story and sometimes a new level (change, variation). you can do without it or replace it, to make a good game.

# Answer
> 3 votes
Taking the Ys series as an example, there are times where boss fights essentially end up being the whole point of the game, with the dungeon crawling in between serving as a mechanism o advance the story and power up the character. In games with emphasis on pace, reflexes, and skill, boss fights can be a major way to test the player's abilities within the confines of the provided systems. These bosses are notoriously difficult and force you to learn the boss to be able to beat it, and while this may not appeal to many people, it has its popularity.

The goal in this sense isn't to provide a sense of epic scale as far as I can see, and it's not about punctuating the story. Sure, as a matter of general pacing and storytelling it may fulfill either of these roles to throw in a boss battle, but that's just a consequence of storytelling. The boss fight is rather a spectacle in itself, and the sense of relief and reward when completing these challenges is wonderful. And even if you manage to beat a boss, there are still harder playthroughs or faster times to go for. In fact the games themselves emphasizes this boss-battle-centric approach by including time attacks and boss rush modes.

Ask anyone who knows the Ys series to say something about it and they will invariably mention brutal boss battles. This shows that boss battles can be a crucial centerpiece to a game, and it's a model that has demonstrated appeal.

# Answer
> 2 votes
Boss battles are one means to an end. The end is to break up the story into units of play, where the player feels like they've accomplished something. Platformers do this very artificially, with worlds and levels, often with some gatekeeper enemy that takes a special touch or just a few more jumps on the head versus your average enemy. Adventures, RPGs and shooters focus more on exploration. That's great, and challenging, but it gets old quick without a few set pieces to break up the monotony of go here, collect this, kill everyone in your way, bring the item back here, rinse, repeat.

The Legend of Zelda franchise is one that I've followed since the first installment on the NES, and it lives or dies on its boss battles. Up until Twilight Princess, the "overworld" simply ties together the main dungeons and provides a few interesting distractions from the main plot like mini-games. The dungeons, with the requisite puzzles, mini-bosses and big bosses, are where it's at in Zelda gameplay. TwiPrin changed the formula a little by adding more plot-centric things that you do in the overworld, especially while riding Epona, such as a jousting match on a bridge, escorting a covered wagon, battling a horde of warg riders, and even a phase of the final battle. It also kicked up the dungeon boss battles about five notches, giving each battle a unique, thematic feel.

Metroid is another Nintendo franchise that's come to rely heavily on the boss battles. You'd call most of the titles platformers (with the Metroid Prime titles changing it to straight-up shooters), but unlike most platformers, it's all one big world, more or less a maze, more like an adventure game than a traditional platformer. By that same token, to help you keep your bearings and break up the monotony, this one big world is broken into sub-areas, each with a different theme (rock, vines and rock, lava and rock, Chozo ruins and rock, Pirate technology and rock), with valuable stuff guarded by monsters.

Half-Life's writers, on the other hand, are usually more subtle about their "boss battles". More often than not, the "boss" is just a big setpiece against superior forces, like a shooting gallery against zombies, marines or metrocops (with or without a mounted weapon to avoid an ammo drain), though there are a few more traditional boss battles against supersized or super-powerful enemies (including of course the final battles of each of the titles in the series). The big boys like tanks, striders, tentacle-pit monsters, etc are present but somewhat rarer, and usually they're little more than an obstacle that you clear by solving a puzzle (for instance, clearing out a tentacle monster that's taken up residence inside the blast chamber of a rocket testing lab; one guess how). Another difference from the Zelda or Metroid approaches, more like HL's uncles from Id Software (Wolfenstein, Doom, Quake) is that your weapons and other enhancements are not the goal of gunning down bosses; most big baddies are just blocking the way forward. Virtually all of your weapons are either laying around on the ground (often after killing the enemy that held it), or are handed to you by allies.

# Answer
> 2 votes
I think it really lends itself to the game and how well the boss battle is handled. While many games do have lackluster boss fights as you describe, some have quite interesting and fun fights.

Take WoW for example, I recall some very fun fights that are both challenging and rewarding, as well as being downright fun. I think that's the point of a boss fight, to have a fight that rewards you with a new skill weapon while having you work for it. A lot of boss fights lack one of these two components.

# Answer
> 1 votes
I think that the most important thing a boss fight brings to the table (in the gameplay sense) is a test of new abilities under stressful conditions. For example, if the player learned to climb and shimmy in that level, the boss of the level requires the player to climb up, possibly jumping between moving limbs, to hit its weakpoint.

This is common in item-based games like Zelda or Metroid where the boss of an area requires you to use one or more items that you acquired in that area.

Another common use of bosses is to serve as "guardians" of the next area. Many RPGs use bosses as barriers between two levels, but they are mostly just damage sponges because the player doesn't really acquire new abilities as they progress. This still allows the player to feel a sense of progression because the bosses have increasingly greater health and damage output to match or induce a character's level.

---
Tags: game-design
---


title: Teamwork in Unity

text:
# Question
Title: Teamwork in Unity
I have a Unity project without any version control, and I need to share it with another developer so that both of us can work on the project.

What strategies should be use that play nice with Unity Assets?

# Answer
Unity has a built in facility for supporting version control properly.

Just go into the File-\>Project Settings-\>Editor and enable external version control.
> 18 votes

# Answer
I recommend using Git, it's free and the best around.

A while ago I wrote about version control (using Git) on my blog

Long story short:

Enable external version control File-\>Project Settings-\>Editor and create the .gitignore file in order to avoid unnecessary stuff on the repo (this is not really necessary, but it will be priceless during development).

Here's how the file should look like:

```
[Oo]bj/
[Tt]emp/
[Ll]ibrary

#These are files in the root folder of the project
*.tmproj
*.csproj
*.unityproj
*.sln
*.suo
*.user
*.pidb
*.userprefs

```
> 11 votes

# Answer
Unity 3.0 is configured to play nicely with subversion. (At-least nicer than before) I don't know if this is only in the pro version or not, I'll have to check.

In general though, the most recommend version control system is the Unity Asset Server.
> 4 votes

# Answer
Unity specific - work on different scenes and different code files at all times, and merge in the other person's changes manually. If you both need to be working on the same scene, duplicate it and use the copy as a test. Otherwise, if you both modify the same scene, one person's changes will overwrite the other. You can still use source control for your source files, just don't move them around at all, in the file system or via Unity, once they're created.

Beginner advice - get yourself a decent diff/merge tool (I like WinMerge) and get used to using it to see what changes the other person made, and to manually merge changes in conflicted files. Set up a central documentation space, eg. a Google writing document or a wiki, and keep your documentation there - documentation should contain a basic feature list at a minimum so you know what you're aiming for, and ideally a task list derived from the feature list, along with a clear indication of who is working on the task. Talk to each other to get a rough idea of who needs to work on which task and cross them off the list as they get done. Keep revisiting and re-evaluating the list to see if everything is still valid and if you need to rework any priorities.
> 4 votes

# Answer
I work with a team that calls itself Defective Studios. We've struggled with the same issue for years, and just recently I finally gave in and started writing an extension to help me merge gameobjects.

Basically the approach is to create an inspector-like interface in a window that lines up each gameobject, component, and property side-by-side for comparison, and provides buttons to copy values (or whole objects) from one side to another. If you're familiar with the `SerializedProperty` class, that's what is doing the bulk of the work here. We basically create a GUI that synchronizes the foldout state between the right and left side, and creates vertical space wherever a `GameObject` or `Component` exists on only the right or left side. A comparison function checks equality at each level, and turns the background of each line to red or green depending on the state of the equality. Any line whose children contain a difference will also become red, and we also included a nifty button to recursively search the tree and expand all objects that are different or have differences in their children.

As well, there is a set of mask fields that let you filter certain component types out of the comparison. GameObject attributes like name, layer, and tag are also compared. We use `SerializedObject` and `SerializedProperty` to loop through the `gameObject`'s properties, and draw them just like they're drawn in the inspector. This ensures consistency, and is a heck of a lot easier to code!

One last nifty detail is that the comparison process (triggered when the objects are loaded and whenever a change is made) is run in an ad-hoc coroutine that is updated by the `EditorWindow.Update` function, so that in case you are comparing a hugely complicated object, the window doesn't lock up the editor. This was a must when comparing objects with hundreds (or thousand!) of children. All in all, it was kind of a "lego project" as my friend likes to say, but definitely an invaluable tool which instantly became a part of our collaboration workflow.

The tool, Unity Merge is documented on the Unify wiki, which includes a roadmap and an e-mail address for feedback and issue reporting. If you're really struggling with a complicated merge, give it a shot and let us know what you think! Also, I didn't bother to build it into a DLL, so feel free to poke around at the source. The ad-hoc coroutine implementation and `SerializedProperty` manipulations, as well as a few GUI tricks that I ended up needing are a great part of your editor extension toolkit. I'm very interested in changes/improvements that users might have, so please get in touch!
> 4 votes

# Answer
If you have the funds for it, the Asset server with the pro version of Unity is pretty decent. I have used it on a large, multi-person project in the past and it did the job. For vanilla version control, it did what we expected it to do.

I've tried using an SVN repository with a Unity project and it was a bit of a hassle. We ended up scrapping the idea before getting it to work, however. Unity keeps a lot of backup files that I didn't want to take the time to find out what would happen if they weren't synced to the server. I think, with a little finesse, it could be doable but I haven't had experience with it working well.

I have done a small project using the free features of DropBox. It made me nervous but we never had any issues. And, I don't think we ended up needing any real version control stuff for that project so I can't speak much to how reverting or merging files would have gone.
> 1 votes

# Answer
Dropbox supports versioning per file (rather than per commit) and plays nicely with Unity. It is free initially (2 gigabytes) and quite cheap thereafter (about $10 for 50gig). You need the PackRat addon to have access to version history.

Just like with SVN, CVS, GIT etc., you will need to make sure you create tag folders when you get to each key stage in development (eg. end of week, end of milestone). Unlike the aforementioned, it will be much harder to revert to such a stage if you *don't, because you would have to revert every single file individually.* Bear that in mind while developing and you'll have an easy time without paying for the Asset Server.
> 1 votes

---
Tags: unity, version-control
---


# Question
Title: How can a resource manager have dynamic loading/unloading without creating dangling pointers?
I have a resource manager that manages the lifetime of resources in memory. A "resource" is something like a texture, mesh, et cetera. I also have an entity class that, the base class for things in my game world, which has pointers to individual resources.

I'm thinking about giving my resource manager a memory quota so it can free and reload resources as it needs to in order to satisfy this quota, and I'm wondering how I could go about this without ending up with dangling pointers in my entity objects.

I'll need the ability to free up a mesh or texture at any time in the resource manager.

I could use `shared_ptr` in the resource manager and `weak_ptr` in the entities (as long as I don't expose a `shared_ptr` out side of the resource manager, I'd still get the ability to free them on demand), but I am more interested in how you would do it without those classes, for example before C++11 existed or before Boost's smart pointer library existed.

# Answer
> 7 votes
Instead of holding raw pointers, hold some other lightweight reference to the resource. A `shared_ptr` and corresponding `weak_ptr` instances are one such mechanism, but you can easily implement your own if you don't have access to those types (or their earlier Boost equivalents) or there are other reasons why those types would not be appropriate for your scenario (such as being too heavyweight).

This kind of 'handle' system can be as simple as handing out integers which refer to internal slots in the resource system, which can then be used to dynamically reload a resource if access to it is requested while it's been unloaded.

In practice you probably want something a little more robust, at least a way to treat the handle "like" a pointer and provide `operator ->` overloads, for example, by wrapping it in a `Handle` type. That `Handle` type can just contain a pointer to a "control block" stored within the resource manager. The control block has the raw resource reference and a boolean flag that indicates if the resource is alive or not, and some kind of key that can be used to reload the resource if needed (I assume a string in the example below). A very simple example of this might look like:

```
template <typename Resource>
struct Handle {
    Resource * operator -> () }
        return m_owner->retrieve_resource(m_resource_id);
    }

private:
    int m_resource_id;
    resource_manager * m_owner;
};

namespace detail {
    struct control_block {
      Resource * resource;
      bool is_alive;
      std::string key;
    };
};

struct resource_manager {
    Resource * retrieve_resource (int id) {
        auto block = m_resources[id];
        if (block->is_alive) {
          return block->resource;
        } else {
          block->resource = reload_resource(key);
          block->is_alive = true;
          return block->resource;
        }
    }

private:
    std::vector<detail::control_block> m_resources;
};

```

In this implementation, the resource manager just stores a flat array of control blocks which can be referenced by an integer, and provides a method to recover a resource pointer by ID, reloading that resource if needed. The `Handle` class is just a useful wrapper around that behavior. Obviously this is a very simple example, though. If you want something more complete, consider Scott Bilas' article on a generic handle-based resource manager. It takes a somewhat different approach, but is well worth the read.

(Be warned that a need your question implies may mean your resource utilization is very chaotic in nature, and that isn't necessarily a good thing for performance, so you might want to consider that.)

# Answer
> 8 votes
Smart pointers or handle classes, just like C++11. You could write your own long before C++11. I would even argue that the `shared_ptr` in C++11 is probably the wrong model entirely.

All you do is make a type that holds a reference to a resource. This reference could be a pointer with some kind of lifetime management or it could just be some kind of numeric identifier used as a key into a data structure (array index, map key, whatever). Use that to access resources. Similar to how `weak_ptr` works, except you shouldn't need to worry about "locking" them with a `shared_ptr` first. Resources should only ever be released after all logic and rendering for the frame is done and there's no possibility of dangling pointers remaining (assuming you use the appropriate handles everywhere in your non-temporary data structures).

Note that just paging out resources randomly is a *bad* idea. If an object exists and says it needs a texture, it *needs* that texture. If you're running out of memory, either (a) target better hardware, (b) make a smaller game, or (c) implement a more sophisicated resource management system that can more accurately determine the current working set and appropriate times for objects to release or reacquire their resources (using level-of-detail, area-of-interest, or so on).

---
Tags: resource-management, c++
---


title: How to play a YouTube video in XNA?

text:
# Question
Title: How to play a YouTube video in XNA?
Is there any way to play a YouTube video given the URL in XNA? I know it can be done using a shockwave control but I need it in XNA.

I need to make a game where it has to be a YouTube video on the back... something like this:

`Texture2D texture = YouTubevideoPlayer.GetTexture();`

Because I need the streaming on a texture.

I think it can be done by using the youtube APIs... but some tutorial or useful code its a great help.

# Answer
According to the documentation, only .wmv format is supported, and even then it must be encoded using a limited set of parameters.

From the link:

```
1) Video enabled with Digital Rights Management cannot be used.
2) Video must be encoded to the Windows Media Video 9 "Main" profile by using the VC-1 standard.
3) Video must be encoded with a constant bit rate (CBR).
4) Video must include an audio track.
5) Audio accompanying the video must be Windows Media Audio (.wma) encoded, with a single-pass CBR format.
6) XNA Game Studio supports the following maximum bit rates:
Profile          Level          Maximum Bit Rate          Representative resolutions by frame rate
Main             Low            2 Mbps                    320 × 240 @ 24 Hz (QVGA)
                 Medium         10 Mbps                   720 × 480 @ 30 Hz (480p)
                                                          720 × 576 @ 25 Hz (576p)
                 High           20 Mbps                   1280 × 720 @ 30 Hz (720p)

```

That's not to say there isn't possibly some clever way to stream the video from YouTube, convert chunks of it to .wmv with the required encoding as they stream in, and load those chunks to the content manager, but it's nothing that would be supported by the framework, and sounds like a lot of work for a problem that probably has a better solution.
> 1 votes

# Answer
You can use Awesomeium in XNA which has a built in flash player - simply creating a local page with the player and then playing it will be enough. You can then render this texture to the screen.
> 0 votes

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


# Question
Title: Why Inverse Transform the Ray when doing Transformation?
I am adding 3D affine transformations to my ray tracer, and it seems all the literature on the web recommend inverse transforming the ray instead of transforming the 3D objects.

Why is that? There are a lot more rays than objects in a typical ray tracing scene, so wouldn't it be more efficient to transform the objects themselves?

# Answer
In a typical raytracer, you are not just raytracing triangles and vertices, but various implicit surfaces. Each has their own associated hit test. In general, it's a lot easier to just inverse transform the ray than to modify every specific hit test.
> 7 votes

# Answer
The number of *vertices* that would require transforming may be higher than the number of rays. I haven't written a raytracer so I wouldn't know, but all I'm saying is that the number of distinct objects is irrelevant- only the number of verts.
> 3 votes

# Answer
Another point to mention, is that sometimes complex objects have much more than just geometry. They could also have spatial partitioning data such as kd-trees or bsp-trees for accelerating intersection tests. Imagine a high polygon spaceship fying through space. The spatial partitioning data is constant in the local frame, but not in world space. Transforming rays to object space means that these extra data do not need to be precomputed every frame.
> 1 votes

---
Tags: graphics-programming, raytracing
---


title: Vertex and Fragment Shader worldNormal

text:
# Question
Title: Vertex and Fragment Shader worldNormal
How to access/calculate worldNormal in a Vertex and Fragment shader ?

Thanks a lot !

# Answer
> 2 votes
Multiply the normal with the worldmatrix, not the world\_view\_projection.

do this in the vertex shader, and then pass the value down as a linear interpolation value. then you dont need to do it in the pixelshader.

---
Tags: opengl, shaders, glsl, hlsl, fragment-shader
---