text:
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?

If you want to compute an acceleration based purely on positions, you'll need at least three points.

I can have as many positions as I want. I can have the position at StartPoint minus half second and for StartPoint plus half second and the same for end point. The only problem is that I don't know how to compute the acceleration given this input of the problem.

Speed is just a change in position divided by a time interval. Acceleration is a change in speed divided by a time interval. This already gives you a basic approach. But more elaborated ones could use some smoothing of the trajectory. If nobody answers before I come back, I'll post an approach.

Since this question has been migrated from Physics SE, but we don't have MathJax support like they do, you may see funky sequences of symbols below where there should be equations. As a workaround, paste the bit between the $$s into this sandbox to see a properly rendered equation.

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.

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.


text:
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.

Entities should contain only data Components, which are processed by systems which contain the logic
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

I like to think in terms of first-class functions - functions are data! You can use them sparingly in your components if you use that methodology.

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.

Thank you! Pretty much exactly the kind of overview I was looking for

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
C++ Namespace vs Reference passed around like crazy - Implement a quest journal
May sound funny, but that's what the question is about.
Suppose you have this situation:
http://i48.tinypic.com/whl6pk.jpg
Red squares are data types. Hexagons are methods and Journal is the main issue here. Or more exactly, how the link between Game and Journal should be interpreted. Basically, a lot of game components (instantiated inside of Game) will have to gain access to the Journal functionality. The two options that I have thought of myself are the following:
Journal could be a namespace w/ 'globally' used methods and fields. Something like:
journal::AddEntry(someEntry);

OR I could make Journal a Class, just like Game, and instantiate it inside of Game, and then pass a reference to Journal to each property of Game that needs to use the journal. Something like:
  GameProperty *property = new GameProperty(&ourJournal);
  //...inside of property:
  Journal *referenceToJournal;

But then, if I'd delete referenceToJournal, the actual ourJournal object would be deleted too, right?
I'm pretty sure this just complicates things by a lot, and having lots of references towards the same object is a bad habit.
I'm kind of thinking that the:
namespace Journal
{
//Fields and methods go here
}
...
#include "Journal.h"
Journal::method();

is the best way to achieve global visibility for the Journal without much stress. But it kind of hurts, since I come from a C# & XNA background where everything is object oriented. Which is the main reason I have thought of a:
class Game()
{
void loadcontent();
void update();
void draw();
}

logic.
How would you attempt to achieve given the scenario? Instantiate a Journal inside of Game and then constantly pass a reference to Journal to all the other game components (instantiated inside of Game), or just treat everything (including Game) as namespaces to provide 'global' access to all required components?
I'm also thinking about classes with public static fields and methods, but that'd be just like namespaces, at least from my point of view.
Here is some more supportive code, to better describe my view on things (pseudocode for the namespace idea):
//FILE Journal.cpp (implementation of Journal.h)
namespace Journal
{
struct JournalEntry
{
    INT QuestID;
    String Description;
};

Vector<JournalEntry> Entries;

void AddEntry(JournalEntry theEntry)
{
    Entries.Add(Entry);
}

/*
* Used at getting all text that has to be shown on the
*/
Vector<String> GetDescriptionsForEntriesWithQuestID(INT theQuestID)
{
    Vector<String> Descriptions;
    foreach (JournalEntry jEntry in Entries)
    {
        if (jEntry.QuestID == theQuestID)
        {
            Descriptions.Add(jEntry.Description);
        }
    }
    return Descriptions;
}
};

//FILE GameComponent.cpp implementation of GameComponent.h
#include "Journal.h"
void GameComponent::ShowInfo()
{
Vector<String> info = Journal::GetDescriptionsForEntriesWithQuestID(3);
//go through the collection and do stuff
}

Thanks!

My first instinct is that you've got a mistaken assumption hiding in the sentence 'Basically, a lot of game components (instantiated inside of Game) will have to gain access to the Journal functionality.'  Why will a lot of game components need access to the journal?  The way you've laid it out, journal entries should only be coming from your 'story manager' or equivalent; information the player learns about NPCs can come from this, information they learn about objects can come from this, etc.  At worst, it feels like you should hang the journal methods off of your core Player class somewhere and be making calls along the lines of Player->AddJournalEntry() (which will then call to the journal class behind the scenes, of course).  Regardless, the upshot is that 'lots of game components' needing access to this fairly specialized entity is a good sign of a design error somewhere else in the chain.

Good point. Perhaps implementing an Observer design pattern? So that each game component that needs to add something to the journal sends an event that eventually propagates up to Game which then calls the this->Journal->AddJournalEntry()?

And because I did not answer to the first part: what I meant by a lot of game components is something that includes most objects on the map. Doing something, say, with a rock, adds something to the journal.

'Doing something with a rock adds something to the journal' - that's fine, but that doesn't mean that it's the rock's responsibility to add the journal text.  Instead, it could easily be the action that the player takes (or the player itself) that queries the rock and says 'do you have journal text to add?  If so, what?'.  That way the rock is responsible for its content (the journal text) but the player is still responsible for the activity.

What's more, even the content responsibility can be taken away from the rock and given to a 'journal text manager' which knows about the objects in the world and keeps e.g. a table from objectID to JournalText.  This has the advantage of leaving all your text in one place for proofreading and localization if need be.

Makes sense. All text content will be found in separate files assigned to particular objects. Thanks for your answer, it was indeed enlightening in the matter. I'll mark it as good.

@StevenStadnicki Was commenting on your first comment on this answer, but my comment turned into an answer. Added this comment to notify you and make sure I interpreted your comment correctly.

+1 - Adding the journal functionality to the Player class allows you to implement a multi-player addition much easier as well, as each player will have potentially differing quests.

Well, namespace are more to organize code, and a journal seems to me better as a class.
To help you out, you could use C++ references (Journal& myJournal) and also use the theory of "whoever creates, is the same one that deletes". That is, if your Game new'ed Journal, it should delete it too, no other object should bother about deleting it, Game should.
This works very well, and avoid memory leaks, since you know who should delete it, and you don't get confused about where to delete it.
And just one plus: Namespaces are just names. a static global and namespace members are just the same on compiled code.

delete Object; when the Object has a reference to Journal, then the reference won't be altered in any way (the reference would be a private member Journal *journal;, right? I won't be adding delete journal; in Object's destructor.

Yeah, the memory will still untouched unless you put a delete journal. And I'd really think you should take a look at the reference types. (just use & instead of *), this way, you have a reference that you dont have to bother about deleting or newing around.

This started as a comment on Steven Stadnicki's comment, but grew too big so I figured might as well answer it fully.
As for your question on whether to use a class or module-type thing with a namespace, I don't think it actually matters. Rid yourself of this need to constantly be object-oriented! Whether you should use a namespace or some kind of global/singleton/dependency-injected class depends on how you're using namespaces in general.
If you'd have multiple journals loaded at one time with different state, then yes it should be a class. Otherwise, it might be unnecessary. I presume that the general flow for setting up and using the journal is something like this:
On game startup:
  Initialize Journal (either Player.Journal = new Journal(); or Journal::Initialize()).
    This should grab memory that the journal needs to do work
  On game startup, Journal load quest data from disk for lookup by ID
  On saved-game load, Journal loads quest data for the current player
  During gameplay, Journal accepts queries and operations to lookup quest info or add quests to current player's journal
  On saved-game unload, flag all player-specific data as "dirty" or reset on the spot
  On game quit, Journal cleans itself up

For games where you'd only have a single Journal (ie: no multiplayer, sync or async), the namespace approach is perfectly valid so long as it fits within your scheme of namespace usage. You could also make a class with entirely static members. The differences are subtle and not worth thinking about. There's fundamentally little difference between calling Journal* journalInstance = new Journal(); ... delete journalInstance; and Journal::Init(); ... Journal::DeInit();. You're just allocating  and initializing memory, manipulating it, and then freeing it.
Now for my commentary on Steven's comment. I might have misinterpreted what you were getting at, I apologize and please let me know so I can edit this to make more sense. This approach doesn't seem to be that flexible in the long run. If I'm following your logic correctly, this means that for any sort of system like this related to any system that may be a part of the player, you'd need to add a check to the list of things that happens when the player interacts with an object. Say you wanted a rock that would add something to your journal and give you a buff. That's an extra conditional in the Interact() function. "Do you have journal text to add? Do you have buffs to apply to the player?" Now what if you have another rock that adds a buff to the player, but also triggers a cutscene. Now you have "Do you have journal text to add? Do you have any buffs to apply to the player? Do you have a cutscene to play?" This will get out of hand.
It would make more sense to me to make AddJournalEntryOnInteract a behavior/component which would be in charge of calling the Journal functions. That way you could add as many sorts of components as you'd like that could respond to a player interact. If there's only ever one Journal ever, then hiding Journal functions behind the player class seems like it's adding unnecessary overhead. This would make sense in multiplayer, since each player would have their own journal, but if this is single player, that's not really necessary to do and just adds one more set of functions to your player class that don't need to be there.
The implementation could be, that in your scene data, you give this rock a list of components that respond to Interact();. When the rock is Interact()ed with, it iterates through all of its components that respond to Interact(); and each has the opportunity to do their thing like adding content to the journal, buffing the player, triggering a cutscene, or whatever.
EDIT
One point I forgot to mention about the Journal namespace vs class thing, is that you'll likely find it easier to create and use mock journal objects if you want to do unit testing with a mocked Journal.
ANOTHER EDIT: But then again, what's so bad about include guards?

Thanks for the great reply! I was thinking about a pseudo-scripting language for the dialogues and stuff. Say, rock 1 will be assigned file dialogue_rock1.script which will have a format like say_player: Something; say_NPC: Something here too; play_cutscene: CutsceneID; etc. I am going to spend some more time planning the whole game logic. I'm also considering switching to C# and XNA, as C# is my main programming language. I was planning on making this game for about 5 years, and the point is to get it done, so the easier it is, the better.

I think that simplifying it down to just an Interact() function might be a little too tight, but I do agree with the notion that a component-based approach is an excellent plan here; having the rock implement a Journalizable component in some fashion.  I think this makes the code a bit cleaner, but I would be worried about the data management aspects if there's a lot of text hanging around; as I suggested in my answer, my gut instinct is that you don't actually want the rock to be directly responsible for its text, but rather to have all the quest text in one place somewhere.

But of course, the rock could load its text from the appropriate spot and be responsible for presenting it when asked.

@SteveStadnicki I agree, I don't want to have some rock having responsibility for the data, so I'd want it to refer to a questID that's in some database-type-thing. I can agree see that Interact() is a bit too simplistic on its own. Bogdan Marginean: A design like this could still work if you had a scripting system for cutscenes. Scripts are just data, after all.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Is there a definitive reference on Pinball playfield design?
I'm looking at designing tables for Future Pinball but I'm not sure where to start as I've little background in game design per se. I've played scores of pinball tables over the years so I've a fairly good idea of what is "fun" in those terms. However, I'd like to know if there is a definitive "bible" of pinball design as far as layout and scoring/mode design goes. I've looked but there doesn't seem to be anything really coherent that I could find. Is it simply a lost art or am I missing some buried gem?

This seems akin to asking if there is a definitive “bible" of first-person-shooter design. Pinball is just a genre/type of arcade game which became popular and was copied in the same why fps games were among video games. The design of pinball games was likely more stable than that of video games due to the complexity and inherently higher cost of developing new mechanical game elements vs. digital game elements. Each player has their preferences as to what would qualify as definitive elements of pinball machine design. Some would swear by the early machines with no computerized components, others are going to think the almost seizure-inducing 1992 The Addams Family /// machine was the culmination of pinball design, and I’m sure someone out there at some point swore that adding paddles was heresy and they shouldn’t mess with the design of Bagatelle.
The only other element of design is profit. This is likely a stronger influence to pinball design than anything else. It’s easier and much more cost effective to use the same mechanical elements in many machines just in different configurations and with different themes/graphics. So once they hit on something that worked it was copied many times over. These common elements are what define “pinball”. As for scoring it is mostly just a way to compare relative skill and the particular mechanics of scoring is generally irrelevant as long as a better player scores higher. Scoring systems also has economic implications as well as discussed here: http://cheaptalk.org/2009/11/17/the-economics-of-pinball/
You’ve played lots of machines, you know what you like, and you know what you find fun, I’d suspect you might also have an idea of what you haven’t seen but think might be fun. You know how you define “pinball.” Game design, be it classic arcade or modern computer games, is about what is fun, and is always a matter of taste and opinion. Just use your own experience and try to make something you would find fun.

There is a bible for FPS design, or rather rules to make gameplay more fun and let a level work. I came here (like 16 other upvoters) to search for some design mechanics and possible illuminate pitfalls before spending many hours on 3D models. There is not much  info on this matter it would be nice, if there is any, to put it here.

There was a program called Pinball Builder where you could build your own pinball games based on different layouts. This would be good for planning and designing ideas. The program is old so it may be hard to find.
I'm not sure if there is a definitive set of rules for designing a pinball game. Flippers, bumpers and ramps are the main things that signify the genre, I guess if you have them you have a pinball game?


text:
How can I stop my Jitter physics meshes being offset?
I'm developing a C# game engine and have hit a snag trying to add physics. I'm using XNA for graphics and Jitter for physics. I am trying to split the XNA model into it's meshes, then create a ConvexHull for each mesh. I then attempt to combine those into a CompoundObject, this however isn't working and depending upon the model the meshes are offset by different amounts.
This is the code I'm currently using and it gives me:

Any ideas?

Hey Ben, if you figured this out by now you can add it as answer and accept it.


text:
XNA: Networking gone totally out of sync
I'm creating a multiplayer interface for a game in 2D some of my friends made, and I'm stuck with a huge latency or sync problem.
I started by adapting my game to the msdn xna network tutorial and right now when  I join a SystemLink network session (1 host on PC and 1 client on Xbox) I can move two players, everything is ok, but few minutes later the two machines start being totally out of synchronization. When I move one player it takes 10 or 20 seconds (increasing with TIME) to take effect on the second machine.
I've tried to :
Create a thread which calls NetworkSession.Update() continuously as suggested on this forum, didn't worked.
Call the Send() method one frame on 10, and the receive() method at each frame, didn't worked either.
I've cleaned my code, flushed all buffers at each call and switched the host and client but the problem still
remain...
I hope you have a solution because I'm running out of ideas...
Thanks
SendPackets() code :
    protected override void SendPackets()
    {
        if ((NetworkSessionState)m_networkSession.SessionState == NetworkSessionState.Playing) //Only while playing
        {
            //Write in the packet manager
            m_packetWriter.Write(m_packetManager.PacketToSend.ToArray(), 0, (int)m_packetManager.PacketToSend.Position);
            m_packetManager.ResetPacket(); //flush

            //Sends the packets to all remote gamers
            foreach (NetworkGamer l_netGamer in m_networkSession.RemoteGamers)
            {
                if (m_packetWriter.Length != 0)
                {
                    FirstLocalNetGamer.SendData(m_packetWriter, SendDataOptions.None, l_netGamer);
                }
                }
            m_packetWriter.Flush();//m
            m_packetWriter.Seek(0, 0);
        }
    }

ReceivePackets() code :
    public override void ReceivePackets()
    {
        base.ReceivePackets();

        if ((NetworkSessionState)m_networkSession.SessionState == NetworkSessionState.Playing) //Only while playing
        {
            if (m_networkSession.LocalGamers.Count > 0) //Verify that there's at least one local gamer
            {
                foreach (LocalNetworkGamer l_localGamer in m_networkSession.LocalGamers)
                { //every LocalNetworkGamer must read to flush their stream
                    // Keep reading while packets are available.
                    NetworkGamer l_oldSender = null;
                    while (l_localGamer.IsDataAvailable)
                    {
                        // Read a single packet, even if we are the host, we must read to clear the queue
                        NetworkGamer l_newSender;
                        l_localGamer.ReceiveData(m_packetReader, out l_newSender);
                        if (l_newSender != l_oldSender)
                        {
                            if ((!l_newSender.IsLocal) && (l_localGamer == FirstLocalNetGamer))
                            {
                                //Parsing PacketReader to MemoryStream

                                m_packetManager.Receive(new MemoryStream(m_packetReader.ReadBytes(m_packetReader.Length)));
                            }
                        }
                        l_oldSender = l_newSender;
                        m_packetReader.BaseStream.Flush();
                        m_packetReader.BaseStream.Seek(0, SeekOrigin.Begin);
                    }
                }
                m_packetManager.ParsePackets();
            }
        }
    }

What FPS is your game running at when this happens?

As far as I can tell this code shouldn't work for more than 1 vs 1. It says here (http://msdn.microsoft.com/en-us/library/bb975947.aspx) that sending the packet clears it. This does however means you can simplify the code a little to remove the (probably) superfluous flush and seek to zero

I have a few suggestions :

Shouldn't you handle network updates on every frame ?
What's your status of GameTime.IsRunningSlowly ?
Did you try to profile your application ?

Here are some links for you :
The Indiefreaks Game Profiler for Xna is here! this one might be of interest
What Are Some Good .NET Profilers?
Plus, on Visual Studio you have Menu Analyze -> Launch Performance Wizard

you definitely don't want to send network updates every frame. That's a fantastic way to overload router buffers and introduce massive latency.

+1 : Yes you're certainly right. What would you do then, every N frames or something ?

@Martin While you don't want to send network updates every frame you should call Update() on your session every frame in XNA to keep your session in sync.


text:
D3D11 Multiple Render Targets
I wanted to try rendering to multiple render targets as a first step to deferred shading, but I'm getting somewhat peculiar behavior where the contents of all render targets are the same as the first one.
So far all the render targets have the same format.
The relevant snippets from the shaders are:
//geometry rendering
struct PS_OUT {
    float4 diff : SV_TARGET0;
    float4 norm : SV_TARGET1;
    float4 spec : SV_TARGET2;
    float4 uv   : SV_TARGET3;
};

PS_OUT PS(PS_IN input)
{
    PS_OUT output;
    output.diff = mytexture.Sample(mysampler, input.uv);
    output.norm = input.normal;
    output.spec = float4(input.pos.xyz, 1);
    output.uv = float4(input.uv, 0, 1);
    return output;
}

//"compositing" with fullscreen quad
Texture2D diff;
Texture2D norm;
Texture2D spec;
Texture2D uv;
SamplerState mysampler;

PS_IN VS(VS_IN input)
{
    PS_IN output ;
    output.pos = float4(input.pos,1);
    output.uv = float4(input.uv, 1, 1);
    return output;
}

float4 PS(PS_IN input) : SV_TARGET
{
    float4 diffuse = diff.Sample(mysampler, input.uv.xy);
    float4 normal = norm.Sample(mysampler, input.uv.xy);
    float4 specular = spec.Sample(mysampler, input.uv.xy);
    float4 uvw = uv.Sample(mysampler, input.uv.xy);

    return normal;
}

Sorry for the long post.
Now, the weird part is, if I return any of the sampled colors alone, like for example the normal, the first G-Buffer "channel" gets drawn to the screen instead. (Even if the normal channel is the only one I sample).
However, if I return this instead: 0.0001*diffuse + 1.0*normal + 0.0001*specular + 0.0001*uvw then it does return the actual normal channel.
This 0.000*diffuse + 1.0*normal + 0.000*specular + 0.000*uvw however results in just the diffuse being drawn again.
There are no Info or Warning or Error messages from the debug layer, turning the debug layer off doesn't change anything either.
Could the HLSL compiler possibly be optimizing the Sample calls away since the result is not used, and then removing the texture objects alltogether since they are not sampled from?
PS, if you think seeing how I create and assign the render targets etc will help, I will add it. I just didn't want to make the post any longer.

Could the HLSL compiler possibly be optimizing the Sample calls away since the result is not used, and then removing the texture objects alltogether since they are not sampled from?

Yes, this is exactly what it will do.  Shader compilers are very aggressive about optimizing away unused code, parameters, and objects.
If you're binding the textures by index in your C++ code (e.g. diffuse to texture 0, normal to texture 1, etc.) that would explain this behavior.  When diff is not used, the shader compiler will likely assign norm to texture 0.
There are two ways to fix this.  You could provide explicit bind points (registers) in your HLSL, like:
Texture2D diff : register(t0);
Texture2D norm : register(t1);
Texture2D spec : register(t2);
Texture2D uv : register(t3);

This tells the compiler to always assign norm to texture 1, even if diff is unused, for example.
Or, you could use the D3D11 shader reflection API (or the Effects 11 API, if you're using it) to look up the shader parameters by name; then you can find out which bind point the compiler assigned to each texture parameter, and bind the correct texture to that register.

Yes, I have an array of ID3D11ShaderResourceView* gbuffer_rv[4] that I bind with PSSetShaderResources(0, 4, gbuffer_rv). Specifying the registers in the shader seems to be the easier, quicker fix for now. Thank you!


text:
How to make a beam follow a path in xna
I'm making a 2D shmup with XNA 4.0 and one of the weapons in the game that I want is a laser beam that follows a path or a series of points and will smoothly beam along the path.
How would I go about achieving this?

This is way too broad of a question. What do you have so far? Have you tried anything? Perhaps you have some code that isn't quite achieving the result you desire but almost?

You've got to google around a bit and try it on your own first. SO is not in the business of hand-holding, sorry.

Is http://gamedev.stackexchange.com/questions/29424/what-are-the-maths-behind-raiden-2-purple-laser what you're looking for?  This question covers the 'bendy laser' that shows up in some shmups.

Try using a Queue of (x,y) coordinates. I don't know if you'll need to do it dynamically or at compile time, but you should be able to figure something out either way.
Are you wanting the laser to follow curves as well, or just connect the dots? If its the first option, you're gonna need to do some math too.

Yes I want the laser to follow a curve.  I have been playing around with some code and I can make lasers go in a straight line just fine so far.

And does it need to go exactly through every point, or would a best-fit curve work?

Also, do we know anything about the nature of the curve? Is it going to depend on user input? I.e, is the equation of the curve going to be ever-changing? If so, you're fairly screwed here without some extremely complex math.

no it doesn't have to go through every point.  And I have never here of a best fit curve until now.  But i'm assuming that it would take the shortest path from start to end.

Kind of. It's calculated using what called the 'least squares method'. An explanation of that method would be out of the scope of this answer, and it too requires some pretty high-level math (at least in nonlinear situations). Last question: where are you getting the points from? Do you have an equation for them, or are you just coming up with them yourself?

I'm planing on using the xna curve class to get the points between the player ship and an enemy that is on screen

I was about to mention that I'm almost positive XNA will have something to do it for you. I haven't worked a lot with XNA so I couldn't think of one. But I do remember curve. So do you need help implementing the curve class or can you get that part on your own?

I can implement the class I actually use it for enemy patterns in my game so I can handle that.


text:
Disposing of ContentManager increases memory usage
I'm trying to wrap my head around how memory management works in XNA 4.0
I've created a screen management test and when I close a screen, the ContentManager created by that screen is unloaded.
I have used ANTS Memory Manager to look at how the memory usage is altered when I do this, and it gives me some results which makes me scratch my head.
The game starts with loading two textures (435kB and 48,3kB) which puts the usage at about 61MB. Then, when I delete the screen and runs Unload on the ContentManager, the memory usage drops to 56,5MB but instantly after goes up to 64,8MB.
Am I doing something wrong or is this usual for XNA games? Do I have to dispose of everything the ContentManager loads seperatly or do I need to do something more to the ContentManager?
Thanks in advance!

I suppose it all depends on what actually happens after screen deletion. In general all (at least standard) resources loaded by Load<T> method of ContentManager are automatically disposed, so you need to dispose additionally only any other resources.
P.S. Even simple CLR Profiler allows you to see what objects actually allocated in memory, that's what profilers are for! Why not to see it yourself?


text:
Animating isometric sprites
I'm having trouble coming up with a way to animate these 2D isometric sprites. The sprites are stored like this:
(Game Folder Root)/Assets/Sprites/(Sprite Name)/(Sprite Animation)/(Sprite Direction)/(Frame Number).png

So for example,
/Assets/Sprites/Worker/Stand/North-East/01.png

Sprite sheets aren't really viable for this type of animation. The example stand animation is 61 frames. 61 frames for all 8 directions alone is huge, but there's more then just a standing animation for each sprite. Creating an sf::Texture for every image and every frame seems like it will take up a lot of memory and be hard to keep track of that many images. Unloading the image and loading the next one every single frame seems like it will do a lot of unnecessary work. What's the best way to handle this?
The reason I am not using a sprite sheet is because these sprites are hi-res images with many animations which all have a large quantity of frames. The resulting sprite sheet would be massive. In case you're wondering, here was my implementation of creating animated sprites.
// Animation class declaration
class Animation
{
public:
        Animation(std::string path, int frames);
        ~Animation();
        void nextFrame();
        void gotoStart();
        bool loadFrames();
        sf::Texture& getActiveFrame();

private:
        int frameCount;
        std::string pathToAnimation;
        int currentFrame;
        sf::Texture frame[];
};

// Animation class implementation
Animation::Animation(std::string path, int frames)
{
        pathToAnimation = path;
        frameCount = frames;
}

Animation::~Animation()
{
        // destructor
}

void Animation::nextFrame()
{
        if(currentFrame < frameCount)
        {
            currentFrame = 1;
        }
        else
            currentFrame += 1;
}

void Animation::gotoStart()
{
        currentFrame = 1;
}

bool Animation::loadFrames()
{
        for(int i = 01; i < frameCount; i++)
        {
            if(!frame[i].loadFromFile(pathToAnimation + std::to_string(i) + ".jpg")) return false;
        }
        return true;
}

sf::Texture& Animation::getActiveFrame()
{
    return frame[currentFrame];
}

// Actor class declaration
class Actor
{
public:
        Actor();
        ~Actor();
        void setActiveAnimation(std::shared_ptr<Animation> anim);
        void draw(sf::RenderWindow& win);

private:
        sf::Sprite sprite;
        std::shared_ptr<Animation> activeAnimation;
};

// Actor class implementation
Actor::Actor()
{
    // constructor
}

Actor::~Actor()
{
    // destructor
}

void Actor::setActiveAnimation(std::shared_ptr<Animation> anim)
{
    activeAnimation = anim;
    activeAnimation->gotoStart();
}

void Actor::draw(sf::RenderWindow& win)
{
    sprite.setTexture(activeAnimation->getActiveFrame());
    win.draw(sprite);
    activeAnimation->nextFrame();
}

It's still not 100% where I'd like it to be but it's working and it's pretty easy to use.

You don't need 61 frames for a animation. Most should look really smooth with 16 frames already. (Depending on how long the animation is of course.)
It's huge, yes, but the computer has a huge amount of memory too. A 100MB (= a enormous amount of data) is a little nowadays.
Load them once and keep them. Its not "per Frame", its once.

You would not want to load/unload a texture after each frame. This is because it would involve accessing the hard drive each time. This takes a very long time compared to accessing memory and you would certainly see a slow down in rendering. So what you want to do is to load all of the textures into memory.
If we have 60, 32x32, rgba8 textures for each 8 directions, this is about 2MB. So we can see that it really isn't that much memory.
(You could just keep each texture in memory and swap around, but the following is the more "correct" way to do it)
I believe you are using SFML, I haven't used it personally but after searching there is a class you can use just for this purpose, an sf::Sprite. This is just the same as rendering an sf::Texture, however you need to pass it a texture to start with. What's the difference? Well you need to pass this sprite a rectangle in the texture to use. So you say this sprite will use this part of the texture.
This is better because we can make one big texture with all of our sprites on and reference each sprite individually. It means we do not have to swap textures after each frame (this is expensive for the GPU to do).
Of course this means that you will have to add all of your separate sprites into one texture before you load them. It also means that you need to know the rectangle that each sprite occupies. After a quick google search you could use this SpriteSheetPacker; it outputs a final texture and a .txt file that gives you where each sprite is located.

In sfml, an sf::Texture is simply an image that we load into memory. The object we use to actually display the image and do things with it is sf::Sprite. I could use sf::Sprite::setTextureRect as you said if I were using a sprite sheet, but I stated in the edit why I chose not to do so. Thanks anyways.

Rather than loading and unloading the textures on a per-frame basis, one possibility would be to load all the frames for a certain animation at once. For example, if you're about to play the attack animation, load all the frames for the attack animation(s) into memory if they aren't already there (checking whether the animation already exists in memory would have to be managed by a texture manager or some similar construct).
Another (probably better) option would be to combine all frames for a specific animation into a single animation-specific spritesheets, which is what Jeff Vogel from Spiderweb Software does for his 2D isometric RPG games. For example, you might combine all the defense animation frames (for all directions) into a single spritesheet, all the running frames (for all directions) into a single spritesheet, etc. Jeff's code is proprietary so I'm not sure how he handles the loading and unloading of the sprite sheets, but his games have good performance, and this approach strikes a good middle ground between having a single colossal spritesheet and having tons of single frames.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Is there a repository of game logic algorithms?
I'm writing my first 2D game, and I'm writing some tracking logic for the computer enemies. Basic follow-the-player tracking was easy, but ineffectual. Too easy to escape. So I'm trying to implement some more sophisticated flanking and other tactics, and (as expected) it's pretty tricky. This is a topic I know nothing about.
I'm going to keep trying, but it'd be awesome to have some examples or tips to work off of.
Is there any place that has a decent set of pseudocode AI algorithms, or tips or advice on the subject, e.g. for 2D tracking?

Oh, yeah, I forgot. I should've totally asked this there. Can a mod migrate this?

Just flagged it for a mod to review. Hopefully they'll help shortly. :-) Good luck. (Just for future reference: StackOverflow is not a link engine - questions about where to find things aren't appropriate to ask here.)

http://www.gamasutra.com/category/programming/

Try Matt Buckland's book.  He overuses templates, but it's still a good book

A great book is Artificial Intelligence for Games, Second Edition, and you can find the code repository here.

What kind of game logic are you looking for? Pathfinding? FSM? Genre-specific logic (RTS, FPS)?
Take a look at Alive.

At the moment I happen to be seeking (As I said?) 2D tracking logic . . . like to make a computer enemy effectively chase the player. Alive isn't really what I was looking for...I'm hoping for help in algorithm design. I can't even really tell what Alive is from it's very poor project description. Thanks anyway though.

Searching for 'steering behaviours' on gamedev.stackexchange.com might help. The steering behaviours can be combined to form more complex behaviour, e.g. flanking would be avoiding the player while moving towards a spot besides the player.

http://aiwisdom.com is run by Steve Rabin, an accomplished game logic engineer (editor for the AI Game Wisdom series of books, and coordinator for the AI dev panels at GDC).  Unfortunately it mostly just contains summaries of the articles in the books themselves, which can be a bit hard to get a hold of these days.  That said, if you can get a copy of the books, they are quite excellent.
http://aigamedev.com is also a good resource.
I also agree with integeruser's answer.  The book he mentions is quite good for someone just starting out.


text:
Is it possible to extract textures or sprites from compiled game files?
For instance, every map in Portal has what appear to be sprites over a texture indicating the obstacles you'll face (see screenshot). Are these resources compiled into the source as byte code, or is it possible to extract them from installation files? Obviously I understand copyright implications, and I am only interested in using it for a recreational project. Instead of recreating them, I wonder if they can be extracted.

You can save yourself a lot of trouble and just download them here.
But as for your question. It totally depends on the game, but usually they are not compiled into the source as byte code. Often times they are available in the resource files found in the same directory as the game install. But really there's no definitive answer on this. Theoretically the texture files will always be extract-able, it just depends on how much work you want to devote to it.

Thank you for posting that resource! Of course, it would still be nice to know the answer to the question :)

Textures (and other resources like models or sounds) are mostly in big games like Portal "compiled" in some sort of data packs in byte form. It would be really hard (if it would be possible) to get them.

@zacharmarz Of course it would be possible, but it doesn't mean it would be practical. So yes, really hard.


text:
Fastest pathfinding for static node matrix
I'm programming a route finding routine in VB.NET for an online game I play, and I'm searching for the fastest route finding algorithm for my map type.
The game takes place in space, with thousands of solar systems connected by jump gates. The game devs have provided a DB dump containing a list of every system and the systems it can jump to. The map isn't quite a node tree, since some branches can jump to other branches - more of a matrix.
What I need is a fast pathfinding algorithm. I have already implemented an A* routine and a Dijkstra's, both find the best path but are too slow for my purposes - a search that considers about 5000 nodes takes over 20 seconds to compute. A similar program on a website can do the same search in less than a second.
This website claims to use D*, which I have looked into. That algorithm seems more appropriate for dynamic maps rather than one that does not change - unless I misunderstand it's premise.
So is there something faster I can use for a map that is not your typical tile/polygon base? GBFS? Perhaps a DFS? Or have I likely got some problem with my A* - maybe poorly chosen heuristics or movement cost? Currently my movement cost is the length of the jump (the DB dump has solar system coordinates as well), and the heuristic is a quick euclidean calculation from the node to the goal.
In case anyone has some optimizations for my A*, here is the routine that consumes about 60% of my processing time, according to my profiler. The coordinateData table contains a list of every system's coordinates, and neighborNode.distance is the distance of the jump.
    Private Function findDistance(ByVal startSystem As Integer, ByVal endSystem As Integer) As Integer
    'hCount += 1
    'If hCount Mod 0 = 0 Then

    'Return hCache
    'End If

    'Initialize variables to be filled
    Dim x1, x2, y1, y2, z1, z2 As Integer

    'LINQ queries for solar system data
    Dim systemFromData = From result In jumpDataDB.coordinateDatas
                           Where result.systemId = startSystem
                           Select result.x, result.y, result.z

    Dim systemToData = From result In jumpDataDB.coordinateDatas
                             Where result.systemId = endSystem
                             Select result.x, result.y, result.z

    'LINQ execute
    'Fill variables with solar system data for from and to system

    For Each solarSystem In systemFromData
        x1 = (solarSystem.x)
        y1 = (solarSystem.y)
        z1 = (solarSystem.z)
    Next

    For Each solarSystem In systemToData
        x2 = (solarSystem.x)
        y2 = (solarSystem.y)
        z2 = (solarSystem.z)
    Next
    Dim x3 = Math.Abs(x1 - x2)
    Dim y3 = Math.Abs(y1 - y2)
    Dim z3 = Math.Abs(z1 - z2)

    'Calculate distance and round
    'Dim distance = Math.Round(Math.Sqrt(Math.Abs((x1 - x2) ^ 2) + Math.Abs((y1 - y2) ^ 2) + Math.Abs((z1 - z2) ^ 2)))

    Dim distance = firstConstant * Math.Min(secondConstant * (x3 + y3 + z3), Math.Max(x3, Math.Max(y3, z3)))

    'Dim distance = Math.Abs(x1 - x2) + Math.Abs(z1 - z2) + Math.Abs(y1 - y2)
    'hCache = distance
    Return distance

End Function

And the main loop, the other 30%
'Begin search
    While openList.Count() != 0
        'Set current system and move node to closed
        currentNode = lowestF()
        move(currentNode.id)

        For Each neighborNode In neighborNodes

            If Not onList(neighborNode.toSystem, 0) Then

                If Not onList(neighborNode.toSystem, 1) Then

                    Dim newNode As New nodeData()
                    newNode.id = neighborNode.toSystem
                    newNode.parent = currentNode.id

                    newNode.g = currentNode.g + neighborNode.distance
                    newNode.h = findDistance(newNode.id, endSystem)
                    newNode.f = newNode.g + newNode.h
                    newNode.security = neighborNode.security

                    openList.Add(newNode)

                    shortOpenList(OLindex) = newNode.id
                    OLindex += 1

                Else

                    Dim proposedG As Integer = currentNode.g + neighborNode.distance

                    If proposedG < gValue(neighborNode.toSystem) Then
                        changeParent(neighborNode.toSystem, currentNode.id, proposedG)
                    End If

                End If

            End If

        Next

        'Check to see if done
        If currentNode.id = endSystem Then
            Exit While
        End If

    End While

If clarification is needed on my spaghetti code, I'll try to explain.

This might do better on the game development stack

A few thoughts without digging too deep into your code. Are you checking the same node twice if you come across it again during the search? Also, does your profiler say anything about your LINQ structures? I'm not very familiar with LINQ but I suspect it adds some overhead, especially since you're using it on every node. In addition, I also noticed that you're using for each statements only to assign variables which means those variables will only take on the last value in the list. Why are you doing this?

@RichardMarskell-Drackir: In regards to use of LINQ, I found that the overhead of using it in my hex-grid path-finding (see below) was less than * 2. It really only had an effect on the PrioirtyQueue, where a hand-rolled MinHeap was somewhat faster than a DictionaryQueue as inspired by Eric Lippert (at the cost of not providing a stable sort, so I use one at short range, and the other at long range.).

I don't know if would be viable but you can get a lot of performance by precalculating the routes and caching for each system the best path to each other. probably would use a lot of space.

Without looking at your spaghetti code, I can say you are doing something drastcically wrong. I have adapted Eric Lippert's C# A-star algorithm to a hex map of ~ 420x750 hexes (~ 133,000 hexes total), and the longest diagonal path determination takes about 3 sec.
A profile analysis would almost certainly identify the performance culprit quickly, as you are off by at least an order of magnitude. Likely candidates are your closed list, so check your hashing algorithm. I used x<<16 ^ y.
Hmm! Where is your closed-list lookup? I can't find it. That wold explain poor performance.


text:
What is the better approach to redraw a static background scene for game?
Take for an example I have the background scene of a game which should remain static for an interval.Then for every time redrawing the scene,is it better for me to store the color buffer for every pixel on the viewport and redrawing using the stored color buffer or to applying a texture to the whole background or to draw the triangular,quad meshes?

In short:
If you are developing for a modern machine, you usually can redraw everything that should be on the screen, the only exception being images that are difficult to compute/are computed once every few frames because of perfomance hit.
Detailed: Try rendering the static parts just like the dynamic. Premature optimization is the root of all evil, and you should generally avoid it. Measure the timings, and there's huge chance you won't even need to cache the background at all.
If, however rendering the background is expensive, you should use FBO to store the data. The method of putting it back on the screen depends on the type of game you're writing, however textured quad rendered with basic fragment shader shouldn't be too slow compared to direct pixel-copy. It will also allow you to reduce the size of the background, if you feel that storing whole screen is too much.

+1; definitely just redraw the entire scene every frame.  It's not going to be a performance problem - honest! - and GPUs are intended to be used this way anyhow, so it will likely be much faster than trying anything clever or tricksy to avoid doing so.

Assuming you can draw on the buffer effectively and you're using a 'clean' scene (only the stuff you want in the background permanently) to render the initial background, using the buffer should be a faster way of rendering the composite scene.  This is especially true if the background isn't a simple image file but rather a separate redering.  Even if you are just using a bilboard image in the back of the scene, rendering the polygons and textures to the image buffer is much higher up in the graphics pipeline.


text:
Blender - creating bones from transform matrices
Notice: this is for the Blender 2.5/2.6 API.
Back in the old days in the Blender 2.4 API, you could easily create a bone from a transform matrix in your 3d file as EditBones had an attribute named "matrix", which was an armature-space matrix you could access and modify.
The new 2.5+ API still has the "matrix" attribute for EditBones, but for some unknown reason it is now read-only.
So how to create EditBones from transform matrices? I could only find one thing: a new "transform()" function, which takes a Matrix too.

Transform the the bones head, tail, roll and envelope (when the matrix
  has a scale component).

Perfect, but you already need to have some values (loc/rot/scale) for your bone, otherwise transforming with a matrix like this will give you nothing, your bone will be a zero-sized bone which will be deleted by Blender.
if you create default bone values first, like this:
bone.tail = mathutils.Vector([0,1,0])

Then transform() will work on your bone and it might seem to create correct bones, but setting a tail position actually generates a matrix itself, use transform() and you don't get the matrix from your model file on your EditBone, but the multiplication of your matrix with the bone's existing one. This can be easily proven by comparing the matrices read from the file with EditBone.matrix.
Again it might seem correct in Blender, but now export your model and you see your animations are messed up, as the bind pose rotations of the bones are wrong.
I've tried to find an alternative way to assign the transformation matrix from my file to my EditBone with no luck.

this is exact duplicate of http://gamedev.stackexchange.com/questions/31959/getting-bone-base-and-tip-positions-from-a-transform-matrix

This question appears to be off-topic because it is about Blender, not game development. Blender questions should be asked on the Blender stack exchange.

This is currently my problem too. You can't set matrix property, and I only have a transform matrix.


text:
Big level objects collision system for 2d game
I read many variants today and get some knowledge in general, so here is a steps of mine thoughts in pictures (horrible paint.net ones).
We need to develop grid system, so we check only thing near, perform simple check to cut out deep check, and at - last deep check like per-pixel collision check.

Step 1 - Let p1, p2 are some sprites lets first just check with circle collision - because large distance between p1, p2 this fails and of course so we don't need test more deeply. But if we have not 2, but 20 objects, why we need to even circle test something so far outside of our view.
Step 2 - Add basic column system, now we don't bother with p2 if it's in a column far from p1 column, so we even don't do circle test. But p3 is in the same col, so let do circle test, which of course will fail.
Step 3 - Lets improve column system to the grid system with grid cell size just like p1, p2, p3 collision boxes, so we cut out things much top or below p1. And this is all great until comes BIG OBJs which is some kind of platforms. They are much bigger then grid cell.

Circle test for will be successful, but deep check for whole big obj will fail
And that the part I can't get.
How do I store the grid position of big object? Like 4 grid coords for big object vertexes? And if one of them close to p1 do circle check for centre of big object then a deep one if succeed? Am I do it wrong?
My possible solution:

your solution link is broken

Personally, I think you should do away with the grid system. Since you have all circles, you should add the radii of two circles together. If the distance between two circle's center points is equal to or less than the radii calculation, you have a collision.
Other option for keeping a grid system:
Instead of checking to see if another object (such as P3) is in the same row and column as your current object (P1), you should check if P3 lies within P1's grid(s) position(s) and also check to see if P3 lies within neighboring grid positions to P1, or positions surrounding them. Then if it's in the same row/column or in a neighboring one, you could check for circle collision. This all depends on how you setup your rectangles for your objects. Many people actually put their rectangles outside of the object rather than inside so that the whole circle (plus a small amount of surrounding area) will collide. This will not always result in a perfect collision, but could give you a more desirable result since other objects won't be inside your object.

This collision implementation seems backwards, in all honesty, but maybe you may have specific reasons for it.
Is there any particular reason why your first pass is to check if circles are touching?
As far as I know, finding collisions between circles can be taxing because of the use of square roots.
Instead, you could use a bounding box for every object on the grid. The box dimensions are dictated by the greatest x and y dimension of an arbitrarily-oriented object.
During every frame, you check to see if there are any collisions between the bounding boxes (which shouldn't be too bad performance and complexity-wise). If there is a collision, you then perform a sub-check of two objects in question and see if the ACTUAL objects are colliding.

You don't need to take the square roots.. you can compare squared lengths. Circle vs. circle tests are about even with AABB tests when it comes to performance (even slightly faster). But generally it's best to chose the shape that closely encompasses the majority of the shapes you use in the game.. so if you have lots of rectangular objects, it's more efficient to use AABB tests instead of circle vs. circle, because it will trigger a in-depth collision test much less frequently...

Thanks for the info. I forgot about the distance squared comparison.
However, this problem set, according to what you're saying, could still benefit from a conversion to AABB because the majority of the shapes seem to be rectangles.

You should take a look at quad trees. Its a common datastructure to store spatial data in cells. When you do the collision testing, you simply test against the objects in the same cell...
I use the same datastructure for rendering. I pass the rect that defines the viewport into a selection method of the tree and receive a list of cells. Now i just have to render all sprites from those nodes...
When the object spans over multiple cells ,you can add it to both cells. Just make sure to remove the duplicates ,when you use the results from the selection method. I'm currently on my phone, so I have no code examples here ,but a quick google for quadtree should help.

Big or small, if an object exceeds one pixel it could show up in multiple grid squares.  You have to put it in multiple lists.


text:
How to take advantage of multiple core GPUs
I'm interested in developing for the new Nexus 7 tablet when it finally arrives.  I've done a little OpenGL development for Android but I'm not sure what I have to do to take advantage of the 12-core GPU on the Nexus 7.  Does OpenGL take advantage of the cores for you (in some/all cases); if not, how do I specify which core does what, synchronize between them etc?

have you read "NVIDIA 3D Vision Automatic Best Practices Guide" http://developer.download.nvidia.com/whitepapers/2010/3D_Vision_Best_Practices_Guide.pdf

GLES2 (OpenGL) pretty much forces you to use vertex buffer objects and shaders to do any rendering.  That's a good thing because it means you are using the GPU correctly and keeping battery life high by keeping information off the power hungry transfer busses.  You don't have to worry about using the entire GPU because those shader units automatically divide up the rendering tasks based on the geometry of your render windows.
http://developer.apple.com/library/ios/#documentation/3DDrawing/Conceptual/OpenGLES_ProgrammingGuide/TechniquesforWorkingwithVertexData/TechniquesforWorkingwithVertexData.html
That's a link to Apple's site, but it will be the same practices for Android.
To the above who says using OpenCL kills battery life, this video speaks differently.  It's a demo of the PowerVR GPU using OpenCL on the CPU, then on the GPU.  It shows power consumption during the examples where they do image processing.
http://www.youtube.com/watch?v=sDrz-w1jzEU
Running benchmark apps will kill your battery, actually using OpenCL to perform tasks efficiently and quickly will keep power consumption down.

Yes, OpenGL spreads the load over all available cores on the GPU. To be more exact, the videocard driver spreads the hardware-specific implementation of the OpenGL commands over the cores. I read here that the Tegra 3 chipset by NVIDIA has 8 pixel shader units. That's not a lot compared to desktop videocards, for instance my NVIDIA GeForce GTX 560 Ti card has 384 CUDA cores.
I wouldn't worry about spreading your commands across all available cores, that's well into driver territory. Unless you're using OpenCL on Android, but that's ill-advised because it will eat up your battery like crazy.


text:
importing animations in Blender, weird rotations/locations
This is for the Blender 2.6 API.
There are two problems:
1. When I import a single animation frame from my animation file to Blender, all bones look fine.
But when I import multiple (all of the frames), just the first one looks right, seems like newer frames are affected by older ones, so you get slightly off positions/rotations.
This is true when both assigning PoseBone.matrix and PoseBone.matrix_basis.
bone_index = 0

# for each frame:
for frame_index in range(frame_count):
    # for each pose bone: add a key
    for bone_name in bone_names: # "bone_names" - a list of bone names I got earlier
        pose.bones[bone_name].matrix = animation_matrices[frame_index][bone_index] # "animation_matrices" - a nested list of matrices generated from reading a file

        # create the 'keys' for the Action from the poses
        pose.bones[bone_name].keyframe_insert('location', frame = frame_index+1)
        pose.bones[bone_name].keyframe_insert('rotation_euler', frame = frame_index+1)
        pose.bones[bone_name].keyframe_insert('scale', frame = frame_index+1)

        bone_index += 1

    bone_index = 0

Again, it seems like previous frames are affecting latter ones, because if I import a single frame from the middle of the animation, it looks fine.
2. I can't assign armature-space animation matrices read from a file to a skeleton with hierarchy (parenting).
In Blender 2.4 you could just assign them to PoseBone.poseMatrix and bones would deform perfectly whether the bones had a hierarchy or none at all.
In Blender 2.6, there's PoseBone.matrix_basis and PoseBone.matrix. While matrix_basis is relative to parent bone, matrix isn't, the API says it's in object space. So it should have worked, but doesn't. So I guess we need to calculate a local space matrix from our armature-space animation matrices from the files.
So I tried multiplying it ( PoseBone.matrix ) with PoseBone.parent.matrix.inverted() in both possible orders with no luck, still weird deformations.

I would flag this for migration to blender.stackexchange.com, but it's too old

There is a dedicated community only for Blender.

The matrix_basis of a pose bone is the transform required to go from the bind pose to the current pose, in parent relative space. It's NOT the final matrix that you want.
pose_bone.matrix_basis = bind_matrix.inverted() * animation_matrix
Both bind_matrix and animation_matrix in the above example are in parent relative space.

My animation_matrix (the one from the file) is in armature space, so the above code gives  wrong results... When there is no parent relation, it looks fine, except still has the problem #1.

I can post a video example of the problem (wrong on in Blender and correct one in game engine)

Solution for problem #1 seems to be using keyframe_insert('rotation_quaternion') instead. Still can't fix problem # 2.


text:
Enemy collision detection with movie clips
I have created multiple movieclips with animations within them.  It is an obstacle avoidance game and I cannot seem to be able to get my enemies to contact my playableCharacter. The enemies I have created are each embedded on certain levels of my game. I have created an array, enemiesArray to have each of my enemies placed within it. Here is the code for that:
//step 1: make sure array exists
if(enemiesArray!=null && enemiesArray.length!=0)
{
    //step 2: check all enemies against villain
    for(var i:int = 0;i < enemiesArray.length; i++)
    {
        //step 3: check for collision
        if(villain.hitTestObject(enemiesArray[i]))
        {
            //step 4: do stuff
            trace("HIT!");
            removeChild(enemiesArray[i]);
            enemiesArray.splice(i,1);

            removeChild(villain);
            villain = null;
        }
    }
}

What I am unsure of is whether or not my enemiesArray is actually holding the movieclips I have suggested. If it was, this code would be tracing back a "HIT" for every time I ran into an enemy and would kill my character. It is not doing that however.
I am thinking I have to push my movieclips into my array but I don't know how to do that or where for that matter.
Any and all help would be much appreciated.

To the point questions are best. The answer you seek is to use a debugger. Step through your code and see what the values are at run time. Typically these, "Here's my code, what's my problem?" questions are not good questions. You can clear up a lot of your own questions with a little debugger work. And problems like this, where you're not even sure what's in your array, are ideal problems for the debugger. Debugger, debugger debugger. Have I said that enough? Good luck!

Also you shouldn't iterate your array like that and use splice inside this loop... either iterate backwards (from enemiesArray.length - 1 to 0) or push the enemies that should be removed to a delete-list and remove them later on. If you want to end the game as soon as a hit occurs, then above code is fine, but you should exit the loop with a break statement.

The enemiesArray.length check is redundant. A forloop automatically skips if the condition is not met. 0 is not smaller than 0. Therefor the for loop is never processed. As to some addition to @bummzack use a while loop instead if you are going to decrease the variable iterator (i). Well at least it reads a bit cleaner since you control 'i' and not the loop.

If you add the enemies to the stage dynamically, via code, you should add a line of code which pushes the enemy onto the enemiesArray every time you create a new enemy and add it to the stage.
For example,
var myEnemy:Enemy = new Enemy();
stage.addChild(myEnemy);
enemiesList.push(myEnemy);

I am a noob user, so take this for what it is worth... I had a similar issue on a simple shooter game.  I switched these two lines:
            removeChild(villain);
            villain = null;
to this:
            villain = null;
            removeChild(villain);
and everything started working correctly.

This does not make sense.

You might want to add the context in which this worked for you.


text:
Calculating the correct roll from a bone transform matrix
Read this forum topic for more info: http://blenderartists.org/forum/showthread.php?260602-transform-matrix-to-bone-%28head-tail-roll%29-bug
I'm trying to get my Blender3d modeller importer to create correct bones from my file's transform matrices.
The Blender Python API doesn't have a way to do this (anymore!), so people had to dig the Blender C source to find out how Blender does it and port that. Here's a Python port of the needed functions, not by me (I don't know C):
def vec_roll_to_mat3(vec, roll):
    target = mathutils.Vector((0,1,0))
    nor = vec.normalized()
    axis = target.cross(nor)
    if axis.dot(axis) > 0.0000000001: # this seems to be the problem for some bones, no idea how to fix
        axis.normalize()
        theta = target.angle(nor)
        bMatrix = mathutils.Matrix.Rotation(theta, 3, axis)
    else:
        updown = 1 if target.dot(nor) > 0 else -1
        bMatrix = mathutils.Matrix.Scale(updown, 3)
    rMatrix = mathutils.Matrix.Rotation(roll, 3, nor)
    mat = rMatrix * bMatrix
    return mat

def mat3_to_vec_roll(mat):
    vec = mat.col[1]
    vecmat = vec_roll_to_mat3(mat.col[1], 0)
    vecmatinv = vecmat.inverted()
    rollmat = vecmatinv * mat
    roll = math.atan2(rollmat[0][2], rollmat[2][2])
    return vec, roll

How to use them:
pos = mymatrix.to_translation()
axis, roll = mat3_to_vec_roll(mymatrix.to_3x3())

bone = armature.edit_bones.new('name')
bone.head = pos
bone.tail = pos + axis
bone.roll = roll

Sadly, it seems even the Blender C code is buggy and doesn't take into account cases when the bone is parallel to (0,1,0). So such bones can get assigned wrong (by 180 degrees) rolls and mess up animations.
Does anyone have better code for generating roll which takes into account such cases?
The old Blender 2.4 API generated correct ones. Its C code can be found here: http://svn.blender.org/svnroot/bf-blender/branches/blender-2.47/source/blender/blenkernel/intern/armature.c
I'm no C coder myself, again.

So you're asking that someone who knows C and Python to convert the C code to Python?

No, that would be one of the few ways to answer this (but only if the C functions in 2.4 are different from the C functions in 2.6 which were ported, which seems to be so since my Blender 2.4 importer works fine). Other ways to answer would be to explain in words what needs to be done, or put together some pseudocde, or modify the existing Pythin functions to work for this scenario.

For anyone looking for a solution to this problem, I'm posting this wherever I found it referred to. I have ported this newer upated internal C code of blender into python. I have not extensively tested it, but it seems correct, produces good results and it was super easy to port. It is used in the exact same way as before (see the above question), should be more accurate and get all (?) bone orientations right!
def vec_roll_to_mat3(vec, roll):
    #port of the updated C function from armature.c
    #https://developer.blender.org/T39470
    #note that C accesses columns first, so all matrix indices are swapped compared to the C version

    nor = vec.normalized()
    THETA_THRESHOLD_NEGY = 1.0e-9
    THETA_THRESHOLD_NEGY_CLOSE = 1.0e-5

    #create a 3x3 matrix
    bMatrix = mathutils.Matrix().to_3x3()

    theta = 1.0 + nor[1];

    if (theta > THETA_THRESHOLD_NEGY_CLOSE) or ((nor[0] or nor[2]) and theta > THETA_THRESHOLD_NEGY):

        bMatrix[1][0] = -nor[0];
        bMatrix[0][1] = nor[0];
        bMatrix[1][1] = nor[1];
        bMatrix[2][1] = nor[2];
        bMatrix[1][2] = -nor[2];
        if theta > THETA_THRESHOLD_NEGY_CLOSE:
            #If nor is far enough from -Y, apply the general case.
            bMatrix[0][0] = 1 - nor[0] * nor[0] / theta;
            bMatrix[2][2] = 1 - nor[2] * nor[2] / theta;
            bMatrix[0][2] = bMatrix[2][0] = -nor[0] * nor[2] / theta;

        else:
            #If nor is too close to -Y, apply the special case.
            theta = nor[0] * nor[0] + nor[2] * nor[2];
            bMatrix[0][0] = (nor[0] + nor[2]) * (nor[0] - nor[2]) / -theta;
            bMatrix[2][2] = -bMatrix[0][0];
            bMatrix[0][2] = bMatrix[2][0] = 2.0 * nor[0] * nor[2] / theta;

    else:
        #If nor is -Y, simple symmetry by Z axis.
        bMatrix = mathutils.Matrix().to_3x3()
        bMatrix[0][0] = bMatrix[1][1] = -1.0;

    #Make Roll matrix
    rMatrix = mathutils.Matrix.Rotation(roll, 3, nor)

    #Combine and output result
    mat = rMatrix * bMatrix
    return mat

def mat3_to_vec_roll(mat):
    #this hasn't changed
    vec = mat.col[1]
    vecmat = vec_roll_to_mat3(mat.col[1], 0)
    vecmatinv = vecmat.inverted()
    rollmat = vecmatinv * mat
    roll = math.atan2(rollmat[0][2], rollmat[2][2])
    return vec, roll


text:
Freeglut vs SDL vs GLFW
I need to port my game project from Android (written in C, OpenGL ES 2.0, thanks to NDK) to Windows and Linux platforms. Of course I will need to rewrite some platform dependent code, but for now I'm stuck with the question of which library to use for creating OpenGL context and handling input.
Just a quick googling gives me 3 candidates:

FreeGLUT - rewritten and free good old GLUT.
SDL - most well know one lib, used in many games.
GLFW - some kind of newer library, but simple and functional.

I'm quite new to PC development and don't see any significant differences between them.
Can you help me with the choice? I need only core mouse/keyboard input and creation of OpenGL context. I'll be using GLEW to load OpenGL functions.

The answer will be highly opinionated and is not really a good question for the SE format.  That said, my highly opinionated answer -- having used all three for real projects, and a few others like SFML, GLUT, Qt, and hand-rolling a solution -- is that SDL gives a good mix of features, stability, and ease of use.  I especially recommend the pre-release 2.0 versions (only available by checking out the Mercurial repo and building yourself, but that's quite easy).  Second to that, SFML is pretty good.  I found too many bugs in GLFW, GLUT is bad for games, and hand-rolling is lots of works.

I personally would recommend SDL because it handles all parts of a game from input to the graphics to the audio and input. However, it can be limiting, but since you're coming from an already developed game for a more limited platform, i think it would be a fine choice.

Yeah, its a poll. My vote is GLFW, simple, easy, never had any issues that weren't resolved. It is super light weight and easy to compile as well.

closed because it's off-topic??? I wonder, what is this site about???

GLFW is modern and has a very well defined scope. It's also under very active development.
SDL on the other side is rock solid and has a lot features in different scopes but is somewhat lacking in all of them (for example: SDL can do audio, but you might prefer using OpenAL because its far superior in that matter). It might be notable that SDL was ported to many different platforms, unlike GLFW which is only for desktop platforms (win/linux/mac).
GLUT, well, should be avoided. There simply isn't really anything about it what makes it good.

In my opinion as perfectionist GLFW is the better choice. Because it does exactly what one wants, nothing less nothing more. The very active development is also a good sign for long term projects because it usually means that bugs will be fixed, that new features will be added, it will keep up with newer standards and that it won't be abadoned anytime near. This isn't important for a quick port or a 6-month game, but for a engine or a library you want to reuse I would keep that in mind.

But the OP is asking about Freeglut not GLUT !!!

@user3473 "FreeGLUT is an open source alternative to the OpenGL Utility Toolkit (GLUT) library."

@YoYoYonnY So are GLFW and SDL, hence this question.

@Dan... no. GLFW and especially SDL are definitly not alternatives for GLUT, because you can do things with them that you can't with GLUT and vice versa.

@YoYoYonnY You can do things with FreeGLUT that you can't do with GLUT. My point still stands.

@Dan ugh, fine, it's all about semantics, I suppose. My personal opinion is that only FreeGLUT is a 'alternative' for GLUT, since GLFW and SDL have very different goals and thus have very different features from GLUT and FreeGLUT. Anyway, to quote some more wikipedia (Because that seems to always be a good idea, ever): "FreeGLUT is intended to be a full replacement for GLUT, and has only a few differences."

@YoYoYonnY Maybe it would be more clear if you just updated your answer to state whether or not FreeGLUT is worth pursuing. I don't think "FreeGLUT, well, should be avoided. There simply isn't really anything about it that makes it good" is an accurate statement, but maybe you could convince me otherwise with some good reasons not to use it (preferably, by editing your answer).

@Dan It isn't my answer :D

@YoYoYonnY Oh.. I guess I had made the assumption that since you were defending it, it was yours. A rather silly assumption I must admit. I'll stop commenting now, and let our previous discussion serve as a note to future readers.

@YoYoYonnY When people say "alternative" they only about the characteristic they would be using. I think the word you wanted is "replacement" (as in "replacement part"), meaning you can swap from one to the other without any loss of functionality. See also Drop-in replacement. FreeGLUT is a drop-in replacement for GLUT. You can swap them. Plus, no additional configuration, adapter or reworking is needed. That is not true for SDL or GLFW.

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Collection of Simple Children's Game Mechanics
Context:
I've tried Googling / searching on Amazon for books on this, but I end up get all types of resources on "How to Gamify XYZ" rather than the mechanics of simple games.
I'm trying to build a collection of "simple game mecahnics" that often shows up in Children's games. For example:

color in the picture
fill in pieces of a puzzle
memory/matching game

Question:
Is there some gigantic list of these "mechanics of simple games" ? Somewhere?
I don't need actual implementation (I can do that on my own).
I just need english descriptions of what the mechanics are.
Thanks!

This is an interesting question you bring up. Which touches on a fairly broad scope.
The problem is that children's games are still games. The subset of mechanics that are in children's games, is not substantially smaller than the set of all game mechanics.
What's more, people are making up new mechanics constantly. It's a trivial process that anyone can, and does do.
And in order to get any sense of those mechanics... while then you're asking for a complete study on game design itself.
May I ask what it is you're building this list for? There might be an easier way of doing this.

Considering that organized, interpersonal games have existed for several thousand years and probably longer... I'd say that "fairly broad scope" is a huge understatement =)  This question is similar to asking for a quick list of all kinds of candy.

Points taken. Is there a list of "20 famous/popular" types of digital games? I'm looking for things that are interactive, and people play for 10-15 minutes, rather than things like Crysis / Quake / Baldur's gate.


text:
Player's feeling towards stage selection in a platform game
In a 2D platform game with RPG elements (not that it matters much), there's three ways, among others, for the player to choose the next stage he will play:

He can only play the next stage and the ones he already beat
On game start, half of the stages are open, and the other half is released when he beats the first half
All stages are available to the player

What's the difference in perspective to the players general experience and his feelings towards a game rating of these three alternatives?
(I know it sounds like a copy of an exercise, but it isn't. I did this way so people may take this question in a more academic way)

The main objective here is to find a suitable progression system which allows a sense of progression, a proper difficulty curve, and a controlled release of game mechanics, without the roadblock problem of a player reaching a point they can't progress past and getting frustrated.
The latter problem can be ameliorated by RPG-elements, if grinding past a difficulty is possible (true for getting through enemy mobs, not necessarily true for platforming challenges). However, there are other ways of addressing this, and option 2 is a subset of those. Some examples of games which do it well:

Super Mario World: starts off linear, but the map very quickly starts diverging, which means that most of the time there are multiple points of progression. Furthermore, the existence of secret exits encourages replay of old levels.
Super Meat Boy: you can play any level from the latest world you've reached, and can face the boss after beating only a subset of the levels in that world, meaning any given level won't ever stop you from progressing. Beating levels within a time limit then unlocks a harder version of that level
Super Mario 3D games: beating a level earns you a star, and access to each group of levels is gated by your total number of stars.

One thing that's common to these games is that whilst they offer divergent options, they also have convergence points - a single point that must be passed to progress to the next section, usually a boss. This is actually really important, in order to give the game a sense of structure, milestones of progression.

Do you think that to a low quantity of stages, the Super Mario 3D progression system make sense? (I'm thiking in 9~12 stages with 3 worlds)

As in, a total of 30ish stages? Or around 4 stages per world? Any branching strategy is going to be a bit out of place if you don't have enough stages for each stage to be incremental - note that Mario 3D games have 120 objectives, Super Meat Boy has 300. That's a large part of how they work.
However, your game's got RPG elements. That adds an extra option: you can factor experience points into level access, allowing access to later levels which isn't predicated on success with earlier ones.

This is kind of a cop-out answer, but I would say that all of them have their pros and cons (like much in life).
Option 1: I feel that this is the weakest option. Players will be forced to play the newest level or the levels that they've probably already learned and crushed. There is no way for the player to take a break from banging their head against a new level while simultaneously making progression. It's either suffer the next level or farm (for lack of a better term) the previous levels (boring).
Option 2: This option reminds me of Mega Man stage selects where you can pick multiple stages in case you need to get an item from one stage to use in another or just want a change of pace after getting your ass kicked on Stage X. At least in this case the user can try to progress without feeling stuck.
Option 3: Truly laissez faire. It kind of ruins progression a bit when there's nothing to give you that "finally I can go to that stage I've seen locked!" feeling. Maybe not everyone likes unlockables, but I think in order to trigger some sort of feeling of accomplishment, you need to allow the user to have the satisfaction of going to the next area as a direct result of their work.

Regarding option 3: If it's an RPG, you can "block" some areas by putting high-level monsters there. The player can still enter the level, but might have to back out and revisit later when he's capable of dealing with some of the monsters there.

@bummzack That would be my choice. It's better to let players decide it's a bad idea to play a level than to disallow it completely.

I find the Mega Man series of games has usually been a mix of all 3. Select any stage, and after finishing them, you are given a set of more difficult stages that are linear in progression. Seasoned players have figured out there's sort of a puzzle to the best order of beating the bosses/stages, as the order of weapons you obtain present better options to tackle future stages. If you can work out a challenge based around the order in which the stages are beaten, this could be a fun way to play the game.
In other cases, the game has no apparent barriers to let you explore the whole world at first, but the extent to which you can explore it is limited by your character's abilities. This is common in RPGs, but also in Metroid/Metroidvania type of games. The world should be set up in a way in which the player would have to figure out where to go next, but without getting lost. If the process of elimination is made easy for the player, he would know where to go next and incidentally obtain an item that will let him pass through to places he previously couldn't go before.
The replayablity of the stages depends on whether or not it is worth the player's time to visit old stages with their newer abilities. You'll have to give him an incentive to go back, either by teasing the player with visible but out of reach areas during the first run, or some storyline component that calls for some backtracking.


text:
Is it considered poor programming to do this with xna components?
I created my own Menu System that is event driven.
In order to have a loading screen and multithreaded loading to work, I devised this sort of implementation:
//Let's check if the game is done loading.
if (_game != null)
{
    _gameLoaded = _game.DoneLoading;
}

//This means the game is loading still,
//therefore the loading screen should be active.
if (!_gameLoaded && _gameActive)
{
    _gameScreenList[2].UpdateMenu();
}

//The loading screen was selected.
if (_gameScreenList[2].CurrentState == GameScreen.State.Shown && !_gameActive)
{
     Components.Add(_game = new ParadoxGame(this));
     _game.Initialize(); //Initializes the Game so that the loading can begin.
     _gameActive = true;
}

In the XNA Game Component that contains the actual game, in the LoadContent method I simply created a new Thread that calls another method ThreadLoad that has all the actual loading.
I also have a boolean variable called DoneLoading in the XNA Game Component that is set to true at the end of the ThreadLoad.
I am wondering if this is a poor implementation.

Instead of polling the game to see if it's done, why not have it just fire an event when the loading thread finishes?

I am not sure how it is supposed to be done in XNA, but using a boolean flag in a multithreaded application = shooting yourself in a foot. Also (_game != null) is rather a parameter validation then a condition to check if the game has finished loading.

@LKIM If I use an event, regarding the Update and Draw methods of the ParadoxGame Component, how would I make sure the objects aren't use when they are not loaded?
@ oleksii I am not checking if the game has finished loading, but I am checking the state of the load boolean variable.

In your event handler you set a boolean _gaveLoaded = true. Then everywhere else, you just need to poll that value instead of continually asking the game.

@LKIM Tell me if this implementation is good: http://pastebin.com/TKak3XHK