text:
Is there a (family of) monotonically non-decreasing noise function(s)?
I'd like a function to animate an object moving from point A to point B over time, such that it reaches B at some fixed time, but its position at any time is randomly perturbed in a continuous fashion, but never goes backwards. The objects move along straight lines, so I only need one dimension.
Mathematically, that means I'm looking for some continuous f(x), x ∈ [0,1], such that:

f(0) = 0
f(1) = 1
x < y → f(x) ≤ f(y)
At "most" points f(x + d) - f(x) bears no obvious relation to d. (The function is not uniformly increasing or otherwise predictable; I think that's also equivalent to saying no degree of derivative is a constant.)

Ideally, I would actually like some way to have a family of these functions, providing some seed state. I'd need at least 4 bits of seed (16 possible functions), for my current use, but since that's not much feel free to provide even more.
To avoid various issues with accumulation errors, I'd prefer the function not require any kind of internal state. That is, I want it to be a real function, not a programming "function".

Your third and fourth requirement can be approximated as f'(x)>0, so the the normalized integration of the absolute value of any noise function will fulfill all your requirements. Unfortunately I don't know of any easy way to calculate that, but maybe someone else does. :)

Would perturbing the perpendicular of your function instantaneous slope work?

When you say "To avoid various issues with accumulation errors" I thought you were worried about precision. It seems that, based on your many comments, you are concerned with the performance cost of excessively many evaluations. You should state exactly what performance and memory constraints we are subject to - the requirement is unhelpful anyway because one can seemingly construct functions with state which do not have accumulation errors (What does that mean, anyway?). Also, your 4th point is wrong. A trivial example: No derivative of e^x is constant, so it's not equivalent to saying that.

For this post, y = f(t) where t is the parameter you vary (time/progress) and y is distance to target. So I will speak in terms of points on 2D plots where the horizontal axis is time/progress and the vertical is distance.
I think you can make a cubic Bezier curve with first point at (0, 1) and fourth (last) point at (1, 0). The two middle points can be randomly placed (x = rand, y = rand) within this 1-by-1 rectangle. I am unable to verify this analytically, but just from playing around with an applet (yeah, go ahead and laugh) it seems that the Bezier curve will never decrease with such a constraint.
This will be your elementary function b(p1, p2) which provides a non-decreasing path from point p1 to point p2.
Now you can generate a b(p(1) = (0, 1), p(n) = (1, 0)) and pick a number of p(i)'s along this curve such that 1

Essentially, you are generating one "general" path, and then breaking it up into segments and regenerating each segment.
Since you want a mathematical function: Suppose the above procedure is packaged into one function y = f(t, s) which gives you the distance at t for the function of seed s. You will need:

4 random numbers for placing the 2 middle points of the main Bezier spline (from (0, 1) to (1, 0))
n-1 numbers for the bounds of each segment if you have n segments (the first segment always starts at (0, 1) ie t=0 and the last ends at (1,0) ie t=1)
1 number if you want to randomize the number of segments
4 more numbers for placing the middle points of the spline of the segment your t lands at

So each seed must supply one of the following:

7+n real numbers between 0 and 1 (if you want to control the number of segments)
7 real numbers and one integer greater than 1 (for a random number of segments)

I imagine you can accomplish either of these by simply supplying an array of numbers as the seed s. Alternatively, you could do something like supply one number s as seed, and then call the built-in random number generator with rand(s), rand(s+1), rand(s+2) and so on (or initialize with s and then keep calling rand.NextNumber).
Note that even though the whole function f(t, s) is made up of many segments, you are only evaluating one segment for each t. You will need to repeatedly calculate the boundaries of segments with this method, because you will have to sort them to make sure no two segments overlap. You can probably optimize and get rid of this extra work and only find the endpoints of one segment for each call, but it is not obvious to me right now.
Also, Bezier curves are not necessary, any suitably behaving spline will do.
I created a sample Matlab implementation.
The Bezier function (vectorized):
function p = bezier(t, points)
% p = bezier(t, points) takes 4 2-dimensional points defined by 2-by-4 matrix
% points and gives the value of the Bezier curve between these points at t.
%
% t can be a number or 1-by-n vector. p will be an n-by-2 matrix.
    coeffs = [
        (1-t').^3, ...
        3*(1-t').^2.*t', ...
        3*(1-t').*t'.^2, ...
        t'.^3
    ];

    p = coeffs * points;
end

The compound Bezier function described above (deliberately left unvectorized to make it clear how much evaluation is needed for each call):
function p = bezier_compound(t, ends, s)
% p = bezier(t, points) takes 2 2-dimensional endpoints defined by a 2-by-2
% matrix ends and gives the value of a "compound" Bezier curve between
% these points at t.
%
% t can be a number or 1-by-n vector. s must be a 1-by-7+m vector of random
% numbers from 0 to 1. p will be an n-by-2 matrix.
    %% Generate a list of segment boundaries
    seg_bounds = [0, sort(s(9:end)), 1];

    %% Find which segment t falls on
    seg = find(seg_bounds(1:end-1)<=t, 1, 'last');

    %% Find the points that segment boundaries evaluate to
    points(1, :) = ends(1, :);
    points(2, :) = [s(1), s(2)];
    points(3, :) = [s(3), s(4)];
    points(4, :) = ends(2, :);

    p1 = bezier(seg_bounds(seg), points);
    p4 = bezier(seg_bounds(seg+1), points);

    %% Random middle points
    p2 = [s(5), s(6)] .* (p4-p1) + p1;
    p3 = [s(7), s(8)] .* (p4-p1) + p1;

    %% Gather together these points
    p_seg = [p1; p2; p3; p4];

    %% Find what part of this segment t falls on
    t_seg = (t-seg_bounds(seg))/(seg_bounds(seg+1)-seg_bounds(seg));

    %% Evaluate
    p = bezier(t_seg, p_seg);
end

The script which plots the function for a random seed (note that this is the only place where a random function is called, the random variables to all other code are propagated from this one random array):
clear
clc

% How many samples of the function to plot (higher = higher resolution)
points = 1000;

ends = [
    0, 0;
    1, 1;
    ];

% a row vector of 12 random points
r = rand(1, 12);

p = zeros(points, 2);

for i=0:points-1
    t = i/points;
    p(i+1, :) = bezier_compound(t, ends, r);
end

% We take a 1-p to invert along y-axis here because it was easier to
% implement a function for slowly moving away from a point towards another.
scatter(p(:, 1), 1-p(:, 2), '.');
xlabel('Time');
ylabel('Distance to target');

Here's a sample output:

It seems to meet most of your criteria. However:

There are "corners". This may be amenable by using Bezier curves more appropriately.
It "obviously" looks like splines, although you can't really guess what it will do after a non-trivial period of time unless you know the seed.
It very rarely deviates too much towards the corner (can be fixed by playing with the distribution of the seed generator).
The cubic Bezier function cannot reach an area near the corner given these constraints.

I guess that instead of blending a bunch of transformed cosines (like the dot products in perlin noise give you), you could blend several monotonic functions that start at f(0)=0, like f(x) = x, or 2x, or x^2, etc.  In fact since your domain is limited to 0=>1 you could also blend in trig functions that fit the bill within that domain like cos(90*x+270).  To normalize your methods to end at 1, you can simply divide the weighted sum of these monotonic methods starting at f(0)=0 by f(1).  Something like this should be fairly easy to invert as well (which I gather you want from the bit about stateless real functions versus programming functions).
Hope this helps.

One can analyze this crude picture
You can end up with a function that performs your animation on the fly, by making use of an uniform rand function. I know this isn't the exact mathematical formula, but there's actually no mathematical formula for a random function, and even if there were one, you'd be coding a lot to achieve this.
Considering you didn't specify any smoothness conditions, the speed profile is $C^0$ continuous (but since you're not dealing with robots, no need to worry about discontinuous acceleration profiles).

"there's actually no mathematical formula for a random function" I want a noise function, not a random function. Noise functions are well-documented to exist. Piecewise definitions like this also tend to create either inefficiency (evaluating becomes O(pieces) which becomes a problem when you have long time scales), impure functions (evaluate in O(1) but need to keep the previous position), or over-constrain possible functions (e.g. all inflection points are at fixed intervals).

Hmm, sorry, I thought that noise functions also use a random number generator procedure and that are also dependent on a discrete set of guide/key points to yield a shape (I saw Perlin Noise was mentioned.. that one works via pseudo-random number generators that are quite difficult to integrate, hence no analytic solution). Can one integrate a noise function analytically? I am wondering if one of these could be a candidate link

As an example, Perlin noise takes a seed state of 255 8 bit numbers, but from that it generates random noise in infinite distance in three dimensions; it's not really accurate to describe them as "guide points", mathematically they are more like another 256 parameters you don't want to keep providing. As you say it's essentially not integrable, but it is a pure function. The page you linked to is a bad explanation of Perlin noise (it's not really Perlin noise he explains). As for whether it's possible for some kind of noise function... well, that's the question, isn't it?

The usual way of generating an increasing sequence of N random numbers from [0,1] is to generate N random numbers in any range, then divide them all by their total sum, then sum them one-at-a-time to get the sequence.

Generate the sequence 2, 2, 5, 8, 6.
Their sum is 23, so our numbers to sum are 2/23, 2/23, 5/23, 8/23, and 6/23.
Our final sequence is 2/23, 4/23, 9/23, 17/23, 23/23

This can be extended to 2D by generating these values for both X and Y.  You can increase N to get any granularity you want.

In @teodron's similar answer, you cited efficiency concerns with large time-scales.  Without knowing the actual problem you're facing, I can't tell if that concern is valid; but another option would be to generate for small N, and simply smooth the result.  Depending on the application, this may actually give better results.

N=100, no smoothing

N=15, with smoothing

Whatever you're doing for smoothing, it seems to have made the result not even a function (around x = 0.95); I'm not sure if that's an artifact of your graphing program or a mistake. Monotonicity also seems to be violated around 0.7. Anyway, I'm familiar with "the usual way" - I'm asking this question because  I suspect the usual way is crappy. Pre-Perlin-noise, after all, no one had a problem with giant LUTs of value noise, it was just "the usual way". Today, we have a way that's considerably more flexible and efficient.

@Joe: Those are artifacts of Excel's smoothing algorithm :) But, that has absolutely nothing to do with the validity of the algorithm:  just use a monotone spline.

Though, I'm not sure why you "suspect this method is crappy" - it should be flexible and efficient, and the results are more than good enough for any game-programming situation I can think of.  After all, in games we typically go for "what looks and feels the best," not "what gives the most rigid and mathematically-precise result."  Or is this for an application that requires exact precision (in which case, the question is probably a better fit for here)?

I agree with BlueRaja: There are well-known, easy-to-implement ways of smoothing without violating monotonicity, regardless of the example. For instance, moving average or drawing splines. However, @JoeWreschnig concern is not irrelevant. Game rules and mechanics may depend on objects never retreating to function - it is rarely a good idea to assume that things the asker doesn't really need what he says he needs.

@BlueRaja: My basic complaints about piecewise approaches like this are described in my response to teodrone. It's not about finding "the most rigid and mathematically-precise result" - it's about opening up new possibilities with a mathematical tool previously unknown to us. Again, consider the analogy between giant value noise LUTs and Perlin noise. Not every question on the site needs an off-the-cuff "good enough" answer any halfway intelligent CS undergrad could bang out between lectures - sometimes, let's shoot for doing something original and professional, okay?

Or we could just continue to let this site wallow in 90% elementary confusion about transformation matrices, 10% "help me stop playing games!" That'll make an awesome Q&A site every professional will love to come to.

@Joe: That's, erm, uncalled for.  You asked for a solution to fit your criteria, I gave you one.  Just because it's simple doesn't make it bad.

To add to my previous comment, here is an example implementation which is guaranteed to never increase: http://i.imgur.com/J9LSy.png I implemented it in Matlab. The seed is propagated to the function's internal random number generation (this one used a Mersenne twister). One problem is that the whole function is evaluated at every call. Another one is that it's really quite conservative with regard to the y=1-x line and this gets worse as N increases.

I suggest this implementation inspired by the summation of octaves found in fractal noise, with a bit of cheap ass shuffling here and there. I believe it is reasonably fast and can be tuned by asking for fewer octaves than stored in the parameters with a loss of precision of about 1/2^octave.
You could see it as a piecewise implementation that only requires O(log(pieces)) time. The parameter array is used both for the divide-and-conquer pivot position, and for the distance traveled when reaching the pivot.
template<int N> struct Trajectory
{
    Trajectory(int seed = 0)
    {
        /* The behaviour can be tuned by changing 0.2 and 0.6 below. */
        if (seed)
            srand(seed);
        for (int i = 0; i < N; i++)
            m_params[i] = 0.2 + 0.6 * (double)(rand() % 4096) / 4096;
    }

    double Get(double t, int depth = N)
    {
        double min = 0.0, max = 1.0;
        for (int i = 0, dir = 0; i < N && i < depth; i++)
        {
            int j = (dir + 1 + i) % N;
            double mid = min + (max - min) * m_params[j];
            if (t < m_params[i])
            {
                dir += 1;
                t = t / m_params[i];
                max = mid;
            }
            else
            {
                dir ^= i;
                t = (t - m_params[i]) / (1.0 - m_params[i]);
                min = mid;
            }
        }
        t = (3.0 - 2.0 * t) * t * t; // Optional smoothing
        return min + (max - min) * t;
    }

    double m_params[N];
};

It could be made faster by pre-computing the floating point divisions, at the cost of storing three times as much information.
This is a quick example:

The example was obtained with the following code:
for (int run = 0; run < 5; run++)
{
    /* Create a new shuffled trajectory */
    Trajectory<12> traj;

    /* Print dots */
    for (double t = 0; t <= 1.0; t += 0.0001)
        printf("%g %g\n", t, traj.Get(t));
}

Thinking out loud, and admitting calculus is not my strong point... is this perhaps not possible? To avoid any obvious pattern, the average of the noise function over any change in x must be close to zero, and to guarantee monotonicity the amplitude of noise over that change in x must be smaller than the change in x, as any larger amplitude could result in a lower value at x' relative to x. But that would mean that as you reduce dx towards 0, such a function must also reduce dA (where A is amplitude) towards zero, meaning you get no contribution from any compliant noise function.
I can imagine it being possible to formulate a function that gradually decreases the noise contribution as x approaches 1, but that will give you a curved function that decelerates as x approaches 1, which is not what I think you want.

I can draw millions of graphs of such functions, and as SkimFlux says the integration of a noise function gives a practically equivalent function if you normalize it. So the functions exist, it's just a matter of whether they can be feasible coded. Hence asking here instead of math.se.

For example, any function that decelerates as x approaches 1 has an equivalent "reversed" function g(x) = 1 - f(1 - x), which instead accelerates as x departs 0.

Sure, the functions exist - you can draw one like teodron did - but are they 'noise' functions? Noise implies a continuous function based on pseudo-random input with an implicit amplitude relative to a baseline. And if that amplitude is too high then you can't guarantee the difference between steps is low enough to keep the output monotonic. But it does occur to me that the density of the noise and the interpolation step could be crafted to meet your specifications, which I'm going to think a bit more about.

Noise just means it's "unpredictable", it says nothing about the generation methods (or even, technically, continuity, though for animation you do almost always want coherent noise). It's true that the fixed endpoints constrain this function's possible amplitude somewhat, but not entirely. Other noise functions have similar properties, e.g. Perlin(x) = 0 for any integer x. Monotonicity is a stronger guarantee than that, but I'm don't think it's so much stronger it makes it impossible.

@JoeWreschnig I'm sure you are aware that the Perlin noise function blatantly violates several of your criteria. Firstly it passes through 0 at grid nodes so f(x+d)-f(x) is a constant multiple of d for some certain (regularly spaced) x. Additionally, because of that clever caching trick, it will repeat for large grids. For classic noise, I think the reference implementation is supposed to have grid tile (x, y) be identical to tile (x+256, y+256). You should state if this is acceptable, and to what extent.


text:
OpenGL 2D Depth Perception
I have a 2D RPG game written in Java using LWJGL. All works fine, but at the moment I'm having trouble deciding what the best way to do depth perception is. So , for example, if the player goes in front of the tree/enemy (lower than the objects y-coordinate) then show the player in front), if the player goes behind the tree/enemy (higher than the objects specific y-coordinate), then show the player behind the object.
I have tried writing a block of code to deal with this, and it works quite well for the trees, but not for the enemies yet. Is there a simpler way of doing this in LWJGL that I'm missing?

What specific problem do you have with the enemies, and what algorithm are you using? Also could you show us a movie or picture where we can see what kind of effect you would like? (Castle Crashers comes to mind although that is '2.5D')

Just went through the prosses of taking screen shots and posting them, to find out new members cant post images. Damn.
Im using an algoritm i wrote, that basicaly cheks if the players y position is lowr or higher than the tree. I wanted to know if there was an es ier way, using LWJGL. Sorry, its hard to explain without an image to show =/
EDIT:
I guess a good example would be the Pokeymon game for gameboy (if you have ever played/seen it). If the player went 'in front' of a object, then the game would draw the player first, and if behind the object, the object would be drawn first

You can't? Hmm, I haven't played pokemon for a long time, maybe you can post some links to screen shots?

http://www.youtube.com/watch?v=gJfbApaxJx0
If you watch this from 1:12 to 1:18, then the player comes out of a house, and is in front of it, but then moves forward and is behind another house, then walks around it, and then is in front of it. This is what I am trying to accomplish

Ah IC now, I think they fake that effect entirely by py using the draw order. The houses are probably made for a few different sprites. Some of the sprites are drawn before your character is drawn. Then your character is drawn so it appears over it. Then finally the last parts of the house are drawn which could overlap the player and should appear on top of him. So alpha-blending (for transparency) and sorting objects to some given Z-order will do the trick for you.

So there is no shortcut with LWJGL that you know of? I'll just have to write an algorithm that runs before drawing to check the players y postition agains all objects (excluding ground elelement, like grass), and then draw what ever is in front last.

I gather you are making an isometric 2D game? You could draw the background first, then sort all sprites (player, enemies, trees) by Y-coordinate and draw them in back-to-front order.

This is very similar to Eric's answer; just elaborated a bit more.
Firstly you should draw your background (graphics that do not obscure anything) first - so as an example this would be your grass, plants, sand etc.
Next you take your foreground (graphics that do obscure) in addition to your entities (player, enemies, etc.) and draw them from the top of the screen downwards. To do this you would essentially sort them according to their Y co-ordinate and then draw them from least to biggest.
In addition I would give each tile/entity a YRenderOffset field (that does not participate in the sorting) that would allow you to, for example, play havoc with the 'darkness' of a door so that it seems as though your character is walking through it: in this specific case the 'darkness' sprite would be physically located above where it appears (basically behind the house) with a YRenderOffset that corrects it back to where it should appear when rendered. You could invert this concept entirely by instead having a field called YSortOffset that would participate in the sorting and not the rendering.
The above two paragraphs can be rendered by the same code entirely. This gives rise to the concept of layers: so you would have the background and foreground layers and they would be rendered exactly the same way. You would then be able to add additional layers at some point in the future (a cloud layer?).

Correct me if I'm wrong, but the gist of your drawing routine is:
public void draw_frame() {
  draw_world();
  draw_character();
  draw_enemies();
}

You will need to make it a bit more sophistocated.
Two approaches come to mind:
(1) make everything drawable in your world a subclass of some base class DrawableThing, say.  Give it x, y and z accessors.  use z to set the height of the thing. To draw a frame, collect all of the drawable things into a great big array, sort the array by, say, z then y, and then draw them in order.  Sorting in Y ensures that (I am assuming you a are using a sort of semi-overhead look like the style of games of the SNES era) when thing A is on the same "level" (z) as thing B but is above it (y), thing B probably needs to be drawn on top of thing A as it will overlap it in the view.
This could result in a big array to sort with a lot of objects, so if you can, group some of the objects together into chunks (the flat ground is a good candidate) that can be drawn in one go.
(2) Use opengl to draw in quasi-3d and let the GL take care of the layering for you: set up an isometric perspective projection that makes your world look the way you want it to, then turn on depth testing and draw everything with a Z coordinate for how high it should be.  It may need to be tweaked a bit for certain objects depending on how you model your sprites/images, but it will work.

As stated previously, layering is done in LWJGL by drawing everything in a certain order. I'd like to add a little to the responses people have given to answer your specific question:
" if the player goes in front of the tree/enemy (lower than the objects y-coordinate) then show the player in front), if the player goes behind the tree/enemy (higher than the objects specific y-coordinate), then show the player behind the object"
As stated above, you'll want to draw using a method that does things in order of bottom to top.
I've been working on this issue myself for a while.
And I think I have a solution. You'll want to create a draw order for each entity (tree, enemy, player, etc).
The draw order will be given priority using the entity's Y-Value.
So We'll draw things at a greater Y Distance BEFORE those of a Lesser.
Remember that Y Distance starts at the top left then goes down as the Y value increases.
So if we have T= tree, and x= player then
if x is behind T, T will be drawn after x (ie, ontop of x)
and if x is in front of T, T will be drawn before x (ie, behind x)
To clarify, we'll draw things sort of like this.

World();
For(y= 0; y < Grid.Size(); y++)
DrawEntitiesByRow(y);

This is mostly what I'll be doing with an Isometric game I've been doing. Of course, there's more details because I have to draw the floor before the walls, and other things. This is all situational to your needs.

source: Stack Exchange

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

sort: votes


text:
Why does a physics engine produce different results each run through?
There are no random numbers in the engine and everything is calculated the same way. How can it happen differently each time?
This is on my own small physics engine that I made earlier that is written in lua and runs in the Moai SDK

Are you using time since last frame? That could very well cause suble (sometimes even brutal) difference. And are you using floating point numbers?

It's obviously chaos theory and quantum mechanics.

You wrote the code, and something in that code is not deterministic, you have got a few bids, but they are shots in the dark, and provide no info you couldn't have found on Google yourself. If you want real help we got to know how your engine works.

Too broad, too vague. I'd vote to close as NARQ if I had the rep. Without lots of additional information, anyone's guess is as good as anyone else's (as you can see from the various answers so far, which really should be just comments). Give us something to work with. This is in your own interest. A good, clear question will get you a good, clear answer. Throwing a one-liner at the wall and hoping that it sticks will only get you people throwing one-liners right back at you.

Had to give you the downvote. This question can be boiled down to "my physics engine acts funny, why is that?" Without more details I wouldn't consider this a real question.

I second Bane, read up on your chaos theory :-)

As your question is vague, the answers are vague as well. Please accept an answer.

Use the same time steps every time. My physics engine is set to use 33 ms time steps, and I can produce the exact same simulations that way (assuming I use the same machine.) If I use different time steps, even 1 ms more, the game will slowly diverge.
You can do this with this basic loop:
void update( long timeMS ) {
    _accumulatedTime += timeMS;
    while ( _accumulatedTime >= _timeStepMS ) {
        // do physics simulation
        _accumulatedTime -= _timeStepMS;
    }
}

This will ensure that you always run your physics simulation with exact time steps, and will also ensure that you never lose any time.

What sort of differences in floating-point number handling are you thinking of?  While that's certainly a possibility, there's more than enough commonality in floating-point arithmetic at this point (including the IEEE standard, even if devices aren't always 100% faithful to it in some corner cases) that that would be way, way down my list of guesses.

I mostly threw that out there to make sure he was aware that it's one possible issue. You're right, though, it's not likely the issue here. I've removed that bit as it's probably not constructive.

Read here for a good explanation of timestep http://gafferongames.com/game-physics/fix-your-timestep/
Timestep should be fixed, and this article takes a good approach and explains everything clearly.

Also note that there are some differences when handling floating points on different computers which can cause differences.

Pointing to helpful articles is always nice, but I thin you should put some effort and write your own explanation (answer) as well.

@TheLima I know that now, but seeing this was my first answer here I did not know back then. Feel free to edit my answer to make it better.

Well, you are the author of the post, not me; I can "make your answer better", but I cannot add an answer in your stead. If I were to do that, I would rather add my own answer and receive the credit for what I answer; This tough is unnecessary, as the problem here has already been addressed in ways very similar to what my answer would be.

This is difficult to answer without more details regarding the engine itself. My hunch, however, would be to look for race conditions in your code.
The kinds of details that would be useful include:

Is your engine multi-process or multi-threaded?
Is your engine event-driven?
How are you guaranteeing your test is consistent?

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


text:
Crash when using datablocks
I have really throughly searched the net and could not find any solution for this so I ask for help here.
Anyway, I have this datablock in datablocks.cs:
    datablock t2dSceneObjectDatablock(EnemyShipConfig)
{
   canSaveDynamicFields = "1";
   Layer = "3";
   size = "64 64";
   CollisionActiveSend = "1";
   CollisionActiveReceive = "1";
   CollisionCallback = true;
   CollisionLayers = "3";
   CollisionDetectionMode = "POLYGON";
   CollisionPolyList = "0.00 -0.791 0.756 0.751 -0.746 0.732";
   UsesPhysics = "0";
   Rotation = "-90";
   WorldLimitMode = "KILL";
   WorldLimitMax = "880 360";
   WorldLimitMin = "-765 -436";

   minFireRate = "2000";
   maxFireRate = "1200";
   laserSpeed  = "800";
   minSpeed    = "100";
   maxSpeed    = "150";
};

This is an exact reproduction of an object that I have manually edited in the editor. So far, I just used clone() to get as many enemies as I need, while it was out of sight. It is a r-type style shooter, so I need a variable amount of enemies. Since clone() spams my log, I decided to use datablocks, since it is also more flexible.
That's what I get when I use clone():

Con::execute - 0 has no namespace: onRemoveFromScene

However, once spawning begins, my game freezes and crashes:
    function SpawnEnemy()
{
    //%spawnedEnemy = EnemyShipMaster.clone(true);
    %spawnedEnemy = new t2dStaticSprite()
    {
       class         = "EnemyShip";
       sceneGraph    = $global_sceneGraph;
       datablock     = "EnemyShipConfig";
       imageMap      = "starshipImageMap";
       layer = 3;
    };

    %speed  = getRandom(%spawnedEnemy.minSpeed, %spawnedEnemy.maxSpeed);
    %y      = getRandom(-320, 320);

    // Set Properties
    %spawnedEnemy.setPositionX(700);
    %spawnedEnemy.setPositionY(%y);
    %spawnedEnemy.setVisible(true);
    %spawnedEnemy.setLinearVelocityX( -%speed );
    %spawnedEnemy.setTimerOn( getRandom( %spawnedEnemy.maxFireRate, %spawnedEnemy.minFireRate ) );
}

// Definition of $global_sceneGraph from game.cs:
$global_sceneGraph = sceneWindow2D.loadLevel(%level);

As I said, it works fine when I use clone() (which is commented out here), but my log gets spammed. I really hope someone can shed some light for me, this is driving me crazy.

I found out what caused it:
First of all, in the documentation it says that you need the datablock with the Keyword "datablock". In a different place on the same page in the documentation it says you need to use "dataBlock".
The real and correct keyword is "config".
The following changed code works:
datablock t2dSceneObjectDatablock(EnemyShipConfig)
{
   canSaveDynamicFields = "1";
   Layer = "3";
   size = "64 64";
   CollisionActiveSend = "1";
   CollisionActiveReceive = "1";
   CollisionPhysicsReceive = "0";
   CollisionPhysicsSend = "0";
   CollisionCallback = true;
   CollisionLayers = "3";
   CollisionDetectionMode = "POLYGON";
   CollisionPolyList = "0.00 -0.791 0.756 0.751 -0.746 0.732";
   UsesPhysics = "0";
   Mass = "0";
   Rotation = "-90";
   WorldLimitMode = "KILL";
   WorldLimitMax = "880 360";
   WorldLimitMin = "-765 -436";

   minFireRate = "2000";
   maxFireRate = "1200";
   laserSpeed  = "800";
   minSpeed    = "100";
   maxSpeed    = "150";
};

function SpawnEnemy()
{
    %spawnedEnemy = new t2dStaticSprite(EnemyShip)
    {
       sceneGraph    = $global_sceneGraph;
       config        = "EnemyShipConfig";
       imageMap      = "starshipImageMap";
    };
    %speed  = getRandom(%spawnedEnemy.minSpeed, %spawnedEnemy.maxSpeed);
    %y      = getRandom(-320, 320);

    // Set Properties
    %spawnedEnemy.setPositionX(700);
    %spawnedEnemy.setPositionY(%y);
    %spawnedEnemy.setVisible(true);
    %spawnedEnemy.setLinearVelocityX( -%speed );
    %spawnedEnemy.setTimerOn( getRandom( %spawnedEnemy.maxFireRate, %spawnedEnemy.minFireRate ) );
}


text:
Game development: Pre-production stage
I´m starting up a new project. It´s going to be a web browser game, developed using HTML5, JavaScript and CSS3.
I have some general questions regarding the process of game developing.

Should you know everything about your game by the time you start writing the first lines of code? I mean should you know all the details, all the things the player can and can not do? Basically: should you be done writing down new ideas before you begin coding?
I understand the pre-production process is about documenting, doing research etc. What does that mean? Does it mean I should open up Word and write down everything about the game? For example what should happen when you click on different things etc.

Thanks for your help!

Is this fundamentally any different a question than http://gamedev.stackexchange.com/questions/732/what-happens-in-pre-production-of-a-game

Here's an interesting episode of "Extra Credits" on the pre-production phase that might be useful: http://extra-credits.net/episodes/the-pre-production-problem/

Whoa, sounds like you're going for a "design up-front" model, i.e. waterfall. That works, but for stuff like games, a more iterative model works better.
What I mean is: have a general idea what your game is about. Know, at least, the main core mechanic of your game. Rotating blocks to make lines (Tetris)? Running to the end goal of a platformer level (Mario)? And so on.
Once you have that, you'll get more benefit from actually trying out the working prototype over designing it on paper. So I recommend you break it down into small iterations, and play it.
That's not to say "don't plan it out up front." For sure, know your vision, core gameplay mechanic, and major features. Beyond that, discovery of what works is half the fun :)

I agree with breaking it down and taking small bites. When I first start planning a project (granted I'm not highly experienced but this works for me) I pickup a marble cover notebook, write the working title of my project on the front of it and then just start pouring my ideas and concepts into it leaving room in the front for a table of contents.

I understand, thanks! The reason why I thought it was a good idea to have it all figured out before you start writing code was because I figured it could be pretty difficult to add new ideas when you have laid the basic code.

@piers for me, ideas flow once I have a working game in front of me. Use whatever works for you.


text:
Scale DIV with tiles
I am trying to create a repeating background. I have a main DIV with a grid of small 16x16 DIVs. I am trying to scale the main DIV in CSS; when the small DIVs simply have a red background color everything works great, but when there is a background image in the small DIVs then borders become visible between the tiles.
This image explains the problem:
http://cl.ly/FpNW/o
Check the HTML in these examples:
With BG-COLOR: http://jsfiddle.net/pTLXw/
With BG-IMG: http://jsfiddle.net/vkpuY/
Does anyone know what is causing this problem and how to fix it? If it is not possible to fix while using DIV, is there another way to do this?
Thanks you so much!

Does it happen with 1.375 instead of 1.4, too?

With 1.375 works great on webkit, but not in Firefox. Check: http://jsfiddle.net/vkpuY/2/ (Why 1.375? Thanks!)

I've edited your question to have the text of your question. Explain your problem/question in the posts you make here, not hidden behind a link.

I assume you did set the borders to 0, yes?

Incidentally, this question isn't about game development, so I'm voting to migrate this to StackOverflow.

@Everu I suppose the browser can only display stuff at integer coordinates. If they resize a 16×16 image, since 16 * 1.4 is 22.4, which is not an integer, there will be inaccuracies. However 16 × 1.375 = 22 which is an integer, so it has better chances to work well.

It's a result of the different scaling methods used by the different browsers. I'd generally stay away from using that scaling, but if you want your current problem solved, have the tiles overlap slightly.


text:
How do you decide upon the price for a game?
I hope this is the right board for the question.
I have this idea for a game, programming Skills with C++ and a licensed Engine. I already made a prototype of the game as proof of concept and a few friends liked it so far.
I don't want to spoil it all, but it is a 2D Robotron Style Precision Shooter in an arena which is set in space.
All you do is beating waves of enemies and when you leveled up, you select a perk to enhance your ship. Examples are making weapons stronger, faster, making the ship more agile, different Weapons as Smartbombs, Mines etc.
Having different maps with this kind of game is quite difficult, since space does not have obstacles. All you can do is make different backgrounds and maybe asteroids etc. Another type of content could be to allow the user to gather some virtual money to unlock goodies that are available at wave 1.
So far for my idea. Now, would this alone already justify asking 5$ for a game? When I compare it for example to puppygames game "Titan Attacks", I say yes, since they do not have more features. On their website the game is 7$, on Steam 4$. Their Ultratron is also 7$, which is also a classic robotron style game. But it does not yield any special features imho ( it is fun nontheless :D ), but has a very adorable artstyle.
Nation Red, which is also an inspiring source for me (Robtron Style 3D Zombie Shooter, awesome game btw), costs 10$ on Steam but also has coop, local and online.
So, how do you estimate the price of your game that you just made so people don't feel ripped off and you still make profit after getting back the investment of licenses?

Pricing is platform dependant. When your competetors are $0.99, you need to have a very superior game to charge $4.99 on an iPhone. But on the other hand, if you price at $4.99 on Steam you are sending a signal to potential buyers about the quality of the game you are offering... a signal that your game is very short/low on content or quality. Different channels have different pricing expectations.
In general you should price your game at a spot that you feel is fair, but offer a variety of promotions and offers to increase visibility of the game. Valve has discussed this on their blog, that developers always make more money when they sell their game at 75% off than they do at full price, because promotions get people interested and raise visibility. But that's not the same as PRICING your game permanently at the 75% off price point... people love deals, and when your game is priced at the lower point it's not a deal, it's just a 'cheap' game.
So find similar games to yours in the channel where you are selling and match their prices, but also offer frequent sales and promotions as this increases visibility and allows you to reach price points that raise your potential audience as well as increasing word-of-mouth about the game.
Finally, here is an interesting point from Gabe about game pricing: Now we did something where we decided to look at price elasticity. Without making announcements, we varied the price of one of our products. We have Steam so we can watch user behavior in real time. That gives us a useful tool for making experiments which you can’t really do through a lot of other distribution mechanisms. What we saw was that pricing was perfectly elastic. In other words, our gross revenue would remain constant. We thought, hooray, we understand this really well. There’s no way to use price to increase or decrease the size of your business.
So take what anyone says here with a grain of salt, because it's quite possible we're completely wrong. Your price point may really do almost nothing to your revenue, good or bad. Real world experiments trump any quantity of theory.

Great to point out the psychological difference between pricing a game at $7.50, versus pricing it at $10 and offering 25% off.

I'd be a little careful comparing to Steam, unless you plan on publishing there as well. Games on Steam have a lot of visibility, and that might skew pricing in some way.
Steam maintains market data for games they've sold in the past, and work with game publishers to set the pricing. From their FAQ:

Who sets the price for my game on Steam?
Pricing is very title specific, and we've got a lot of data and
  experience to help you decide on what the best price is for your
  title. We'll work with you to figure out pricing.

I really don't know a good answer for you though!

Thanks for your answer. Yes I know that Steam has it's own price management and that they set the amount themselves. That's why I compared it with puppygames store, where it is 7$. It is the same type of game (Ultratron) so I took it as an example. I don't plan to sell on Steam right now, I only plan to get it done at the moment hehe. I am very anxious it might not work out at all and it is a huge step for me to go and try...

If you're not even sure you can make the game, then worrying about pricing is very much cart-before-the-horse.

Well I am sure I can make it, but I am not sure if it will sell at all. I have a pixel artist that is interested, so the preconditions are met. As I said, I have a working prototype with the core elements.

Don't. Go to a pay-your-own-price model. Yes, a lot of people will buy it for the minimum allowed price, but you'll significantly increase the visibility of your game (more buyers, more "just interested" people who'll check it for a low price and maybe buy again later, the chance that this is what will give you a spot on gaming news), and that's what will give you the greater gains in the long run.
This has been done by increasing amounts of developers in the last couple of years, and mostly with resounding success.

Have a source for that claim?

"mostly with resounding success" - you only ever hear of the successful ones. Who knows how many have tried this, only to languish in obscurity?

This might not be a proven pricing model, but it is certainly an option.

@Byte56 - yup.
And it seems to work in quite a few areas.
Yes, it's not absolutely conclusive, but the evidence seems to be rather strong.

@Kylotan - sure, having a PYOP model doesn't replace the other demands for success - having a good product and effective promotions. But it allows more people to sample the product, and it provides its own share of word-of-mouth promotion.

In theory, yes. In practice, there's no real suggestion that this works out more viable or more profitable than putting a normal price on it. Maths showing the 'potential' and one anecdotal example of it working for them is not a general proof, any more than a few Kickstarter successes make that a model that works 'best' for everybody.

@nihohit Interesting links. Though, they both share a primary reference (A Field Experiment in Pay-What-You-Want Pricing and Charitable Giving), and that study included a 50-50 split with a charity. Which are likely far different results than if people knew all the money was going to the developer.

I completely agree with both of your comments, but maybe it should be pointed out that while I don't know of any study that shows that the PYOP model is significantly more succesful, there's also no study that shows it's significantly less succesful.
Given that, and the amount of anecdotal evidence in favor of PYOP, I'd say it should be kept as a strong option to consider.


text:
What does Skyrim Creation Kit's NPC class do?
I'm trying to change it with the setclass console command Based on the UESP wiki it looks like it just governs stat gain for leveling, but based on the Elder Scrolls wiki it seems to only control their combat AI.
Obviously it does at least one or both of those - what does it actually do, and does it do anything else? __ Ex: if change Lydia from warrior1handed to vigilantcombat1h with the console command 000A2C94.setclass 0010bfef will it have any unintended side effects that aren't immediately apparent other than letting her use the alteration and healing spells I just gave her with console and setting her stats in a way that works for that?
Will it do something weird like mess with her factions or ability to join as my follower? Or mess with her health scaling as she levels? Something hard to notice until alot of time went by?
@desaivv* I was trying to do it with 000A2C94.setclass 0010bfef wasn't sure if it'd cause hidden issues only showing after hours of play or if i made a new character with the same bat file. but the creation kit sounds like an idea too, i'll have to see how complicated it is. it might just show what it'd do or have some easier way to change her behavior to add spells. I'll try it and see if anything obvious shows up short term just wasn't sure if it had known long term problems

If you can change something like that you could play test it. How do you change it? Maybe I could play test it.

Go to this website it gives you all the basic and some advance info about it
http://tesalliance.org/forums/index.php?/topic/4655-introduction-creation-kit-basics/

I'd like to point out that the "class" is a remnant from the old Elder Scrolls system, in which it defines what skills cause you to level up (and those would start at a higher level at the beginning of the game). I also once saw in the Strategy Guide that it has guidelines for different "class" builds. It sounds like this is the sort of thing "class" is referring to in this context.

Here is the Wikipedia definition of a Class
http://en.wikipedia.org/wiki/Class_(computer_programming)

In object-oriented programming, a class is a construct that is used to create instances of itself – referred to as class instances, class objects, instance objects or simply objects. A class defines constituent members which enable its instances to have state and behavior.[1] Data field members (member variables or instance variables) enable a class instance to maintain state. Other kinds of members, especially methods, enable the behavior of class instances. Classes define the type of their instances.[2]
  A class usually represents a noun, such as a person, place or thing, or something nominalized. For example, a "Banana" class would represent the properties and functionality of bananas in general. A single, particular banana would be an instance of the "Banana" class, an object of the type "Banana".

Here  you will find basics on classes in the Creationkit
http://www.creationkit.com/Class

The Class Form, used on the Actor Stats Tab, allows you to specify how an Actor will distribute the attribute and skill bonuses they gain based on their level. It also affects a few other systems, such as Bleedout for Essential Actors and skill training for Trainers.
  Class is only applicable to NPCs. It has no meaning for the player.

Data Fields  X-- X-- X--X-- X-- X--X-- X-- X--X-- X-- X--X-- X-- X--
1. ID: The Form ID of the object.
2. Full Name: A label to identify the class. Not displayed in game.
3. Auto-Calc Other:
3.1 Recharge: Not used.
3.2 Training: If checked, this NPC is a Skill Trainer, and can train the player in the  selected skill to the selected maximum value.
4. Bleedout Default: If the Actor is Essential or Protected, and their health falls below  this ratio, they enter the Bleedout state
    and drop to one knee until their health recovers. This is typically
    set to 0.1, which means that Bleedout occurs when the Actor's health
    falls below 10%.
5. Voice Points: The pool of 'Voice Points' the Actor has for Shouts. Has no effect if the Actor has no Shouts.
6. Description: Not displayed in the game.
7. Menu Image: Not used.

XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Here you will find the info that governs stat gaining etc.
http://www.creationkit.com/Stats_Tab


text:
Rotating a model AND translating it forward in XNA
I have this enemy class, and I want it to
1) Spawn at a certain place Vector3 pos
2) Rotate to face my player position
3) Move forward
As this code is now, it will appear at it's specified place: pos, and attempt to rotate to face it's target: targetShip. It fails to correctly face it's target, because of this offset.
If I remove the code that assigns a value to translation, or if I normalize pos then the model will appear at   the origin and rotate to face it's target correctly.
If I try to move it at all using any of the comment out code regarding translation, It appears to start someplace else and I never can find it.
However, if I remove the code relating to rotation, and uncomment the code relating to translation, then I can get it to move forward.
The trick is doing it all together.
    class Enemy : BasicModel
    {

        Matrix rotation = Matrix.Identity;
        Matrix translation = Matrix.Identity;
        public Vector3 pos, up, right, targetShip,dir;

        public Enemy(Model m, Vector3 pos)
            : base(m)
        {
            up = Vector3.Up;
            //sets the position to the Vector3 as it's spawn point.
            translation = Matrix.CreateTranslation(pos);

        }

        public override void Update()
        {
            //Glo is a global class, where I store the player world.
            targetShip = Glo.world.Translation;
            targetShip.Normalize();

          pos = transform.Translation;

          rotation = RotateToFace(targetShip, pos, Vector3.Up);
          //Attempt at moving the model forward. Causes it to go out of view
          //translation *= Matrix.CreateTranslation(this.GetWorld().Backward);
          //translation *= Matrix.CreateTranslation(pos);
        }

        public override Matrix GetWorld()
        {
            return rotation * world * translation ;

        }

        /*Params: O = Our target
         * P = Our position
         * U = up.
         *
         * Code from some site I googled up.
          */
        Matrix RotateToFace(Vector3 O, Vector3 P, Vector3 U)
        {

            //The direction we're facing.
            Vector3 D = (O - P);
            //Our relative Right.
            Vector3 Right = Vector3.Cross(U, D);
            Vector3.Normalize(ref Right, out Right);
            //Our back
            Vector3 Backwards = Vector3.Cross(Right, U);
            Vector3.Normalize(ref Backwards, out Backwards);
            //Our relative up
            Vector3 Up = Vector3.Cross(Backwards, Right);
            //Make a matrix out of all of these.
            Matrix rot = new Matrix(Right.X, Right.Y, Right.Z, 0, Up.X, Up.Y, Up.Z, 0, Backwards.X, Backwards.Y, Backwards.Z, 0, 0, 0, 0, 1);
            return rot;
        }

    }
}

----

This is fixed now, and all this code is mostly obsolete.

I think your translation computation looks weird: translation *= Matrix.CreateTranslation(this.GetWorld().Backward);
translation *= Matrix.CreateTranslation(pos);
If you get this: this.GetWorld().Backward, it calculates with current translation. Than you take result and multiplies translation with it (again). First of all: Shouldn't you reset translation somewhere? Is all that multiplication right?

What's your exactly question? I couldn't spot any.

The model's position was coming up as invalid because it's position, {0,0,0} was being normalized.
Also, I changed the RotateToFace method to return a Quaternion.

Matrix PlayerAbsoluteTransform;

void UpdatePlayer( Vector3 EnemyPosition, float PlayerVelocity, float Seconds)
{
     Vector3 PlayerPosition = PlayerAbsoluteTransform.Translation;
     Vector3 Forward = EnemyPosition - PlayerPosition;
     Forward.Normalize();

     // This moves your player towars the enemy
     PlayerPosition += Forward * PlayerVelocity * Seconds;

     // This create the transform matrix for your model,
     // note that maybe you have to rotate the model before to face right
     PlayerAbsoluteTransform = Matrix.CreateWorld(PlayerPosition, Forward, PlayerUp);
}

With that code, the enemy faces away from the player position, and If I apply the code relating to moving the mesh, it disappears.

maybe you are not applying transform right...  because I'm sure that if data is right, matrix.CreateWorld returns a right worldmatrix for the object... facing in the forward direction...

For translating the world forward, I'm using translation*= Matrix.CreateTranslation(this.GetWorld().Backward);

lol... that is bad done... you have to add the translation... and you are multiplying it... you have to think that when you move an object you "add" a translation offset... you should learn some basic algebra before going to make a 3d game...

It's moving for sure... but you are scaling the position... not very useful and a strange math for translating... I hope you will realize soon... As you can see in this video... I know how it can be done... http://www.youtube.com/watch?v=2WuC60U6z4s&feature=plcp

Here you are, http://pastebin.com/YCwbGEkx, the code of my Actors who handles logic, and my AnimatedModel who handles model data... Ahh... don't bother, I don't need you tell me if it works... :P

huh, I'd always wondered what code looks like in a different language. Now I know. Anyway, your code doesn't help me. You just get and set rotation values that you define in another class.
I just want to have an enemy look at me and fly towards me in 3D space. Is that so hard? Apparently, yes, since I haven't gotten a correct answer yet.

@Blau linear algebra != elementary algebra: notice how Translation is a Matrix and not a Vector in his original code. Please watch your tone "learn some basic algebra before going to make a 3d game" is both derogatory and unwelcome here.

Ok, I had a mistake with his code... I can assume it... I did not realize that was a matrix... because I assumed that we are talking of my code and I mixed all.. he should note it... and he didn't... and I think that the phrase is not offensive.. is a good advice... if I were right... :P

You can try to use other way: if you know direction of enemy and position of ship, you can compute angle between current direction of enemy and new direction (ShipPosition - EnemyPosition):
angle = acos(dot(dir,newdir)), dir and newdir should be normalized. Also compute "up vector" of this rotation by cross product: up = cross(dir, newdir).
Then try to make rotation matrix according to this page in section Rotation matrix from axis and angle.

I can rotate the enemy to face it's target just fine.

Some remarks which won't fit in a comment; low quality answer here because it's bed time.
That code looks nearly right.
I don't like the manual matrix creation (especially if you got it from an OpenGL website: OpenGL uses a different 'hand' for the co-ordinate system to DirectX): instead use the built-in Matrix.CreateLookAt.
You might try fiddling with the order of multiplication of the matrices: a * b != b * a with matrices.
In addition you are not looking for Backward, instead Matrix.Invert(). However, again, it doesn't work like elementary algebra so a * b * c * Inverse(a) != b * c - so you will need to recalculate the entire chain of matrices again. Camera classes usually have this information baked in, which you should find extremely useful for your entity class. Basically:
// Fiddle with the order; it should give you the general idea though, you
// can't simply UNDO multiplication in matrices.
var world = Matrix.LookAt(pos, up, ...) * Matrix.Translate(translation, ...) * Matrix.Scale(...);
var wvp = world * view * projection;

He has created another thread.. and it is resolved... :) http://gamedev.stackexchange.com/questions/28379/moving-a-rotated-model-in-xna


text:
If I want to become a professional game developer, is learning Win32 API a must?
If I want to become a game developer, is learning Win32 API a must?
Does X-BOX or PS based game developers need to know Win32 API?
Is it possible for a professional game developer to develop games by only scripting game engines and not using Win32 API?

No.
Consider that many, many games are now made for and sold on platforms that don't even have the Win32 API; I doubt many Android or iOS game developers have a daily need for Win32. But even if you work on a PC/XBOX only title, chances are you will be using multiplatform middleware or your company's game engine and someone else has already done the Win32 programming. The likelihood of a new developer needing to do much beyond a bit of maintenance of Win32 code is pretty low.
In general learning APIs for their own sake is not a productive endeavor. You're much better off learning concepts and fundamentals, then when you need to do something on a specific platform you don't start reading the API documentation like you're starting over from nothing, you find the APIs that do what you already know you need to do. There are a few exceptions to this like learning sockets, as that API is basically a de-facto standard if you need to do that sort of thing on any platform, so knowing anything about networking (at least lowish level) implies knowing how to use sockets. OpenGL is close as well, as it is the graphics API for mobile and WebGL is gaining some steam, although knowing the fundamentals is still most important.

The Win32 API is not a must. Professional games can be developed in anything from AGS to Flash to XNA to low-level C++. The Win32 API is only used for some Windows games, and not at all on non-Windows systems.
I will note, however, that a skilled general-purpose game developer would be able to pick up the Win32 API and learn how to use it if it was the best tool for the job. I wouldn't pick Win32 as the introduction for a new game developer, but it can be a useful tool and isn't fundamentally different than any other API. I find its naming conventions and way of doing business irritating, but I know that I can use it if I feel the need.

The vast majority of game devs I've worked with have had only a passing knowledge of Win32 at best.
Only a teeny tiny fraction of a game's codebase is going to use any platform-specific APIs in general, and unless you're the engine dev who's writing the abstraction layers for those, you can get away without knowing anything about Win32.
Most indie games even just use a simple Win32 message loop (which you can practically cut and paste from Microsoft's documentation) or use an existing abstraction library like SDL or SFML.

Win32 API is simply an interface one uses to natively hook up one's game into the infrastructure of Windows. Managing the application handler, creating windows pertaining to your application/game and registering with the system.
This is what most indie game developers deem as boilerplate code, the bare minimum that has to be done on a specific platform in order to get your relevant code up and running. After you've done that, your code becomes game specific. Mostly you won't tie into Win32 for your GUI needs because you'll have something of your own cooked up. Or perhaps, someone else's solution.
While knowledge of Win32 is useful if you wish to write some hardcore native tools that will wrap around your game engine's content editing environment, you'll most likely find indie developers coding wrappers in a more forthcoming environment, like .NET's C# which makes Windows GUI development a breeze. But that will make your code on Windows dependent on .NET frameworks which forces users to download it, so if that irritates you, you might run back to Win32 and doing a little bit more boilerplate code in return for which you'll gain some sweet nativeness.
It is logical to keep your game code (and that includes everything, from low-level rendering to high-level game logic) separated from platform-specific code. That will open porting opportunities and many other sweet things. Not to mention the ease of development which comes from abstracting away the boilerplate and concentrating on what matters - the game.
In that respect, many choose SDL (and thus OpenGL) to do their boilerplate. And some simply enjoy the challenge of extended understanding and getting the most out of every platform. Remember, the easier it gets, the more conformed you are to a given platform.
"By using the technology of the mass relays, your society develops along the paths we desire" - Sovereign, Mass Effect
Applies here. So, it is not mandatory to know Win32. But it's nice. However, with today's many platforms and available runtime-managed solutions which tie in with OS-included tools for application development, it would be a shame not to utilize the offerings.

No
The Win32 API is simply an interface, it is not that much required for becoming a game developer. Having knowledge of Win32 is also useful.

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


text:
Height Map vs 3D Model Mesh
I'm currently working on a 3D PC game (written in C++ and DirectX 9.0) and I'm trying to find the best way to store level data in the memory.
The game's action takes place under the ground, so there's always a ceiling above the player. The ground is rather bumpy and there are things like stalagmites present at all times. Levels are small-ish in size and mostly look like corridors. Here are the options that I've managed to find so far:
Two height maps stored on the hard drive as either a bitmap or binary/text file. One height map for the ceiling (top), one for the ground.
OR
A single 3D mesh in some 3D model format (say, .fbx, .x, .obj whatever).
How should I approach level data storage? What would my best option be, performance-wise speaking? I'm also having some trouble when it comes to texturing a level loaded via a height map; using a 3D model makes texturing a breeze.
Thanks!

Performance-wise, both options should be equivalent since everything will be converted to a model sooner or later.
Heightmaps:
+Easy to store and edit
+Easy to calculate texture coordinates if they're not precalculated
-Poor texturing on steep surfaces
-Needs companion models for better detail
-Does not allow overlapping terrain (no overhangs).
Models:
+More control over horizontal displacement
+Overlapping terrain is possible
+Maximum control over textures
-Collision is a bit more complicated
-Could use up a bit more memory on disk
In my experience, it's best to use a somewhat flat heightmap for the base terrain and the use models for things like the stalagmites, and you can even use repeating models for such objects (to save memory).
Of course, you could use a vector field, but that's basically a model with easier texturing.

It might help if you told us what genre the game is, what the camera sees, etc. I assume you're talking about an FPS but I'm not sure.
Anyway, here's a link to a talk about the terrain in Halo Wars that I found interesting and may give you ideas: http://www.gdcvault.com/play/1277/HALO-WARS-The-Terrain-of . It deals with some of the issues and possible solutions you mentioned.

You don't necessarily have to choose one over the other, both can be effective, and there's no reason you can't combine the two.
If you use heightmaps, I would personally choose a bitmap format though. Directx should be able to do all the bitmap loading for you and turn it into a resource you can use. If you use a plain text file, you'll have to parse it yourself. This of course gives you some more freedom in interpreting the file, and might be a good starting point to allow easier experimentation.
One thing to consider though is that a heightmap will leave you with a fixed resolution, so the stalagmites you mention might be hard to represent well, unless you increase the pixel density of the entire map.
Generally, I'd say a heightmap is an effective means to store your terrain, but adding detail like stalagmites would be a lot more flexible with models.


text:
How powerful is modern hardware for complex, intensive 2D graphics?
I am embarking on a massive (image quality, file size, high frame count) project. I am still working on the basic engine, but have a big question that I would like answered before I begin testing. (It requires a lot of work to test, and possibly fail and have to recreate all sprite sheets, so an answer can help me save weeks of work if I'm wrong.)
The game is entirely in 2D, with 2.5D view. I want to eventually have 40 animations, which all have to be animated in 8 directions. I want each direction/animation to have its own sprite sheet. This equates to hundreds of spritesheets and thousands of files.
Before the obvious solution "Degrade quality for file size!" I would like to take every step possible to prevent degradation of quality, animation frame count, and image size.
Before my solution, one character was 350MB in ram (LOL!) but that was fixed quickly down to 10-20MB per whole character. That is...if I were to load ALL (40) animations in ALL directions (8). So if I were to load 320 sprite sheets into memory, it was going to be a ridiculously large amount per character in ram.
MY QUESTION IS THIS:
How much (of total sprite sheets) should I have loaded into memory at any given point?
Can I get away with loading ONLY the CURRENT spritesheet (Direction + Animation) into memory? Is modern hardware fast enough to constantly swap textures on the fly?
Players could, at any moment, change direction. This would change the entire spritesheet.
Same for animation. So within a split second, the game would have to load a specific new spritesheet, unload the old one (or unload it eventually), and render all within a split second. This would have to be done once for every character, anytime they animate or change directions in a real time game.
Fortunately, the amount of characters on screen at once will be limited by the fact the game is 2D, but I'd prefer to be able to cram in the maximum amount without performance issues on a mediocre computer.
Is texture swapping, file loading, instant rendering from HDD and memory-- all so fast with modern hardware that I wont even need to worry about ANY of this?
I just dont want to work on all of these spritesheets (from thousands of images I already have) only to find out my performance will be horrible and have to redo all spritesheets. Even to test, since I have a layering equipment system, is a time consuming task for spritesheet creation. That is, until I find a solution to process those faster (automation, i do it manually currently, using a program)

You're talking about using gigs of ram to hold the animations of one 2D character? Yes your performance will be horrible. Even a modern bleeding edge computer is going to choke. I'm not sure what the point is either, you're going to be loading pixel information for far more pixels than a user could even display. Why load 10,000 pixels for a sprite that is only going to be displayed on 50 pixels of screen space? Beyond that, this question is overly broad and depends on far too many variables to be accurately answered.

If you really wanted to go hog wild with it you can look into sparse virtual texturing (sometimes also called megatexturing) http://silverspaceship.com/src/svt/  But it's likely that you don't need to go that far.

No, I am NOT talking about using gigs of ram to hold aniamtions of one 2D character. I am talking about what created my concern (gigs of ram) before finding a possible solution (cutting it down to only 10-20MB per whole character) but with it comes some drawbacks (depending on how fast computations can calculate spritesheet creation).
My first question is in a 2D game, such as Diablo 2 or Baldurs Gate 2, or a 2D or 2.5D game, how many spritesheets or animations are typically loaded into memory per character? All of them? Only the current? Only a few (Current + Last few)?

Have you tried severing your character's head, arms, body, legs into individual parts? Individual parts will pack tighter into spritesheets and may allow sharing of parts over animations.

If it takes so much to test it, you are likely doing the wrong test.

@user15858: "My first question is in a 2D game, such as Diablo 2 or Baldurs Gate 2, or a 2D or 2.5D game, how many spritesheets or animations are typically loaded into memory per character?" All of them. Each character only had one "sprite sheet" (the concept of having more than one was meaningless since they were directly addressing GPU memory). They also rendered at 640x480 or 800x600.

Individual parts is actually the biggest problem in memory. A single part (a single character sprite) is about 1-3MB in memory with all my animations it cannot possibly exceed 20MB for a single character. If I were to NOT compound all the paperdoll technique (layers of images for equipables) and do them in pieces, that is what would exceed 350MB per character. I have to either not load so much in memory, or have the game create compounded spritesheets on load from a series of layered images. My only fear is that this will be too slow to allow fast equip/unequip actions.

A single equip requires it to compound thousands of images again to form the new character sprite.
I think though this isn't a problem because texture swapping is handled quick enough to allow for only required spritesheets to be loaded in memory. The rest stay on the HDD.

Swapping textures will kill your performance.  Modern hardware has only gotten more susceptible to this problem, not less, as the speed and power of the shader units and video RAM are growing much faster than the speed increases of the bus between system RAM and the GPU.
The only sane approach is to cut down your texture sizes, or generate procedural sprites (using vector art).  As another reply stated, there is absolutely zero reason to have huge textures for sprites that will only be a few dozen pixels tall on the output.  It sounds like you're looking for a solution to a problem that you're imposing on yourself for no reason.
Also, you will usually have better looking art if you design for the target pixel size than if you downscale a high-res texture.

Indeed - "It sounds like you're looking for a solution to a problem that you're imposing on yourself for no reason"

"As another reply stated, there is absolutely zero reason to have huge textures for sprites that will only be a few dozen pixels tall on the output."
Zero reason to have spritesheets as opposed to tiny single images? This is contrary to what I read on here about spritesheets vs single images. (Always load a huge image than to load a lot of tiny ones).

Any "problem" I impose on myself is obviously for a reason, such as a game feature or quality.  If there was no reason, there wouldn't be a problem lol.

@user15858 If it was easy like this, the AAA 2D games would be like this, dont you think? And no. He wasn't referring to the sprite sheets, he was referring to having ultra HD quality on your images to then scale them down. And also he said texture swapping that is, changing from one spritesheet to other THIS will kill your game. By the way, have you thought about Vector art? you do one size, get a very HD quality with animations as smooth as the CPU can.

@user15858: of course use sprite sheets.  But your sprite sheets should be able to fit a LOT of sprites on them.  I'm shipping a high-res 2D action game in the next few weeks that only has a dozen 1024x1024 sprite sheets, and it looks great.  There's no reason to have bazillion sprites at large resolutions.

Can you show me a screenshot or example of one of your sprite sheets or a character (and tell the # of frames of that character in a single sheet).
If I were to make an action game or a smaller game, it wouldnt be a problem even with huge massive sprites. An RPG is a much, much bigger project than a smaller game. Every monster, item, character type, and world object is yet another sprite.

My sprite sheets do fit a ridiculous number of sprites on them. The frame rate isn't very high, either. It's just a lot of content.

The frame rate isn't very high, either. It's just a lot of content. It is not a good thing to assume without any evidence that the problem is specific [too high res, too big sprites] and that there is no reason (there is always a reason). Anything can bulk up a sprite sheet, and a developer has to consider what to cut to save performance since there is so many ways to save on performance. Cutting the frame# will obviously will degrade animation. Cutting resolution will prevent zooming or lose detail. A simple change from png to jpg could save HDD space but can make memory worse.

@user15858: since you're so convinced you don't have a problem with the design of your data, why are you asking for help?  Just ship your game with a ton of spritesheets and test on target hardware to make sure it all works.  If it does, don't worry about it.  Performance will suffer, but if that just means that you go from 350fps to 70fps, who cares?  For the (very old) games you're using as reference, just remember that sprites were tiny, animations were not particularly smooth, and the target graphics hardware were not modern GPUs expected to be running tons of shaders and effects.

I'm not sure if the performance would be bad or not. I do not know if there is a problem, and although there isn't IF I handle it a certain way, there are downsides to handling it that way.
I took some of your advice and did the best I could to shrink the size down to as low as I could without losing any real quality. (It's exactly 70% the original size, and all detail is still visible.) I mostly however decided to take another look at my animation frame count and fps of my animations.

I tried shrinking the fps from 15 to 6, it was really crappy. Fortunately it actually looks significantly better at 7.5 (every other frame of my 15) than created with 6fps (very strange, but theres a huge difference: 6fps looks choppy, 15fps and only using every odd frame is smooth). I still am sticking with 15fps, but for a more "packed" lower quality version (last poster's suggestion) I might ship with a smaller HDD version that'll be half the HDD space with 7.5fps animations.

What I did the best was edit my animations to be shorter, without losing much quality. If at worst I can reverse animate everything, making only half the animation of most animations animate. This means instead of a 20 frame animation, it just does the 10 then reverses the animation for 20 frames animated but only 10 used. This makes the animations look less realistic though. In a worst case scenario, I can reduce fps, reverse animate, and even shrink. Best case scenario this works and very little quality is lost.
Either way I think modern hardware can handle it.

I took my longest animation (Idle) and shrunk it to be shorter than most of my other animations (<20 frames). Most of my animations, in a single direction for a character, is 70-85kb each.
This is a huge deal for me as although I still can't tell the GPU/RAM performance, I do now know that even with 40 animations, 40 characters, 8 directions, will all only be 1 GB of HDD space. So my game wont be 200GB like I feared. Not even close, as I'll be surprised if it passes 4GB.
Each sheet though still says 3MB in memory in TexturePacker, even if a 80kb JPEG.

I'm pretty sure the GPU has to constantly swap textures and not store very much in memory. Even with compressed jpegs, in memory the jepgs are uncompressed and so a 80kb file can consume 3MB of memory. Even so a 27kb file would still be 1MB in memory and that would fill up quickly. I'm pretty sure games like Ultima Online or Diablo 2 didn't hold ALL animations in ALL directions in ALL possible characters at once in memory. I'm pretty sure even with CPU graphic acceleration the texture swapping was constant. I dont think swapping textures is a problem, as you dont even REQUIRE spritesheets.

Again, you are comparing ancient low-res games made before GPUs were a thing to the requirements for a modern high-res game.  These things are not the same.  The optimization tricks from even a few years back are often conpletely invalidated on new hardware.  Older games ran on hardware  where the difference between the bus interconnect speed, memory speed, and processing speed were much much smaller than today.

Older games didn't use OpenGL or modern D3D, didn't store textures in VRAM, and were basically just accelerated blitting engines; this is not at all how modern hardware works.  The acceleration methods used by old games are literally not even in new hardware anymore.  Your question was whether there's be a performance hit doing things the way you describe - the answer is yes, a big one.  Also rememer that modern GPUs do allow compressed textures, which can help a lot.  Look into trying DDS textures instead of JPGs (no game uses JPGs - worst possible texture format for a game).

You're right, JPG's wont work. I swear I had the alpha color perfected where the artwork looked perfect as JPG's with black as the alpha color, but no matter what I try now, they are outlined with nasty black edges. Whatever I did, I obviously didn't do, and must have dreamt it and confused myself. It was a long time ago when I thought I had successfully used JPG's, but apparently I either lost how or just THOUGHT I did/could. back to PNG for me :(

DDS Textures are massive, most often worse than the original PNG. The solution was PNG-Quant. The ram and texture swapping was never a problem, it was actually the HDD space that the files would consume. I couldn't have a 200GB game unless I streamed the assets as required. Thx for the help though.

Just an update- swapping textures did NOT kill performance in any way. The CPU usage is minimal and the framerate doesn't drop at all even when constantly swapping textures.
This user 'Sean Middleditch' was entirely wrong. Modern Hardware is extremely powerful, and can handle nearly anything except perhaps MASSIVE 8192x8192 or higher textures.

"It works" proves nothing.  Swapping textures means transferring things over the bus.  This is slow; you're just lucky and not stressing it much; common for little hobbyist games.  Doing this in general is bad juju, and that is plain fact.  Modern hardware is plenty "powerful", so longed as it's not abused too hard.  You're only abusing it a little.  :) and yes, disk transfer is a major problem, disk is much slower than anything else; finding the balance between disk and runtime speeds is part of what we get paid to do.

You need to prototype this, with placeholder data.
Create a simple program that outputs a sprite sheet where each frame consists of text describing what it should be (e.g. "Sprite 7 frame 5"). Use that to create the final number of sprite sheets you're going to end up with, and see how well that runs a test scene with everything loaded into memory.
If it runs ok on your target hardware then go ahead and create your sprites, otherwise you'll need to adjust your plans or optimize the code to make it work.

Consider making the graphics quality configurable in the game.  For example you could set a target for the "high end" of hardware you want your game to work on, and design your graphics and animations around that target.  Then provide graphics quality settings that let you, say, use 50% scaled versions of the sprites, or use every other frame of animation.

If you're only targetting Windows/Mac/Linux, I wouldn't worry about HDD space.
Some of the most popular AAA titles are 20GB+ or larger.
If it's an online game, a singleplayer RPG, or a MMORPG, you could easily introduce a small client with less content (6-8GB max) and then introduce "expansion packs".
What people don't realize is that some games have a large client of 6+GB, and the expansions grow it to over 20GB.
The key though is to allow accessibility without having to download all 20GB of content. Example, WoW's streaming client vs Vanguard: Saga of Heroes. WoW is actually larger than the 20GB beast of Vanguard, but the former can be played in an hour of downloading on Cable, while the latter can take days for people to download.
Your problem is definitely going to be memory, as HDD space isn't a real requirement, nor are the draw calls for 2D graphics. Your memory problem will occur long, long, long before any HDD space (a virtually non-existent problem in modern streaming tech) or Rendering problems.
Keep the number of characters loaded small. Refrain from excessively large spritesheets. It is better to have a Dragon composed of 4+ sprites (chopped up dragon pieces) or stream single images (no sprite sheet at all for Dragons) than to load massive sheets.
Trying to animate a 4000x4000 sprite sheet dragon will make your game slow. Animating 10, 400x400 sprites will not. As long as your memory usage doesn't explode, your game should have no problem. As a 2D game, I can't imagine that many characters being on screen at any given moment unless the camera is zoomed out. If the camera is zoomed out, perhaps having smaller sprite images for that viewpoint would be better. It would create a ton more HDD space, but would help with memory dramatically.
Also, see about loading RGBA4444 instead of RGBA8888 to keep memory even lower. The former can still result in beautiful sprites.


text:
Moving a rotated model in XNA
This seems like a simple problem with an equally simple solution that is invisible to me.
I have a model that spawns at the origin and looks at my player model wherever it goes.
I would like it to move forward where it's going. Whenever I try to translate it, it disappears. What am I doing wrong and how do I fix it?
public override void Update()
{
    //Glo is a global class, where I store the player's world.
    targetShip = Glo.world.Translation;
    targetShip.Normalize();

    //Rotates the model to face the player's position
    rotation = RotateToFace(targetShip, pos, Vector3.Up);
    pos += Vector3.Normalize(targetShip - pos) * 20f;

}

public override Matrix GetWorld()
{
    // return  rotation * translation * world ;
    return Matrix.CreateFromQuaternion(rotation) * Matrix.CreateTranslation(pos);
}

UPDATE:
When I replace:
translation *= Matrix.CreateTranslation(direction);

with
translation *= Matrix.CreateTranslation(Vector3.Forward);

It now moves forward.
It does not correctly face me, however. It still thinks it's at the origin, and is rotating accordingly.

Here is the edited RotateToFace function
The original just returns a Matrix.
Quaternion RotateToFace(Vector3 O, Vector3 P, Vector3 U)
{

    //The direction we're facing.
    Vector3 D = (O - P);
    //Our relative Right.
    Vector3 Right = Vector3.Cross(U, D);
    Vector3.Normalize(ref Right, out Right);
    //Our back
    Vector3 Backwards = Vector3.Cross(Right, U);
    Vector3.Normalize(ref Backwards, out Backwards);
    //Our relative up
    Vector3 Up = Vector3.Cross(Backwards, Right);
    //Make a matrix out of all of these.
    Matrix rot = new Matrix(Right.X, Right.Y, Right.Z, 0, Up.X, Up.Y, Up.Z, 0, Backwards.X, Backwards.Y, Backwards.Z, 0, 0, 0, 0, 1);
    Quaternion rot2 = Quaternion.CreateFromRotationMatrix(rot);
    return rot2;
}

Draw code:
public void Draw(Camera camera)
{
    Matrix[] transforms = new Matrix[model.Bones.Count];
    model.CopyAbsoluteBoneTransformsTo(transforms);

    foreach (ModelMesh mesh in model.Meshes)
    {
        foreach (BasicEffect be in mesh.Effects)
        {
            be.EnableDefaultLighting();
            be.Projection = camera.projection;
            be.View = camera.view;
            be.World = GetWorld() * mesh.ParentBone.Transform;

        }

        mesh.Draw();
    }
}

Try to in GetWorld method multiply matrixes in this order:  return rotation * translation *world; btw what is world matrix there?

I tried that, and that did not seem to change anything.
world is read by other classes for hit detection and seems to be the object's real position

I can't figure out your code, a lot of parts in it don't make sense, such as normalizing the position. But if I understood the problem, you want to make the model to always be looking and moving in the direction of a certain target. And you already have an helper method called RotateToFace that takes care of the rotation part.
Then moving the model should really be as simple as taking the direction between itself and the target, and adding that direction to the model's position multiplied by a certain speed factor. Something like:
public class Entity
{
    public Vector3 Position { get; set; }
    public Quaternion Rotation { get; set; }
    public Vector3 Target { get; set; }
    public float Speed { get; set; }
    public float MinChaseDistance { get; set; }

    public void Update(float elapsed)
    {
        Rotation = RotateToFace(Target, Position, Vector3.Up);
        if(Vector3.Distance(Target, Position) > MinChaseDistance)
            Position += Vector3.Normalize(Target - Position) * Speed * elapsed;
    }

    public Matrix GetWorldMatrix()
    {
        return Matrix.CreateFromQuaternion(Rotation) *
               Matrix.CreateTranslation(Position);
    }
}

Note: Missed it earlier, but the distance check is actually essential, because if you don't have that and Target happens to match Position, you'll get a call to Normalize on a zero vector, and the Position becomes corrupt (i.e. filled with NaNs).

The RotateToFace function returns a Matrix, so I applied your code accordingly.
However, it didn't work. My model does not move

@OWiz That's part of the problem. You're doing all of the intermediate calculations with matrices, and it's a mess. You really should be working with simple position and rotation properties, and the only part in the code that needs to convert it to matrices is the GetWorldMatrix method. It would be a lot simpler and cleaner that way. I would recommend trying it in a separate class for starters.

Okay, well that theory helps. Forgive me for not doing it the "right" way, I don't have much experience in dealing with quats and matrices. I'll try this now.... It doesn't work. Whenever I include the code relating to translating the object, the model appears to vanish.

@OWiz edit your question by including the code for 'RotateToFace' please

@Steve H
There you go.

@OWiz Regardless of the rotation code, that single Position += ... line should be enough to move the model towards the target. If it's  not moving, then it's either that you're not calculating the world matrix correctly, the Position or Target values are wrong, or the Speed is too large.

@DavidGouveia
I edited my code in the question to match what I have now. I don't know what to tell you.

@OWiz The part where you call Normalize on the target's position should be removed. That really doesn't make sense, and will definitely mess up the results. Other than that, your Update method should be taking a float elapsed (or a GameTime gameTime in which case you have to call (float)gameTime.ElapsedGameTime.TotalSeconds to get the elapsed value) so that you can multiply that by your speed. Otherwise your model will move too fast. In this case it would move 20 units per frame instead of 20 units per second which is what happens when you multiply elapsed.

@OWiz If that still doesn't work, show us your drawing code. Make sure that you're drawing with the world matrix from GetWorld().

@David That didn't work, and I updated to show the drawing code.
If the drawing code was wrong, wouldn't it never draw?

@OWiz I think be.World = GetWorld() * mesh.ParentBone.Transform; should probably be this instead: be.World = transforms[mesh.ParentBone.Index] * GetWorld();. What you currently have is wrong in two ways, the order of multiplication, and that mesh.ParentBone.Transform is relative, not absolute, so you need to use the transforms array that you previously copied the absolute transforms to.

@David I applied your change and it did not fix anything.

let us continue this discussion in chat


text:
Clever way to do the Sonic 2 Bonus Stage effect saving memory
What would be a good way to save memory to achieve an effect like this one?
http://www.youtube.com/watch?v=K89LkvL9JZ0

We're using pre-rendered 3D.
I'm asking this because this naive approach of just rendering all frames and putting them into a single file (sprite sheet) is producing a gigantic file, would we have to manage this loading creating multiple files?
If it helps, we are using Flex SDK.

If you're concerned about memory, measure some numbers, and then profile. Don't assume you have a problem if you don't.

Already did. With just turning left we're using 39 MBs. Using a rough calculation our game is going to take about 200 MBs to just have this background effect, surely most computer can handle it, but we are thinking in porting it to mobiles later, and that use of memory is prohibitive.

I suspect they used a pseudo 3D technique similar to what is described here.

I dont know how technically Sonic 2 bonus stages are done, they could be computed by the cpu/special custom chip (and thus realtime) or totally precalculated and stored inside cartridge (like a very low resolution movie).
If you are using same color range, resolution and low framerate as sonic example you give, you should be able to get really lower than those 200MBs.
Here is what you could do to help to reduce the size:

reduce color palette size as much as possible (eg: to 8 bit) (i dont know if its possible in Flex)
use vertical/horizontal symmetry to only store the half/quarter.
If you look closely at the first animation you provided (the straight tube) : only light yellow parts change, blue/dark yellow regions are static. To show the animation, you could use more than one layer : one that is static, one that is animated, on the top of the first one (this one will compress very well since it contains lot of transparent pixels)

Of course if your animation is running at 30 fps, and contains complex details (eg : not using flat shaded, but textured polygons) it won't help. Maybe you should give a little more information about animation you want to store ?
It your animation looks like a movie (like those laserdisc racing games in the 80's) you should check if its possible to store your animation as a H.264 file movie and play it inside Flex (dont know very well that platform so i dont know if its possible).

EDIT : I recently had a chance to take a look at a Sonic 2 disassembly.
Here is how special stage is done :

there is no realtime rendering, everything has been precalculated and is stored in ROM
it run at a very low frame rate : around 8 frames per second
the internal resolution of each frame is 128x112 (when in game, it is played double size (256x224)). that's why you have vertical black borders when playing special stage (megadrive resolution is 320x224).
it use a 8 colors palette (3 shades of blue, 4 shades of yellow and one transparent color)
this mean a single pixel can be stored in only 3 bits.
some frames are re-used in a single animation. an animation is stored as an array of frames indexes.
eg for turning : 0, 1, 0, 1, 2, 3, 4, 5, 4, 5, 6.
it use horizontal flipping for left animations (eg : left turn animation is just a h-flip of right turn)
each frame is compressed. compression scheme is unknow (RLE maybe?) but it must use a very simple algorithm to allow megadrive to decompress frames on the fly. there is not enough RAM to store all frames uncompressed.

some stats for special stage :

there is 56 frames in total.
there is only a few animations : slope up, straight, slope down, curve right, begin curve right. during special stage, the game then play theses in a predefined sequence eg :  straight, curve right, straight, curve right (h-flipped), straight, slope up, straight, slope down, etc...
all frames (when compressed) take only 72.3 KB (around 1500 bytes per frame). this is pretty small compared to size of ROM (which is 1 MB)

Really nice trick this one of reflection.

I'll try using your tips to see if we can solve our problem


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

Really not one has anything to do with the other.  I assume you're referring to Astle.  Book authors might tend to write using the O/S combination they think their target audience has (ie they think they can sell more copies if the teach OpenGL/Win32, as opposed to OpenGL/Mac or OpenGL/Linux.)  The Red Book doesn't even cover O/S, so there's that..

Why almost every book on OpenGL teaches or discusses the API in the context of Win32 API? OBJECTION! Fact not in evidence. I've seen many OpenGL books that use an abstraction layer for creating an OpenGL window.

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.

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.

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.