# Question
Title: XNA4 - Trouble updating part of a Texture2D
I have a big `Color[] ColorMap` in memory (1280x720), and I have a `Texture2D` that I've uploaded this `ColorMap` to. I update parts of the in-memory `ColorMap`, and want to upload those changed parts to the texture. I'd rather not re-upload the entire texture every time, so I'd like to use

```
public void SetData<T> (
     int level,
     Nullable<Rectangle> rect,
     T[] data,
     int startIndex,
     int elementCount
)

```

As far as I can see, I can not use this directly to upload just a part of my in-memory map to the texture since I can't specify a stride in the `SetData` method.

So say I'd like to update the area specified by `DirtyRect`, I'd first need to create a temporary in-memory buffer

```
Color[] tempBuffer = new Color[DirtyRect.Width*DirtyRect.Height];

```

then copy the wanted data from my `ColorMap` to the `tempBuffer`, and then upload the `tempBuffer` to my `Texture2D` like

```
Text.SetData<Color>(0, DirtyRect, tempBuffer, 0, DirtyRect.Width*DirtyRect.Height);

```

This seems to work - sometimes... But sometimes it appears in the wrong place ?!

If I get rid of the rectangle code and reupload the entire texture every time using

```
Tex.SetData(ColorMap);

```

it works fine, so apparently I must be doing something wrong.

Anyone got any idea? Or is there any code-example of updating only parts of a texture that I can have a look at (XNA 4)?

# Answer
> 1 votes
Never mind, I'll just go stand in the corner with my stupid-hat on :-/

There's nothing wrong with the SetData methods, I accidentally swapped a "point.X" with a "point.Y" in some code that would execute only very rarely. That it only showed up when I was using the SetData without rectangle was pure coincidence.

But one question remains - why do i need to copy part of my big ColorMap into a smaller version before I can upload the partial bit ? That's extremely inefficient ! Why isn't there a version where I can specify an array and a stride so I can copy straight from the source ?

---
Tags: xna, textures
---


# Question
Title: How can I link to callback functions in Lua such that the callbacks will be updated when the scripts are reloaded?
I'm implementing Lua scripting in my game using LuaBind, and one of the things I'm not clear on is the logistics of reloading the scripts live ingame.

Currently, using the LuaBind C++ class `luabind::object`, I save references to Lua callbacks directly in the classes that use them. Then I can use `luabind::call_function` using that object in order to call the Lua code from the C++ code.

I haven't tested this yet, but my assumption is that if I reload the scripts, then all the functions will be redefined, BUT the references to the OLD functions will still exist in the form of the `luabind::object` held by the C++ code. I would like to be able to swap out the old for the new without manually having to manage this for every script hook in the game.

How best to change this so the process works?

My first thought is to not save a reference to the function directly, but maybe save the function name instead, and grab the function by name every time we want to call it. I'm looking for better ideas!

# Answer
It seems to me that you're probably going about implementing your script interface the wrong way.

If you're reloading scripts, that generally means some level of teardown and rebuilding of the mirror C++ objects that talk to them. For example, if you have a Lua script that runs the AI for an entity, there would be some C++ object that represents that AI. That object is responsible for communicating with the Lua script (so that external code is insulated from knowing that a Lua script is even involved).

That object needs to be destroyed and rebuilt with the newly loaded script.

---

> let Lua do whatever it will without having to destroy / rebuild / manage anything on the C++ side.

If you want Lua to be in charge of this, then this means that *Lua be in charge of this*. With great power comes great responsibility. And if you want Lua to have the power, then the onus is now on Lua to have the responsibility to use it correctly.

If Lua hands some "function" to C++, then it is the responsibility of the Lua script to ensure that this function is properly and transparently updated when scripts change. There are several ways to do this in Lua. One way is to build a simple stub function which searches some global registrar object for the actual function to call:

```
local stubForDoStuff = function(...)
  return Registrar.DoStuff(...)
end

```

You can even make a simple stub generator function (it would need to be more complex to find things that aren't direct members of the registrar):

```
function MakeStub(stubName)
  return function(...)
    return Registrar[stubName](...)
  end
end

```

When a script changes, you simply update the functions in the `Registrar`. There are more complex ways of doing it, by giving C++ code tables that contain metamethods for `__call` that will go track down the actual function or whatever. But this is the simplest and most obvious method of doing it.

This sort of complexity is generally why I *don't* give Lua this power. I want to focus my Lua scripts on doing their *actual* job, rather than updating functions and other nonsense. So I give C++ the responsibility for managing Lua-created object loading and destroying.

I tend to use Lua scripts as an alternate means of instantiating C++ derived classes. So "reloading a script" means destroying an object and replacing it with a new one.
> 3 votes

---
Tags: lua
---


title: OpenGL and Win32 API

text:
# Question
Title: OpenGL and Win32 API
Why does almost every book on OpenGL teach or discuss the API in the context of Win32 API?

Is Win32 API necessary to learn OpenGL Game Programming?

# Answer
> 7 votes
OpenGL itself is platform-netrual. In order to maintain that neutrality however, OpenGL expunged anything platform specific. Like creating a window. Or managing a window. Or *creating OpenGL itself*.

Yes, the API does not explain how to create it. Only how to use it once created.

The creating of an OpenGL context is something that is done using platform-specific APIs. On Windows, this means using the Win32 API to create and manage a window. On Linux, this requires using X11 or something similar. And so forth.

Now, there are many, *many* platform-neutral wrappers around these APIs that allow you to create and manage an OpenGL window without touching platform-specific code directly. But that platform-specific code still exists; it's just hidden from sight.

# Answer
> 1 votes
OpenGL is independent of Win32 API. OpenGL is compatible with other platforms (Linux, MacOSX, iOS, ...) where the Win32 API is not even present.

You can use glut to manage your window and create your OpenGL context in a platform independent way, and learn OpenGL without any knowledge of Win32 API.

# Answer
> -1 votes
I have found GLUT much easier to work with if you are just starting to learn OpenGL. After you have some experience you can move onto Win32 API. Although not necessary the knowledge will never be a waste, not to mention it will also make it easier to understand other advanced Windowing/GUI systems.

---
Tags: opengl, win32
---


# Question
Title: Identifying connected lines drawn free-hand by a user
I have a series of 'images' described by a mixture of connected lines and curves. Users will draw on the screen, free hand, and my goal is to break their drawing down into a series of lines and curves that can be matched with the 'images' in my set.

For the sake of simplicity, let's assume this is occurring on a touch screen. These lines will be connected. Each time the user's finger moves, the dx and dy is recorded. The drawing is considered complete and analyzed when the user's finger leaves the screen.

I'm having trouble figuring out a good way to break the user's drawing down into lines. Is there any well known approach to this problem, a C++ library that solves it, or any good articles/technical papers on how to achieve this?

# Answer
> 13 votes
Recognising arbitrary shape vectors is hard!

A simpler technique is to use a grid and count the edges crossed by the stroke drawn by the user. This list of edges is used as a "signature" which is compared against a dictionary of signatures of pre-defined shapes.

**Algorithm**

1. Sub-divide the input area into a grid (eg: 3x3 with infinite edges), and give each edge a unique ID. The exact size and number of divisions depends on your implementation. More grid divisions leads to greater versatility at the cost of robustness.
2. The user draws a line over the grid to create a stroke. Note that the grid does not actually need to be visible on the screen, but doing so will assist in the usability of the interface.
3. The path taken by the stroke is analysed for intersections with grid edges. Each edge that the stroke intersects is added to a list of edges. This becomes the signature for the character. In this example, the "S" curve intersects with the edges Y12, Y7, X7, Y8, Y13, X14, Y14, Y9.
4. The signature is compared against a dictionary of pre-defined signatures and the closest match (or matches) is returned.

**Usability considerations**

1. The user input will not be perfect and the search needs to cater for inexact matches caused by extra or missing edges in the input. One way to deal with this problem is to build a directed graph of the input. This will record the relationship of the points to each other. It will tell you that X7 comes before Y8, but after Y12 for example. The search then compares this against the graph of each character in the dictionary. Each node that matches is assigned a percentage based on the exactness of the match. The node (or nodes) with the highest total percentage matches is used as the overall match.
2. Multiple variations of each character in the dictionary may also be helpful. In the example above, the signature is valid for the character when drawn from the upper-right quadrant, but it may be useful to have a signature for the same character drawn from the lower-left quadrant, which will essentially be the reverse of the example.
3. Characters may be made of multiple strokes. For example if the user draws and upside-down "U" and then a "-" the algorithm may match this to two separate characters such as "n-", or it could combine the two strokes and recognise an "A". A time based heuristic could be used as the differentiator, so that multiple strokes in quick succession will result in one character, whereas strokes drawn with more time in-between will result in multiple characters.
4. If the input system is to be used for hand-writing the number of potential characters and input styles can be large. A word dictionary and/or grammatical analysis could be used to find a set of characters which are most likely to occur next. This is intersected with the list of the matching character signatures to produce an likely candidate.

**EDIT: Additional considerations**

1. It may not always be desirable to show the grid during input. In this case it may be necessary to scale the stroke before applying it to the grid. Naive scaling would work but the results may be skewed by points which fall far outside the input region. A workaround is to find the centroid (the average x,y coordinate) of the input stroke, then calculate the average distance of each point in the stroke from this centroid. The stroke is then scaled based on this average distance.
2. I posted another answer with a different approach using vectors. That algorithm also used the Levenshtein distance to match the character signature. The same approach can be applied to this algorithm during the search phase.

# Answer
> 3 votes
To rephrase the original question:

You have a series of points which represent samples of a continuous (but not necessarily straight) line, and you want to represent that line using fewer samples.

Basically what you're trying to find is samples which don't contribute much to the overall shape of the line. The fastest way to do this, in my experience, is to, one at a time, calculate how much "error" would be introduced by removing each sample, and then actually remove the one which results in the least total error.

You then repeat this process, for each remaining point. You continue finding "what's the least bad point to remove" and removing it, as long as the total error induced in the line is less than some maximum "error" threshold.

Important that your error calculations need to be compared against the original line shape, NOT the progressively optimised shape, or else you can end up with the optimised line devolving away from the drawn shape.

I have sample code (from years ago) available here: http://www.vectorstorm.org/svn/repos/VectorStorm/trunk/Games/VectorPhysics/VP\_Drawable.cpp

Look inside vpDrawable::OptimiseOutOneIndex() for my implementation of this process.

# Answer
> 1 votes
I think you can find good resources by searching for articles about OCR. as far as I could understand your question your problem is a one of OCR sub-problems. you can also search for pattern recognition.

after searching a little bit, I've found this article. I just looked at images (didn't read it at all) and it seems like it's providing algorithm to extract both curves and lines. and it's doing a good job!

# Answer
> 1 votes
Here's an implementation of another algorithm: http://www.bytearray.org/?p=91

It works by decomposing the input stroke into a set of vectors which are multiples of 45 degrees. This simplified representation is compared against a database using the Levenshtein distance.

* Note: the Levenshtein distance can also be applied to the other algorithm I posted here.

# Answer
> 0 votes
Maybe you can use the Douglas-Peucker algorithm to find corners of the lines and break the lines that form points.

---
Tags: c++, input, hand-drawn
---


# Question
Title: How would I successfully split a vector to increase game performance?
Okay so I have a vector for all of the monsters that are spawned in my game. All of these monsters are in a single vector and are "active" according to what zone they are in relative to the player's zone.

If the player is in the same zone as the monster, then have the monster move around and commit actions such as attacking other monsters or the player.

This is all done on a very powerful computer: my main computer.

-BUT-

If I were to attempt using this game on my medium-end computers, the game runs on a steady 2 FPS(where on the main does 50+)

What I attempted is splitting the vector into an array of vectors `vector SpawnList` to `vector SpawnList[100]` as a quick example

Now with this code the monsters are in separate vectors according to their zones(zone is the area that the monster is spawned in)

Note: I use Ogre3D for rendering and bulletPhysics for the physics, and I haven't figured out a way to split the monsters' rendering accordingly.

And with this new idea, my main computer even faces severe slowdowns.

I am wondering if maybe the vectors have been created wrong or it is not a good idea to have an array of vectors.

Is there a better way of having the monsters grouped together where the performance is almost maximum on any computer?

EDIT: I have Profiled my code and here are the updated results. I hope they are of help to this situation: http://pastebin.com/v0PFQf0X

# Answer
> 1 votes
Maybe you could use a look up table for the zones and then each cell of the table having the list of all mobs in the area ,and then only update the state of the monsters ,that are in the current zone you're in . I am assuming here that maybe you're iterating threw the big vector and then updating all the states ,only that would have a non-memory performance toll.Of course i might be missing something.

Edit.Ok i looked up your code and it seems you're doing that as it is so this seems irrelevant,although a small optimization would be just call this once myPlayer-\>getZone() and assign it to some variable instead of calling it all the time ,though just quite minor.

# Answer
> 0 votes
If the monsters are continuously being created and destroyed (if the vector is changing size), then try using a `list` instead.

# Answer
> 0 votes
How about using a Quadtree http://en.wikipedia.org/wiki/Quadtree

I don't know what the performance results between the vector and a Quadtree are. Do update here when you find a good solution would like to know too.

---
Tags: c++, vector, ogre, bullet-physics
---


# Question
Title: Is there any JavaScript game library good for mobile gaming?
I do not know how should I ask this question. I am a very new in this field. I want to learn game development. I want to learn it for Android and iPhone game development. That's why i was looking for JavaScript game engine or libraries. But, I got many. I do not know which one will good for me for 2D or 3D JavaScript game development.

# Answer
> 1 votes
Check out http://impactjs.com/

Also, check out https://github.com/bebraw/jswiki/wiki/Game-Engines which has a rather good list of JavaScript game development libraries. It's not just for mobile, but some are mobile.

Plus, consider that you may actually end up combining libraries - one for rendering your game, another (like JQuery Mobile for example) for managing the general mobile device.

---
Tags: mobile, browser-based-games
---


title: Game testing using mock input

text:
# Question
Title: Game testing using mock input
In this post Patrick Hughes suggested, and michael.bartnett was kind to explain a bit how to do that. While it seems rather clear how to implement and use it, I'm still a bit doubt if this useful enough. Does this kind of "testing" is used widely? I mean every change in a game usually change either how input is processed or a response to same input. This makes all recorded input obsolete. Or maybe I'm missing something?

I feel like implementing a unit testing for core parts (see also) of a game are much more useful, despite it also seems much harder to implement.

So the question is, does mocking input is really good at something in game testing?

# Answer
Record+playback in a complex, interactive environment like a game pretty much has to be done in situ and not as part of a traditional unit test. The recording is intended to help QA set up a saved game and give a repeatable scenario to engineering for bug fixing.

Unit testing of core components IS useful, but only in the context of ensuring that the engine itself is functioning properly.

Examples of engine unit tests would be to load a static scene and compare a render versus renders in the past, or (more on topic) to load a player and feed it recorded inputs to test whether it ends up at the same coordinates as previous runs.

There are other, non-deterministic tests that are very useful in online games. The best example is load testing with a large number of headless clients fed from a pool of recorded inputs, this would catch networking problems and help the engineers optimize.

And there are failure tests where all sorts of bad juju is thrown at the engine to help flush out problems, including malformed inputs as part of the test.

In summary, record+playback is useful but in constrained ways that supplement living people instead of replacing them.
> 3 votes

---
Tags: input, testing
---


title: Drawing on XNA screen

text:
# Question
Title: Drawing on XNA screen
I need to use Microsoft.Ink library on XNA. Previously I used ink library on winforms application and drawing on the form screen is very easy and it looks pretty good. However, when I do the same thing on the XNA screen, the ink shows up for a 1 sec then it disappears or sometimes, it shows up but flashes. Is there a solution for that? Thanks for your help.

# Answer
well, it has to do with the way xna works vs win forms. In xna, the screen is updated every refresh, which is by default 1/60 sec. However, win forms are only updated when they're invalidated (something changes). What I would suggest you do is draw the ink to some kind of texture and just render that every frame to the XNA window. However, I would also suggest just using the XNA framework to draw anything anyway
> 3 votes

---
Tags: xna-4.0, hand-drawn
---


title: What is a "solver" in a physics engine?

text:
# Question
Title: What is a "solver" in a physics engine?
I am self-taught and have successfully coded simple collisions of planes, spheres, rays and up until interactive cloth simulations so I do have some basic sense of which part of the physics goes where in code; but no idea of the terminologies.

It's the jargon that I do not understand: What is a physics solver? How does a solver look like in code or which part of the engine is considered a solver?

For example what does the phrase "Box2d is using iterative solver" mean?

# Answer
Generally physics engines are split into two major parts: Collision detection and collision resolution. The solver is just responsible for the second part.

After your collision detection part determines which pairs of objects collide, and where, the solver is responsible for creating the correct physical response.

"Iterative solver" just means that the solver uses an iterative method to calculate those responses. It's iterative because you can, for various reasons, not calculate a completely physically accurate response in physics engines. Therefor these engines perform certain approximations (via numerical integration) to the correct physical response.

These approximations are done more than once per simulation frame (hence, "iterative") since it generally gets more accurate the more iterations of these approximations you have.
> 6 votes

# Answer
As far as I know, physics can be split up in two areas: Collision detection and resolving collisions / constraints. While the first one detects collisions, the seconds job would be to adjust bodies positions and velocities in order to (a) get them collision-free ASAP and (b) assure all their constraints (joints, etc.) are met at all times.

Note that I'm not experienced in developing physics engines. I work with the Farseer physics engine but mostly keep my hands off its code and just use it, so I'm more or less guessing here.
> 1 votes

---
Tags: physics-engine
---


# Question
Title: What are the dangers of self-teaching game development?
I am about to embark upon a journey into game development. Following answers to my last question, I will be using C# and XNA.

However, I don't personally know any other game developers and I don't work in the industry so, as such, will be self-taught. The exception to this is obviously the asking of questions and reading of online/printed information but I would still class this as being self-taught.

With that, I want to be prepared for issues that I may encounter through not having someone to "keep me under their wing".

As an analogy, when self-teaching myself to play guitar, I played the A major chord in such a manner that it made moving to a chord I learned later more difficult.

If you could share your lessons learned and advice on what might go wrong in my learning of game development I'd be grateful.

I am well aware that making mistakes is the biggest part of learning but, if there're mistakes I can be prepared for then I'd be happier with that.

# Answer
### Game development is like structural engineering

There are minimum requirements for functionality. The minimum requirements are not exceptionally challenging and many people can learn how to fulfill them. That's the **function** part. It's the small part. This is where the decisions of what language to use, platform to develop on, or what libraries to utilize come in.

The next part is the big part. The **form** part. Form is what really distinguishes the good games from the great games. This is the part that's the *art* of game development. I'm not talking about just the sensory assets (graphics, sound, etc?). I'm talking about crafting an experience. This is the hard part.

The function part comes from tutorials, libraries and a bit of time. Anyone can do it.

The form part comes from you. It's the passion that got you to want to make games in the first place. It's like telling a story, a made up story (or a true story you embellish, a lot). **The more you tell the story, the better it gets**. In software development we call it iterating. Your story is your code. The first time you tell it, it won't be very good. Things will be out of place, you'll realize that this bit should go there and that one here. You'll find that things will probably flow better if you arranged things this way or expanded on this bit. So, just like a good story, you'll tell it, gauge how good it is, and then modify it. This takes dedication and this takes time. Don't fret if the first thing you produce isn't gold. I have worked long and hard on many parts of my game only to rip them out later because I thought of a *much* better way of doing it. Don't worry about this, it's all part of the learning process. You always learn from your mistakes, and often making those mistakes is what leads you to the better way of doing things.

So what you should take away from this is this:

* Play test often.
* Don't get caught up on the function right now. Don't worry to much about optimization, or which library will be the best in the long run. Just get the minimum functionality, *then* iterate.
* Once the function is done, congratulate yourself, you're a small fraction of the way done.
* Wear sun screen
* This is a skill that takes time to develop, you know that from learning a musical instrument, this is no different, you will get better.
* Remember what you're in this for, the joy of creating! If things get boring, then switch to something else (try out some game jams to break-up your development time). But don't quit just because it's hard.
* The game development community here on SE is great. You'll find everything you need here. You can post a question or hop into chat and discuss your ideas.

The internet is full of feathers of information in blog posts, tutorials and communities like this one. Collectively, I'd say that's a pretty good wing to be under. Basically the dangers are not severe. You might do things the "wrong" or hard way for a while, but you'll learn eventually. You appear to have plenty of programming experience, so I think you'll pick up on the function part quickly. The mistakes made in game development and "regular" development overlap a lot. Your experience will help you avoid many of the common issues the befall new game developers. I think you'll do just fine. Good luck.
> 55 votes

# Answer
Yes, not having someone that have been there before to say to you what to do, how to fix, etc etc may be the worst thing you'll pass. But no fears! You still can read LOTS of blogs of people that have been there, they share their experiences in the industry, how they got into the success, how a previous game failed and why, etc etc.

Good examples are:

And lot's more!

My last sayings are: Don't fear. I'm self taught too, 4 years I've been introduced to game dev, lot's of barriers come, but nothing that you can't solve googling and reading some texts. Good luck on your journey :)
> 28 votes

# Answer
This attitude. This "don't touch it, until you know how to do it perfectly" attitude. That'll really hold you back.

You see this attitude among beginning developers of all kinds though - not just games. Websites as well. Hey, a website is a database with an html front end with some javascript. You learn the technologies any way you can, you put your first site together. It isn't going to be fantastical, but after *doing things in a sub-optimal way isn't a big freaking deal*!! If you do it "the long way" the first time around, you can always do it better the second time around. **My point is, there is no danger.** Except this attitude, perhaps. This attitude is what will **stop you** from ever making anything, because you will always balk at the task and say "I don't know how to do that yet."

The attitude that there is a "right way" to do things. There isn't. Things are exactly as they seem. You have to put pixels on the screen, and make sounds when things happen.
> 17 votes

# Answer
Depending on whether or not you want to make this your profession later on (Im just going to assume you're thinking about it and this isnt just a hobby thing), here's what I found to be extremely effective:

1. Start small

It's been said before, but i'll say it again - start with small bits, familiarize yourself with an engine, a framework, a tool or program. Once you got the basics down -\> go bigger.

1. Learn EVERYthing

This might seem a bit extreme, but what I mean is learn as much as you can about EVERY aspect of the game development - no matter whether or not you'Re a coder, artist or designer. Knowing the pipeline is key to building things in the most efficient way. If you're implementing a weapon -\> design it, concept it, model it, implement it, code it! You obviously do not need to be a Grade A concept artist,designer and Pipeline nerd - but you should be familiar with all the tools of the process, and understand each step of the creation. Also, check out the game websites for news and updates in the business - gamasutra.com, kotaku etc all have great articles on both business and technique topics. Don't limit yourself to just one field of development - soak up ALL the knowledge you can get :)

1. Fail often, fail hard.

You'll suck at what you're doing. In the beginning. It's always like that (believe me, I know. :D), but it'll get only better if you keep on going and NEVER cease to look for ways to improve your work. The internet is a great source for tutorials,references and help. You'll never be truly stuck, so embarge on the craziest ideas, fail, learn from your mistakes and become more badass with that process.

1. Talk to people!

While the internet is a great source, getting face-to-face feedback is something you'll have to deal with on the job ALOT. So improving your soft skills is important as well. If you don't have a mentor yet, or in general dont know too many people working in the industry then you should look around your area for indie dev meet ups, go to conventions, and check for other events where you can start to build a personal network of knowledge and contacts. It also helps to build something with other people - self-taught is great, but game development is a team-based game, so check the forums for hobby project - for example the Epic Forum for UDK projects, Unity forums or even the CryEngine Forums -all three of those engines are widely spread, there's a truckload of talented people working on side-projects there, and they're mostly also keen on learning new stuff.

I think that's pretty much all the advice I can give. I hope this helped you in some way :)
> 5 votes

# Answer
Somehow this is a great question! :-)

I've started my gamedev activity not so long ago, and it will be second time, so I can share my thoughts. You are actually right about that it's a good thing to have a mentor. This mentor will be the internet. So the more info is shared in internet, the easier it will be to learn for you. That's why XNA/C# is an excellent choice to start with. There is a lot of both amateur and professional indie gamedevs who is sharing articles and in the web. Other things to mention:

1. Go open source! Codeplex, GitHub, Google.Code, Bitbucket. There are a LOT of valuable things there.
2. Go to community! You are here, and it's a good thing. But also there is a large Microsoft XNA community with some good official stuff. Codeproject is also a good resource (however gamedev activity is rather low there).
3. You probably will need to read/watch a lot. Already mentioned before. Game development is not only coding. Game design is also important. Enthusiasm is important.
4. As usual don't try to bite to much at once, writing you own copy of tetris or breakout is actually a good idea.
5. It could be hard at start, game development is not only actually hard, it's also very different from say "enterprise" apps. There is a lot of new aspects, grapics, sound, etc. The more you go, the easier it gets (as usual).
6. Write a blog. Express your dev process (in this process you will find answers to your own questions), store links with comments to valuable articles.
7. Don't think your code is the worst thing you ever seen. Game code is harder to control, it's always somehow a little dirtier then whose pretty "enterprise" code. But I assure you, there I've seen some terrible creations (in terms of source code quality and game organisation) which were successful indie games. So, don't be to harsh on yourself, esp. at beginning.
> 3 votes

# Answer
I have no C# and XNA experience at all, but I think it won't make me wrong in the following statement:

It is perfectly fine to learn programming without a teacher. If your code works\*, it doesn't really matter how it was coded. Well, it does for collaborative programming, but then you won't be coding alone anymore, will you? It also may make your code less readable for you in future, making it hard to use old components or debug new errors, but in the long run all your mistakes will be your strengths. Hardest thing in learning OOP and MVC design is understanding why I should do "this" in "that way". If you already have experience making bad programs you will know the strengths of patterns and use them to your advantage. If you always made good programs by following patterns someone taught you, then You will keep making good (in sense of valid code) programs, but instead of taking advantage of the patterns You will be limited by them, as You won't understand them enough to make useful modifications. In the end, it is most important that you practice, not how, so in both cases sooner or later You'll get quite similar experience.

***one thing is important though!** In case of security You really should ask someone experienced if Your code is done well, as security holes don't popup error alerts.
> 2 votes

# Answer
This applies to about any discipline related to a creative industry:

The biggest danger is trying to build something 'too big' or 'epic' out of the gate.

For example, if you starting out at making some music you wouldn't start with trying to make a 50 piece 2 hour symphony.

In level design this manifests as trying to make the 'biggest map ever', or using the game system to build the largest most complex thing the game engine is capable of handling. In programming this can fall into 'making an entire game by yourself' starting with zero source code. You really need a lot of experience and discipline to start with zero source, and even then it is incredibly hard, and making design decisions over everything is hard the whole time you are working out the design of everything. Even a simplistic game requires a fairly large amount of programming in a modern OS and language these days. Also if you start with someone elses code you can learn what works and what doesn't work so well, so working with as many engines as possible is a huge plus as well.

So starting out I would recommend something like the following plans:

* Level Design: build a small room, build half a building, build a full building etc
* Art: make a hat for TF2 or something similary simple, or some texture replacements for Skyrim or some other bite size task to get started, before getting into skeletal or morph meshes and figuring out how to animate or paint them in zbrush them well.
* Programming: take an existing modable or opensource game engine, and modify some part of it (like a weapon), then make a new weapon. If you end up not liking the gameplay code, you could start hacking on the graphics engine.

The best thing to do would be to take an existing finished engine (either a modable one or some opensource one) and start hacking on it, and do that a few times to several different engines until you find one you like.
> 1 votes

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


title: List of Anti-Cheat Packages for MMOs?

text:
# Question
Title: List of Anti-Cheat Packages for MMOs?
i would like to start this topic for programs to counter-attack link text.

I am not aware of a big list but with everyone's help i hope to make this a fine topic.

Posting format:

**NAME:** nProtect GameGuard

**GAME TYPE:** any type of game

**Website:** http://global.nprotect.com/product/gg.php

**FEATURES?**

* Protect the users' PC from fast evolving hacking technologies and viruses.
* Real-time protection, diagnose various patterns latest hacking tools that can harm games, but also memory debugging prevention technology will be applied, completely blocking hacking tools through real-time hacking tool monitoring and blocking function.
* Blocks hacking attacks through memory scan
* Blocks online outflow of personal information

# Answer
> 1 votes
**NAME:** xTrap

**GAME TYPE:** any type of game

**WEBSITE:** http://www.wiselogic.co.kr/product4.htm

**FEATURES?**

Unfortunately I can't read korean and I havent found much information regarding this one but I've seen quiet an amount of games using it.

# Answer
> 10 votes
**Name:** Writing secure networking code.

**Game Type:** Any, but especially good for MMOs.

**Website:** Any real trusted networking standard, Writing Secure Code, and many others specific to your language.

**Features:**

* Fewer angry or confused users.
* No unexpected overhead due to poorly-written third party programs.
* Likely to have trickle-down effects improving the rest of your project's code.
* Cannot be defeated by kernel drivers, virtual machine trickery, or other well-documented undetectable methods of cheating.

# Answer
> 1 votes
**NAME:** PunkBuster

**GAME TYPE:** FPS

**WEBSITE:** http://www.evenbalance.com/

**FEATURES?**

* Real-time scanning of memory by PB Client on players' computers searching for known hacks/cheats
* Throttled two-tiered background auto-update system using multiple Internet Master Servers to provide end-user security ensuring that no false or corrupted updates can be installed on players' computers
* Frequent status reports (highly encrypted) are sent to the PB Server by all players and the PB Server raises a violation when necessary which causes the offending player to be removed from the game and all other players are informed of the violation
* PB Admins can also manually remove players from the game for a specified number of minutes or permanently ban if desired
* PB Servers can optionally be configured to randomly check player settings looking for known exploits of the game engine
* More ...

# Answer
> 1 votes
**NAME:** sXe Injected

**GAME TYPE:** FPS

**WEBSITE:** http://www.sxe-anticheat.com/introduccion

**FEATURES?**

* Anti-Wallhack
* LocalBan
* 16bpp Detection
* Screenshot
* Anti-Speedhack

# Answer
> 1 votes
NAME: X-Ray Anti-Cheat

GAME TYPE: multiplayer Steam games (Counter Strike, Team Fortress 2, ... )

Website: http://www.xraygaming.com/

FEATURES?

* X-ray uses state-of-the-art methods to protect you and your online gaming experience.
* It will periodically take screenshots of what you are seeing in-game
* It wwill scan for known cheats and bad processes in the background to help with cheat detection.
* When you are finished playing your game, X-ray will upload these screenshots to our servers, where our experienced admin team and massive userbase will help catch cheaters by reviewing screenshots and 'flagging' them if they appear suspicious.

# Answer
> 1 votes
**NAME:** FAIRPLAY by Use It Better

**GAME TYPE:** flash games

**WEBSITE:** http://www.useitbetter.com/fairplay

**FEATURES?**

recording gameplays to detect

* speedhacks
* non-human behaviors (bots and trainers)
* exploits
* memory and code attacks

# Answer
> 0 votes
**NAME:** HackShield

**GAME TYPE:** any type of game

**WEBSITE:** http://www.hackshields.com/

**FEATURES?**

* Memory Hacking Protection
* Speed Hack Protection
* Debugger Protection
* Auto Update

---
Tags: mmo, anti-cheat
---


title: How to invert background pixel's color

text:
# Question
Title: How to invert background pixel's color
I'm writing a game and map editor using Java and jMonkeyEngine. In the map editor, I've got a brush done by wireframed sphere. My problem is: I want to make it visible everywhere, so I want to invert color of the pixel "behind" this brush. I wanted to do it with fragment shader (GLSL), but I don't know how to get color of this pixel.

# Answer
> 19 votes
The quick and easy way to do this is to use the standard blending equation with the following parameters:

```
glEnable(GL_BLEND);
glBlendFunc(GL_ONE_MINUS_DST_COLOR, GL_ZERO);

```

If `src` is the source colour (the one from your new object) and `dst` is the destination colour (the one which is in the framebuffer) it will compute the new colour as follows:

```
new = src * (1 - dst) + dst * 0
    = src * (1 - dst)

```

So you just need to set `src = 1`, *ie.* white, and you will get inverse video. The GLSL fragment shader will be:

```
void main(void) {
    gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0);
}

```

---
Tags: opengl, java, shaders, glsl, jmonkeyengine
---


title: CG/CGFX to GLSL

text:
# Question
Title: CG/CGFX to GLSL
So, I'm making the painful move from my beloved XNA to OpenTK, and I'm stuck:

Since I've got a LOT of existing shaders written in HLSL, NVidia's CG compiler seems like a natural way to minimize the impact on my existing code.

I'm confused, however, about how to compile shaders that use techniques and passes rather than separate vertex and fragment shader programs. The cgc compiler seems to require that one specify an entry point for a shader. However, it's unclear what this means in terms of a shader that has multiple potential entry points without a main() function. For instance, the simple CG effect (an off-the-shelf CG effect created in the ever-flakey FX Composer):

```
/*

% Description of my shader.
% Second line of description for my shader.

keywords: material classic

date: YYMMDD

*/

float4x4 WorldViewProj : WorldViewProjection;

float4 mainVS(float3 pos : POSITION) : POSITION{
    return mul(WorldViewProj, float4(pos.xyz, 1.0));
}

float4 mainPS() : COLOR {
    return float4(1.0, 0.0, 1.0, 1.0);
}

technique technique0 {
    pass p0 {
        CullFaceEnable = true;
        VertexProgram = compile vp30 mainVS();
        FragmentProgram = compile f340 mainPS();
    }
}

```

The only way I can get this to compile with the cgc command line compiler is:

```
cgc -noentry test.cgfx

```

And,of course, I get no output other than a statement that the program was compiled without errors.

The NVidia docs say that the CG compiler can output GLSL if the appropriate profile is passed to the compiler. However, all of the profiles I've seen are either vertex- or pixel/fragment-specific, which seems to contradict the idea of having both in a single file, linked by the technique and pass definitions.

What am I missing here?

Note that I've been able to build this effect using the Cg runtime via the Tao.Cg stuff, but using that appears to require including the Cg runtime in my app distribution, and I can't see a way to make that work on OSX and Linux.

**Update** I've noticed that by specifying the vertex shader or pixel shader directly as an entry point, and including a `-profile glslf' or`-profile glslv\`, that I can get GLSL output for either shader, but this obviously doesn't include setting the state or take into account multiple passes or multiple techniques. Do I really have to run the compiler once for each function defined in the shader source?

# Answer
> 1 votes
CgFX files are *not* shaders. They are FX files. Shaders are a lower-level construct; a shader is *just* the source code for a particular shading stage. Techniques, passes, etc are all higher level than Cg.

You cannot process CgFX's FX data into GLSL because GLSL has no equivalent constructs (just as Cg itself doesn't). You can process the files themselves with `cgc`, but you have to select whether you're getting the vertex shader, fragment shader, or whatever out of the CgFX file. That's why you need to specify an entrypoint.

---
Tags: xna, opengl, glsl, hlsl, cg
---


# Question
Title: 2D AABB vs AABB Sweep : How to calculate hit normal?
I've implemented a 2D AABBvsAABB sweep cast into my game, however, I'm having difficulty calculating the hit normal of the sweep cast.

I have the sweep direction, both a and b AABB positions and xy min-maxs, first and last hit times to work with, but not the colliding edge(s) or normal direction. I just can't conceptualise an efficient solution to this specific problem. Any Ideas? :)

\*edit

This is what I have so far - just a general implementation of Gomez's and Christer Ericson's AABB sweep. There's no hit normal, so while the normal calculation is a mystery to me I'm unable to produce any collision response for my character controller.

```
bool SweepVelAABBvsAABB(AABB a, AABB b, Vector2 v, out Vector2 outVel, out Vector2 norm )
    {
        outVel = v; //Initialise out velocity
        norm = Vector2.zero;

        if( AABBvsAABB(a,b) ) return true; //return early if a,b overlap

        v = -v;
        float hitTime = 0.0f;
        float outTime = 1.0f;

        if(v.x < 0.0f) //sweep is going right
        {
            if(b.max.x < a.min.x) return false;
            if(a.max.x < b.min.x) hitTime = Mathf.Max( (a.max.x - b.min.x) / v.x, hitTime );
            if(b.max.x > a.min.x) outTime = Mathf.Min( (a.min.x - b.max.x) / v.x, outTime );
        }
        else if(v.x > 0.0f) //sweep is going left
        {
            if(b.min.x > a.max.x) return false;
            if(b.max.x < a.min.x) hitTime = Mathf.Max( (a.min.x - b.max.x) / v.x, hitTime );
            if(a.max.x > b.min.x) outTime = Mathf.Min( (a.max.x - b.min.x) / v.x, outTime );
        }

        if(hitTime > outTime) return false;

        //=================================

        if(v.y < 0.0f) //sweep is going up
        {
            if(b.max.y < a.min.y) return false;
            if(a.max.y < b.min.y) hitTime = Mathf.Max( (a.max.y - b.min.y) / v.y, hitTime );
            if(b.max.y > a.min.y) outTime = Mathf.Min( (a.min.y - b.max.y) / v.y, outTime );
        }
        else if(v.y > 0.0f) //sweep is going down
        {
            if(b.min.y > a.max.y) return false;
            if(b.max.y < a.min.y) hitTime = Mathf.Max( (a.min.y - b.max.y) / v.y, hitTime );
            if(a.max.y > b.min.y) outTime = Mathf.Min( (a.max.y - b.min.y) / v.y, outTime );
        }

        if(hitTime > outTime) return false;

        outVel = -v * hitTime;

        return true;
    }

```

# Answer
I've managed to come up with a simple and efficient solution by observing the separating axes.

```
// Sweep a in the direction of v against b, returns true & info if there was a hit
// ===================================================================
bool SweepBoxBox( AABB a, AABB b, Vector2 v, out Vector2 outVel, out Vector2 hitNormal )
{
    //Initialise out info
    outVel = v;
    hitNormal = Vector2.zero;

    // Return early if a & b are already overlapping
    if( AABBvsAABB(a, b) ) return false;

    // Treat b as stationary, so invert v to get relative velocity
    v = -v;

    float hitTime = 0.0f;
    float outTime = 1.0f;
    Vector2 overlapTime = Vector2.zero;

    // X axis overlap
    if( v.x < 0 )
    {
        if( b.max.x < a.min.x ) return false;
        if( b.max.x > a.min.x ) outTime = Mathf.Min( (a.min.x - b.max.x) / v.x, outTime );

        if( a.max.x < b.min.x )
        {
            overlapTime.x = (a.max.x - b.min.x) / v.x;
            hitTime = Mathf.Max(overlapTime.x, hitTime);
        }
    }
    else if( v.x > 0 )
    {
        if( b.min.x > a.max.x ) return false;
        if( a.max.x > b.min.x ) outTime = Mathf.Min( (a.max.x - b.min.x) / v.x, outTime );

        if( b.max.x < a.min.x )
        {
            overlapTime.x = (a.min.x - b.max.x) / v.x;
            hitTime = Mathf.Max(overlapTime.x, hitTime);
        }
    }

    if( hitTime > outTime ) return false;

    //=================================

    // Y axis overlap
    if( v.y < 0 )
    {
        if( b.max.y < a.min.y ) return false;
        if( b.max.y > a.min.y ) outTime = Mathf.Min( (a.min.y - b.max.y) / v.y, outTime );

        if( a.max.y < b.min.y )
        {
            overlapTime.y = (a.max.y - b.min.y) / v.y;
            hitTime = Mathf.Max(overlapTime.y, hitTime);
        }
    }
    else if( v.y > 0 )
    {
        if( b.min.y > a.max.y ) return false;
        if( a.max.y > b.min.y ) outTime = Mathf.Min( (a.max.y - b.min.y) / v.y, outTime );

        if( b.max.y < a.min.y )
        {
            overlapTime.y = (a.min.y - b.max.y) / v.y;
            hitTime = Mathf.Max(overlapTime.y, hitTime);
        }
    }

    if( hitTime > outTime ) return false;

    // Scale resulting velocity by normalized hit time
    outVel = -v * hitTime;

    // Hit normal is along axis with the highest overlap time
    if( overlapTime.x > overlapTime.y )
    {
        hitNormal = new Vector2(Mathf.Sign(v.x), 0);
    }
    else
    {
        hitNormal = new Vector2(0, Mathf.Sign(v.y));
    }

    return true;
}

```
> 6 votes

# Answer
Notice how the A's hit normal is `sum(Normals of Vectors of Edges on B involved in collision)`. In order words:

1. Find the edges involved on the object **we are colliding with**.
2. From get the vertices from those edges.
3. Sum the normals of those vertices.
4. Turn the resulting vector into a unit vector (normalise).

Remember that an 'edge' might actually be just one vertex (**we are colliding with** the corner on another box).

You will also note that this applies to **B**'s hit normal.
> 2 votes

# Answer
If I understand correctly, your algorithm so far finds the position along the motion of A at which A and B are just touching.

With that position, perform an one-dimensional intersection test between A and B on all three axes. One (or more in corner cases) of these axes will have no overlap; the hit normal should be parallel to that axis and in the direction from B to A.

If more than one axis has no overlap, then you have hit an edge or corner perfectly; you could either arbitrarily pick an option, or sum the results for a "rounded" corner.
> 0 votes

---
Tags: collision-detection, normals, aabb
---


# Question
Title: What is the best method to use to write and handle multiple levels?
I have a level class that does all of the updating and drawing and everything pertaining to the level. My question is, what would be the best approach to creating different levels? Should I just write them all in this single class which just chooses what to load and do depending on the level, or should I write each level in its own class that inherits from a base level class?

My code handles switching levels through the game's state manager...

```
void Game::change(GAMESTATE changeTo) {
  state = changeTo;
  load(state);
}

void Game::load(GAMESTATE loadState) {
  while(!currentState.empty()) {
    delete currentState.back();
    currentState.pop_back();
  }
  if(state == TITLE) {
    currentState.push_back(new Title());
  }
  else if(state == LEVEL) {
    currentState.push_back(new Level(&levelNumber));
  }
  else if(state == CUTSCENE) {
    currentState.push_back(new Cutscene());
  }
  else if(state == GAMEOVER) {
    currentState.push_back(new GameOver());
  }
}

```

\[edit\] For this question, let's assume I want to hard code the levels and don't want to use external files.

# Answer
Instead of hard coding them into the game, write a routine that would load your level from an external file such as a text file. This is the best way to do it and the way you really should do it. If you are worried about your level files being changed then encrypt them or something.

However, if you really want them to remain coded into the game itself then you would not want to make separate classes. Each level acts like a level so they don't need different classes, they should all just be instances of your level class, perhaps a vector. `vector<level> levels` would be one example. Then you could have another variable, say `int currentLevel` that would be used to access the level vector (I guess it could be a regular array if you wanted).

Upon further thinking, that would also create a huge quagmire. Inheriting from a level base class would probably be better for making a hard coded level. You would declare the level stuff in a base class, then inherit this and use that to fill in the numbers. `class LevelOne : public LevelTemplate` something like that. You could then use the default constructor to have the program initialize all the values.

Then have an array of pointers or a vector of pointers and utilize `new` to make the levels.

This throws other problems into the mix though. You should really consider loading from external files.
> 1 votes

# Answer
reasons to treat each level as a separate class:

* each level has special events in it (these usually relate to special effects sequences)
* some abilities are not allowed in specific levels even if the character doesn't lose them (the character can double jump in level2, but in level3 they can only single jump) explanation is a story thing.

problems with treating each level as a separate class:

* if the logic behind the levels is all the same (the 2 points above are not in effect) then all your doing is using inheritance to control construction which violates OOP practices.
* having to worry that the correct `child` is being used (though this can be a moot point if polymorphism is understood)

for the actual implementation unless your game uses either of the 2 points at the beginning you can just treat the loading of each level as a different method called by your constructor. for example

```
// in fileIO
ifstream input; // input stream
switch (map){
case 0:
    input.open("maps/Map0.txt", ios::in);
    break;
case 1:
    input.open("maps/Map1.txt", ios::in);
    break;
case 2:
    input.open("maps/Map2.txt", ios::in);
    break;
case 3:
    input.open("maps/Map3.txt", ios::in);
    break;
case 4:
    input.open("maps/Map4.txt", ios::in);
    break;
default:   // generate map
    break;
}
// parse file
// construct level based on parsed file

```

for without fileIO: it would look about the same, but instead the `input.open(...)` would be replaced with a method calls that performed the creation of the objects.

I have done this conversion in a project where I was paranoid about distributing my level files, but I realized that even though yes someone could go in and modify the files, and cheat in that regard I was not selling the game, and if they broke it trying to cheat that's their dumb fault.

Though this process does work, whenever I look back at that program it just feels like overkill paranoia, and possibly even breaking object-orientation
> 1 votes

# Answer
Definitely make subclasses that inherit from the base level class. This gives you full flexibility over what happens in each level without the code becoming exceedingly complex.

While you are building this game, always take note of all code duplication and other code smells you might encounter. It might make sense for some code to be part of the base class, or perhaps some levels subclass each other or really start reading in files for level data.

Depending on how different the levels are from each other, it might make sense to do like most game studio's do and have the levels run scripts. A powerful scripting language like Lua, Ruby or Python can significantly increase your versatility when building a level. They all have libraries that make it easy to embed them in your c++ project and have access to the objects therein. Since level-loading and basic level operations don't have real performance constraints, scripting language performance is not an issue.

Also, I'm not sure what your reasons are from being averse to loading files, but are you aware that it is possible to embed files in your .exe's and .dll's? This also goes for the script files, which can even be pre-parsed to further tamper-proof them.
> 1 votes

# Answer
I assume that the level is not too complicate, but very straight forwards enough to let this to flexibly happens. The level itself should not be a type of platformer-level, or angry bird-like level. That's it, the other things in a level can be easily done through normal approach.

Then for my thought, I would go for writing specific level in its own class but inherits from the base level class. Surely each level would have something different from others such as events, new enemies, background images, available weapons / items to use, etc, in order to tackle this we should allow for specific class to override the normal (or empty) behavior of the base class through **virtual** function. We added these kind of functions to cover differentiation that might happens. Those virtual function usually be provided for the following cases

* Initialization (different enemies via point info such as health point or spawn position or others AI/Gameplay related variables, different kind of resource to be used in such a level such as sfx or background image)
* Winning/Losing condition (1st mission needs to acquire 2 coins, but 2nd needs 3)
* Availability of weapons / items (1st mission, we won't allow to use rocket, but 2nd we're allowed)
* Events

Last thing is that be sure to put common / core things into a base class that allow flexible use for inherited classes.

**Anyway**, please be warned that if one of your team or yourself have already finished creating several level-specific classes, and right after that something is changed in a base class. It may effect all its child to be updated and corrected! (I think that the approach to load a level from external file usually needs only 1 main class file and handle everything inside, so it's trading off.)
> 0 votes

---
Tags: c++, level-design, levels, objects
---


# Question
Title: Absolute newb Java programmer seeks "dumbed-down" tutorials/resources
I understand the basics of Java and Object Oriented Programming so far, and am still working on refining my understanding of it. I have sought several different resources - two books and Oracle's own tutorials - but keep running into instances where the authors/tutorials explain things that assume understanding of the learner (like referencing arrays long before the basics are even finished being explained).

Throughout my efforts to gain a better understanding, I'm finding that visual presentations of the concepts and explanations (like trying to *picture* how the JVM is "thinking" through images).

It's difficult to summarize what I understand about programming, in general (I learned HTML and BASIC for the TI-83 calculators), but specifics to Java and beyond are, well, beyond me greatly. I need a resource, tutorial, IDE, or...something...that walks the learner *through* each step and makes little to no assumptions about the understanding the learner has about programming.

I'm also trying to see if there are any IDEs or drag-and-drop Android/Java programs (think Google's/MIT's App Inventor) that allow the programmer/learn to get started easily but still allows a great deal of flexibility in design while learning.

Last (and I apologize if this is a lot for one "question"), are there any advantages for me to be looking into an Android game engine at my level of Java programming skill (basically zero)?

Thank you.

# Answer
> 2 votes
No, there is not a drag-and-drop way to program, unless you're using a language specifically designed for drag-and-drop (which are not in any way easier than written programming, and can be nightmares).

No, you shouldn't be looking into making an Android game when you're an absolute newbie to programming in general and Java. Making a game isn't easy, so learn programming with more generic things first.

I can't answer your question about tutorials.

# Answer
> 0 votes
Besides the already mentioned great "Head First" book, you might also want to take a look at Bruce Eckel's "Thinking in Java". You already mentioned the Oracle Java Tutorials which are a good source of information in my opinion. Also take a look at the Javadocs of essential Java classes and try to read, understand and learn from the source code of existing Java projects. A book I always recommend when it comes to programming Java is "Effective Java" by Joshua Bloch, which will not help you at your current level, but will greatly improve your programming style after you understand the basics of Java.

Instead of using an IDE to help you learn programming in Java (I wouldn't know of such an IDE anyways), I'd rather recommend you to start using Java with a simple text editor (syntax highlightning should of course be supported). This way you have to do the essential stuff by hand - and that's the way to learn it.

---
Tags: java, android, editors, ide
---


title: Quaternion rotation

text:
# Question
Title: Quaternion rotation
I have a problem understanding quaternions rotation in OpenGL. So far I have implemented all function and operators related to quaternions.They are definitely working right!. However I can't find where I'm making the mistake within rotation function.

Let's say I have a a cube in 3d space at (xyz)`(1, 5, 2)` if I am not wrong the position in 4D is `p = 0 + i + 5j + 2k`, and the orientation and rotation `(0, 0, 0, 0)` in 4D space is `q = 1 + 0i + 0j + 0k`

Now I want to rotate it by 30 degrees along y-axis.

```
q = cos(a / 2) + (ix + jy + kz)sin(a/2)

```

So 30 degrees along y-axis is `q=0.96+0.25j` now:

```
Pout = q * Pin * con(q)

Q = q * Pin = (0.96 + 0.25j) * (0 + 1i + 5j + 2k) = -1.25 + 1.46 + 4.8 + 1.67

```

Shall I normalize it now or not?

```
conj(q) = 0.96 - 0.25j
Pout = Q * con(q) = 0 + 1.81 + 4.92 + 1.32

```

Normalized:

```
q = 0 + 0.33i + 0.91j + 0.22k

```

This is definitely the wrong answer according to this site

Rotating the object along the Y-axis by 30 degrees from a point `(0,0,0)` gives the correct result just by computing `q`. If I use the above algorithm and multiply it by `Pin` I get `(0,0,0,0)`

Can you show me how to do it right step by step?

Also how do I to orbit one point along another. Lets say I have the given point above and I want it to orbit around the point `(2, 10, -2)` using quaternions.

And when I manage to get the correct quaternion, how do I use it in the proper way along with openGL `glRotatef`?

So far my program runs like this:

1. Quaternion = x, y, z of object
2. Compute Rotation by X degrees along axes.
3. Quaternion to Axis Angle
4. `glRotatef` (by result of point 3)
5. Quaternion = result of point 2
6. Go to point 2
7. Go to step 1

Do I always have to change quaternions to Axis-angles, or is there another way which allow me to represent the rotation without conversion?

# Answer
Your computations **are correct**. Maybe you missed it, but here's your vector, rotated 30 degrees around the Y axis:

```
Pout=Q*con(q)=0+1.81+4,92+1.32

```

You **must not normalise** the result, that's all. Note that you seem to be having precision problems, because this is what I get:

```
             v = [1 5 2]
             q = [.965926 0 .258819 0]
            ~q = [.965926 0 -.258819 0]
     q * [0 v] = [-1.294095 1.483564 4.829629 1.673033]
q * [0 v] * ~q = [0 1.866025 5 1.232051]
            v' = [1.866025 5 1.232051]

```

If you want to orbit around a given point, just subtract that point from your source point, perform the rotation usings quaternion arithmetics, and add the point back at the end. Using your values above:

```
            p1 = [1 5 2]
            p2 = [2 10 -2]

   v = p1 - p2 = [-1 -5 4]
q * [0 v] * ~q = [0 1.133975 -5 3.964102]
            v' = [1.133975 -5 3.964102]

 p1' = p2 + v' = [3.133975 5 1.964102]

```
> 1 votes

# Answer
> Lets say I have a a cube in a point of 3d space (x=1,y=5,z=2) if I am not wrong the position in 4D is p=0+i+5j+2k orientation and rotation (0,0,0,0) in 4D q=1+0i+0j+0k now I want to rotate it by 30 degree along y axis.

Nothing in this statement after the words "if I am not wrong" made any kind of sense.

You do not use quaternions to encode positions (unless you're using dual-quaternions and you're not). A quaternion, for the purposes of graphics, is nothing more than a fancy way to encode a rotation matrix. It is just an encoding of an orientation in space.

So there is no quaternion position.

Since you're using fixed-function rendering, if you want to apply a quaternion to the matrix stack, then you do it by generating a matrix from it and applying it to the stack with `glMultMatrix`. If you want to rotate an object's position based on a quaternion, then you `glMultMatrix` the quaternion onto the stack, then `glTranslate` the position onto the stack.

And you should never "change quaternions to Axis angle". There is never any reason to do so.
> 2 votes

---
Tags: opengl, quaternion
---


# Question
Title: Normal Mapping for 3D-Like Lighting in 2D Games
I recently saw this video about a game engine that uses normal mapping to generate lighting and shadows for amazing, 3d-like lighting effects. (Like the three barrels below on the right side, they all use a single image, with lighting applied.)

After googling for some time and reading the articles, I'm not sure I understand exactly how this effect works -- that is, how I would implement this. It seems like you need your original image, plus a grey-scale "normal map", where the colour represents depth -- the "farthest away" pixels are black, and the "closest to the viewers" are white.

But even if I have this, how does this information combine with lighting to create that 3D effect?

Also, how would I use this information to create casted shadows (see bottom-left barrels in the picture below)?

# Answer
I believe the name of "normal map" may be misleading (i'm not sure), the image itself contains color information which anything can be stored inside R/G/B/A channel and finally name the whole texture to anything totally different.

Anyway please take a look at this similar question. The first comment inside the link below may interest you.

How is 2D lighting implemented?
> 1 votes

# Answer
It's close to the exact same as for 3D. If you aren't familiar with 3D graphics programming (including forward lighting, deferred shadong, normal mapping, and shadow mapping) then you should step back and study those topics first. They're all fairly easy; I'd argue that normal mapping is the hardest simply because you have to deal with tangent and binormal basis conversions, but they're just basic linear algebra.

From there, you need to do a few tweaks and simplifications to the algorithms. Assuming you aren't just using a full 3D engine will bill-boarded sprites, that is. First of course is to move from a 3D projection to a 2D projection (simulated using an orthographic projection matrix in a 3D stack combined with keeping all your objects locked in the XY place and oriented toward the positive Z axis). Basic 2D rendering stuff, nothing special at all, but with those 3D lighting algorithms applied in your shaders.

From there, you have a couple small tweaks to make. The most important is your light source location. If your lights are in the XY plane and your objects are in the XY plane and oriented perpendicular to that plane, the lights are going to look "weak". The lighting will look like you laid a flashlight on a table and are trying to light up pages of a book also laying on the same table. The tweak to make then is to simply move the light outward some distance; the distance chosen will need experimentation to find a nice looking value.

For shadowing, the change is to switch from a 2D shadow map to a 1D shadow map. For regular shadow mapping, you project a 3D light source location and direction onto one (or 6, for cube mapping) 2D shadow plane. In 2D lighting, you project a 2D position and direction (just an angle) onto a 1D shadow line. The line can represent the entire 360 degree circumference of the light's affected circle. The math is very similar; all just basic linear algebra. Once you have the shadow line (which contains distances of shadow-casting objects to the light, with each texel corresponding to a particle angle from the light), when rendering any other fragment in the scene, you need only calculate the distance and angle to the light to read from the shadow line and determine if the fragment is in shadow.

It's worth using deferred lighting in 2D, as scenes will generally have lots of lights that affect only a small portion of the scene. The algorithm is basically the exact same between 2D and 3D, expect you replace the planar shadow map lookup with the linear one.

I've yet to use this algorithm in an actual game, but I did build a nice tech demo that looked alright. I'm fairly sure that replacing my coder-art would have made it looked nice.
> 1 votes

---
Tags: 2d, lighting
---


# Question
Title: Calculating other objects based on the transform of another
What I want to do is create my graphics to be independent of the game framework. So basically the graphics won't know anything until it is told where things are. so the thought was that every GameObject would hold its own transform like here, but then I would also want to calculate the camera, and say a directional light based on these as well.

My thought was to in an update method:

1. receive a container of objects,
2. step through them to get the needed data to be rendered (full transform matrix, and enums resulting in model to be rendered, and texture/material to be applied)

3.0 put that data into something like a stack. 3.1. when the player object is found calculate the position of the camera behind/above the player at a determined downward angle, and a directional light in front of the player at the same orientation.

4. 4.in the render method pop the information off the stack to be rendered to the screen.
5. 5.possibly using the frustum of the camera to ignore some objects (can be overlooked)

I have gotten steps 1, 3.0 and 4 completely working, step 2 I can get the enums out, but I still don't know how to apply the transform matrix to be usable (answers to above link would be greatly appreciated), and then 3.1 is a total mystery to me. as stated 5 would be nice, but can be overlooked if not possible (formatting edit requested)

# Answer
You apply matrices in the vertex shader, you have to calculate it and pass it to the shader. You have the transform matrix, I'm assuming that's effectively your model to world matrix, maybe without scaling.

Then if you want to set up your camera, you'll need to have have camera translation and orientation in world space, it's a regular object, you can move it and rotate it as you like, this information is used to calculate the world to camera matrix, it's not anything hard if you understand matrix calculations. You apply this matrix after transforming from model to world space.

Now, you should have your vertices in camera space. Now you have to do perspective projection, this transforms vertices and effectively squeezes the back end of the view volume, you get a cube (an irregular cube, I don't know the English term, depending on how you set up your view volume), it's too complicated to explain the whole process here. Then you have to scale the view volume so it matches the homogeneous clip space, for DirectX it's \[-1, 1\] on the x and y axis and \[0, 1\] on the z axis IIRC. You don't have to know this, this whole transformation is a simple matrix, you just have to fill the appropriate fields correctly.

This homogeneous clip space gets transformed into NDC (it's a hardware operation, it divides x y and z of a vertex by w component, if you set up the projection matrix, this will achieve the actual projection and give you 3D space instead of 4D).

I'm saying all this to show you that calculating the camera is a non issue, you just set it up properly and calculate the world to camera matrix once per frame.

Also once you understand this transformation then frustum culling gets easy because the view volume is just an AABB in homogeneous clip space.

How you send this information to the renderer (as a stack or as a scene object) is up to you.
> 1 votes

---
Tags: c++, rendering, directx9
---


# Question
Title: 3D format or software that stores a vertex normal
At the moment i'm using .obj file format to store 3D models. It's popular, easy to read and parse. The issue is that it stores sufrace normals for each face. This isn't an issue for me yet, but i'm keeping in mind that i have to deal with lights once i'm done with the basics of my engine. This will require vertex normals and not surface normals. I want to avoid vertex multiplication and i want nice, curved surfaces. Blender seems to be unable to store vertex normals, only sufrace normals, is this typical of 3D rendering software and file formats?

Now i'm still kind of bad at profiling and i lack experience of what's "standard", but still i want to write effective code and i can't benchmark my ideas, so please excuse me asking weird questions here.

Is it "normal" to load surface normals from the .obj file and then for each vertex do an average of all the surface normals of surfaces that use this vertex (f.e. a plane "f " in .obj says vertex of index "i" has some normal "n", so i averate this normal "n" with the one already stored for this vertex)? This seems like such an expensive calculation to do when loading a model, is this the right way to think about it? Or is there a better way (or a file format/3D editor) to deal with this issue. Having multiple normals per vertex means that i have to duplicate vertices which is out of the question, not to mention that i'd get flat shading.

I'm mostly asking this because it seems illogical that a 3D model would be stored with surface normals that are very easy to calculate and not vertex normals which aren't easy to calculate and which are required for realistic lighting. Maybe it's a "legacy" thing?

---

Also, while we're on the subject, how do people deal with surfaces that have to be flat planes like a brick? For light calculations these models need vertices normals to be surface normals. but if i had a model like a knife that would consist of the blade that needs to be flat and the handle that i want round i would have to have the blade with duplicate vertices and the handle with not duplicate vertices which seems like a weird thing to request from my 3D softare (if it's even possible).

How do people deal with it, the only "smart" idea i can think of is to do separate models for flat objects (that would be stored in an innefficient way with vertex copies instead of indices) and separate models for round objets that would use the averating described above. The other idea is to have a program with a geometry shader in case i want to render a flat surface that would calculate a surface normal and set each vertex's normal to the one calculated and pass that to the fragment shader (though the extent of my geometry shader knowledge is a short article, haven't used them yet, is this even possible in OpenGL?).

I feel like i'm trying to brute force the issue, maybe there's a "magic" math trick that could help me or am i just stuck with more models or shader programs to manage.

# Answer
> 6 votes
Pretty much every mesh file format includes vertex normals, *including* .obj. If you're not getting vertex normals, then it would likely be because of how you're *exporting* the mesh, not the file format.

---
Tags: graphics-programming
---


# Question
Title: Collision detected on only the latest added tile
I'm making a 2D platformer and I'm using tiles as the ground. I have a Tile class and I'm loading the tiles with the help of a list in the main game class:

```
public static List<Tile> tiles = new List<Tile>();

```

The following is how I load the tiles from the list with 2 for loops in the LoadContent method:

```
for (int i = 0; i<=20; i++)
            tiles.Add(new Tile(Content.Load<Texture2D>("tile"), new Vector2(i * 16, 304)));
        for (int i = 0; i <= 10; i++)
            tiles.Add(new Tile(Content.Load<Texture2D>("tile"), new Vector2(i * 16, 288)));

```

Now, I wanna apply some kind of gravity and collision, still it's just something primitive. I'm applying these inside a Player class within a foreach loop like this:

```
foreach (Tile tile in Game1.tiles)
        {
            if (isInAir == true) { velocity.Y = 100f; }
            else { velocity.Y = 0f; }

            if (recBot.Intersects(tile.rectangle)) colBot = true;
            else colBot = false;
        }

        if (colBot == true) isInAir = false;
        else isInAir = true;

```

The issue is that the collision occurs only on the last loaded tile by the for loop in the LoadContent method. The sprite stops falling when it collides with the last added tile, but when I'm moving left or right and it intersects with other tiles, it doesn't apply the collision and it falls through them.

I'm kinda new to programming, so take me easy :) Any other things that you need to know, just tell me and I'll add more details or code!

# Answer
The problem here is that you are checking the collision for each of the tiles, and setting the single collision flag to true or false based on that. So if the player collides with the first tile, then colbot is true after the first tile. However, you then check the rest of the tiles, where there is no collision, and set colbot to false.

**Suggested solution:** set colbot to false *before* the loop, and remove the else from the intersection check (only check if it intersects, and set colbpt to true if it does).

Some additional tips: \- once you find a collision and set colbot to true, you could break out of the loop and not bother checking the rest of the tiles \- move the vertical speed check/adjustment out of the loop
> 2 votes

---
Tags: collision-detection, xna-4.0
---


title: Sphere and AABB intersection

text:
# Question
Title: Sphere and AABB intersection
I'm looking for an algorithm that will determine if a sphere is in any way touching an AABB or contained within it. Profile results indicate that this specific use is taking up a *large* percentage of my time, so it would be nice if it was as efficient as possible.

Edit: ATM, I've got this:

```
        bool IntersectsAABBWithSphere(Math::AABB rhs, Physics::Sphere sphere) const {
            // http://www.gamedev.net/topic/335465-is-this-the-simplest-sphere-aabb-collision-test/
            auto aabbcenter = (rhs.BottomLeftClosest + rhs.TopRightFurthest) / 2.0f;
            auto SepAxis = sphere.origin - aabbcenter;
            auto Dist = Math::Length(SepAxis);
            SepAxis = Math::Normalize(SepAxis);
            if( SepAxis.x >= SepAxis.y && SepAxis.x >= SepAxis.z )
                SepAxis /= SepAxis.x;
            else if( SepAxis.y >= SepAxis.x && SepAxis.y >= SepAxis.z )
                SepAxis /= SepAxis.y;
            else
                SepAxis /= SepAxis.z;

            auto extents = (rhs.TopRightFurthest - rhs.BottomLeftClosest);
            SepAxis.x *= extents.x / 2.0f;
            SepAxis.y *= extents.y / 2.0f;
            SepAxis.z *= extents.z / 2.0f;

            return Dist <= (sphere.radius + Math::Length(SepAxis));
        }

```

My AABB's are currently represented as min/max, and my spheres as origin/magnitude.

# Answer
> 1 votes
Found an SSE implementation in the paper and source code given here. Now that function has gone from 45% of my run-time, to so little I can't even find it in the list. win!

---
Tags: collision-detection
---


# Question
Title: What income models are available for Xbox games?
There are number of income models available for different games on various platforms - income from ads, paid games, paid DLCs, microtransactions and so forth. What sources of income are available for developers of Xbox games (both on physical discs, Live Arcade and Live Indie)?

# Answer
> 3 votes
This is not an exhostive list, and will ignore some extraneous things such as T-shirts, figures, posters, etc..., and any costs will be given in US$($1 = 80 Microsoft points) for MSRP, and will discount profit margin/cut, and distributor cut (some of these must be directly negotiated by medium)

Physical Media:

considering that the average Xbox game retails for $60 these usually are purchased by the retailer in bulk (1-10 thousand at a time) up front (independent on actual sales), and distributed among locations (usually 5-10 copies per location). Keep in mind that in order to release any physical media game on the XBox Microsoft must give it a green light, and to have it placed in any store requires that the owner give permission by purchasing them.

these can have digital material in addition to the physical media (see DLC for details)

XBox live:

* A full game that is released physically (that retails for $60) can be sold over Xbox live for $40 (though these can still sell for $60 depending on several factors that I will not address here)
* A smaller game (XBLA) can be sold for anywhere between $10-$20 these costs generally do not shift to often, but Microsoft can chose to put the game on sale at their discretion.
* A game that is on physical media, download, or XBLA can feature add-on content distributed through the Xbox live market place. (see below)

DLC:

* expansion/episode/add-on: a game can feature content on the Xbox live market place that increases functionality of the game (adding locations, abilities, levels, etc...) these generally cost $10
* map-packs: these simply add maps to a multiplayer experience. they cost from $5-$10
* themes: these modify the appearance of the Xbox, while on the dashboard. these generally cost free-$15

I am not directly sure as to if there are any direct influences from Microsoft for anything beside the general game. they have the right to not allow a game to be released for their system by just a single word.

As to the actual successfulness of any of these different options that will actually very from IP to IP, and could very well be dependent on the exact game. you could probably go and find the top sellers for physical media games, and downloaded games, and probably see that some game types sell better as physical media while others sell better as downloaded games. For a time it was sited that thousands of people were buying an Xbox360 just to play Bejeweled though this most likely will have changed.

Though this might not be what you wanted to hear, but like many things in popular culture the success, or failure of a given IP, or game can be determined not on its features, development time, or means of release, but on its ability to be that "flavor of the month" granted some IP/games have more of a staying power they are still just the current "flavor of the month".

---
Tags: xbox360, monetization, sales, microtransactions, xbox-live
---


# Question
Title: Why is 3D game development supposed to be so hard?
This may be kind of a dumb question. I have little experience in programming and no experience in game programming. I've only done simple "if, then" programming and simple circuit board chip programming. I do have experience with graphics software similar to 3DS Max. I was wondering what makes programming a game so difficult. All I want to create is a game world the size of a room with earth like physics such as gravity. More of a physics simulator than a true game. Would that be very difficult?

From what I've read it sounds like it would be difficult but I don't know why. I know the physics and have the graphics and rendering experience. Why is it supposed to be so difficult? Is C++ just really hard to learn or am I missing something. I'm curious because I'm considering learning C++ but don't know if it's worth it.

# Answer
It's difficult because creating the physics simulation is hardly any of the actual work. You also have to make sure it performs reasonably well, for example. Right now, I have an N-body physics simulation (roughly). Do you know how much code that takes up? About 1-200 lines of it deals with the physics. Do you know how much code I need to make it all happen? I think I'm up to 6-7k now and rising. There are so many things that you require to actually *make it usable* that don't occur to you when you're looking at the end product. Stuff like an octree so you can frustum cull objects. Classes for dealing with various meshes and effects. Classes for dealing with user input; for dealing with memory; for abstracting over the operating system; classes to render the user interface.

It's like looking at a house and saying "How hard can it be? All you do is stick a brick on top of another brick". There's plumbing, wiring, decorating, it has to be very carefully measured and specified and designed, etc.
> 5 votes

# Answer
Programming a game isn't all that **difficult**, but programming a game does require you to be very **meticulous** and games are often **elaborate** in their logic.

What you're building a simulation, not a game. Simulations are pretty simple, assuming that you've got a good grip on what you're simulating, and I think that you should be able to pick up enough C++ to build what you describe. You could even use Java or C#.

When people talk about the difficulty of making a game the discussion is almost always related to either the **sheer amount of details** that need to be taken care of or **building the logic** to handle what the design calls for.

Middleware and engines have become popular because they take care of some of those details for you (Unreal, Unity, etc...), plus have tools to help build the logic in some cases.

So to answer your questions: Games are considered to be difficult because they do a lot under the hood and since you have a handle on basic programming with if/else and loops and knowledge of your subject learning C++ will be easier for you and probably a good thing if you want to continue beyond just one room.
> 4 votes

---
Tags: 3d, software-engineering
---


# Question
Title: How to compute acceleration by using Kinect device joint positions
I have an application which uses the Microsoft Kinect camera device.

At each point I can obtain the position of my hand in the 3 Dimensional space ( X - Y - Z ) and I want to compute acceleration of my hand over each second on each axis.

Basically, I can obtain the coordinates at each frame(where 1 sec = 30 frames), and I want to compute the acceleration of my hand in 1 sec.

`StartPoint - (x1, y1, z1)`

`EndPoint after 1 sec from StartPoint ( 30 frames ) - (x2, y2, z2)`

`Acceleration between StartPoint and EndPoint = ?`

Also I can obtain all the other coordinates of my hand over time, but I want to compute the acceleration in the period of time between start point and end point.

Could you please explain or show me how?

# Answer
Suppose you have a sequence of positions for different times which could be summarized in a table

$$ \begin{array}{c|ccc} t & x & y & z \\ \hline t\_1 & x\_1 & y\_1 & z\_1 \\ t\_2 & x\_2 & y\_2 & z\_2 \\ \vdots & \vdots & \vdots & \vdots \\ \end{array}$$

then computing velocities amounts to compute the following differences:

$$(v\_{x,i},v\_{y,i},v\_{z,i}) = \frac{(x\_{i+1}-x\_{i},y\_{i+1}-y\_{i},z\_{i+1}-z\_{i})}{t\_{i+1}-t\_{i}} \\; .$$

Strictly speaking, these are mean velocities for the time intervals $\[t\_i,t\_{i+1}\]$. You could for instance associate them to the midpoint time of each interval $t^\*\_i=(t\_i+t\_{i+1})/2$.

From there the accelerations can be computed as

$$(a\_{x,i},a\_{y,i},a\_{z,i}) = \frac{(v\_{x,i+1}-v\_{x,i},v\_{y,i+1}-v\_{y,i},v\_{z,i+1}-v\_{z,i})}{t^\*\_{i+1}-t^\*\_{i}} \\; .$$

These could again be associated to midpoints \\$ t'\_i=(t^\*\_i+t^\*\_{i+1})/2 \\$.

Another approach would be to use some curve fitting techniques for your data points. For instance some Bézier curve techniques. This would have the advantage that you could then immediately define instantaneaous velocities and accelarations for any point in time you'd like.
> 1 votes

# Answer
Does it matter if your hand isn't moving in a straight line? For example, suppose you're moving your hand in a circle, do you just want the acceleration as defined by the magnitude of the speed? This matters because if you're moving your hand in a circle the acceleration is non-zero even when your hand is moving at a constant speed. This will be true for any curve.

If you want to ignore the direction your hand is moving in, and I would guess you do, then for each pair of \\$ (t, x, y, z) \\$ points calculate the distance moved using Pythagorus:

$$ds\_i = \sqrt{(x\_i - x\_{i+1})^2 + (y\_i - y\_{i+1})^2 + (z\_i - z\_{i+1})^2}$$

This gives you a squence of $(t, s)$ points where $s$ is the distance moved if the curve your hand moved in was unrolled along a flat line.

Assuming constant acceleration the equation you need to fit is then simply:

$$s(t) = ut + \frac{1}{2}at^2$$

You've probably used linear regression to fit a straight line to experimental data. To fit your data you need quadratic regression. The equations for this are a bit more complicated than for linear regression, but are easily programmed. I think I have C code lying around somewhere if you want it. Alternatively Googling for "least squares quadratic regression" finds lots of code snippets, or I bet asking on Stack Overflow would quickly get you some code to do the job.

The least squares fit gives you the best fit average acceleration (and initial speed if that matters) over your whole set of points. An alternative would be to just take three points and calculate the parabola passing through those three points. This is a lot simpler and quicker, but noisier because you don't get the averaging over a whole sequence of points. I found a Stack Overflow post giving the equations for this here.
> 1 votes

---
Tags: 3d, physics, kinect
---


# Question
Title: ID3D10Device creation failure in release mode
My ID3D10Device creation works fine in debug mode but I throws an error in release mode:

```
DXGI_SWAP_CHAIN_DESC scDesc = {0};
    scDesc.BufferDesc.Width = desc.width;
    scDesc.BufferDesc.Height = desc.height;
    /*scDesc.BufferDesc.RefreshRate.Numerator = 60;
    scDesc.BufferDesc.RefreshRate.Denominator = 1;*/
    scDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
    scDesc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
    scDesc.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;

    scDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
    scDesc.BufferCount = 1;
    scDesc.OutputWindow = desc.hWnd;
    scDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
    scDesc.Flags = 0;

    scDesc.Windowed = true;
    scDesc.SampleDesc.Count = desc.sampleCount;
    scDesc.SampleDesc.Quality = desc.sampleQuality;

    // Create the device.
    UINT createDeviceFlags = 0;
#if defined(DEBUG) || defined(_DEBUG)
    createDeviceFlags |= D3D10_CREATE_DEVICE_DEBUG;
#endif

    HRESULT hr;
    hr = D3D10CreateDeviceAndSwapChain(
        nullptr,
        D3D10_DRIVER_TYPE_HARDWARE,
        NULL,
        createDeviceFlags,
        D3D10_SDK_VERSION,
        &scDesc,
        &g_Renderer.m_DxCore.pSwapChain,
        &g_Renderer.m_DxCore.pDevice);

    std::tcout<<hr;

//////RUNTIME ERROR HANDLING
    if(FAILED(hr)) {
        throw std::runtime_error("ERROR: Failed to create ID3D10Device and IDXGISwapChain");
    }

```

I've already checked each of these options, but none of it triggers. http://msdn.microsoft.com/en-us/library/windows/desktop/bb205278(v=vs.85).aspx

The value of the hr seems to be -2005270527, after checking it with `std::cout<<hr` My debugger also can't show the value of hr when hovering over it, for some reason. :(

What could the problem possibly be?

# Answer
> 1 votes
The error code translates into DXGI\_ERROR\_INVALID\_CALL. A likely reason for that error is an invalid (or zero) window handle being passed in the `OutputWindow` parameter. Could you check that it is properly set in your release mode run?

# Answer
> 1 votes
You're not supposed to specify a refresh rate when the device is windowed.

# Answer
> 1 votes
Release mode runtime won't zero out allocations if I recall correctly, perhaps some of the parameters in scDesc are junk values that now need initializing.

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


# Question
Title: Implementing match-making & community system for multiplayer games
These days, games often have multiplayer portals with chat channels & match making system for the multiplayer aspects of the game.

An example would be battle.net, magic the gathering online's chat rooms, halo etc.

Now, for the rest of us indie gamers that probably won't be able to spend much development effort on creating those back-ends from scratch, what options do we have?

I was thinking of something along the line of using IRC as the backbone of the system. From there, implement the "community" aspect, player tracking, game tracking and match making on top of that. It seems to be what the old battle.net (brood war era) used to be.

The question is, is this easy to do? What does it take to run an irc server, and I suppose this also requires writing an IRC client (which seems to have been done a lot these days?)?

If there are other ways as well (say, an open framework for this stuff), let's hear them too.

# Answer
I wouldn't do this with IRC. IRC is straightforward and simple, but in the end is nothing but chat and some management commands, which is relatively simple to build yourself. I think EVE uses IRC for some in-game community stuff, but most games do not, despite looking similar.

There are a few APIs available to provide match-making and other social/community features. GameSpy is one, Steamworks also provides the functionality. OpenFeint and Scoreloop exist for mobile platforms and provide some social features (but I don't see an obvious mention of match-making in either).
> 5 votes

# Answer
Typically, if you're on the PC, you use Steamworks for a smaller game. Half the reason the indie game scene is rocking on the PC is because of Steam and Steamworks. Steam is an excellent sales platform and Steamworks is basically the best you can get.

If you're on a console, then the console manufacturer provides this functionality through Xbox Live/PSN/whatever.
> 4 votes

# Answer
I am from Skiller, we've developed SDK that enables developers to add social layer to their new or existing games, use turnbased or real time tools to make the games multiplayer, or generate more revenues using built in store. The SDK is for free, and you don't need to worry about server hosting, making sure the server is scalable etc... We take care of that. Try it out on www.skiller-games.com and tell me what you think.
> 1 votes

---
Tags: architecture, multiplayer, community-management
---


title: Variants of Entity Component Systems

text:
# Question
Title: Variants of Entity Component Systems
I've been reading up on these, and there seem to be two major variations which I'd like to understand better.

1. Entities should contain only data Components, which are processed by systems which contain the logic
2. Entities can contain data and behaviour components

What are the benefits of one over the other? Which scenario would be appropriate for which approach?

What about the other variations, such as message handeling entities/components?

For example, say I want to attach a certain AI behaviour to an entity, approach #2 would let me do that intuitively by simply adding it to the behaviours of the entity. With approach #1, I'm not sure how it would be done, possibly by attaching a data member specifying which AI to use?

Wouldn't the AI processing system turn into one big `switch(AI) { case AI_XYZ : AI_XYZ(); ...}`, as opposed to simply calling entity.AI(), or sending a message to the entity that tells it to update the AI...?

As with many things, there doesn't seem to be one "right" way to do this, trying them all doesn't seem feasible, I think most of the dis-/advantages wouldn't become apparent without implementing a sizable number of components and/or systems.

Personally, the message handling kind of components look appealing in a game context, simply being able to grab an entity and telling it to react to something, but I have no experience using such a system. I hope this question isn't too vague

# Answer
Data-only components are good for high performance systems as you can store all the data together and increase cache coherence for that particular system, meaning it should run well on a single core or a separate processor (eg. in consoles like the PS3).

The disadvantages, to me at least, is that it's not easy to code in a style that works well with completely independent systems.

There are many different variations on the component-based theme; rather than repeat myself too much I'll direct you to a past answer of mine here. But in general you have a choice of:

* "Inboard vs. outboard" which was covered above
* static vs. dynamic composition, which gives you either high performance + simpler code versus flexibility and data-driven objects
* data on component vs data on entity, which is a choice of better encapsulation and reusability of components vs simpler collaboration between components on an entity.

Whether the end result requires switch statements or function calls is really about the language rather than the system you use. But generally speaking if your data is handled by systems external to the entity, you wouldn't have the entity look at its own data to decide which AI system to call - each AI system holds a reference to the data of the entities it handles and updates them during its own update() call, and that's the whole point - the external systems handle everything, and the entity in that case is just a loose association of things handled by systems.
> 4 votes

---
Tags: entity-system
---