text:
Passing through edges of AABB collision
When I move, I grab the tile in front of the player, but when the player is colliding between two tiles, I grab the wrong tile due to rounding error. I made a video explaining what I mean.
As you can see, when the player is moving down on the edge of a tile, they pass through. This is how I find the tile:
Tile t = world.tiles[(int) ((int) getX() / 32 + x)][(int) ((int) getY() / 32 + y)];`

This is my collision detection code:public static boolean isColliding(AABB a, AABB b) {
        if (Math.abs(a.pos.getX() - b.pos.getX()) < a.size + b.size) {
            if (Math.abs(a.pos.getY() - b.pos.getY()) < a.size + b.size) {
                return true;
            }
        }
        return false;
    }
The pos variable in the AABB class is the center of the entity and the size is half the size of the player.
How can I fix this so it finds the correct tile?
Edit:
Ok, I changed my move method to get the tiles around the player, but now the player only collides if he is colliding in the middle of four solid tiles! I don't understand!
private void move(int x, int y, float sx, float sy) {
    Vector2f tempPos = new Vector2f((pos.getX() + (pos.getX() + 32)) / 2, (pos.getY() + (pos.getY() + 32)) / 2);
    box.update(new Vector2f(tempPos.getX() + sx, tempPos.getY() + sy), 16);
    if (getX() / 32 + x > 0 && getX() / 32 + x < world.mx && getY() / 32 + y > 0 && getY() / 32 + y < world.my) {

        for (int xx = 0; xx <= 1; xx++) {
            for (int yy = 0; yy <= 1; yy++) {
                if (world.getTile((int) (getX() / 32) + xx, (int) (getY() / 32) + yy) != null) {
                    Tile t = world.getTile((int) (getX() / 32) + xx, (int) (getY() / 32) + yy);
                    t.color = true;
                    if (t.type != 0 && !Collision.isColliding(box, t.getBox())) {
                        setPos(getX() + sx, getY() + sy);
                    } else if (t.type == 0) {
                        setPos(getX() + sx, getY() + sy);
                    }
                } else {
                    setPos(getX() + sx, getY() + sy);
                }
            }
        }

    } else {
        setPos(getX() + sx, getY() + sy);
    }
    glPushMatrix();
    glTranslatef(getX(), getY(), 0);
    glPopMatrix();
}

The type in Tile is just for checking to see if the tile is air. As you can see, I have two for loops that loop through the four tiles above, below and to the right and left of the player, and see if he collides with any of them. I have no idea why this isn't working, and I've tried to figure out how to do this for a week now. Can anyone show me a link or code to get the tiles around a player and see if he collides with them?

I am not sure it's a rounding error. If I get your code correctly, you are just considering left corner of player when 'grabbing' the tile. You should check for both left and right corners, in order to work properly.
But if I got your problem wrong, a little more code explanation would help. What are 'x' and 'y' exactly?

x and y are the tile based movements. For instance, if I want to move up, I call my move method with an x value of 0 and a y value of 1. I realize its not a rounding error, more that its just since my tiles are in an array, the wrong tiles are being picked.

The comments have it covered pretty well, but just to lay it out there:
Your current code is treating your tile as though it's a point. The most common case for your tile, however, is that it's overlapping two tile boundaries (whether horizontally or vertically) because of its size (again, horizontally or vertically).
Change your above code to a loop that checks tileX and tileX + 1; and tileY and tileY + 1; and you should be good to go.

Actually, why would I need a loop? Can I not just grab the tiles without one?

Yeah, you're right: you could just grab tile1, tile2, tile3, tile4 and check those. Just trying to cover the case where you're placing something bigger than a single tile.


text:
How to call game Update from another form
I have three projects in one solution:

a form with some tool (see it as a level-editor), in which there is PictureBox where I want to redirect drawing of the game.
My game, with some methods and its Update/Draw methods:
A launcher (where I can start the game or start the level-editor)

 protected override void Update(GameTime gameTime) {...}
 protected override void Draw(GameTime gameTime) {...}

This is the launcher's "Open game in editor mode" button code:
private void cmdEditorMode_Click(object sender, EventArgs e)
{
    using (Game1 game_instance = new Game1(true))
    {
        using (MapEditor form = new MapEditor())
        {
            form.Show();
            form.game_wrapper = new GameWrapperForLevelEditor(
                game_instance,
                form.pctSurface.Handle,
                form,
                form.pctSurface);
            game_instance.Run();
        }
    }
}

Note that:

true in Game1 constructor is just a bool used to tell the game to open it in editor mode.
GameWrapperForLevelEditor is another class used to make the form of the level editor and the Game itself in relation.

In particular (to draw inside the pictureBox drawSurface):
 public GameWrapperForLevelEditor(
            Game1 game,
            IntPtr drawSurface,
            System.Windows.Forms.Form parentForm,
            System.Windows.Forms.PictureBox surfacePictureBox)
        {
            graphics = new GraphicsDeviceManager(this);
            //...
            //...other things
            //...
            graphics.PreparingDeviceSettings +=
                new EventHandler<PreparingDeviceSettingsEventArgs>(graphics_PreparingDeviceSettings);
        }

and:
 void graphics_PreparingDeviceSettings(object sender, PreparingDeviceSettingsEventArgs e)
 {
    e.GraphicsDeviceInformation.PresentationParameters.DeviceWindowHandle = drawSurface;
 }

This is the launcher's Main code:
using System;
namespace Launcher
{
#if WINDOWS || XBOX
    static class MAIN
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main(string[] args)
        {
            using (Launcher_form form = new Launcher_form())
            {
                form.Show();
                //Creo un'istanza del picture_box_render all'interno del form
                form.picture_box_render = new launcher_picture_render(form.pctLauncher.Handle);
                form.picture_box_render.Run();
            }
        }
    }
#endif
}

Note that:

I use here another game (picture_box_render) because in my launcher's form I put a picture box where I want to run an animation that is rendered as another game loop.

Finally the draw part:
protected override void Draw(GameTime gameTime)
{
    GraphicsDevice.Clear(Color.Black);

    spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend);
    spriteBatch.Draw(game.LastRender, Vector2.Zero, Color.White);
    spriteBatch.End();

    base.Draw(gameTime);
}

My problems are:

game_instance.Run(); (up) gives me this error (translated from italian, so sorry):

Starting a second message loop on a single thread is not valid operation Use
  Form.ShowDialog.

game.LastRender is Always empty because the game never run. game.LastRender is just a RenderTarget2D where Game1 draw method draws the game.

As a solution, I thought that I may don't game_instance.Run();, but just use game.Update(...) and game.Draw(...) inside my wrapper class. The problem is that these two methods are protected, and if I try to set them public it says me that I can't.
What am I doing wrong?

You should use the official sample. It demonstrates exactly how to get XNA to output inside WinForms.
Any other method for doing this is almost certainly wrong and will either fail outright, or fail unexpectedly in certain circumstances.

To use the official sample, you will have to extricate your existing code from the Game class. This means you must implement your own Draw and Update methods, your own timing mechanism (you can use System.Diagnostics.Stopwatch), and possibly a replacement for GameComponent (if you use it).
I find it helps to separate your game into three projects: A shared "engine" XNA library, a "game" XNA project, and an "editor" WinForms project.
Then use the "game" and "editor" simply as thin wrappers for setting up the graphics device and calling your own Update and Draw methods on your own class in your "engine" project.
If you want a launcher, it's probably best to create a fourth project to contain it. I'd simply have it invoke the selected executable.

Thanks a lot! A last question: inside another project, what's the instruction to invoke an executable?

System.Diagnostics.Process.Start.

source: Stack Exchange

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

sort: votes


text:
Why is interpolation passed into the rendering routine when the position and speed are related to the update routine?
I've read this in several well known articles, including this one:
http://www.koonsolo.com/news/dewitters-gameloop/
Under the Interpolation and Prediction subheading is the description of the formula. I'm currently using the suggested game loop from the article (without passing in the interpolation). I get why interpolation is used, but I'm having trouble understanding why it is applied during rendering, and how it relates to my game.
I'm presently using pure tile based movement for 32x32 tiles. So my player moves from tile A to tile B so long as tile B can be occupied, and at a fixed rate of 1 pixel per 10ms. The state is "walking" until the player moves the full 32 pixels, at which point the state is "stopped". This all happens in a standard timer, but all during my update routine. My rendering routine simply takes the player's position and renders it onto the map. There is no "speed" per say in that equation that is accessible. So how would I use interpolation?

The idea is to run your game simulation at a fixed time step in all situations, while rendering does the interpolation based on an object's current (or target) position and velocity. This post may answer some of the questions: http://www.learn-cocos2d.com/2013/10/game-engine-multiply-delta-time-or-not/

I'm sorry to be so dense about this, but can you define "fixed time step"? I've read the terms variable and fixed time step, but don't quite understand simply what a time step is.

Some of the problem may also be that I have no separate field for velocity. I'm moving the length of a tile (32 pixels) at a presumably fixed rate. If instead I did have a velocity integrated it might make more sense to me.

I once worked on a PS2 game where we did exactly this so that the rendering could draw objects at slightly different positions on odd-numbered scan lines than on even-numbered ones.  The television's interlaced video signal gave us the appearance of 60fps rendering when we were actually only rendering at 30fps.  With modern televisions you can't do this trick any more, but it was a neat hack at the time.

Combining a physics engine that uses a fixed time-step with a variable-timed rendering loop can lead to very choppy movement. Sometimes you have two physics frames between two renders, sometimes none at all and you render the same thing twice. This can lead to choppy movement and scrolling.
The solution to that is to pass not just the current but also the last game-state to the rendering engine and a delta-time variable that states how many milliseconds the current game-state is in the past. That allows the rendering engine to either interpolate or extrapolate object positions accordingly, which results in much smoother movement.
For example:

Last tick: object was at horizontal position 3.0
Current tick: object is at 5.0
Time information: We are 30% between current tick and the next tick

When the rendering engine uses extrapolation, it would calculate that the object is moving with a velocity of 2.0 units per tick, so it now draws it at 5.6 units. When the rendering engine uses interpolation, then it will linearly interpolate between the last and the current tick and place the object at 3.6 units.
But because the player has a pretty good gaming rack, just a few millisecond later the frame is finished and we want to draw another one. Time advanced to only 70% to the next physics frame. So we draw the object at 6.4 (extrapolation) or 4.4 (interpolation).
As you can see, passing timing information to the rendering engine allows us to give the impression that the game runs with a much higher physics framerate than it actually does, resulting in much smoother rendering.

That article seems to be written around a variable framerate. This is okay for rendering, but many parts of a game are time-dependent (want to avoid huge jumps in time). Variable framerate is especially bad for physical simulation. To avoid such issues most parts of a game can be updated at a fixed timestep, while rendering can be updated at maximum FPS.
You take previous positions from the game, and current positions and interpolate between the two to form a smooth animation for animating the sub-steps between two simulation loops.
If you want more detail I wrote a better article here. See the section on time stepping.

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

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


text:
Would seam carving/liquid rescale make changing aspect ratios easier?
Seam carving is an algorithm which allows for resizing images without major distortions. I think it might help to make games which would adapt to different aspect ratios/resolutions much easier. But am I right?
You can watch this presentation to see how seam carving works for videos.

If it's viable or not isn't a question that suitable for this site. Your question seems to be asking for a discussion about seam carving. If you have a specific question about it, you should ask that instead. This is not the place for discussions.

By quickly looking at the algorithm it seems more suited to image/video processing.
The problem with such image processing based techniques is that they are highly analytical, and they are more likely to leave some artifacts that might not be suitable for games due to the dynamic nature of the games, unlike movies or images were the data is previously known. This is even mentioned in the article, which makes it not so suitable for games. Quoting from Wikipedia:

The algorithm may need user-provided information to reduce errors.    This can consist of painting the regions which are to be preserved.
  With human faces it is possible to use face detection.
Sometimes the algorithm, by removing a low energy seam, may end up inadvertently creating a seam of higher energy. The solution to this
  is to simulate a removal of a seam, and then check the energy delta to
  see if the energy increases. If it does, prefer other seams
  instead.

Other reasons not to use such approach is that it's more likely to be expensive performance wise, but this needs to be proved by actually testing it.
Keep in mind that games use much different techniques to output for multiple resolutions that usually don't use traditional image processing techniques, as they can usually natively render to a render target (or multiple) with the target resolution. Think of traditional image processing techniques as the ones require analyzing pixels in color domain or frequency domain. I said usually because some Anti Aliasing aliasing techniques do some analysis on the image. Even though I don't know how widely they are used in games.

No.

Seam carving makes no sense for dynamic images. It is for static images, by design. If you blindly apply it to every frame of video, you will get different unrelated results on every frame. Objects on that video will look jittering around and cause nausea.
It is useful when altering raster data is cheaper than reproducing image with different composition / angle / whatever. In games, every new frame is rendered at runtime, so reproducing frames with new FOV aspect ratio and GUI layout is not quite an issue. Also adjusting some variables in calculations that will happen anyway is much cheaper than involving new shader pass that requires whole image analyzis.
It is based on assumption that pixels are comparable by how much they are interesting / important for perception, and seams of most useless pixels may be thrown out. This approach distorts screen-space distances between objects. It is fine for illustrations, but not acceptable in games, because game wants player to know these distances, otherwise it will be lying about actual game situation.
In lot of games, gameplay objects are bound to GUI. For example, figures in chess. Image distortion may not be tolerated, because it will just ruin GUI.


text:
What is the standard C# / Windows Forms game loop?
When writing a game in C# that uses plain-old Windows Forms and some graphics API wrapper like SlimDX or OpenTK, how should the main game loop be structured?
A canonical Windows Forms application has an entry point that looks like
public static void Main () {
  Application.Run(new MainForm());
}

and while one can accomplish some of what is neccessary by hooking the various events of the Form class, those events don't provide an obvious place to put the bits of code to perform constant periodic updates to game logic objects or to begin and end a render frame.
What technique should such a game use to achieve something akin to the canonical
while(!done) {
  update();
  render();
}

game loop, and to do with minimal performance and GC impact?

The Application.Run call drives your Windows message pump, which is ultimately what powers all the events you can hook on the Form class (and others). To create a game loop in this ecosystem, you want to listen for when the application's message pump is empty, and while it remains empty, do the typical "process input state, update game logic, render the scene" steps of the prototypical game loop.
The Application.Idle event fires once every time the application's message queue is emptied and the application is transitioning to an idle state. You can hook the event in the constructor of your main form:
class MainForm : Form {
  public MainForm () {
    Application.Idle += HandleApplicationIdle;
  }

  void HandleApplicationIdle (object sender, EventArgs e) {
    //TODO: Implement me.
  }
}

Next, you need to be able to determine if the application is still idle. The Idle event only fires once, when the application becomes idle. It does not get fired again until a message gets into the queue and then the queue empties out again. Windows Forms doesn't expose a method to query the state of the message queue, but you can use platform invocation services to delegate the query to a native Win32 function that can answer that question. The import declaration for PeekMessage and its supporting types looks like:
[StructLayout(LayoutKind.Sequential)]
public struct NativeMessage
{
    public IntPtr Handle;
    public uint Message;
    public IntPtr WParameter;
    public IntPtr LParameter;
    public uint Time;
    public Point Location;
}

[DllImport("user32.dll")]
public static extern int PeekMessage(out NativeMessage message, IntPtr window, uint filterMin, uint filterMax, uint remove);

PeekMessage basically allows you to look at the next message in the queue; it returns true if one exists, false otherwise. For the purposes of this problem, none of the parameters are particularly relevant: it's only the return value that matters. This allows you to write a function that tells you if the application is still idle (that is, there are still no messages in the queue):
bool IsApplicationIdle () {
    NativeMessage result;
    return PeekMessage(out result, IntPtr.Zero, (uint)0, (uint)0, (uint)0) == 0;
}

Now you have everything you need to write your complete game loop:
class MainForm : Form {
  public MainForm () {
    Application.Idle += HandleApplicationIdle;
  }

  void HandleApplicationIdle (object sender, EventArgs e) {
    while(IsApplicationIdle()) {
      Update();
      Render();
    }
  }

  void Update () {
    // ...
  }

  void Render () {
    // ...
  }

  [StructLayout(LayoutKind.Sequential)]
  public struct NativeMessage
  {
      public IntPtr Handle;
      public uint Message;
      public IntPtr WParameter;
      public IntPtr LParameter;
      public uint Time;
      public Point Location;
  }

  [DllImport("user32.dll")]
  public static extern int PeekMessage(out NativeMessage message, IntPtr window, uint filterMin, uint filterMax, uint remove);
}

Furthermore, this approach matches up as close as possible (with minimal reliance on P/Invoke) to the canonical native Windows game loop, which looks like:
while (!done) {
    if (PeekMessage(&message, window, 0, 0, PM_REMOVE)){
        TranslateMessage(&message);
        DispatchMessage(&message);
    }
    else {
        Update();
        Render();
    }
}

What's the need for dealing with such windows apis features? Making a while block ruled by a precise stop watch (for fps control), wouldn't be sufficient?

You need to return from the Application.Idle handler at some point, otherwise your application will freeze (since it never allows further Win32 messages to happen). You could instead try to make a loop based on WM_TIMER messages, but WM_TIMER isn't nearly as precise as you'd really want, and even if it was it would force everything to that lowest-common-denominator update rate. Many games need or want to have independent render and logic update rates, some of which (like physics) remain fixed while others aren't.

Native Windows game loops use the same technique (I've amended my answer to include a simple one for comparison. Timers to force a fixed update rate are less flexible, and you can always implement your fixed update rate within the broader context of the PeekMessage-style loop (using timers with better precision and GC impact than WM_TIMER-based ones).

@JoshPetrie To be clear, the above checking for idle uses a function for SlimDX. Would it be ideal to include this in the answer? Or is it just by chance you edited the code to read 'IsApplicationIdle' which is the SlimDX counterpart?

** Please ignore me, I just realized you define it further down... :)

@JoshPetrie In what way does this approach differ from setting the UserPaint and AllPaintingInWmPaint ControlStyles, and then overriding OnPaint to call Update(); Render(); Invalidate();? I don't know enough about the Windows messages queue to grasp what the meaningful differences are.

@JoshPetrie I'm trying to make a small game loop to handle a few animations in my winform, and I noticed that even having nothing within the while loop, runs CPU up to about 20%. Obviously this is because it is looping so fast over nothing, but even with code, it is the same story. The only way to make it go down is to put a Thread.Sleep, and even with 16ms of sleep (60fps), there is still ~10% CPU usage. Is there any way to alleviate some of this further?

Actually the Application.Run Method is a message loop. I don't know why people call them a pump because they receive messages, not send them out. Saying message pump in this context conceals the truth that Application.Run is already a message loop. A traditional game loop is fundamentally the equivalent of a message loop. This answer helps to explain how to use the existing message loop but the idle loop might not be needed.

I understand that this is an old thread, but I’d like to provide two alternatives to the techniques suggested above.  Before I go into them, here are some of the pitfalls with the proposals made so far:

PeekMessage carries considerable overhead, as do the library methods that call it (SlimDX IsApplicationIdle).

If you want to employ buffered RawInput, you’ll need to poll the message pump with PeekMessage on another thread other than the UI thread, so you don’t want to be calling it twice.

Application.DoEvents is not designed to be called in a tight loop, GC problems will quickly emerge.

When using Application.Idle or PeekMessage, because you’re only doing work when Idle, your game or application will not run when moving or resizing your window, without code smells.

To work around these (except 2 if you’re going down the RawInput road) you can either:

Create a Threading.Thread and run your game loop there.

Create a Threading.Tasks.Task with the IsLongRunning flag, and run it there.  Microsoft recommends that Tasks be used in place of Threads these days and it’s not hard to see why.

Both of these techniques isolate your graphics API from the UI thread and message pump, as is the recommended approach.  The handling of resource/state destruction and recreation during Window resizing is also simplified and is aesthetically much more professional when done (exercising due caution to avoid deadlocks with the message pump) from outside the UI thread.
Do not be afraid of using another thread.  I recognise that it's a topic most would prefer to avoid but in this instance, it's easy to employ.  By simply using a Threading.Thread with the IsBackground property set to true, along with something like an "While IsRunning" style loop, you can control the flow of the main loop and gracefully exit when your application concludes.

Agreed with the answer from Josh, just want to add my 5 cents. WinForms default message loop (Application.Run) could be replaced with the following (without p/invoke):
[STAThread]
static void Main()
{
    using (Form1 f = new Form1())
    {
        f.Show();
        while (true) // here should be some nice exit condition
        {
            Application.DoEvents(); // default message pump
        }
    }
}

Also if you want to inject some code into message pump, then use this:
public partial class Form1 : Form
{
    protected override void WndProc(ref Message m)
    {
        // this code is invoked inside default message pump
        base.WndProc(ref m);
    }
}

You need to be aware of the DoEvents() garbage-generation overhead if you choose this approach, however.


text:
2D Sidescroller camera
I'm using OpenGL. For my tiles, I'm using a display list and I'm just using immediate more for my player (for now). When I move the player, I want to center him in the center of the window, but allow him to jump around on the y axis and not have the camera follow him. But the problem is, is that I can't figure out how to center the player in the viewport! Here is the player update method:
public void update() {
    if (Keyboard.isKeyDown(Keyboard.KEY_D)) {
        World.scrollx -= Constants.scrollSpeed;
        setCurrentSprite(Sprite.PLAYER_RIGHT);
    }
    if (Keyboard.isKeyDown(Keyboard.KEY_A)) {
        World.scrollx += Constants.scrollSpeed;
        setCurrentSprite(Sprite.PLAYER_LEFT);
    }
    move((Constants.WIDTH) / 2  + -World.scrollx, getY());
}

World.scrollx and World.scrolly are variables that I increase/decrease to move the tiles. move() is just a method that sets the player position, nothing else. I render the player at his current coordinates like this:
public void render() {
    glBegin(GL_QUADS);
    Shape.renderSprite(getX(), getY(), getCurrentSprite());
    glEnd();
}

Shape.renderSprite is this:
public static void renderSprite(float x, float y, Sprite sprite){
    glTexCoord2f(sprite.x, sprite.y + Spritesheet.tiles.uniformSize());
    glVertex2f(x, y);
    glTexCoord2f(sprite.x + Spritesheet.tiles.uniformSize() , sprite.y + Spritesheet.tiles.uniformSize());
    glVertex2f(x + Constants.PLAYER_WIDTH, y);
    glTexCoord2f(sprite.x + Spritesheet.tiles.uniformSize(), sprite.y);
    glVertex2f(x + Constants.PLAYER_WIDTH, y + Constants.PLAYER_HEIGHT);
    glTexCoord2f(sprite.x, sprite.y);
    glVertex2f(x, y + Constants.PLAYER_HEIGHT);
}

Pretty simple, I just render the quad at the current player's position. This is how I actually render everything:
public void render(float scrollx, float scrolly) {
    Spritesheet.tiles.bind();
    glPushMatrix();
    glTranslatef(scrollx, scrolly, 0);
    glCallList(tileID);
    glPopMatrix();
    player.render();
}

This is the part I'm confused on. I translate the tiles according to the scrollx and scrolly variables, and then I render the player at his current position. But the player moves faster than the tiles scroll, and he can escape out the side of the screen! How do I center the player with moving tiles?
Thanks for any help!

Why are you even using immediate mode? and all the deprecated functions, you shouldn't do that.

Oh, I'm sorry, did I ask for anyone's opinion on what I should be using? No. Of course I shouldn't be using immediate mode. But you know what, this is just a personal project and I don't feel like dealing with buffer objects right now considering this was supposed to only last for about a week. I find it annoying that people need to comment on that every time I ask for help, but don't answer my question. Thanks for pointing out the obvious yet again.

Well, I didn't know that. You could write a little comment in the bottom of your question saying "I know you shouldn't use the deprecated functions, but I'm only using them to be able to make my small projects faster". - Okay this comes from a really experienced OpenGL programmer, you should really start making some functions and/or classes to do all your dirty work. That way when creating textures, VBOs, VAOs, Matrix Stack, etc. It will be nice and clean in your small project.

I have already started creating my own wrapper library. To be perfectly honest with you, I don't think this is relevant at all to my issue. Its my decision to use deprecated functions, and it doesn't matter in this instance because side scrollers can be made in the fixed function or programmable pipeline.

As said, you did state that you knew it was deprecated in the question. Therefore I said it, as there actually exist a lot of people using the fixed-function pipeline without knowing it's deprecated. Also, even though that a game is capable of using the fixed-function pipeline, doesn't mean you should, there a reason for that it's deprecated... When something is deprecated it means that you shouldn't use it, and that it probably isn't available in the future. Graphics Cards should support the old functions, but don't have to, so your game might not work on some modern graphics cards.

Did you at all read my above comment? Its my choice to to use deprecated functions. I've been working with OpenGL for a few years now, but I chose to use the fixed function pipeline because its MY project. I have no idea why I would ever want to distribute it, therefore telling me that I shouldn't use deprecated functions because they may not be supported on certain graphics cards is pointless. Now please, let's not fill up the comments with arguing.

You should not base the x and y position of your player in the glVertex, i.e remove those x,y and replace it all by 0. Then you can only worry on the glTranslate side


text:
Is the Key Bindings delay unavoidable in Java when pressing different directional keys quickly?
I've read just about every tutorial I can on why to use Key Bindings instead of implementing the KeyListener interface, including all the examples that show using a field to track the key event because of the repeating delay when holding down the same key. No matter what I do though I simply can't get past a keyboard delay when alternating quickly between directions (i.e. - 'W','D','S','A'). I've read some comments that state this is very dependent on your keyboard OS settings, and in some cases is just unavoidable. Some of the registry editing suggestions for keyboard speed seem to indicate there is some truth in that. Is there a posted solution somewhere that guarantees a "hardware independent" Java solution for handling quick key presses without delay?

You might consider using JInput, you won't suffer the same problem.

Where is it documented that I won't suffer the same problem with JInput? I can't find any good examples for easily detecting key presses with this API. It looks to be built primarily for emulating game controllers, which is not what I want.

JInput is the equivalent of DirectInput on Windows platforms. That's the best you can use for getting the states of any of your devices. It contains some examples as well, check its source code and you will find it.

LMGTFY: http://www.java-gaming.org/index.php?topic=16866.0

How about you take the time to read your own link. If it contains examples of handling keyboard input then you should point me at those because I'm not seeing it. If the only way I can use the library for keyboard input is by grokking source code then it's not something I'm interested in using.

I took a look at my link, I listened to you. I see how to launch a program which displays the state of the devices connected to the computer. That should be enough for you to know where to look at in the source code in order to find the example classes, and to know how to implement what you need.
Maybe you need me to write it for you?

Which still does not answer my original question, does not address the issue that there is no sample documentation for keyboard input for the API you recommend, and demonstrates your total lack of willingness to help beyond posting a one sentence answer. I've had great success with this stack exchange and the community has been very helpful and polite. Don't ruin it for others who make an honest attempt to be involved.

Good luck with other answers.


text:
In an XNA game object, what should I use to represent a texture for serialization?
While trying to save to a file a list of objects needed to run my game, I noticed that Texture2D is not serializable. Why? What was the purpose?
The object I want to serialize looks like this:
[Serializable]
public class GameObject
{
    private Vector2 position_ = Vector2.Zero;
    private float rotation_ = 0.0f;
    private Vector2 scale_ = Vector2.One;
    private float depth_ = 0.0f;

    private Texture2D texture_;

    private bool is_passable_ = true;

    private GameObject(
        Vector2 starting_position,
        string filepath,
        ContentManager content)
    {
        this.position_ = starting_position;
        this.texture_ = Content.Load<Texture2D>(filepath);
    }

    //Properties
    //Update/Draw
}

So, what should I serialized since Texture2D isn't made to be used that way?

You should serialize a reference to the texture (such as its file name), not the texture itself. That way when you load the serialized game object later, you know which texture to look up and associate with the object.
You don't want to serialize the entire texture with the object, because that would be a huge waste of space when objects started to share textures (when serialized, they'd each have a complete copy of the texture bytes). That's why the Texture2D object itself isn't marked as serializable. It's trying to protect you from yourself.
This is related to why it's generally a good idea to separate game logic state from rendering and visual presentation state.

One tip it to see the object constructor. You see that you only need the starting position and the filepath.

@GustavoMaciel Maciel Should I add a "filename" private field for every GameObject, serialize it and then while deserializing reload the texture using that filename?

@JoshPetrie In this simple case, what does it mean "separate game logic state from..."? Does it mean that the texture shouldn't be inside my GameObject class? Can please give me a simple pattern to show that?

At the basic level it means to keep anything directly render-related (like texture objects) out of your game logic classes. Have separate objects for rendering things, and at the top level of your game, facilitate the transfer of data between the two. It's a broad topic and you should be able to find many resources on such a separation of concerns by searching.


text:
LWJGL Camera Rotation Issues
I am quite new to LWJGL and OpenGL and I am trying to create an FPS camera. I had no problem with 2D stuff, so I decided to step things up and try and make some things in 3D. I have this 3D camera which I am working on, but for some reason my rotation doesn't seem to be working. The pitch and the yaw values are always 0.
Here is my code:
My3DGame.java
import static org.lwjgl.opengl.GL11.*;

import org.lwjgl.LWJGLException;
import org.lwjgl.input.Keyboard;
import org.lwjgl.input.Mouse;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
import org.lwjgl.util.glu.GLU;

public class My3DGame {

private static My3DGame instance;

private final int DISPLAY_WIDTH = 840;
private final int DISPLAY_HEIGHT = 480;
private final String DISPLAY_TITLE = "My 3D Game";

private final int FPS_CAP = 60;

public My3DGame() {
    try {
        Display.setDisplayMode(new DisplayMode(DISPLAY_WIDTH, DISPLAY_HEIGHT));
        Display.setTitle(DISPLAY_TITLE);
        Display.create();
    } catch (LWJGLException e) {
        e.printStackTrace();
    }

    init();
    initGL();

    while (!Display.isCloseRequested()) {
        render();
        update();
    }

    Display.destroy();
}

Camera camera;

private void init() {
    try {
        Mouse.create();
        Keyboard.create();
    } catch (LWJGLException e) {
        e.printStackTrace();
    }

    camera = new Camera(0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.15f, 2.4f);
    Mouse.setGrabbed(true);
}

private void initGL() {
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();

    GLU.gluPerspective(45.0f, ((float) DISPLAY_WIDTH) / ((float) DISPLAY_HEIGHT), 3.2f, 2.0f);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
}

private void update() {

    if (Keyboard.isKeyDown(Keyboard.KEY_ESCAPE) && Mouse.isGrabbed())
        Mouse.setGrabbed(false);

    if (Mouse.isButtonDown(0) && !Mouse.isGrabbed())
        Mouse.setGrabbed(true);

    if (!Mouse.isGrabbed())
        return;

    Mouse.setCursorPosition(DISPLAY_WIDTH / 2, DISPLAY_HEIGHT / 2);

    camera.update();
}

private void render() {
    glClear(GL_COLOR_BUFFER_BIT);

    glBegin(GL_QUADS);
    {
        glColor4f(3.2f, 23.1f, 0.2f, 1.0f);
        glVertex3f(100, 200, 1);
        glVertex3f(200, 200, 1);
        glVertex3f(200, 100, 1);
        glVertex3f(100, 100, 1);
    }
    glEnd();

    Display.update();
    Display.sync(FPS_CAP);
}

public static void main(String[] args) {
    instance = new My3DGame();
}

public static My3DGame getInstance() {
    return instance;
}

}

Camera.java
import static org.lwjgl.opengl.GL11.glLoadIdentity;
import static org.lwjgl.opengl.GL11.glRotatef;
import static org.lwjgl.opengl.GL11.glTranslatef;

import org.lwjgl.Sys;
import org.lwjgl.input.Keyboard;
import org.lwjgl.input.Mouse;
import org.lwjgl.util.vector.Vector3f;

public class Camera {

private Vector3f position = null;
private float pitch = 0.0f;
private float yaw = 0.0f;

private float sensitivity = 0.0f;
private float moveSpeed = 0.0f;

public Camera(float x, float y, float z, float pitch, float yaw, float sensitivity, float moveSpeed) {
    position = new Vector3f(x, y, z);
    this.pitch = pitch;
    this.yaw = yaw;
    this.moveSpeed = moveSpeed;
}

public Camera() {

}

public void pitch(float amount) {
    pitch += amount;
}

public void yaw(float amount) {
    yaw += amount;
}

public void walkForward(float distance) {
    position.x -= distance * (float) Math.sin(Math.toRadians(yaw));
    position.z += distance * (float) Math.cos(Math.toRadians(yaw));
}

public void walkBackwards(float distance) {
    position.x += distance * (float) Math.sin(Math.toRadians(yaw));
    position.z -= distance * (float) Math.cos(Math.toRadians(yaw));
}

public void strafeLeft(float distance) {
    position.x -= distance * (float) Math.sin(Math.toRadians(yaw - 90));
    position.z += distance * (float) Math.cos(Math.toRadians(yaw - 90));
}

public void strafeRight(float distance) {
    position.x -= distance * (float) Math.sin(Math.toRadians(yaw + 90));
    position.z += distance * (float) Math.cos(Math.toRadians(yaw + 90));
}

float dx = 0.0f;
float dy = 0.0f;
float dt = 0.0f;
long lastTime = 0L;
long time = 0L;

public void update() {

    time = Sys.getTime();
    dt = (time - lastTime) / 1000.0f;
    lastTime = time;

    dx = Mouse.getDX();
    dy = Mouse.getDY();

    yaw(dx * sensitivity);
    pitch(dy * sensitivity);

    System.out.println("DT: " + dt);

    if (Keyboard.isKeyDown(Keyboard.KEY_W)) // Move forward
    {
        walkForward(moveSpeed * dt);
    }
    if (Keyboard.isKeyDown(Keyboard.KEY_S)) // Move backwards
    {
        walkBackwards(moveSpeed * dt);
    }
    if (Keyboard.isKeyDown(Keyboard.KEY_A)) // Strafe left
    {
        strafeLeft(moveSpeed * dt);
    }
    if (Keyboard.isKeyDown(Keyboard.KEY_D)) // Strafe right
    {
        strafeRight(moveSpeed * dt);
    }

    System.out.println("Position: " + position.toString() + ", Pitch: " + pitch + ", Yaw: " + yaw);

    glLoadIdentity();

    glRotatef(pitch, 1.0f, 0.0f, 0.0f);
    glRotatef(yaw, 0.0f, 1.0f, 0.0f);
    glTranslatef(position.x, position.y, position.z);
}

}

make that edit an answer so we know you solved it (and how for future readers)

Ok, I'll do that now, I have to wait a day before I can accept it as my answer though.

I have fixed this now. I forgot to set the mouse sensitivity value in the constructor of Camera, which meant the sensitivity float was equal to 0.


text:
Texturing a PyOpenGL 3D Cube with PySDL2
So, I've just started learning OpenGL with PySDL2, and I've created a class that will create a cube to the window that I've created with PySDL2. What I'd like to do now, is to figure out a way to texture the cube. I don't believe that the actual texturing part is the problem, but actually loading the image. I've tried to do this with PySDL's image loader, but this causes an error from the OpenGL texture creator. Here is my code to load an texture and bind it to OpenGL:
def LoadTexture(self, filename):
    """Loads a texture for the cube"""
    surface = SDL_LoadBMP(filename)
    #Checks if the loading succeeded
    if surface:
        #Translate the LP_SDL_Surface-pointer got from SDL_LoadBMP() to a real SDL_Surface
        texture_surface = surface.contents
        texture_format = GL.GL_RGBA
        GL_TEXTURE_ID = GL.glGenTextures(1)
        GL.glBindTexture(GL.GL_TEXTURE_2D, GL_TEXTURE_ID)
        GL.glPixelStorei(GL.GL_UNPACK_ALIGNMENT, 1)
        GL.glTexImage2D(GL.GL_TEXTURE_2D, 0, 3, texture_surface.w, texture_surface.h, 0, texture_format, GL.GL_UNSIGNED_BYTE, texture_surface)
        return GL_TEXTURE_ID
    return None

And the error that gives looks like this:
TypeError: ("No array-type handler for type <class 'sdl2.surface.SDL_Surface'> (value: <sdl2.surface.SDL_Surface object at 0x030762B0>) registered", <OpenGL.GL.images.ImageInputConverter object at 0x02EC49F0>)

I'm using Python 3 so using something like PIL won't work for me. Any ideas how to get the texture loaded, preferably with PySDL2?

You should use the 'pixels' member of SDL_surface to get the raw data. see http://wiki.libsdl.org/SDL_Surface?highlight=%28%5CbCategoryStruct%5Cb%29%7C%28SDLStructTemplate%29 . I can't find any reference on .contents that you are using :|

Thanks, that totally fixed it. Since the SDL_LoadBMP returns a pointer instead of a proper object, I need to get the proper object from it by calling the .contents member.

You should use the 'pixels' member of SDL_surface to get the raw image data. See SDL_Surface.


text:
How does this formula for generating water waves work?
I have been trying to implement the wave equation described in this paper ("Water Simulating in Computer Graphics," Kai Li and Liming Wu) in Java. Part of the paper discusses modeling waves as a sum of sine waves ("sine wave piling"); in that section there an equation for describing a single sine wave:
Y（x，y，t）= A * cos（w *（x，y）+ wt * t + FI;

where

A = amplitude of wave
L = wave length
w = spatial angular frequency
s = speed
wt = temporal angular frequency
d = direction
FI = initiatory phase

I understand that it returns a vector, but I don't see what this section of the formula means:
w *（x，y）

I believe that w is a vector, but I'm not sure if it's a 3D vector or 2D vector, and how it is used. If you have time, could you please explain this formula to me?

This is interesting, but what does this have to do with Java?

I have been attempting to implement it into java. And thus i needed to simplify it.

I know you are implementing it in Java, but I don't think that a Java implementation wouldn't differ from a C++ implementation. This is more of a math/physics question than a programming question is what I am trying to say.

Oh yes you are right. Im sorry. I thought if someone knew java really well they might be able to help more or something. BUt yes you are right.

The function returns a scalar, but the variable w is indeed a vector. More traditionally, the one-dimensional wave function is written as:
Ψ(x,t) = A cos( k x - ω t )
In more than one dimension, for example waves in water instead of on a rope, the spatial part is written as the dot product of two vectors:
Ψ(x,t) = A cos( k·x - ω t )
In the formula you referred to, x is written in full as the two-dimensional vector (x,y), the vector k is called w and the symbol * is used to denote a dot product. The wavenumber (or angular spatial frequency) k indicates the direction in which the wave propagates and its magnitude is inversely proportional to the wavelength. The effect of different wavenumbers on the propagation of the wave is illustrated below.

Per request, below the Mathematica code used to generate these images:
a = 1;
k = {1,1};
\[Omega] = 2\[Pi];
Export["C:\\Users\\Mark\\tmp.gif",
    Table[
        Plot3D[
            a Cos[k.{x,y} - \[Omega] t],
            {x,-2,2},{y,-2,2},
            PlotRange->{-a,a},
            PlotLabel->"k = " <> ToString[k],
            AxesLabel->{"x","y",None},
            Ticks->{Automatic,Automatic,None}
        ],
        {t,0,.96,.04}
    ]
]

+1 for the graphic exemples ! don't know what you used to generate those, but its awesome.

i would love to know what you used too :)

@NeeL: Wolfram Mathematica. I've appended the code used to generate these animations.

The formula returns a scalar (the height of the water surface at coordinates x,y), not a vector.
It is hard to tell what the authors had in mind, because the paper is very confused, but my guess is that it should have looked like this:
Y（x,y,t） = A * cos(w * f(x,y) + wt * t + FI)

Where f is a function that controls the shape of the wave.
This function will generate a circular wave centred at x0,y0:
f(x,y) = sqrt((x - x0)² + (y - y0)²)

This function will generate a directional wave with angle α:
f(x,y) = x * cos(α) + y * sin(α)


text:
3d Water Simulation formula questions
I have created a Grid:

At each point along the grid, is a vertex (Intersection Points):

Each of these points has an x,y,z position. Vector3f(x,y,z). In an attempt to animate the grid into a group of ocean waves, I used this formula to adjust the y position of each “Vertex”:

This is my attempt at implementing the formula into java:
private float sineY(int x, int y, float time) {
Vector2f position = new Vector2f(x, y);
float yPos = (float) ( (2 * amplitude) *Math.pow((Math.sin((wavenumber.dot(position))  + temporal_angular_freq * time +  initiatory_phase) + 1)/2, k));
    return yPos;
}

This function is running from inside a for loop that is updated every ms:
Time ++;
for (int y = 0; y < sizeY; y++) {
        for (int x = 0; x < sizeX; x++) {
            float xPos = x;
            float yPos = 0;
            float zPos = y;
            xPos += 0;
            yPos += sineY(x,y,time);
            zPos += 0;
            waterVertexPos.set(xPos, yPos, zPos);
            vertBufArray[index++] = waterVertexPos.getX();
            vertBufArray[index++] = waterVertexPos.getY();
            vertBufArray[index++] = waterVertexPos.getZ();
        }
    }

As you can see, for each vertex, along the grid, the yPosition of the vertex is set to whatever value the sineY method returns, which is whatever the above formula returns.
Running this code reults in this:
WHEN K = 1.0:

WHEN K = 1.5

As you can see, they both do not follow in accordance with this image here:

All the formulas and graphs have been retrieved from this pdf file. The aim of this program is to simulate water using the presented equations. The pdf is really interesting have a read if you like :)
Source:
http://http.developer.nvidia.com/GPUGems/gpugems_ch01.html
Thank you VERY MUCH for all of your time :)
EDIT:
After implementing the fix suggested by msell. It fixed this previous issue, however a new issue arose when the waves peaks still do not look as they did in the above graph:
WHEN K = 2.0:

The pdf specifies:
A common complaint about waves generated by summing sine waves directly is that they have too much "roll," that real waves have sharper peaks and wider troughs. As it turns out, there is a simple variant of the sine function that quite controllably gives this effect. We offset our sine function to be nonnegative and raise it to an exponent k. The function and its partial derivative with respect to x are.
And then refers to the formula mentioned above, and another formula:

Is there something wrong with my implementation?
And again. I cannot thank you enough for your time :)
Sidney de Vries

There is no + 1 in your function after Math.sin.

Make it the answer or something so i can Tick it as the answer :) Least i can do

Still an excellent question.

You have incorrectly implemented the formula as a function. The function is missing + 1 after the call to Math.sin(), which moves the wave to the range [0, 2].
Regarding your second problem, I don't see anything wrong. In fact the screenshot looks exactly like it should and seems to match the plotted curve. Try with k=10 and you should see the difference clearly.

I've update the question. If no one answers my new issue, ill vote this as the answer and remove part two.


text:
Gerstner wave function simplified?
The gerstner wave function is a commonly used method to calculate waves and simulate water in video games and movies or most 3d simulations. It is however quite complex so it is very hard for young developers such as myself to understand and implement it into code.
Would it be possible to simplify the formula:

A = amplitude of wave (Float)
W = wave number (Vector)
D = direction (Vector) how do i know what to set the direction to?
S = Speed
L = wave length
phase-constant = S x 2* pi/L.

According to the article Q = 1/(W * A)

Issues and Questions:

Why are all three lines of the formula seperated by commas?
D refers to a directional vector (i think)
Q = 1/(W * A) but W is a vector and A is a float?
What does this line mean: wiDi.(x,y) is that reffering to w * dot product of(d , (x,y))

sigma returns the sum of what exactly?

Here is my attempt to implement it into java code:
float yPos = (float) ((steepness * amplitude) * direction.y * Math.cos(wavenumber.y * (direction.dot(position)) + phase_const * time));

Dont know if its correct
This may help:
https://github.com/armanuguray/water-surface/blob/master/src/engine/waterengine.cpp

Here’s a tip: the common typographic convention for vectors is to use boldface.

I spend some time figuring this out, and ended up writing a post about it with very simplified, yet complete code here gerstner wave ocean.

Why are all three lines of the formula seperated by commas?

P(x,y,t) is a vector valued function. Its values are thus 3D vectors. The commas just separate these components, probably akin to a Matlab style of coding.

D refers to a directional vector (i think)

D is a 2D vector in the (x,y) plane. It describes the direction (and magnitude, if not noramlized!) of a principal wave component. Several such components (D_is) are actually added together, as seen in the formula, to equate the desired wavy/wobbly effect. It's akin to a Fourier decomposition of a signal into A sine + B cosine polynomials

Q = 1/(W * A) but W is a vector and A is a float?

W_i and A_i are both scalars! (1D values!). The A_i is the wave amplitude or height, whereas W_i should control the wave's sharpness (more pronounced crests)

What does this line mean: wiDi.(x,y) is that reffering to w * dot product of(d , (x,y))
sigma returns the sum of what exactly?

W_i multiplies the dot(Di,(x,y)). Thus the dot is taken between the wave direction and the current grid position, (x,y). This dot product appears in the arguments of two trig functions (cos and sin), and it is present in there to introduce a phase difference into the waves, otherwise all points  on the surface of the wave would have the same water level height (this explanation is a layman's view of something a bit more complicated - I can't fit the whole explanation here :( ).

Your pseudocode is looking ok-ish. It should actually be written as:
yPos += (float) ((steepness[i] * amplitude[i]) * direction[i].y * Math.cos(w[i] * (direction[i].dot(position[i])) + phase_const[i] * time));
..that is, you need at least N=2 (i=0,1,..N) different wave directions for something more interesting to develop, otherwise you're going to end up with a sine-like wave (pretty bland looking).


text:
LWJGL SlickUtil Texture Binding
I am making a 3D game using LWJGL and I have a texture class with static variables so that I only need to load textures once, even if I need to use them more than once. I am using Slick Util for this. When I bind a texture it works fine, but then when I try to render something else after I have rendered the model with the texture, the texture is still being bound. How do I unbind the texture and set the rendermode to the one that was in use before any textures were bound? Some of my code is below. The problem I am having is the player texture is being used in the box drawn around the player after it the model has been rendered.
Model.java
public class Model {

public List<Vector3f> vertices = new ArrayList<Vector3f>();
public List<Vector3f> normals = new ArrayList<Vector3f>();
public ArrayList<Vector2f> textureCoords = new ArrayList<Vector2f>();
public List<Face> faces = new ArrayList<Face>();

public static Model TREE;
public static Model PLAYER;

public static void loadModels() {
    try {
        TREE = OBJLoader.loadModel(new File("assets/model/tree_pine_0.obj"));
        PLAYER = OBJLoader.loadModel(new File("assets/model/player.obj"));
    } catch (Exception e) {
        e.printStackTrace();
    }
}

public void render(Vector3f position, Vector3f scale, Vector3f rotation, Texture texture, float shinyness) {
    glPushMatrix();
    {
        texture.bind();

        glColor3f(1, 1, 1);
        glTranslatef(position.x, position.y, position.z);
        glScalef(scale.x, scale.y, scale.z);
        glRotatef(rotation.x, 1, 0, 0);
        glRotatef(rotation.y, 0, 1, 0);
        glRotatef(rotation.z, 0, 0, 1);

        glMaterialf(GL_FRONT, GL_SHININESS, shinyness);

        glBegin(GL_TRIANGLES);
        {
            for (Face face : faces) {
                Vector2f t1 = textureCoords.get((int) face.textureCoords.x - 1);
                glTexCoord2f(t1.x, t1.y);
                Vector3f n1 = normals.get((int) face.normal.x - 1);
                glNormal3f(n1.x, n1.y, n1.z);
                Vector3f v1 = vertices.get((int) face.vertex.x - 1);
                glVertex3f(v1.x, v1.y, v1.z);

                Vector2f t2 = textureCoords.get((int) face.textureCoords.y - 1);
                glTexCoord2f(t2.x, t2.y);
                Vector3f n2 = normals.get((int) face.normal.y - 1);
                glNormal3f(n2.x, n2.y, n2.z);
                Vector3f v2 = vertices.get((int) face.vertex.y - 1);
                glVertex3f(v2.x, v2.y, v2.z);

                Vector2f t3 = textureCoords.get((int) face.textureCoords.z - 1);
                glTexCoord2f(t3.x, t3.y);
                Vector3f n3 = normals.get((int) face.normal.z - 1);
                glNormal3f(n3.x, n3.y, n3.z);
                Vector3f v3 = vertices.get((int) face.vertex.z - 1);
                glVertex3f(v3.x, v3.y, v3.z);
            }
            texture.release();
        }
        glEnd();
    }
    glPopMatrix();
}

}

Textures.java
public class Textures {

public static Texture FLOOR;
public static Texture PLAYER;

public static Texture SKYBOX_TOP;
public static Texture SKYBOX_BOTTOM;
public static Texture SKYBOX_FRONT;
public static Texture SKYBOX_BACK;
public static Texture SKYBOX_LEFT;
public static Texture SKYBOX_RIGHT;

public static void loadTextures() {
    try {
        FLOOR = TextureLoader.getTexture("PNG", new FileInputStream(new File("assets/model/floor.png")));
        FLOOR.setTextureFilter(GL11.GL_NEAREST);
        PLAYER = TextureLoader.getTexture("PNG", new FileInputStream(new File("assets/model/tree_pine_0.png")));
        PLAYER.setTextureFilter(GL11.GL_NEAREST);

        SKYBOX_TOP = TextureLoader.getTexture("PNG", new FileInputStream(new File("assets/textures/skybox_top.png")));
        SKYBOX_TOP.setTextureFilter(GL11.GL_NEAREST);
        SKYBOX_BOTTOM = TextureLoader.getTexture("PNG", new FileInputStream(new File("assets/textures/skybox_bottom.png")));
        SKYBOX_BOTTOM.setTextureFilter(GL11.GL_NEAREST);
        SKYBOX_FRONT = TextureLoader.getTexture("PNG", new FileInputStream(new File("assets/textures/skybox_front.png")));
        SKYBOX_FRONT.setTextureFilter(GL11.GL_NEAREST);
        SKYBOX_BACK = TextureLoader.getTexture("PNG", new FileInputStream(new File("assets/textures/skybox_back.png")));
        SKYBOX_BACK.setTextureFilter(GL11.GL_NEAREST);
        SKYBOX_LEFT = TextureLoader.getTexture("PNG", new FileInputStream(new File("assets/textures/skybox_left.png")));
        SKYBOX_LEFT.setTextureFilter(GL11.GL_NEAREST);
        SKYBOX_RIGHT = TextureLoader.getTexture("PNG", new FileInputStream(new File("assets/textures/skybox_right.png")));
        SKYBOX_RIGHT.setTextureFilter(GL11.GL_NEAREST);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

}

Player.java
public class Player {

private Vector3f position;
private float yaw;
private float moveSpeed;

public Player(float x, float y, float z, float yaw, float moveSpeed) {
    this.position = new Vector3f(x, y, z);
    this.yaw = yaw;
    this.moveSpeed = moveSpeed;
}

public void update() {
    if (Keyboard.isKeyDown(Keyboard.KEY_W))
        walkForward(moveSpeed);
    if (Keyboard.isKeyDown(Keyboard.KEY_S))
        walkBackwards(moveSpeed);
    if (Keyboard.isKeyDown(Keyboard.KEY_A))
        strafeLeft(moveSpeed);
    if (Keyboard.isKeyDown(Keyboard.KEY_D))
        strafeRight(moveSpeed);

    if (Mouse.isButtonDown(0))
        yaw += Mouse.getDX();

    LowPolyRPG.getInstance().getCamera().setPosition(-position.x, -position.y, -position.z);
    LowPolyRPG.getInstance().getCamera().setYaw(yaw);
}

public void walkForward(float distance) {
    position.setX(position.getX() + distance * (float) Math.sin(Math.toRadians(yaw)));
    position.setZ(position.getZ() - distance * (float) Math.cos(Math.toRadians(yaw)));
}

public void walkBackwards(float distance) {
    position.setX(position.getX() - distance * (float) Math.sin(Math.toRadians(yaw)));
    position.setZ(position.getZ() + distance * (float) Math.cos(Math.toRadians(yaw)));
}

public void strafeLeft(float distance) {
    position.setX(position.getX() + distance * (float) Math.sin(Math.toRadians(yaw - 90)));
    position.setZ(position.getZ() - distance * (float) Math.cos(Math.toRadians(yaw - 90)));
}

public void strafeRight(float distance) {
    position.setX(position.getX() + distance * (float) Math.sin(Math.toRadians(yaw + 90)));
    position.setZ(position.getZ() - distance * (float) Math.cos(Math.toRadians(yaw + 90)));
}

public void render() {
    Model.PLAYER.render(new Vector3f(position.x, position.y + 12, position.z), new Vector3f(3, 3, 3), new Vector3f(0, -yaw + 90, 0), Textures.PLAYER, 128);

    GL11.glPushMatrix();
    GL11.glTranslatef(position.getX(), position.getY(), position.getZ());
    GL11.glRotatef(-yaw, 0, 1, 0);
    GL11.glScalef(5.8f, 21, 2.2f);

    GL11.glDisable(GL11.GL_LIGHTING);

    GL11.glLineWidth(3);
    GL11.glBegin(GL11.GL_LINE_STRIP);

    GL11.glColor3f(1, 1, 1);

    glVertex3f(1f, 0f, -1f);
    glVertex3f(-1f, 0f, -1f);
    glVertex3f(-1f, 1f, -1f);
    glVertex3f(1f, 1f, -1f);

    glVertex3f(-1f, 0f, 1f);
    glVertex3f(1f, 0f, 1f);
    glVertex3f(1f, 1f, 1f);
    glVertex3f(-1f, 1f, 1f);

    glVertex3f(1f, 1f, -1f);
    glVertex3f(-1f, 1f, -1f);
    glVertex3f(-1f, 1f, 1f);
    glVertex3f(1f, 1f, 1f);

    glVertex3f(1f, 0f, 1f);
    glVertex3f(-1f, 0f, 1f);
    glVertex3f(-1f, 0f, -1f);
    glVertex3f(1f, 0f, -1f);

    glVertex3f(1f, 0f, 1f);
    glVertex3f(1f, 0f, -1f);
    glVertex3f(1f, 1f, -1f);
    glVertex3f(1f, 1f, 1f);

    glVertex3f(-1f, 0f, -1f);
    glVertex3f(-1f, 0f, 1f);
    glVertex3f(-1f, 1f, 1f);
    glVertex3f(-1f, 1f, -1f);

    GL11.glEnd();

    GL11.glEnable(GL11.GL_LIGHTING);

    GL11.glPopMatrix();
}

public Vector3f getPosition() {
    return new Vector3f(-position.x, -position.y, -position.z);
}

public float getX() {
    return position.getX();
}

public float getY() {
    return position.getY();
}

public float getZ() {
    return position.getZ();
}

public void setPosition(Vector3f position) {
    this.position = position;
}

public void setPosition(float x, float y, float z) {
    this.position.setX(x);
    this.position.setY(y);
    this.position.setZ(z);
}
}

Thanks for the help.

The quick way is enabling/disabling textures using glEnable(GL_TEXTURE_2D) / glDisable(GL_TEXTURE_2D). Whether it would be best to enable textures before rendering the player and then disabling them after or disabling them before the box and enabling them after, depends on the how/if the rest of your program uses textures throughout.

Most of my rendering is done using a texture so I tried disabling GL_TEXTURE_2D before I rendered the box around the player, and enabling it after but the texture still ends up being bound to the box when it is drawn.


text:
Most common format & good practice for 3D models for a placeholder in a PC game
I'm soon starting programming my first 3D game in OpenGL, C++, for PC. It's going to be a top-down space-based game.
Early on I want to create basic placeholder 3D models for my objects, and then in later stages (if I prove able to write C++ game mechanics successfully...) I'll collaborate with / employ a 3D model artist for the full textured models.
What's the best format to create these placeholders in for optimum integration later on?
Any particular advice for how to program it from the start to make it easier to work with the artist later on?

I would say that wavefront is the best one to start with. The .obj layout can be exported from almost every editor out there and is really easy to use(Read/write/modify).
The wavefront format is also easy to build upon and to get into a even better suited for your own needing later on, but when you start doing custom adds to it, you are going to need a special exporter from the artists editor.
There is also an awesome library called Assimp that will handle most of the different format loading for you, so you can focus on just hooking it with vertexs instead. Both links are worth a good dig-in-to.


text:
Why do I see a lot of games using Unreal engine when there are much better alternatives?
I play games on my computer often and I see a lot of games using the Unreal engine. Can someone explain why do developers choose to use this engine? In my opinion there are much better alternatives. For example games running on the cry engine look way better and the engine itself is more optimized.

Why do people still try to solve their differences with violence?

I don't understand your comment.

I'm trying to lead you gently to the idea that it's a matter of opinion, and that there might not always be a rational reason behind a game using one tech. over another except someones emotions.

The question is not appropriate for the site either way. Which Tech is more useful and why is a matter of opinion. Why are there dozens of brands of cars, clothes etc.

The only thing you have to do is run a benchmark and it will turn out that cry engine is like 2 times faster on the same hardware than the unreal engine.

The unreal engine, or more specifically the Unreal Development Kit (UDK) is a very versatile and user friendly engine. There is a big community involved with it and it has great documentation and support for it. Furthermore, everyone can use the complete engine for free until a good amount of cash is earned with your product, i believe that is $50.000 I'm not familiar with the cry engine but i'm pretty sure it is not as versatile. Other then that, you say the cry engine looks way better, i doubt that. Since UDK is so versatile you can write your own shaders for it, i have seen very beautiful shots from the UDK engine, though i never compared it with cry engine.
That being said, a developer should pick a platform that will work for his game. If you need all the optimization you can get don't pick an engine at all but write one in C++. That goes for all needs.


text:
Is padding brackets objectively the best way to write C programs?
void Function( int, char )
versus:
void Function (int,char)
My friend keeps saying otherwise. What is objectively the best way to write brackets?

It is important for each project to stick to a consistent coding style. But it is quite irrelevant which one you pick, as long as you just stay consistent. Any minute arguing about the best coding style is a minute of your life wasted.

Not only is this primarily opinion based, it's not game development specific. Please review the [help] before asking further questions.

There is not a best way. There is just a preferred way, and that changes from person to person. There are many different semantics that various programmers with bicker on about style. I have personally seen the following 3 ways in commercial code:
void DoSomething(int,float,string);
void DoSomething(int, float, string);
void DoSomething( int, float , string );
Although I have a preference for one of these, I can't tell someone that my way is best. Therefore the best advice is to write what works best for you, or the chosen style for a given collaborated project.

Though I will say that if you write the first version, you will annoy many other programmers you work with. "Space-averse" programming results in dense, hard-to-read code. Also, can you fix that extra space after the third float? I can't edit it since it's a single-character edit.

Oh totally. But that hasn't stopped the horrible messes of projects with that style :p

Case in point: http://hg.icculus.org/icculus/lugaru/file/97b303e79826/Source/GameTick.cpp#l7276

There's some severe tabbing issues going on there. Someone needs to learn how to use functions =P

There is no best way, but there are some cases where one way is better than another.

If you're working as part of a team, that team will have it's own coding style, and you should conform to that.
If you've inherited a bunch of legacy code you may prefer to conform to the coding style already used by that legacy code.
If you're coding something on your own you can sometimes just use whichever style you find most readable.
If you're writing something where a pre-defined style already exists and is expected to be used (e.g a GNU utility) you'd better use that pre-defined style.

However, in a world where source code formatters exist and are common (and free) discussions or arguments over coding style seem silly.


text:
Where do I store (or how do I refer to) textures for custom blocks?
I'm making my first foray into Minecraft modding on Ubuntu using Minecraft Forge. I'm finding it a little hard to get started as many of the tutorials seem to refer to older versions of Minecraft (e.g. that use the BaseMod base class, which now appears to be deprecated).
I've created a simple block type:
package net.minecraft.block;

import net.minecraft.block.*;
import net.minecraft.block.material.*;

public class RolyBlock extends Block {
    public RolyBlock(int par1, Material par2Material) {
        super(par1, par2Material);
    }
}

and added the following static initialiser to the Block class:
public static final Block rolyBlock = new RolyBlock(174, Material.rock)
                                      .setHardness(1.5F)
                                      .setResistance(10)
                                      .setStepSound(soundStoneFootstep)
                                      .setUnlocalizedName("rolyBlock")
                                      .setCreativeTab(CreativeTabs.tabBlock)
                                      .setTextureName("roly_block");

I created a 256x256 PNG file called roly_block and placed it in Forge's MCP folder, in the same location as the other textures. However, when I start Minecraft (v. 1.6.5) via Eclipse, it is unable to locate the texture:
2014-03-14 11:38:34 [SEVERE] [Minecraft-Client] Using missing texture,
unable to load: minecraft:textures/blocks/roly_block.png

I suspect this is because I put the texture in the directory
forge/mcp/temp/src/minecraft/assets/minecraft/textures

(where I found the other textures) where this temp folder is presumably a decompiled version of the Minecraft 1.6.5 .jar file. I can't actually remember how I ended up with this folder, though.
My question is: how do I add a new texture to my Eclipse mod development environment? Must I rebuild a .jar each time, and if so how? Or can I have Minecraft load textures from a directory?
(I'm a complete Minecraft newbie, so there are many things about the configuration/dev environment for Minecraft that are confusing me. For example if I run recompile.py from Forge's MCP folder, I get a swathe of errors relating to IconRegister not being found.)

The String you pass to setTextureName() has a special format which isn't very well documented. If you just pass it a filename such as roly_block, it internally gets changed like so.
No mod is specified, so it assumes it's a default Minecraft file, and as you're calling it from a Block class, it knows you're talking about a Block texture and all textures are .png so it becomes:
"minecraft:textures/blocks/roly_block.png"

Which is then evaluated to the following file:
assets\minecraft\textures\blocks\roly_block.png

What you should use is the lower case Forge Mod ID followed by a colon, let's assume that's rolymod, you'd pass it the string:
"rolymod:roly_block"

Then in the same way, this will be evaluated to the file:
assets\rolymod\textures\blocks\roly_block.png

This makes it much easier to keep your assets separated from the defaults as well as other mods. You shouldn't need to rebuild your mod jar to test it either.

Thanks. I got it working in the end (finally figured out the location of the 'assets' folder), but forgot to come back and answer my own question. So, I'll accept yours.


text:
UV Texture coordinates out of [0,1] (WebGL)
I'm creating a 3D game with WebGL and i'm using Wavefront Objects as a base model format.
I recently found some models, their texture coordinates of which are out of the typical [0,1] range and i really don't know how to handle them (in code).
I know of course this is a known issue, texture coordinates can be outside of [0,1] and the solution is to use GL_REPEAT wrap mode.
But this is no solution to me since i have a lot of non-powered-by-2 textures and i need to use CLAMP_TO_EDGE wrap mode (the solution to non-pow-2 textures).
I tried to bypass this issue by coding, so to convert [0-,1+] ranges into [0,1] but with not much of success (although somewhat). Here's what i did:
I looped "vt" entries (from my parser) and the cases i'm checking are these (pseudo):
U,V = texture coordinates as they come from file

if (U<0) {
   U = U + Math.abs( Math.floor(U) );
}
if (U>1) {
   U = U - Math.floor(U);
}
if (V>=0) {
   V = Math.ceil(V) - V;
}
if (V<0) {
   V = Math.abs( Math.floor(V) - V );
}

The above fragment will take a U,V of unknown range and will convert it into [0,1], taking also care the WebGL texture coordination system (0,0 buttom-left for WebGL but 0,1 for Wavefront, the 3rd case above)
The numbers are calculated correctly but the result is not the expected and i'm afraid there is a misunderstanding by my side on how the GL_REPEAT mode works.
So my question(s)

Can this be solved by code, so i can use CLAMP_TO_EDGE?
In case there's no way, is there any program than can take a model of REPEAT-ed coordinates and produce one in [0,1] range? I'm already using Blender but could not find a setting for this in exporter.

I think you would be better off re-sizing your textures to the nearest power-of-two. You won't need to adjust the texture coordinates as they are relative to the size of the texture image (although you may need to set v = 1 - v to account for the different origins).
The problem with wrapping the texture coordinates yourself is that filtering will not work correctly at the "seams" where a value goes suddenly from 1 -> 0.

Thanx, well i ended up by resizing all of my textures of my paid models. I am quite surprised there's no solution to this. In my opinion texture coordinates outside [0,1] are just wrong and weird and there's no solution for converting, yet Open/Web GL REPEAT mode is the default. I'm confused but hey, thanx for clearing that out :)


text:
(WebGL) Point light per-fragment issue
I'm using an FPS-like camera, this is the code:
CAMERA
mat4.identity(mat.mvMatrix);
mat4.rotate(mat.mvMatrix,degToRad(-camera.pitch),[1,0,0]);
mat4.rotate(mat.mvMatrix,degToRad(-camera.yaw),[0,1,0]);
mat4.translate(mat.mvMatrix,[-camera.pos[0],-camera.pos[1],-camera.pos[2]]);

The above code produces the model-view matrix as i roam the map (handling the camera position via WSAD style keys)
The uMVMatrix from vertex shader is the passed mat.mvMatrix from the above code.
I'm also using a shader for point lighting per-fragment in WebGL, the fragments are:
VS
vPosition = uMVMatrix * vec4(aVertexPosition, 1.0);
gl_Position = uPMatrix * vPosition;
vTransformedNormal = uNMatrix * aVertexNormal;
// pass to fragment shader
vColorLight = uColorLight;
vColorAmbient = uColorAmbient;
vLightPosition = uLightPosition;

FS
vec3 lightDirection = normalize(vLightPosition - vPosition.xyz);
float directionalLightWeighting = max(dot(normalize(vTransformedNormal), lightDirection), 0.0);
vec3 lightWeighting = vColorAmbient + vColorLight * directionalLightWeighting;
vec4 textureColor = texture2D(uTex0, vec2(vTextureCoord.s, vTextureCoord.t));
gl_FragColor = vec4(textureColor.rgb * lightWeighting, textureColor.a);

The vLightPosition is actually the camera's position (the light position moves as i move around)
I don't have a problem by moving around and putting correctly transformed objects.
But my lighting position seems to run away from me (i can't describe it better) as i roam the map. At position [0,0,0] is good, but as i move from there i can see actually the light source goes far away, and actually sinking (although i'm not changing my height =Y position)
Surprisingly, i solved the above problem by multiplying the input vLightPosition by 0.00054687 (!) before i send it to shader, where it gave me a centered bulb in the terrain. I post 2 images to illustrate this:
When i multiply my light position by the above number...
var lightPosition = [5,2,5];   // just example
gl.uniform3f(gl.getUniformLocation(program,"uLightPosition"),
             parseFloat(lightPosition[0])*0.00054687,
             parseFloat(lightPosition[1])*0.00054687,
             parseFloat(lightPosition[2])*0.00054687);

When i'm passing light position directly as camera position..
var lightPosition = [5,2,5];   // just example
gl.uniform3f(gl.getUniformLocation(program,"uLightPosition"),
             parseFloat(lightPosition[0]),
             parseFloat(lightPosition[1]),
             parseFloat(lightPosition[2]));

In fact you can hardly see a light source that comes from far, far away (stones are lit).
It seems i need to scale down my input light position to microscope level, yet i dont understand why and though i solved it mostly by luck, i would like to know where's the problem to prevent future issues.
Thanx
EDIT
My full shader fragments:
VS
precision mediump float;

attribute vec3 aVertexPosition;
attribute vec3 aVertexNormal;
attribute vec2 aTextureCoord;
uniform mat4 uMVMatrix;
uniform mat4 uPMatrix;
uniform mat3 uNMatrix;

// lighting
uniform int uLightType;
// general
uniform vec3 uColorAmbient;
uniform vec3 uColorLight;
// directional light
uniform vec3 uLightDirection;
// point light
uniform vec3 uLightPosition;

varying vec3 vTransformedNormal;
varying vec4 vPosition;

// lighting on fragment shader
varying vec3 vColorAmbient;
varying vec3 vColorLight;
varying vec3 vLightPosition;

varying vec2 vTextureCoord;
varying vec3 vLightWeighting;

void main(void) {
    vTextureCoord = aTextureCoord;
    // none light
    if (uLightType==0) {
       gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0);
       vLightWeighting = vec3(1.0, 1.0, 1.0);
    }
    // directional light
    else if (uLightType==1) {
       gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0);
       vec3 transformedNormal = uNMatrix * aVertexNormal;
       float directionalLightWeighting = max(dot(transformedNormal, uLightDirection), 0.0);
       vLightWeighting = uColorAmbient + uColorLight * directionalLightWeighting;
    }
    // point light (per-fragment)
    else if (uLightType==2) {
       vPosition = uMVMatrix * vec4(aVertexPosition, 1.0);
       gl_Position = uPMatrix * vPosition;
       vTransformedNormal = uNMatrix * aVertexNormal;
       // pass to fragment shader
       vColorLight = uColorLight;
       vColorAmbient = uColorAmbient;

       vLightPosition = uLightPosition;
       //      vLightPosition = uMVMatrix * uLightPosition;
       //      vLightPosition = uMVMatrix * vec4(uLightPosition, 1.0);
       //      vLightPosition = (uMVMatrix * uLightPosition).xyz;
               vLightPosition = (uMVMatrix * vec4(uLightPosition, 1.0)).xyz;

    }
 }

FS
precision mediump float;
varying vec2 vTextureCoord;
varying vec3 vLightWeighting;
uniform sampler2D uTex0;

uniform int fLightType;
varying vec4 vPosition;
varying vec3 vTransformedNormal;
// lighting
varying vec3 vColorAmbient;
varying vec3 vColorLight;
varying vec3 vLightPosition;

void main(void) {
   // point light (per-fragment)
   if (fLightType==2) {
      vec3 lightDirection = normalize(vLightPosition - vPosition.xyz);

      float directionalLightWeighting = max(dot(normalize(vTransformedNormal), lightDirection), 0.0);

      vec3 lightWeighting = vColorAmbient + vColorLight * directionalLightWeighting;
      vec4 textureColor = texture2D(uTex0, vec2(vTextureCoord.s, vTextureCoord.t));
      gl_FragColor = vec4(textureColor.rgb * lightWeighting, textureColor.a);
   }
   else {
      vec4 textureColor = texture2D(uTex0, vec2(vTextureCoord.s, vTextureCoord.t));
      gl_FragColor = vec4(textureColor.rgb * vLightWeighting, textureColor.a);

   }
}

EDIT2

vec3 lightDirection = normalize(vLightPosition - vPosition.xyz);

vPosition is in view/camera space, vLightPosition is in world space, hence the buggy results.
You need to transform your light from world coordinates to view coordinates, i.e. multiply the light coordinates by the view matrix (just as you multiplied the position by the model-view matrix).

I did vLightPosition = uMVMatrix * uLightPosition but since light position is a vec3 and not vec4 (like vPosition) it doesnt allow me.

So make it a vec4: uMVMatrix * vec4(vLightPosition, 1.0);

I tried that too with error ERROR: 0:56: 'assign' :  cannot convert from '-component vector of float' to 'varying mediump -component vector of float'

It's probably complaining about trying to assign a vec4 to a vec3. Try it like this: vLightPosition = (uMVMatrix * vec4(uLightPosition, 1.0)).xyz;

Lots of errors now :). They are:  ERROR: 0:57: '*' :  wrong operand types  no operation '*' exists that takes a left-hand operand of type 'uniform mediump X matrix of float' and a right operand of type 'uniform mediump -component vector of float' (or there is no acceptable conversion) ERROR: 0:57: 'xyz' : illegal length of matrix field selection  ERROR: 0:57: 'assign' :  cannot convert from 'float' to 'varying mediump -component vector of float'

It would help, yes, if you posted the full vertex shader.

I can't tell what it's throwing errors for. vLightPosition = (uMVMatrix * vec4(uLightPosition, 1.0)).xyz; should work, it's the exact same thing you are doing with gl_Position in =0, except with an added .xyz swizzle. I just tried the syntax in a shader of my own, it worked just fine.

Check my second edit (image) in my post, it seems the bulb is finally centered under me with your help, hence no lighting in front of wall. It seems the bulb moves with me but like without spiting light :)

So the light is moving as it should, but it's not lighting things up properly? Try negating lightDirection in your fragment shader (if the dot product is negative, max() will return 0.0).

Do you mean this: float directionalLightWeighting = max(dot(normalize(vTransformedNormal), -lightDirection), 0.0). Seems like it negates normals as well (i got bulb under terrain). I'm not sure if it helps, but seems like light source comes somewhere from the right, yet bulb is right under me. Weird.

It's not that then. Just one more point, you are currently multiplying the light position by the model-view matrix. That means that any transformations applied to the model you are currently rendering will be applied to the light as well. To avoid this you are going to have to pass the view matrix to the vertex shader as well, use that for your light position computation.

Hmm it seems there was a huge problem with original model's normals as well. I recalculated them via a function of mine (typical per-face) and problem seems was already solved by your latest solution (.xyz) above which centered the light position. I thought i was already sending the model's transform via UMVMatrix; this one is sent just before each call to gl.drawArrays. I hope it's over now :)


text:
Best mobile games resolution ratio
What is the best landscape and portrait resolution ratios that will fit the most of the devices out there and the black bars size will be minimum?

What have you researched?  The question appears to be too broad.

We'd also need to know more about the nature of what you are displaying. Can you pad with a background image? Can you increase the field of view to use any display shape? Why must your game must have a fixed aspect ratio? Check out the section titled "The Problems of Resolution and Aspect Ratio", starting at page 113 of this online book (link is to page 114, scroll up a bit) and continuing to page 116.

For minimizing the amount of black bars you should aim around the median ratio of target devices, that would probably be 8:5 or 5:3.
But if you really need your game to be a fixed ratio, consider using some filler art instead of black bars, you might simply have a playing field background with some out of bounds area that is cropped away depending on screen aspect ratio.


text:
How do I get hardware accelerated graphics and shaders in PyGame?
I have created several simple games with PyGame, but until now, I have focused on mechanics rather than graphics. The graphics in my games have been extremely rudimentary, consisting of basic shapes on black backgrounds.
I've recently decided to change that and create a 2D graphics engine supporting proper texturing, some animation, and most importantly: lighting. While researching these, especially the last, I've started doubting whether PyGame is the right tool for this. Many tutorials concering implementation of lighting, shadows, et cetera recommend using techniques such as GPU shaders and pixel-level manipulation.
Looking at the documentation of PyGame, I don't see anything that would let me implement such things with any degree of efficiency. I can access bitmaps directly with PixelArray, but doing any significant processing this way seems like it would be a performance nightmare.
How can I get hardware accelerated graphics, vertex and pixel shaders when making a game with PyGame?

My problem isn't quite what technology to use in my specific case, but rather understanding the capabilities and applications of the technologies I mentioned. I honestly can't tell if that is within the guidelines.

I edited your question to focus on getting hardware/GPU access with PyGame. For your original, more broad questions, you may want to read the [help] and look for the list of other sites you can ask those broad discussion-oriented questions on.

Thank you, that's better than I could have done. I'm very confused about this topic as a whole, so knowing how to ask a specific question is difficult for me.

PyGame itself, being a wrapper around SDL, is unable to directly use hardware acceleration. You can, however, use PyGame to create an OpenGL context and then render into that via an OpenGL library like pyglet or PyOpenGL, which will let you then also use GLSL vertex and fragment shaders.
This blog post does a good job of explaining the basics of using PyGame in conjunction with each other (domain now not working but archive available on archive.org).

http://www.jason-hayes.com/?page_id=37 is a broken link


text:
SDL_GameController automatic detection
Here's something that's been bugging me all day: Controller detection in SDL.
First thing is that it doesn't automatically detect when a controller is connected. Finding out when a controller is disconnected is no problem:
if(joystick.closed > 0) { SendEvent(E_CONTROLLER_DISCONNECTED); //cleanup }

I simply have a little loop to detect for new controllers:
SDL_QuitSubSystem(SDL_INIT_JOYSTICK);
SDL_InitSubSystem(SDL_INIT_JOYSTICK);
joysticks_.Clear();
joysticks_.Resize(SDL_NumJoysticks());

Which works but is very, very slow. Regardless if I have a controller plugged in or not, this step alone takes 10-20ms. Even spacing it apart every few seconds, there are obviously noticable lag spikes whenever I am doing the detection; even with another thread, the lag spikes are still there. However I have not found any better alternative.
This type of behavior is imperitive to proper operation. This is especially so since if a controller gets disconnected, it won't automatically re-open in SDL when I reconnected it. Is there any better way to do this?
Oh, and as another point to make, I don't want to use SDL Events. They do basically what I've listed above, but don't work well with my existing multithreaded approach.

Only allow controllers to be plugged in while in a menu?

Is upgrading to SDL 2.0 an option for you?  The new version reportedly supports hot-plugging joysticks.

I'm running 2.0.1 atm.

There's only one clean way, and that's to use a SDL_Event regardless.  I don't know how you are handling event so that it is inconvenient in your architecture, but have you considered Event Filters ?
Basically you register a callback that catches the events before they are pushed to the event queue.  If the event is a SDL_JOYDEVICEADDED or SDL_JOYDEVICEREMOVED event, you can handle the joystick behavior there or warn some other thread and return 0 (do not push the event in the queue).  Else you do nothing and return 1 (push the event in the queue).  That way you can treat joystick event as soon as they are spawned, and you don't need to treat every event in the queue first.
For more specific answer, we need more specific details of your architecture.

I really just have to man it up and use events. I've been playing around with SDL2 all day, and I've come to realize that there's just no way around it. Thanks for the filter idea, though I ended up using something different.


text:
XNA C# Mario Collide
I'm trying to make Mario so im trying to do the collision part but whenever I do the side collision it bounces back too far. I want to make it so that it only stops Mario not bounces him back.
        public void MarioBrickCollide()
    {
        for (int collide = 0; collide < brick.Length; collide++)
        {
            if (Mariovec.Y <= brickvec[collide].Y && Mariovec.Y + Mario.Height + 3 > brickvec[collide].Y && Mariovec.X + Mario.Width > brickvec[collide].X && Mariovec.X < brickvec[collide].X + brick[collide].Width)
            {
                Mariovel.Y = 0;
                brickHitTop = true;
            }
            if (Mariovec.X + Mario.Width >= brickvec[0].X && Mariovec.X < brickvec[0].X + brick[0].Width && Mariovec.Y + Mario.Height > brickvec[0].Y && Mariovec.Y < brickvec[0].Y)
            {
                Mariovec.X = brickvec[collide].X - Mario.Width;
            }
        }
    }

What can I do to make the collisions work?

Formatted your code so I can read it:
public void MarioBrickCollide() {
   for (int collide = 0; collide < brick.Length; collide++) {
      if (Mariovec.Y <= brickvec[collide].Y
         && Mariovec.Y + Mario.Height + 3 > brickvec[collide].Y
         && Mariovec.X + Mario.Width > brickvec[collide].X
         && Mariovec.X < brickvec[collide].X + brick[collide].Width
      ) {
         Mariovel.Y = 0;
         brickHitTop = true;
      }

      if (Mariovec.X + Mario.Width >= brickvec[0].X
         && Mariovec.X < brickvec[0].X + brick[0].Width
         && Mariovec.Y + Mario.Height > brickvec[0].Y
         && Mariovec.Y < brickvec[0].Y
      )
         Mariovec.X = brickvec[collide].X - Mario.Width;
    }
}

should the 0 indexes in the second if statement actually be collide instead?

This looks more like an edit and a comment than an answer.


text:
Copying rotation between matrices
I have a transformed Matrix A and an another transformed Matrix B. How can I COPY the rotation of Matrix B to Matrix A?

what language ?

What do you mean transformed Matrix A & B? You use matrices as transformation on vectors. Do you mean you wish to find a matrix C such that BC = A?

This belongs to http://math.stackexchange.com/

This question belongs on http://math.stackexchange.com/

I think this question does belong on GameDev - as I outline in my answer below, there are certain conventions in game development that make this easier to answer for the matrices we usually care about than for the general/pure math case.

Generally the "top-left" 3x3 block of coefficients will be the rotation/scale/shear component of a 4x4 (or 3x4) transformation matrix.
If both matrices have no scale (including reflection) or shear, you can simply copy this block of coefficients, something like:
matrixA[0][0] = matrixB[0][0];
matrixA[0][1] = matrixB[0][1];
matrixA[0][2] = matrixB[0][2];

matrixA[1][0] = matrixB[1][0];
...
matrixA[2][2] = matrixB[2][2];
// Leave row [3] and column [3] alone.

If both matrices contain some scale aligned to the axes of the source space (eg. if these are ModelView matrices, and they contain scale solely along the model's local x, y, and z axes, as is a common convention in games), but still no shearing, then it's a little bit trickier but still feasible. The details will depend on your environment's conventions for matrix storage and multiplication.
In principle you can take the basis vectors from matrix B (these will be the rows of the top-left 3x3 block, or the columns, depending on your environment), normalize them, then multiply each by the corresponding scale coefficient for A, something like:
(abusing some hlsl notation to keep this compact...)
matrixA[0].xyz = scaleA.x * normalize(matrixB[0].xyz);
matrixA[1].xyz = scaleA.y * normalize(matrixB[1].xyz);
matrixA[2].xyz = scaleA.z * normalize(matrixB[2].xyz);

(You may need to transpose your matrices before & after this operation, if your environment uses the opposite row/column convention)
If either matrix contains shear, or scaling that isn't aligned to axes within the source coordinate space, then it becomes ambiguous what "copying the rotation" from one to the other would mean. Fortunately we don't encounter those types of matrices too often in gamedev, apart from perspective projection matrices.

I can't believe I'm this stupid. "simply copy this block of coefficients" - this is the answer to my problem. Thank you.

There's nothing "stupid" about asking a question when you're unsure - and now this question will provide a resource others can find easily if they find themselves wondering the same thing. :)

I assume you work with a homogenous transformation matrix like those used with OpenGL.
Your question implies that you assume that one can extract a rotation part from that transformation matrix.
Or more mathematically speaking, that it is possible
to factor the transformation into a product of simpler transformations, where one
of the simpler transformations is a rotation.
It turns out that this is not such easy for an arbitrary homogenous transformation matrices. In general there are many decompositions possible with different resulting rotation matrices which might or might not be useful for your purpose.
E.g. you can try a polar decomposition to factor a homogenous transformation matrix M into
M = P T R N S = Q S

where

P is a simple perspective matrix
Tis a translation matrix
Ris a rotation matrix
N is either I (identity matrix) or -I
S is a stretch matrix
Q is an orthogonal matrix (length and angle preserving, i.e. a combination of rotations and reflections)

The situation can be simpler if you can assume that the transformation matrix is the result of multiplying only a restricted set of intermediate transformation, see this blog post.
Also see this SO entry.
And this Math.SE entry on SVD, but beware, read the comments about the numerical and graphical properties of that decomposition in the above paper about polar decomposition.


text:
3D Background for a Verticle Shooter: Making it loop?
I know how to scroll a background using spritebatches + 2D background images, but how would I do it with a 3D model?

You will first need to ensure the model actual tiles seamlessly in the direction you want it to scroll. Then, a simple solution is to draw the model twice.
Consider the viewport of your game, represented by this ASCII box:
+------------+
|            |
|            |
|            |
+------------+

When you draw your 3D background model, represented by the ASCII M, it normally ends up looking something like this:
   MMMMMMMM
   MMMMMMMM
+------------+
|  MMMMMMMM  |
|  MMMMMMMM  |
|  MMMMMMMM  |
+------------+

That is, some portion of the model is visible and some portion is outside the viewing area. To "loop" this background model, you detect when the edge of the model is about to come into view (this is a simple rectangle-rectangle containment test, because you can project the bounding volume of your model onto your viewing plane), and the frame just before the edge would be visible, you draw a second copy of the model above the first (represented below by the ASCII 'm'):
   mmmmmmmm
   mmmmmmmm
   MMMMMMMM
+------------+
|  MMMMMMMM  |
|  MMMMMMMM  |
|  MMMMMMMM  |
+------------+
   MMMMMMMM
   MMMMMMMM

As the game continues to scroll, both models are onscreen, giving the illusion of a seamlessly tiling world:
   mmmmmmmm
   mmmmmmmm
   mmmmmmmm
+------------+
|  mmmmmmmm  |
|  mmmmmmmm  |
|  MMMMMMMM  |
+------------+
   MMMMMMMM
   MMMMMMMM
   MMMMMMMM

Once the first model has scrolled entirely off the screen you can stop drawing it, so at most you are only rendering the model twice.
If the model is particularly huge, you may want to break it into smaller chunks simply to avoid all the extra geometry processing to determine that large portions of the model are offscreen.