text:
Is caching tiles like this a good idea?
I have a 2d int array which represents tiles on level like this:
0000000000000000000000
0000000000000000000000
0000000000000000000000
1111111111111111111111

I have a tileset vector, where each element has it's own tileX and tileY value(position of a tile in a tileset image), collision data etc. So, when I draw a level each time I draw a tile, I ask about them like this:
draw(tileset[currentTile]->tx, tileset[currentTile]->tY, tileWidth, tileHeight);

But, as you can see, there will be lots of the same elements when I iterate through for loop, so do I need to keep lastCollisionData variable in level class to reduce time used to access each tile separately?

I'm not sure what you're asking about. Are you wondering about run length encoding your tile data? Or sharing a pointer to similar tile data if said tile data takes up a lot of memory? Or something else?

I can't use lenght encoding, because I'm not really sure data will always stay the same way. I'm just wondering if storing last value will be faster than accessing vector

It's not clear exactly what you'd be caching, because you've not told us what 'lastCollisionData' means or what it's used for, or why caching a previous value will help.

Well, every tile has it's own collision property. It's just an int. (0 - solid, 1 -walkable, for example). So instead of trying to find those values using tiles id, I can just compare id and if it was the same as now, that I don't need to search in vector

Ok, are you trying to say that each position in your level tiles does not have collision data, but that each tile type does? And that you don't want to have to look up the properties of the tile type each time? If so, then no - that's a premature optimisation.

Yeah, I don't need to do this every frame, but I have to get position of left-top corner of tile texture in a tileset image to draw it.

Depending on how many times you need to traverse the list, as well as how big it will be in the long run, using something such as run length encoding could be valuable, but you have to consider the time required to encode the tiles each time there is a change to it. This is a situation where the trade off of more time spent up front, could increase performance during actual usage. If the performance hit is insignificant though, then it may not be necessary at all.
edit run length encoding is a process for identifying multiple values of the same time within a single run. For instance, rather than representing 00000000 as so, it could be represented as 80, where 8 represents the number, and 0 the value. Of course this takes time up front to perform the encoding, and may not save you time depending on how you are using the data.
http://en.wikipedia.org/wiki/Run-length_encoding

Well, drawing is 60 frames per second and there are like 50-60 tiles on the screen on the moment, so I need to access elements of vector for 60 * 2 times(to get tx, ty) per frame

The amount of effort necessary to traverse the list and get position information isn't significant. I would say unless you are seeing legitimate performance issues from this specific process, it isn't worth stressing over.

Thanks, I'm just beginning to make my game and worry about everything because there will be a lot more stuff on the screen so I won't really know what causes perfomance issues

@winch keep measuring performance of it and you'll know how your changes effect your performance as you add them.


text:
League of Legends Spectator Stream Format
Intro
I have been fiddling around with the spectator system for LoL in hopes of eventually scraping data from the streams and building a dataset with it for analysis.  I understand that there are already some unofficial APIs and techniques, but I am looking for really specific game events (champion kills, turret kills, item puchases, jungle mob kills, champion co-ords for particular events, etc).
What I have figured out so far
When you begin spectating a game (in NA), your client connects to the following host:
spectator.na.lol.riotgames.com:8088
I assume this host is backed by Amazon AWS or similar.  Anyways, the next thing that happens is the client sends a version request to the spectate server:
GET /observer-mode/rest/consumer/version
This returns whatever the current spectator server version is. Ex: '1.80.54'
Next, the client sends a request for the game metadata:
GET /observer-mode/rest/consumer/getGameMetaData/NA1/[gameid]/[some random nonce]/token
This returns metadata about the game. An example of this data: http://pastebin.com/3N4qs0hx
The client now knows the parameters by which the spectate session should progress. It tries to locate the latest data chunk by calling:
GET /observer-mode/rest/consumer/getLastChunkInfo/NA1/[gameid]/30000/token
Sample of this data: http://pastebin.com/Cj7dEAr9
Once the data chunks have been identified, they are requested:
GET /observer-mode/rest/consumer/getGameDataChunk/NA1/[gameid]/[token#]/token
Sample of a token's data (binary converted to hex): http:// pastebin.com /GyqPRP5J
The game cycles between calling getLastChunkInfo and getGameDataChunk as data becomes available from the replay stream. There is also a call which occurs after about 5 chunks are grabbed to the following:
GET /observer-mode/rest/consumer/getKeyFrame/NA1/[gameid]/[somechunkid]/token
I believe this call only occurs at the replay start up and whenever the user seeks to a different time.
I know the game uses encryption at some level. I believe it to be Blowfish ECB, with the actual key specified on the command line. I have attempted to decrypt these tokens using the session's key, but they still look pretty random.
Edit 3/23/2013

I have determined that the tokens are most likely not encrypted by modifying the command line argument containing the key and re-launching the game from debugger (it loaded the replay correctly).
The tokens seem to be compressed. There is a call to a subroutine which if returns non-zero integer will trigger the following:
if ( sub_B71120(v21, v15, (int *)&Size, *(_DWORD *)(v6 + 108)) )
{
sub_BAD700(
(int)"!\"Error Decompressing data chunk.\"",
(int)"D:\\jenkins\\workspace\\Code-CI-Releases-Public\\code\\HeroWars_clientServer\\Sources\\ReplaySystem\\ReplayServerConnection.cpp",
6,
(int)"Riot::Replay::ReplayServerConnection::GetChunk",
(int)"Assert occurred, game may crash.");
sub_9BB750("ReplayServerConnection GetChunk error. Error decompressing chunk data. Error: %d\n");
}

Upon investigation of sub_B71120 I have located a call which eventually enters a fairly large function. This function contains strings like:

"incorrect header check"
"unknown compression method"
"invalid window size"

A quick Google search of these strings reveals the following:
http://www.opensource.apple.com/source/zlib/zlib-22/zlib/inflate.c
I have also found the string reference "1.2.3" in a function call just before the call to inflate.c method, as well as another reference "inflate 1.2.3 Copyright 1995-2005 Mark Adler". It definitely looks like they are using Zlib version 1.2.3 for the decompression of the tokens. I just can't get them to decompress regardless of what file offset I start at.

My question(s)
Does anyone know how these 'tokens' might be formatted or if there is some type of compression/encryption I am unaware of? I have a suspicion that they are some compressed or packed form of the ethernet packets used during live play which are simply played back internally to the client.
Alternatively, can anyone think of some other method by which to scrape this data without running the actual game client? Keep in mind I would like to grab data from many streams simultaneously.

The way I thought to go about it was to grab as many replay files from LOLReplay as possible and just crunch those. There is, I think, an open archive where people can upload their own games, and I think the new spectator mode lets the Replay client grab more information than it did before.

What other APIs and Techniques are there?  Why do you think there is encryption? I found this in the GetGameMetaData: "encryptionKey":"" and "decodedEncryptionKey":""

As an FYI for the people who keep landing on this question from various LoL forums, seeing my name on the post under "edited by," and emailing me to ask about the topic... I don't know anything about LoL or the format of its streams. Please don't email me about it.

I've been researching the same thing and I found this repo to be extremely helpful. The file decrypt.rb decrypts both chunks and keyframes.
Edit: check out this reddit thread too.

Excellent. The first link answers my question precisely. The second link is also really helpful. Thanks a ton!

source: Stack Exchange

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

sort: votes


text:
Why cant I use slick-util with image IO and bufferedImage
My problem is that I get errors when I use
texture = TextureLoader.getTexture("PNG", ResourceLoader.getResourceAsStream("TEXTURE PATH HERE"));

it gives me these errors:
Exception in thread "main" java.lang.RuntimeException: No OpenGL context found in the current thread.
    at org.lwjgl.opengl.GLContext.getCapabilities(GLContext.java:124)
    at org.lwjgl.opengl.GL11.glGetError(GL11.java:1277)
    at org.newdawn.slick.opengl.InternalTextureLoader.getTexture(InternalTextureLoader.java:226)
    at org.newdawn.slick.opengl.InternalTextureLoader.getTexture(InternalTextureLoader.java:184)
    at org.newdawn.slick.opengl.TextureLoader.getTexture(TextureLoader.java:64)
    at org.newdawn.slick.opengl.TextureLoader.getTexture(TextureLoader.java:24)
    at game.Map.Init(Map.java:34)
    at game.Game.start(Game.java:17)
    at game.Game.main(Game.java:63)

My code uses ImageIO, Buffered Image and image.getRGB();
But it also uses the Slick-Util library for loading textures to render.
The full code for the Map.java class is:
`
package game;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import org.lwjgl.LWJGLException;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
import org.lwjgl.opengl.GL11;
import org.newdawn.slick.Color;
import org.newdawn.slick.opengl.Texture;
import org.newdawn.slick.opengl.TextureLoader;
import org.newdawn.slick.util.ResourceLoader;

public class Map {

    int mapSize=100;
    int[] Tiles = new int[mapSize+1];
    int Tile;

    public Texture texture;

    public void Init()
    {
        try {
            // load texture from PNG file
            texture = TextureLoader.getTexture("PNG", ResourceLoader.getResourceAsStream("res/Tiles/Grass.png"));

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

     public void LoadMap()
        {

            File file= new File("res/map.png");
              BufferedImage image = null;
            try {
                image = ImageIO.read(file);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            for(int Y = 0;Y<image.getHeight();Y++){
                for(int X = 0;X<image.getWidth();X++){

              int clr=  image.getRGB(X,Y);
              int  red   = (clr & 0x00ff0000) >> 16;
              int  green = (clr & 0x0000ff00) >> 8;
              int  blue  =  clr & 0x000000ff;
              if(red==0&&green==0&&blue==0){
                  Tiles[Tile]=0;
              }
              if(red==255&&green==0&&blue==0){
                  Tiles[Tile]=1;
              }
              if(red==0&&green==255&&blue==0){
                  Tiles[Tile]=2;
              }
              if(red==0&&green==0&&blue==255){
                  Tiles[Tile]=3;
              }
              Tile++;
            }
            }
            for(int i = 0;i<mapSize;i++)
            {
                System.out.println(Tiles[i]);
            }

        }
     public void RenderMap()
     {

     }

}
`

So all I want to know is how can I fix this error and draw the textures down in the
 void Render()
    {

    }

method.
Thanks, Griffin.

I hope this clarifies it for you. I've noticed you're importing lwjgl, I take it you want more functionality than what Slick 2D is offering? I would need to see your lwjgl construction to comment further...
In a normal Slick 2D setup with BasicGame, you would do something similar to this:
import java.io.IOException;
import org.newdawn.slick.*;
import org.newdawn.slick.opengl.*;

public class TextureTest extends BasicGame
{
    private Texture texture;
    private Image grass;

    public TextureTest()
    {
        super("Texture Load Test");
    }

    @Override
    public void init(GameContainer container) throws SlickException
    {
        try
        {
            // load texture from PNG file
            texture = TextureLoader.getTexture("PNG", getClass().getResourceAsStream("grass.png"));
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }

        grass = new Image(texture);
    }

    @Override
    public void update(GameContainer container, int delta)
            throws SlickException
    {
    }

    @Override
    public void render(GameContainer container, Graphics g)
            throws SlickException
    {
        grass.draw();
    }

    public static void main(String[] args) throws SlickException
    {
        TextureTest game = new TextureTest();
        AppGameContainer app = new AppGameContainer(game);
        app.setAlwaysRender(true);
        app.start();
    }
}

Are you trying to load images into OpenGL before you create an OpenGL context (as in, open the game window via Slick)? That's not going to work.

This is only one of the 3 classes a have in my game so far. The game is launched in the game class then the init(); and loadMap(); are called.

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


text:
Swap Child and Child's Child
Is it possible to use swapChildren() with a child and a child's child? Every time I try, I get this error:
ArgumentError: Error #2025: The supplied DisplayObject must be a child of the caller.

Why can I not compare a child with a child's child? How can I?

You're not comparing anything. You're trying to swap children in different parents. That's not what swapchildren does. It only looks at the containing children of said parent.

Note, that DisplayObjectContainer has 3 main methods: addChild, removeChild and getChildAt. All other mehtods (addChildAt, contains, getChildIndex, removeChildAt, setChildIndex, swapChildren, swapChildrenAt) are redundant (unnecessary) and can be implemented using 3 main methods above. Adobe added them for convenience, but it doesn't do quite what you're expecting.
Why don't you implement that "weird swapChildren" by yourself, using those 3 methods? Like so:
function weirdSwapChildren(childA:DisplayObject, childB:DisplayObject):void
{
    var p1:DisplayObjectContainer = childA.parent;
    var p2:DisplayObjectContainer = childB.parent;
    var i1:int = p1.getChildIndex(childA);
    var i2:int = p2.getChildIndex(childB);
    p1.removeChild(childA);
    p2.removeChild(childB);
    p1.addChildAt(childB, i1);
    p2.addChildAt(childA, i2);
}

Good answer. I took the liberty to improve your code a bit by introducing proper AS3 syntax and removed the need for container parameters (you can get these using the parent property on the child).

Just as a note: You don't need to remove a child when adding it to a different parent. The property "parent" automatically changes. Thus calling addchild on Y to add K while K being child of X, K is automatically "unregistered" from X. Also  if(childA.parent) en if(childB.parent) are needed incase the parent property is null.

I know that parents are "swapped" automatically and one DisplayObject can not have multiple parents, but it may look confusing without removeChild.

Thanks for your answer it just came to me there are many things adobe forgot in actionscript that i can make with intense functions.

From the documentation: swapChildren: Swaps the z-order (front-to-back order) of the two specified child objects.
A DisplayObject's z (or index) and it's position in the display object hierarchy are two different things. The z describes in what order the display objects are rendered within the container. A handy way of deciding what should be on top of what. swapChildren is designed for changing this property.
The DisplayObjects' position in the hierarchy also affects the rendering order but it's not the main thing. Children inherit the location, visibility, filters and a lot more.
Enabling one method to do both z swapping and changing the hierarchy is against good practice as they are two very different things. https://sites.google.com/site/unclebobconsultingllc/one-thing-extract-till-you-drop

The asker said nothing about z-index. I don't see how this answers the question.

The question was about swapChildren, why it doesn't do what he would ike it to do. From AS3 documentation, "swapChildren: Swaps the z-order (front-to-back order) of the two specified child objects." So the z is relevant.

I did not until just this moment even know swapChildren() exists. Reading the description it seems pretty pointless to me. For what you want I would just use calls like object1.parent and parent.addChild(object2)

I don't see how it's pointless. It's simply a build in function that swaps two DisplayObjects in the SAME parent. It's not meant to swap a child from a parent to another. Unless you mean it's pointless to use it in the context of how Abe is trying to use it, then I agree.

Well it looks pointless to me since that functionality is so easy to do with other calls. But that's just me; clearly Adobe disagrees so whatever.

And you can achieve other things differently as well. This function is a convenient and probably optimized way of doing it( after all it's their API). Adobe flash is also geared towards designers rather than just pure programmers.


text:
JFrame launcher stays open when I'm finished with it
I have written a launcher that prompts the user for their name then starts the game when they hit enter. The launcher looks like this:
But when the user hits enter, this happens:
The launcher stays open.
This is the relevant code in the launcher class:
    public void actionPerformed(ActionEvent evt) {
        String text = textField.getText();
        System.out.println(text);
        entered=true;
        Game game = new Game();
        game.start(text);
    }

    public void Launch() {
        //Create and set up the window.

        JFrame frame = new JFrame("Login");
     // maximize the jframe here
        frame.setSize(800,600);
        frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //Add contents to the window.
        frame.add(new Launcher());
        //Display the window.
        frame.pack();
        frame.setVisible(true);
        while(entered==true){}
    }

And this is for the main method in the game:
    public static void main(String[] argv) {
        Launcher launcher = new Launcher();
        launcher.Launch();
    }

So how would I go about closing the launcher when the user has no use for it?
I am using a JFrame for the launcher and Lwjgl for the actual game window.

I've edited your question to remove the irrelevant code. When you include all your code, it looks like you don't have any idea what you're doing and clutters the question. For example, in a problem like this, we can assume that you have all the required include statements, there's no need to include them, same goes for your rendering code.

You want to think more about what your actual problem is. Always try to boil down these larger issues into smaller bits. In this case, your JFrame is staying open. That's expected behavior, since you haven't tried to close it!
So the problem isn't that your JFrame is staying open, it's that you don't even try to close it. Check out this question on SO for programmatically closing a JFrame.

So would I add frame.dispose(); after game.start(text);

Griffy, best way to find out is to try! I'm trying to be less direct in my answers to you, I want you to learn how to find help yourself first since it's an important skill for you to learn. Good luck with your game!

I can't get anything to work! :(

You'll need to be specific about what you've tried and what exactly isn't working. Take it one step at a time, try the most basic approach first and then build up from there once it's working.


text:
How to check the device type using Adobe AIR for iOS
How do I check what kind of device the user is running my Adobe AIR app on?
Example: if(device == ipad3) { stagestuff.width = 300; }

http://forums.adobe.com/thread/745385
At this link, it shows the following:
'Hi all,
I am sharing some of my library of iOS specific stuff in the hope that the community can suggest improvements and that it may be useful to others.
The following code can determine iPhone, iPodTouch and iPad based on screen res and geolocation (iTouch has no GPS). If anybody can help with code that can narrow the selection (i.e. determine between 3G, 3GS, 2nd gen, 3rd gen etc) that would be most welcome!
edit: hmm. Just realised that the iPhone 1st gen also didn't have GPS, so i can't use that to distinguish iTouch from iPhone...
package com.pixelthis.frameworks.ios

{

     /**

      * ...

      * @author Peter Vullings

      */

     public class DeviceType

     {

          import flash.system.Capabilities;

          import flash.sensors.Geolocation;

          // ------------------------------------------------------

          // CONSTANTS

          // ------------------------------------------------------

          public static const IPHONE : int = 1;

          //public static const IPHONE_3G : int = 2;

          //public static const IPHONE_3GS : int = 3;

          public static const IPHONE_4 : int = 4;

          public static const IPODTOUCH : int = 100;

          //public static const IPODTOUCH_2GEN : int = 101;

          //public static const IPODTOUCH_3GEN : int = 102;

          public static const IPAD : int = 200;

          // ------------------------------------------------------

          // PROPERTIES

          // ------------------------------------------------------

          public static var _currentDevice : int = 0;

          // ------------------------------------------------------

          // METHODS

          // ------------------------------------------------------

          /**

           * Determine the current device type

           * @return The device type

           */

          public static function get currentDevice():int {

               // If we have already calculated it, return it. The device

               // isn't exactly going to change at run-time is it!

               if (_currentDevice>0) return _currentDevice;

               // Screen size

               var w : int = Math.max( Capabilities.screenResolutionX, Capabilities.screenResolutionY );

               var h : int = Math.min( Capabilities.screenResolutionX, Capabilities.screenResolutionY );

               if (w <= 480){

                    if (Geolocation.isSupported){

                         _currentDevice = IPHONE;

                    }else{

                         _currentDevice = IPODTOUCH;

                    }

               }else if (w<=960){

                    _currentDevice = IPHONE_4;

               }else{

                    _currentDevice = IPAD;

               }

               return _currentDevice;

          }

     }

}'

authors: ศรัณย์วีร์ เรืองวงษ์


text:
web based quizz game database design, how do I store results?
I'm building a very basic quizz type of php/mysql/ajax game.
At this stage I'm thinking about the DB design, and specifically how to score results, I've two options in my mind. But cannot decide which one is better (being self taught. mostly by doing things, I have no idea what are best practices or what can be useful or not.)
So, I've 3 tables:

Users -> contains: user_id, user_name, user_pass, user_score
Quizz -> contains: quizz_id, quizz_answer, quizz_question, quizz_value
Results -> this is the one I'm debating. Should I keep user results in a separate table and have it like: result_id, result_user_id, result_quizz_id, result_score
Or simply include results for user inside users table under user_results and save it as array of answered quizz_ids

I'm debating if it is good practice to have separate results table or not. If I've it separately it means 10K users can easily create 10K*100 results rows. On the other hand array in user_results can become to contain 100 keys.
Performance wise, and taking into consideration good practices, which way is better?
Can mysql handle 10K*100 row lookups constantly on the bases of user_ID? Or is it wiser to just explode array from user_results column?

Let my explain, why you should definitely add your results as a separate relation-table and why having a string of IDs inside the user table is "wrong":
First of all, try to look at the database as a separate sub-system. The sub-system should be self-contained. So if you have a table Users and Quizz and there's a relation between the two (eg. user have multiple or one results per quiz), then this should be reflected in your database design.
Why? Most importantly, it allows you to work with the Database outside of your application code. If you leave it up to your application to make the relation between Users and Quizz, then you're severely limiting the usefulness of the database itself. You won't be able to use any other tool (eg. directly querying your database for these relations) without re-implementing or re-applying that logic you used in your application.
Having your Results stored in the Users table can also limit performance if you have to implement DB locking (which might be necessary with lots of concurrent users).
Also be aware that you're about to perform premature optimization. Databases are already heavily optimized and can handle thousands and millions of rows. Without identifying the database as a bottle-neck, there's no reason to deviate from good practice. I highly doubt that querying the user table, splitting the IDs to an array and then querying the Quizz table with these IDs individually is going to be any faster than what the DB would do for you with some simple JOIN statements.
If you're interested in the topic, you might want to read up on Database normalization. There's another candidate in your design that might be off, which is the user_score column in your Users table. I suspect that this is a running total of all result scores? If yes, you should get that with a query from your results instead:
SELECT SUM(result_score) FROM Results WHERE result_user_id = <yourUserID>

Perfect, very informative, thank you for taking time to write this up. I've a better idea now how to make DB :)

If I remember my database design 101; long tables are always preferable to wide tables.
Essentially, a million rows isn't really anything even close to a big deal for a relational database; even 10 million shouldn't really make MySQL sweat.
This also comes back to design: the results shouldn't be on the user table, because they are not part of the user, but a property of the user.

+1. I wonder why this is even a question. Storing results as comma separated values in the user table is just plain wrong. Then you could just as well skip the database entirely and use a text-file..

@bummzack: I'm thinking he is thinking separate rows. :P

"Or simply include results for user inside users table under user_results and save it as array of answered quizz_ids" and "Or is it wiser to just explode array from user_results column?" made me think otherwise. Either way is a bad idea though.

Thank you for explaining it to me. I had a hunch having a separate table for results was the best way to go... but I wanted to know why. As for @bummzack it might not be obvious to hobby programmers... just plain wrong is not an explanation either.

@SandroDzneladze I'm sorry, that was indeed a bit out of line and not really helpful. I tried to explain it in a separate answer.


text:
Entity/Component based engine rendering separation from logic
I noticed in Unity3D that each gameObject(entity) have its own renderer component, as far I understand, such component handle rendering logic.
I wonder if it is a common practice in entity/component based engines, when single entity have renderer components and logic components such as position, behavior altogether in one box?
Such approach sound odd to me, in my understanding entity itself belongs to logic part and shouldn't contain any render specific things inside.
With such approach it is impossible to swap renderers, it would require to rewrite all that customized renderers.
The way I would do it is, that entity would contain only logic specific components, like AI,transform,scripts plus reference to mesh, or sprite.
Then some entity with Camera component would store all references to object that is visible to the camera.
And in order to render all that stuff I would have to pass Camera reference to Renderer class and render all sprites,meshes of visible entities.
Is such approach somehow wrong?

I removed the part of the question that asks "why does Unity do this," because it's (a) a second question and (b) not likely relevant to your actual problem.

"With such approach it is impossible to swap renderers" 1) That's a bit of an assumption, it seems like the "renderer" component could just be a front end to whatever platform-specific rendering code it needs (pimpl idiom, for example) and 2) How much does that really matter for your needs?

Such approach sound odd to me, in my understanding entity itself
  belongs to logic part and shouldn't contain any render specific things
  inside.

In some entity systems, components only contain logic. In others, they only contain data. In yet others, they contain both. I'd certainly argue that putting the actual render commands (as in the OpenGL or D3D code) into the rendering component isn't ideal (see my answer here regarding the question "should objects render themselves?", which is the same principle under discussion). However, it is certainly possible to do so and even to do so in a fashion that allows the implementation of the rendering components to be swapped without having to alter the consumers of the component system. Doing so just involves any typical implementation-hiding technique.
It's acceptable, and common, to have a "visual component" that contains a reference to some renderable object that comes from the lower-level rendering subsystem and have that component export behavior or interface to allow the appearance data to be specified by other components (such as ones containing scripts).

The way I would do it is, that entity would contain only logic
  specific components, like AI,transform,scripts plus reference to mesh,
  or sprite. Then some entity with Camera component would store all
  references to object that is visible to the camera. And in order to
  render all that stuff I would have to pass Camera reference to
  Renderer class and render all sprites,meshes of visible entities.
Is such approach somehow wrong?

I don't really see what you gain by having a "camera" component. It seems like a very heavyweight operation inject into the entity system. Does, for example, the presence of the camera component mean that you always get a scene rendered from that camera's perspective? How then do you determine which of those scenes to present to the user, and where? It feels like -- without knowing more about this design -- you'd be shoving a lot of unrelated responsibility into the camera component. I'd prefer to see that responsibility handled by something external to the entity system.
Otherwise, that sounds like a perfectly usable system. It will have it's pros and cons, of course, but those will become apparent in practice and many of them will be specific to your needs and/or the needs of your game.

Camera component have the value that they allow a view to be attached to a game object (like the player, a kill cam, etc.) and manipulated using the same interfaces and such that any other game object component uses.  Separating the idea of a "view" from a camera certainly makes sense (where a view can have an active camera from the scene, be switched out, be assigned a specific viewport, be bound to an offscreen buffer, etc.).  Super useful for cinematics, split-screen, security cams, etc.  Having the camera manage visibility directly is a little off, though.

You are right and wrong at the same time. The entity/component model is very flexible and that is one reason why it is used. What you very well point out is that it muddles the simulation (game logic) and presentation (graphic & sound).
The first thing to note is that a component does not mean that it will actually do something. For example a MeshRenderComponent may not actually render the mesh. It can be implemented as containing all relevant data and hand the actual rendering to a "system" of the engine.
This has two advantages. First, the entity can be fully instantiated on the server. All components that don't "work" on the server are just dumb data containers. The second, is that a system with all data resident can run tighter and more efficient loops, then when moving over components.
The quint essence, is that the data of entity/component model is muddled, but you can still keep the different systems properly isolated.
The second thing to note is, the good old question: "Does it matter?"
This is a way harder question to answer. From a software engineering standpoint the decision is clear, you have a pure simulation and a pure presentation layer. (Model-View-Controller) But when it comes to artists and level designers, it gets harder. You mention Unit3D and you may see where I am coming from.
A level designer says, I want this splash here over the waterfall. The engineer will implement a water simulation and determine where these effect need to go, the level designer just want to place it there, who cares that it is not perfectly accurate.
As it turns out the way that Unity3D muddles logic and presentation is how most non engineers actually think how things should work. (And don't try to explain why multi-player is so hard to implement with such a model...)

Unity3D docs says, that Renderer components are actually rendering the stuff. The thing I also can't wrap my head around is that, as far as I know each component is being updated at fixed timestep. That means that if we believe what Unity docs say and the timestep is 40ms, then despite I could have 1000fps, in reality the entities visual representation would render/update only at 25fps?

That is Unity3D specific and I can't answer you that. Then again the 40ms probably relates to the logic tick time... not frame rate, since rendering just cannot be done "initiated" by the component. (Painters algorithm and all.)

It seems that Renderer is just a component (http://docs.unity3d.com/Documentation/ScriptReference/Renderer.html).
As far as I understand Renderer provides common functionality to more specific inherited components:
http://docs.unity3d.com/Documentation/Components/class-MeshRenderer.html
http://docs.unity3d.com/Documentation/Components/class-ParticleRenderer.html
http://docs.unity3d.com/Documentation/Components/class-LineRenderer.html
As far as I know Unity supports several underlying renderers for its various platforms, Direct3D and OpenGL among them:
Does Unity for PC use Direct3D or OpenGL?
So it must be possible to swap underlying renderers even if it is not available to end user (scripter).
If you have already read general information on component-entity-system architectures, then you know that entities are generally collections of components. A component may generally be anything including physics, animation, game logic etc. Why treat graphics differently?
Some component-entity-system architectures tend to put more logic in components, while some concentrate it all in systems and use components as pure data.
Read this if you had not already:
https://stackoverflow.com/questions/1901251/component-based-game-engine-design/3495647#3495647

I agree, that graphical representation of entity should be component, but disagree, that any rendering should be done through component. The ball in real world have it's visual representation, but ball does nothing to be seen by man's eye, it's the light which delivers light particles to viewers eye.
Than why entity comp should be doing any rendering?
As written in unity docs "MeshRenderer renders meshes inserted by the MeshFilter or TextMesh.". So I'm trying to find out if it's common and if there is alternative approach which I could use in my realisation of simple entity/component engine.

@DenisNarushevich Ball emits reflected light in a particular way (texture) so it does something to be seen. Otherwise you can say that ball also does nothing to move - it's the unified impulse of its molecules that moves it. You "give" your ball a stream of raw light and it reflects it the way it wants and thus produces a rendering result. An eye is a different component that takes a stream of reflected light and transforms it into set of electric impulses.

@DenisNarushevich There is no "common" approach here. In my personal engine I only hold graphic data in rendering components and have a rendering system that iterates over components, but this is just my preference. IMHO you either put it in components or in systems.

All i can say is GUI.Button is the worst kind of code any development team can write.
This can lead to slow downs and what not..
Rendering and Logic in the same loop? Why then does Unity need an Update function?
If Unity wanted to draw and run logic at the same time then it does not need any Update functions... In a team which is working on big projects handling code in the OnGUI() for logic is a disaster .. I'd rather not use Unity for this reason alone.
Also the other reason is the concept of the Loading and Unloading meaning memory management is left on Unity to decide which is not at all ideal for any programmer.
A programmer must know where and when memory is being used but Unity hides all of that.
As far as I come to understand Unity lets you create a lot of code and infact the full game in a matter of days if not a few months. But the time when you actually try and sell this game over PSN or XBOX you will repent why you chose Unity because now you have a game that works but you have no control of its memory management or FPS because of Rendering and Logic being written in the same code.
Also having rendering and logic in the same code makes it a mandatory to have lesser and lesser team mates working on the project. If one day you change the programmer your team will suffer.
In my view this Entity Component structure is not suitable for large teams making huge games.
Try making an MMORPG on Unity3D ... you'll know what PAIN is! :D

Unity is not an ECS, though it does use a form of component-based design.  Also, its immediate-mode GUI is designed for tools and editors, not in-game HUDs and menus; if you use the wrong tool for the job, that's on you, not the tool.


text:
Tile Maps in Java JFrame Game
I am making a 2D Java game with Java's own drawing library. I was wondering how I would make a tile map display on the screen. I would prefer to use a GUI application to make the maps. I'm looking for orthogonal projection: a top down view.

What type of display are you trying to get? Do you want it in perspective, as an isometric projection or in top-down perspective?

Sorry, I forgot to mention that I was looking for top-down view: 'orthogonal' projection.

You can try using Tiled Map Editor. This editor has GUI for you to import tiles, make maps and outputs in XML format. You will need to parse the XML data in your game according to your needs. The XML format is described here and you can refer to this page for  java XML parsers. There is a lot of sample games made with Tiled and documentation here.

Just to add to xiao's post, slick2D has a tiled map editor parser built into it so you can use that game library if need be

Thanks, I made my own maps in text files, and rendered the maps manually.


text:
Proper approach to handle transformation matrix and extract its components
Basically I have a Transformation component object with following structure(pseudo):
TransformComponent{
  Vec3 position;
  Vec3 rotation; //in euler angles
  Vec3 scale;
  Mat4 worldMatrix; //transformation matrix in world space
  Mat4 localMatrix; //transformation matrix relative to parent transform
  Mat4 worldToLocal; //Matrix to convert children worldMatrix in localMatrix
  TransformComponent parent;

  /* calculates worldMatrix using position,rotation & scale.
   * Also calculates inverse of worldMatrix and stores it in worldToLocal;
   */
  void CalculateWorldMatrix();

}

Then I do some transformations like:
    transform.position = [1,1,1]; //set new position

    transform.CalculateWorldMatrix(); //recalculate worldMatrix with new translation coordinates.

    //Multiply worldToLocal with worldMatrix in order to get localMatrix.
    localMatrix = transform.parent.worldToLocal * transform.worldMatrix;

After that, I have localMatrix with position, rotation etc relative to parent transform.
But I can't figure out how to get components(position,eualerAngles,scale) out of localMatrix. As far as I googled I found some really difficult solutions, which I couldn't understand, and as I'm writing on JavaScript I hope there is a simple solution.
Maybe I am using wrong structure for transform object?
What is the common approach here?
I read that its preferred to use quaternions, but only advance they give is about gimbal lock, at this moment because of simplicity I would like to stick with euler angles if it's possible.

I think your approach is backwards.  You maintain data (like position and Euler angles) to produce matrices.  Why try to extract that data from the matrix?  (That isn't really how to use a matrix anyway; I will explain in paragraph two.) Use the source data when you need the source data, use the matrix when you need the matrix.  Don't try to interchange them back and forth.
As for your question about how to "extract" a position from two multiplied matrices: you multiply your global position vector by the combined transformation matrix.  That's it.
You seem to have an incomplete understanding of matrices, what they are and how to use them.  I suggest that you dedicate some time to studying this topic on your own.  It will make your project that involves a transform hierarchy much more feasible.  Also, maybe you'll decide you don't even need to reinvent the wheel, and you can use someone else's js matrix library.  Like this guy's or even Apple's.

Thanks for answer. Actualyl I'm already using glMatrix library.

And  I initialy stored a source data, but then I got a situation:
parent transform updated it's data and child transform should be updated, ok to update child position I can multiply vec3 position with parent.localToWorld matrix, but i didn't figure out how to maintain scale and rotation. That's why I'm trying to apply parent transformation on child transformation and then extract the components)


text:
How to extract euler angles from transformation matrix?
I have a simple realisation of entity/component game engine.
Transform component have methods to set local position, local rotation, global position and global rotation.
If transform is being set new global position, then local position also changes, to update local position in such case I'm just applying current transform local matrix to parent's transform world matrix.
Until then I have no problems, I can get updated local transform matrix.
But I'm struggling on how to update local position and rotation value in transform.
Only solution I have in mind is to extract translation & rotation values from localMatrix of transform.
For translation it's quite easy - I just take 4th column values.
but what's about rotation?
How to extract euler angles from transformation matrix?
Is such solution right?:
To find rotation around Z axis, we can find difference between X axis vector of localTransform and X axis vector of parent.localTransform and store result in Delta, then:
localRotation.z = atan2(Delta.y, Delta.x);
Same for rotation around X & Y, just need to swap axis.

Normally I store all objects as 4x4 Matrices (you could do 3x3 but easier for me just to have 1 class) instead of translating back and forth between a 4x4 and 3 sets of vector3s (Translation, Rotation, Scale). Euler angles are notoriously difficult to deal with in certain scenarios so I would recommend using Quaternions if you really want to store the components instead of a matrix.
But here is some code I found a while back that works. I hope this helps, unfortunately I do not have the original source for where I found this. I have no idea what odd scenarios it may not work in. I am currently using this to get the rotation of YawPitchRoll rotated, left handed 4x4 matrices.
   union {
        struct
        {
            float        _11, _12, _13, _14;
            float        _21, _22, _23, _24;
            float        _31, _32, _33, _34;
            float        _41, _42, _43, _44;
        };
        float m[4][4];
        float m2[16];
    };

    inline void GetRotation(float& Yaw, float& Pitch, float& Roll) const
    {
        if (_11 == 1.0f)
        {
            Yaw = atan2f(_13, _34);
            Pitch = 0;
            Roll = 0;

        }else if (_11 == -1.0f)
        {
            Yaw = atan2f(_13, _34);
            Pitch = 0;
            Roll = 0;
        }else
        {

            Yaw = atan2(-_31,_11);
            Pitch = asin(_21);
            Roll = atan2(-_23,_22);
        }
    }

Here is another thread I found while trying to answer your question that looked like a similar result to mine.
https://stackoverflow.com/questions/1996957/conversion-euler-to-matrix-and-matrix-to-euler

It seems that my proposed solution is almost right, just don't know why isntead of atan2 asin is used for pitch.

Also, how it would help me, if I would store each component in separate mat4x4? How could I then get and e.g. output angle of rotation around some axis?

Your original question lead me to believe that you are storing your objects as 3 vector3s: Translation, Rotation, and Scale. Then when you creating a localTransform out of those doing some work and later attempting to convert (localTransform*globalTransform) back into 3 vector3s. I could be totally wrong I was just getting that impression.

Yeah I don't know the math well enough for why pitch is done with ASIN but the linked question uses the same math so I believe it is correct. I've been using this function for a while to without any issue.

Is there any particular reason for using atan2f in the first two if cases and atan2 in the third, or is it a typo?

There's a great writeup on this process by Mike Day:
https://d3cw3dd2w32x2b.cloudfront.net/wp-content/uploads/2012/07/euler-angles1.pdf
It is also now implemented in glm, as of version 0.9.7.0, 02/08/2015.  Check out the implementation.
To understand the math, you should look at the values that are in your rotation matrix.  In addition, you have to know the order in which the rotations were applied to create your matrix in order to properly extract the values.
A rotation matrix from Euler angles is formed by combining rotations around the x-, y-, and z-axes.  For instance, rotating θ degrees around Z can be done with the matrix
     ┌ cosθ  -sinθ   0 ┐
Rz = │ sinθ   cosθ   0 │
     └   0      0    1 ┘

Similar matrices exist for rotating about the X and Y axes:
     ┌  1    0     0   ┐
Rx = │  0  cosθ  -sinθ │
     └  0  sinθ   cosθ ┘

     ┌  cosθ  0   sinθ ┐
Ry = │   0    1    0   │
     └ -sinθ  0   cosθ ┘

We can multiply these matrices together to create one matrix that is the result of all three rotations.  It's important to note that the order that these matrices are multiplied together is important, because matrix multiplication is not commutative.  This means that Rx*Ry*Rz ≠ Rz*Ry*Rx.  Let's consider one possible rotation order, z-y-x.  When the three matrices are combined, it results in a matrix that looks like this:
         ┌      CyCz              -CySz        Sy  ┐
RxRyRz = │  SxSyCz + CxSz   -SxSySz + CxCz   -SxCy │
         └ -CxSyCz + SxSz    CxSySz + SxCz    CxCy ┘

where Cx is the cosine of the x angle of rotation, Sx is the sine of the x angle of rotation, etc.
Now, the challenge is to extract the original x, y, and z values that went into the matrix.
Let's first get the x angle out.  If we know the sin(x) and cos(x), we can use the inverse tangent function atan2 to give us back our angle.  Unfortunately, those values don't appear by themselves in our matrix.  But, if we take a closer look at elements M[1][2] and M[2][2], we can see we do know -sin(x)*cos(y) as well as cos(x)*cos(y).  Since the tangent function is the ratio of the opposite and adjacent sides of a triangle, scaling both values by the same amount (in this case cos(y)) will yield the same result.  Thus,
x = atan2(-M[1][2], M[2][2])

Now let's try to get y.  We know sin(y) from M[0][2].  If we had cos(y), we could use atan2 again, but we don't have that value in our matrix.  However, due to the Pythagorean identity, we know that:
cosY = sqrt(1 - M[0][2])

So, we can calculate y:
y = atan2(M[0][2], cosY)

Last, we need to calculate z.  This is where Mike Day's approach differs from the previous answer.  Since at this point we know the amount of x and y rotation, we can construct an XY rotation matrix, and find the amount of z rotation necessary to match the target matrix.  The RxRy matrix looks like this:
       ┌   Cy     0     Sy  ┐
RxRy = │  SxSy   Cx   -SxCy │
       └ -CxSy   Sx    CxCy ┘

Since we know that RxRy * Rz is equal to our input matrix M, we can use this matrix to get back to Rz:
M = RxRy * Rz

inverse(RxRy) * M = Rz

The inverse of a rotation matrix is its transpose, so we can expand this to:
┌ Cy   SxSy  -CxSy ┐┌M00  M01  M02┐   ┌ cosZ  -sinZ  0 ┐
│  0    Cx     Sx  ││M10  M11  M12│ = │ sinZ   cosZ  0 │
└ Sy  -SxCy   CxCy ┘└M20  M21  M22┘   └   0      0   1 ┘

We can now solve for sinZ and cosZ by performing the matrix multiplication.  We only need to calculate the elements [1][0] and [1][1].
sinZ = cosX * M[1][0] + sinX * M[2][0]
cosZ = coxX * M[1][1] + sinX * M[2][1]
z = atan2(sinZ, cosZ)

Here's a full implementation for reference:
#include <iostream>
#include <cmath>

class Vec4 {
public:
    Vec4(float x, float y, float z, float w) :
        x(x), y(y), z(z), w(w) {}

    float dot(const Vec4& other) const {
        return x * other.x +
            y * other.y +
            z * other.z +
            w * other.w;
    };

    float x, y, z, w;
};

class Mat4x4 {
public:
    Mat4x4() {}

    Mat4x4(float v00, float v01, float v02, float v03,
            float v10, float v11, float v12, float v13,
            float v20, float v21, float v22, float v23,
            float v30, float v31, float v32, float v33) {
        values[0] =  v00;
        values[1] =  v01;
        values[2] =  v02;
        values[3] =  v03;
        values[4] =  v10;
        values[5] =  v11;
        values[6] =  v12;
        values[7] =  v13;
        values[8] =  v20;
        values[9] =  v21;
        values[10] = v22;
        values[11] = v23;
        values[12] = v30;
        values[13] = v31;
        values[14] = v32;
        values[15] = v33;
    }

    Vec4 row(const int row) const {
        return Vec4(
            values[row*4],
            values[row*4+1],
            values[row*4+2],
            values[row*4+3]
        );
    }

    Vec4 column(const int column) const {
        return Vec4(
            values[column],
            values[column + 4],
            values[column + 8],
            values[column + 12]
        );
    }

    Mat4x4 multiply(const Mat4x4& other) const {
        Mat4x4 result;
        for (int row = 0; row < 4; ++row) {
            for (int column = 0; column < 4; ++column) {
                result.values[row*4+column] = this->row(row).dot(other.column(column));
            }
        }
        return result;
    }

    void extractEulerAngleXYZ(float& rotXangle, float& rotYangle, float& rotZangle) const {
        rotXangle = atan2(-row(1).z, row(2).z);
        float cosYangle = sqrt(pow(row(0).x, 2) + pow(row(0).y, 2));
        rotYangle = atan2(row(0).z, cosYangle);
        float sinXangle = sin(rotXangle);
        float cosXangle = cos(rotXangle);
        rotZangle = atan2(cosXangle * row(1).x + sinXangle * row(2).x, cosXangle * row(1).y + sinXangle * row(2).y);
    }

    float values[16];
};

float toRadians(float degrees) {
    return degrees * (M_PI / 180);
}

float toDegrees(float radians) {
    return radians * (180 / M_PI);
}

int main() {
    float rotXangle = toRadians(15);
    float rotYangle = toRadians(30);
    float rotZangle = toRadians(60);

    Mat4x4 rotX(
        1, 0,               0,              0,
        0, cos(rotXangle), -sin(rotXangle), 0,
        0, sin(rotXangle),  cos(rotXangle), 0,
        0, 0,               0,              1
    );
    Mat4x4 rotY(
         cos(rotYangle), 0, sin(rotYangle), 0,
         0,              1, 0,              0,
        -sin(rotYangle), 0, cos(rotYangle), 0,
        0,               0, 0,              1
    );
    Mat4x4 rotZ(
        cos(rotZangle), -sin(rotZangle), 0, 0,
        sin(rotZangle),  cos(rotZangle), 0, 0,
        0,               0,              1, 0,
        0,               0,              0, 1
    );

    Mat4x4 concatenatedRotationMatrix =
        rotX.multiply(rotY.multiply(rotZ));

    float extractedXangle = 0, extractedYangle = 0, extractedZangle = 0;
    concatenatedRotationMatrix.extractEulerAngleXYZ(
        extractedXangle, extractedYangle, extractedZangle
    );

    std::cout << toDegrees(extractedXangle) << ' ' <<
        toDegrees(extractedYangle) << ' ' <<
        toDegrees(extractedZangle) << std::endl;

    return 0;
}

Note, however, the problem when y = pi/2 and thus cos(y) == 0. Then it is NOT the case that M[1][3] and M[2][3] can be used to obtain x because the ratio is undefined, and not atan2 value can be obtained. I believe that this is equivalent to the gimbal lock problem.

@PieterGeerkens, you're right, that is gimbal lock.  BTW, your comment revealed that I had a typo in that section.  I refer to the matrix indices with the first one at 0, and since they are 3x3 matrices, the last index is 2, not 3.  I've corrected M[1][3] with M[1][2], and M[2][3] with M[2][2].

I'm pretty sure second row first column of the example combined matrix is SxSyCz + CxSz, not SxSySz + CxSz!

@Lake, you're correct.  Edited.

There's a function in scipy called "scipy.spatial.transform". You can look over in Rotation method which is trasform between euler_angles <-> R-matrix <-> quaternion.

Since the question doesn't say they're using Python, this answer would be better if it explained how to implement a method like this that does not rely on a specific Python library.

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


text:
Creating a BufferedImage with several smaller images?
I am making a 2D tile based game. The tiles render fine from a spritesheet and a text file. However, I am using a for loop to draw the map to the screen. When it refreshes, it slows down the loop, and the bottom is black for a fraction of a second.
I was wondering if I could create a separate method to create a BufferedImage to hold the map, so I could render it continuously, and change it when needed.
Map Class:
package uk.co.madmonkeystudios.distortioner;

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;

import javax.imageio.ImageIO;
import javax.swing.JOptionPane;

public class Map {

    static BufferedImage sheet;

    public static void SetSpriteSheet() throws IOException{
        sheet = ImageIO.read(new File("res/grid.png"));
    }

    public static BufferedImage GetTile(int id) throws IOException{
        if(sheet == null){SetSpriteSheet();}

        int across = 24;

        BufferedImage tile = null;
        int x = 0;
        int y = 1;
        int w = 31;
        int h = 31;
        for(int done = 0;done<id;done++){

            x= done * w;
            x += id;
            if(done >= across){
                y += h;
                y++;
            }

        }
        tile = sheet.getSubimage(x, y, w, h);

        return tile;
    }

    public static void DrawMap(int id) throws IOException{

        Graphics2D g = (Graphics2D)Core.myself.getGraphics();

        g.clearRect(0,0,640,480);

        int[][] map = ReadMap(0);

        int xsize = map.length;
        int ysize = map[0].length;
        System.out.println("Map Read, size (" +xsize + "," +ysize+")");

        int x = Player.x;
        int y = Player.y;

        for(int loopy = 0;loopy<ysize;loopy++){
            for(int loop = 0;loop<xsize;loop++){
                g.drawImage(GetTile(map[loop][loopy]),loop * 32 + x, loopy * 32 +y + 25,32,32,null);
            }
            }
    }

    public static int[][] ReadMap(int id){
        int [][] map = null;
        try{
        @SuppressWarnings("resource")
        Scanner s = new Scanner(new File("res/maps/area"+id+".map"));
        int [][] map1 = new int[Integer.parseInt(s.next())][Integer.parseInt(s.next())];
        String current;

        int xsize = map1.length;
        int ysize = map1[0].length;

        for(int loopy = 0;loopy<ysize;loopy++){
        for(int loop = 0;loop<xsize;loop++){
            current = s.next();
            map1[loop][loopy] = Integer.parseInt(current);
        }
        }
        map = map1;
        }catch(NullPointerException ex70){
            System.err.println("Cannot read map in area ID " +id);
            JOptionPane.showMessageDialog(null, "Couldn't read map...","",JOptionPane.ERROR_MESSAGE);
            System.exit(1);
        }
        catch(FileNotFoundException ex71){
            System.err.println("Cannot find map in area ID " +id);
            JOptionPane.showMessageDialog(null, "Couldn't read map...","",JOptionPane.ERROR_MESSAGE);
            System.exit(1);
        }
        catch(ArrayIndexOutOfBoundsException ex72){
            System.err.println("Cannot add map to array in area ID " +id);
            JOptionPane.showMessageDialog(null, "Couldn't send map...","",JOptionPane.ERROR_MESSAGE);
            System.exit(1);
        }

        return map;
    }

}

Why not add double buffering to everything drawn in your game?
This is the way I would do it...
you would declare 2 variables in your main game class like so:
private Graphics g;
private BufferStrategy bs;
//private YourTileMap map;

then in my main class I would have a render method which does exactly what it sounds like it does... It renders all of my components in the game.
Note: To use the "getBufferStrategy();" method; my main class extends Canvas
There are many ways to skin a cat and this is my take on it :)
public void render() {
    bs = getBufferStrategy(); // Gets BufferStrategy
    if (bs == null) { // If it = null
        createBufferStrategy(3); // Create 3 Buffer Strategies
        return;
    }

    try {
        g = bs.getDrawGraphics(); // Gets BufferStrategies draw graphics
        g.setColor(Color.BLACK); // Sets Color to black
        g.fillRect(0, 0, (int)SCREEN_SIZE.getWidth(), (int)SCREEN_SIZE.getHeight()); // Fills the background of window with black

        // Render Components Here
        //Example:
        // map.render(g);

    } finally {
        g.dispose(); // Disposes of the graphics once finished copying them
    }

    bs.show(); // Shows the image you just created behind the scenes

}

As I stated before, this is just one take on double buffering and I'm sure there are people who have different ways of doing it...
I find this the best way of doing :)
Dont forget to initialise your map either ;)


text:
How wise is this multithreading architecture?
I'm rewriting a game engine I wrote in an attempt to parallelize as much as possible. I'm considering making properties which may be accessed from multiple threads all use accessors which use boost scoped_locks to avoid race conditions.
So then this way, say I have a character with base class CharacterBase. The X/Y/Z coords of the character are controlled through accessors with scoped locks. The main loop has 3 threads running, one to process physics, one to process rendering and one to process user input etc.
This will result in scoped_locks basically being everywhere and explicitly required by design when users are extending the engine. I am planning on making this open source so I'm wondering if there are any significant flaws or draw-backs in this design either from a technical perspective or end-user perspective (for those extending the engine). Thanks!

Boreal's answer was right.  Try these links for more research info.  http://gamedev.stackexchange.com/questions/2116/multi-threaded-game-engine-design-resources

You propose running each separate "system" in parallel.  The problem with this is that you will have to lock every single piece of shared state.  CLARITY EDIT: When you have two parallel operations using all of the same data, lock contention and synchronization is going to slow things down so that you're not gaining many benefits from the parallelization.
The key to multithreading a game engine is to realize that many systems perform SIMD-like operations, where a single operation is performed over a large number of game objects.  One example is adding each object's acceleration to its velocity, and then adding its velocity to its position.  When something like this is happening, you can spread the workload over multiple threads.  You'll see huge performance increases when parallelizing CPU-intensive operations like pathfinding or collision checking.
This is better because it doesn't require locking the game state and does not introduce any problems relating to synchronization or racing.  In fact, your main loop does not really need to change at all!

+1 So to sum up, not very wise. This will surely avoid race conditions, but this is a road to bad performance and worse, dead locks. Ideal multithreading is lock-free.

Ideally, yes.  Sharing a few variables here and there is fine, but if you need to lock down everything you're operating on, nothing is going to be able to run in parallel anyways.

Marked as correct although I've found some resources that suggest that the answer is subjective. http://preshing.com/20111118/locks-arent-slow-lock-contention-is. Anyway I'm not trying to be argumentative I agree with your answer now in that it is not the most ideal approach. Thanks for posting!

Maybe I wasn't clear enough.  When you have two parallel operations using all of the same data, lock contention and synchronization is going to slow things down so that you're not gaining many benefits from the parallelization.  Very interesting article, though.

No I understood I was just saying that from the benchmarks in the referenced article even a relatively high amount of locking (320k per sec) showed there was still a performance gain of 1.5x over the single threaded version. It depends on how long locks are held etc. But in general and the way I asked my original question I agree with your answer that generally the performance is impacted negatively.

I guess, one parallel_for (I'm using Microsoft implementation) on the same kind of data structure is a better idea than trying to manually "parallelize" operations on multitude of different data structures.


text:
Moving character on x axis
I am new to unity scripting.
I am trying to move my character towards right side(on x-axis) to create a running effect, I've imported the character from blender which contains two animations, "jump" and "run". What I want to do is I want my character to move on x-axis for which I've written following code
void Update () {
    transform.Translate(5f * Time.deltaTime, 0f, 0f);
}

But I am facing one problem, if I set my character's y-axis rotation to 90 degrees in order to make him look towards right side I am getting strange results. That is, in play mode instead of moving towards right side(on x-axis) it move on x-axis and z-axis simultaneously & if I set the y-axis rotation to zero it behaves like I want it to. Please see the attached image for detail. How can I solve this problem?

I have suggested that a moderator migrate this to Game Development.

Use Translate overload, which takes Space enumeration values, indicating, that shift is an absolute value, like:
transform.Translate(5f * Time.deltaTime, 0f, 0f, Space.World);

or in more readable way
transform.Translate(Vector3.left * 5f * Time.deltaTime, Space.World);

Vector3.left returns a unit vector pointing left

I found the solution to my problem. And just like I thought, When Switching to my player model I had to change the movement direction from
transform.Translate(speed* Time.deltaTime,0,0);

to
transform.Translate(0,0,speed* Time.deltaTime);

you don't need to switch direction after each rotation. Consider setting Space.World parameter


text:
Displaying (3D) objects' name above them
The Elder Scrolls: Morrowind has a rather interesting way to display each focused objects' name. It's all a bit fuzzy in my memory right now, but the most important part I remember perfectly: the object's name is always displayed in the proximity of the object (most of the time on top of it).
My question is: given a 3D mesh, how should I proceed to calculate the name's position on the screen? I'd like to always position it on top of the given mesh for now. Like in this screenshot of Morrowind:

I'm working under Unity, if it helps. The first thing that comes to my mind is to somehow use the distance between the player and each object, then take the object's actual height in consideration, and determine a line in 2D space (the screen) that just "touches" (intersects) the top of the 2D representation of the mesh (what we're actually able to view on the screen). Something like this:

But this feels a bit complicated and clunky, and might not work for characters that are not standing tall for example.
The 2nd thing that comes to my mind: would there be a way to achieve this using matrix multiplication, in the same way 2D representations of 3D objects are obtained?
Thanks!

If you already have bounding boxes for collision checks you could use easily make use of them.

Billboard positioned at the top of (or slightly above) the character model.

Never heard of billboarding before :) I've taken a look at it; this also makes Xerosigma's answer make more sense to me. I wonder if I can combine this with decals to make a different text show up for different objects (or is there a better way?)

If you are using GameObjects you could easily:
float SomeYOffset = 1.1f;

// Set position of GUI element
nameBar.position = new Vector3(player.position.x, player.position.y * SomeYOffset, player.position.z);

If you're not using GameObjects, you can take the vertex with the highest Y value and offset the nameBar mesh from there.
for(int i = 0; i < nameBar.verts.Length; i++)
{
    nameBar.verts[i] += new Vector3(vert.x, vert.y += SomeYOffset, player.z);
}

Using the vertext with the highest Y-value might lead to weird placement on the horizontal axis. Maybe it would be better to use the Y-value of the highest vertext and the average of the outmost vectors for the X- and Z-coordinate.

Averaging could work with that approach. I use averaging to determine the center of my dynamic meshes all the time.

Is player.position.y *= SomeYOffset meant to be player.position.y * SomeYOffset?

Lol yes, yes it is.

So basically you're telling me to treat the namebar itself as a 3D mesh?

Initially yes, that is what I thought we where dealing with, I may have interpreted this wrong: "...given a 3D mesh, how should I proceed to calculate the name's position on the screen?" In general I don't like to use Unity's built in GUI. It is not well made. But if you decided to go with a Mesh it should be easier to position as you have real 3D space values.

And... how would I go about displaying the name itself given your solution?

What I mean is, in the end I still draw a box or label or whatever at (X,Y) coordinates.

Since you're using Unity's GUI, you'll have to calculate the ScreenPosition of the player by converting the WorldPosition. Once you have the screen position of the player, you might able to adjust the GUI element as expected. See this answer for a tip on how to do the conversion: http://answers.unity3d.com/questions/155208/world-to-screen.html

Some things to consider here are that the object might not be rotated towards the camera, and that the position in 3d world space of the object is not always linear. So, objects farther away from the camera would need the font size reduced in relation to their depth in the view.
Here is some sample code that transforms relative to the camera:
   objectname = GameObject.Instantiate(Resources.Load("HoverText")) as GameObject;
   GUIText name = objectname.GetComponent<GUIText>();

   name.text = "Test Name"; // Change Me

   objectname.transform.position = Camera.mainCamera.WorldToViewportPoint(transform.position) + new Vector3(0f, 0.05f, 0f); // Change the 0.05f value to some other value for desired height

"HoverText" should be in the Resources directory in the project. The gameobject itself should have a GUIText component added to it.


text:
Hide movieclip parts that are out of bounds
I'm making a game where one takes a picture of their face to use on a character.  I have them zoom in on the picture, but the bitmapdata extends out of its movieclip.  How do I assign bounds to my bitmapdata?

I decided to try getBounds

...and it didn't work

Since this task is not just relevant to games (I can imagine websites doing this) there may already be an explanation on the main StackOverflow.

I think you need to dynamically create a shape with the x, y, width, and height of what you want to be visible, make it a mask and then add it to the display list in front of the bitmap data's movie clip. See this article on the subject.

Use the scrollRect property of your Bitmap. Here's the API documentation. You might also be interested in the following question/answer.


text:
Simple 3D particle gravity in javascript?
I'm trying to do some simple gravity handling in my 3D environment (I'm using three.js). I've got some code, but it doesn't work. I'm hoping it's just a silly bug somewhere. Note: This is a cross-question from stack overflow since I've got no responses
function handleGravity() {
    for(var j = 0; j < spheres.length; j++) {

        for(var i = 0; i < spheres.length; i++) {

            var r1 = new Array( spheres[j].position.x, spheres[j].position.y, spheres[j].position.z);
            var r2 = new Array( spheres[i].position.x, spheres[i].position.y, spheres[i].position.z);
            var r12 = new Array(r2[0]-r1[0], r2[1]-r1[1], r2[2]-r1[2]);
            var r12UnitVector = new Array( r12[0]/Math.abs(r12[0]), r12[1]/Math.abs(r12[1]),r12[2]/Math.abs(r12[2]) );

            var m1 = masses[j];
            var m2 = masses[i];
            var r12Squared = r12[0]*r12[0] + r12[1]*r12[1] + r12[2]*r12[2];
            var a12 = new Array( -(gravConst*m2/r12Squared)*r12UnitVector[0], -(gravConst*m2/r12Squared)*r12UnitVector[1], -(gravConst*m2/r12Squared)*r12UnitVector[2]);

            velocities[j][0] += a12[0]*timePassed;
            velocities[j][1] += a12[1]*timePassed;
            velocities[j][2] += a12[2]*timePassed;
        }

    }
}

If you can see anything wrong with it, or give me any tips on using JavaScript to simulate many particles in a 3D environment most efficiently (I'm very new to physics + simulation), that would be awesome!

What do you mean by "simulating gravity" ? Do you want to make animation of falling stuff, or just compute positions of objects after some time? Do you want objets to collide with each other?

Gravity between the particles. So they act like planets in space. I think I've solved it though - thanks

This seems to work. It's a little clunky though - it makes me think there's some sort of rogue rounding going on:
function handleGravity() {
    for(var j = 0; j < spheres.length; j++) {

        for(var i = 0; i < spheres.length; i++) {
            if(i != j) {
                var r1 = new Array( spheres[j].position.x, spheres[j].position.y, spheres[j].position.z);
                var r2 = new Array( spheres[i].position.x, spheres[i].position.y, spheres[i].position.z);
                var r12 = new Array(r2[0]-r1[0], r2[1]-r1[1], r2[2]-r1[2]);
                var r12UnitVector = new Array( r12[0]/Math.abs(r12[0] + r12[1] + r12[2])/3, r12[1]/Math.abs(r12[0] + r12[1] + r12[2])/3, r12[2]/Math.abs(r12[0] + r12[1] + r12[2])/3 );

                var m1 = masses[j];
                var m2 = masses[i];
                var r12Squared = r12[0]*r12[0] + r12[1]*r12[1] + r12[2]*r12[2];
                var a12 = new Array( -(gravConst*m2/r12Squared)*r12UnitVector[0], -(gravConst*m2/r12Squared)*r12UnitVector[1], -(gravConst*m2/r12Squared)*r12UnitVector[2]);

                velocities[j][0] -= a12[0]*timePassed;
                velocities[j][1] -= a12[1]*timePassed;
                velocities[j][2] -= a12[2]*timePassed;
            }
        }

    }
}


text:
Transform translation relative to world space
What is common algorithm for translating a transform matrix relative to world space axis?
E.g. Matrix M is representing some local space.
When I want to translate M relative to it's own local axis, I just do it like
        M.Translate(translationVector);
But what should I do when I want to translate same matrix but relatively to world space axis?

pseudo code:
Vector mLocation = (M.41, M.42,M.43);

mLocation += normalizedWorldAxis * distanceToMove;

M.41 = mLocation.x;
M.42 = mLocation.y;
M.43 = mLocation.z;

In general you do not translate transforms. You translate points which are usually represented by vectors.
If you're wondering how to generate a transformation that produces a translation relative to the world axis, then you should look into homogeneous coordinates.


text:
How can I convert screen coordinates to world coordinates on the floor (when the y component = 0)?
I am using the Irrlicht Engine and would like to convert the coordinates of the mouse on the screen to the floor of my world. I am currently trying to use
getRayFromScreenCoordinates()

which returns a "Ray starting from the position of the camera and ending at a length of the far value of the camera at a position which would be behind the 2d screen coodinates." Then I do this to get the position:
    core::line3df line = getRayFromScreenCoordinates(receiver.mousePos, device);
    irr::core::vector3df lineVector = line.getVector().normalize();
    irr::core::vector3df pos = line.start + lineVector*x;

x would be the magnitude from camera to the coordinate. However I do not know how to calculate x (as I don't know the coordinate yet).
The page I got the code from, written in 2003

What you need to do is get a ray intersection against a plane which is your floor. I'm not certain how this is done in Irrlicht, but my guess is that there's some function such as:
vector3df plane::getIntersectionWithRay(line3df)
You can then discard the y part of the vector (or z, depending on your co-ordinate system ) as it will be equal to zero, and use the other two for a 2D vector.


text:
Creating Animal Crossing style world rendering with Python
I've dabbled a bit with writing 3D rendering code in the past, although I'm interested in knowing if there is existing code (libraries) written for/with bindings to Python that might facilitate the creation of a world effect similar to this.
The world is a tile map wrapped to barrel basically with the actor in the center and objects in the horizon falling behind a threshold.
My hope here is to try and spare myself as much as I can to do with the actual perspective, rendering, culling, etc... and focus more on the game and networking logic itself.  However any advice on the subject as to what approaches might be best suited here are welcome!

Related: http://gamedev.stackexchange.com/questions/17567/how-do-they-do-the-3d-effect-in-animal-crossing


text:
How to stretch Movie Clip according to user's touch coordinates?
I have code like this:
touchX = e.stageX;
touchY = e.stageY;

I also have a player movieclip that I'm trying to make shoot lasers.  So I got the MovieClip to appear and rotate according to the player's location and the user's touchX and touchY.  How do I make the laser MovieClip stretch according to the distance between the player's coordinates and the touchX and touchY coordinates?

Simply have the pivot point in the center of your laser clip. Calculate the distance between the player and the input.
var dx:Number = touchX - player.x; //Assuming SAME coordinate space
var dy:Number = touchY - player.y; // Else use localToGlobal
var halfdist:Number = Math.sqrt(dx*dx+dy*dy)/2;

Now scale your movieclip by distance.
   laser.width = halfdist;

Rotate your laser
var rot:Number = Math.atan2(dy,dx);
laser.rotation = rot * (180*Math.PI);

Place your Laser by rotation:
 laser.x = Math.cos(rot) * halfdist + player.x;
 laser.y = Math.sin(rot) * halfdist + player.y;

This code is good, but edit it and change Math.Pi to math.PI, the i should be capital.  Also, when I run this code, the scaleX and scaleY seem to change.

Well im only touching the Width though. scaleY shouldn't be affected

EDIT the height changes because the object is rotating...

Rotation shouldn't affect the scale.

Weird... I found out that as the object rotates, the object is now rotated and so the width becomes a different part of the scaling.

Then you are affecting the scaling elsewhere

I'm not effecting the scaling, it's just when you rotate the movieclip the width increase increases it from a new perspective.

Fixed!  I created a movieclip in the laser that has its own perspective of angle that cannot be changed from its root parent and changed the width of that.

@Abe You're right, width and height have effect on the bounding box. You can also try to calculate the ratio and apply it on scaleX.

ScaleX... good idea!

You could try  laser.scaleX = halfdist/100; instead of laser.width ( not sure if it will work, but to test it you have to put your laser back as it was )

I decided not to use scaleX, because if I wanted to flip it later or something....

you could store the width and height of the movieclip at rotation=0 in a variable for later reuse.


text:
Game Maker: How do I make a score display move with the view?
I have drawn everything needed to the screen including a HUD for the score, but I have my room set to follow my player: When the camera follows the player, the score HUD stays doesn't scroll with him!
How do I make the score display follow along with the player also?

You'll have to set the score position relative to the view position every update event.
Some basic pseudo code from what I remember of GML.
    score.x = view[0].x + 15;
    score.y = view[0].y + 15;

You can do something similar with the drag and drop interface, but I haven't touched GameMaker for years so I can't help you with that.

I think there is an option "relative to view" when you inspect the object in the room. Not sure though, been a few years for me as well (even before YoYo took over).

There's a new Draw GUI event that would be worth looking into: http://www.yoyogames.com/tech_blog/9
It would take care of doing all that relative stuff for you

I added this to event draw, of the object Score and it worked for me
x= view_xview[0] + 320;
y= view_yview[0];
draw_set_font(fnt_score);
draw_set_color(c_white);
draw_text(x, y, (score));

Welcome to GD.SE, Simon! Looking at your code, it's not obvious what everything actually does - for example, why is 320 added to view_xview[0]? It'd be great if you could edit your answer to explain your code.

@Simon was pretty close.
If you are trying to draw relative to the View that is Enabled you can use view_xview[view_current], view_yview[view_current].
For most situations you can get away with using view_xview[0] because most games do not utilize multiple views.

Have a look at the Draw GUI event for this particular problem.
I needed some left/right arrows on my screen to control player movement.  I placed two buttons in the room, added a Draw event to each with nothing in it.  I then added a Draw GUI event, with
draw_self();

as the only code in the event.
However, this only works for the full version.


text:
How to add a timer - Visual Studio, XNA (C#)
I'm wanting to add a timer in an XNA game using C#. The ultimate goal is to increment a score in a game every second by 10 points. As of now the score stays at zero. Watching YouTube videos is proving to be counter productive as they're quite confusing.
Thanks.

Show code of what you have tried up to now.

I believe something like this should work. (Place the code in the Update block)
Timer += gameTime.ElapsedGameTime.TotalMilliseconds; // Increment the timer by the elapsed game time.

if (Timer >= 1000) // Check to see if one second has passed.
{
    Points += 10; // Increment the points by 10.
    Timer -= 1000; // Reset the timer.
}

Note that Timer is a number, not an instance of special class.


text:
Implementing vector based movement in a 2d environment
Good evening.
I apologize if the title is a bit vague, I really could not come up with anything better.
I am currently reading a book called the nature of code and as a side project, I am working on a small 2d game in javascript.
One of the core concepts of this book states that a game object should incorporate three vectors, acceleration, velocity and location, where only acceleration is directly modified by the player. This translates to the following code;
    acceleration.add(0, 0.001);
    velocity.add(acceleration);
    location.add(velocity);

This works perfectly fine and so does the the .sub() method, when I want to move backwards.
However, this requires two functions. Also, all vectors have to be positive. This is quite a pain because I now have to decide whether the applied vector is a positive or a negative one, thus requiring methods like applyForceNeg(vec) and applyForcePos(vec). I'd much rather have one method where I could pass any vector.
I have pasted some of the code here.
How would I implement this without turning the code into a complete mess?
Any help would be much appreciated.
EDIT:
I figured out what actually caused all this;
As you can see here, I initially wrote the if statement so that upon every run, acceleration gets incremented by 0.001. Then acceleration gets added to velocity, which in turn gets added to location. The problem was that I did not set acceleration back to zero.
So in the first run, acceleration is set to 0.001, so is velocity and location. However, in the second run, acceleration increases by 0.001, yielding a total value of 0.002 which in turn gets added to velocity and location. Therefore we now have acceleration = 0.002, velocity = 0.003 and location = 0.003. After the third run, velocity and location are at 0.006 while acceleration is at 0.003.
Now, when I set acceleration to zero, it reduces the problem. Only if I also reset velocity, the problem is gone. However, I doubt this is the right way to do it...

What is the problem, currently?

First, you shouldn't be hard-coding numbers like your acceleration.  Numbers like these, which need to be fine tuned, should be variables that can be easily tweaked, either in one-place or dynamically using a slider or somesuch during testing.
Second, from what I understand (of your comment to MagiSun), your problem with the acceleration giving you odd behavior is that your acceleration value is far too small.
Even at 60 updates per second, you're accelerating at 0.06/s, and unless your velocities and positions are also in similarly small measurements (which I assume they aren't by your description of the resultant behavior), this will result in a very slow deceleration.
If you're keeping the "Down" key pressed the entire time, by the time you reverse course (and travel in negative velocity), your negative acceleration will be very noticeable, giving you the "uncontrollable speeds".
Try raising your acceleration value, but take note that you might also want to increment acceleration at a slower rate than your updates-per-second/fps.  Another concern is that you might want a maximum acceleration, even if it might be unrealistic, simply for the sake of a good "feel".

After some trial and error, this actually fixed it just now. It really was about setting a higher accerleration value. I had used 0.001 and 0.1 really did the trick. Thanks a lot!

Glad I could help  =)

In regards to this comment by OP:

The problem is the resulting behavior, where the object continues to
  move up for example, even if the down key is pressed. It eventually
  changes direction but by then it's at nearly uncontrollable speeds.

That is how velocity and acceleration work. You are simply providing the user with acceleration increments that are too large. Try reducing your acceleration increments to 1/4 of their present value, and report the results.
Because distance travelled varies as the square of applied acceleration, rather subtle changes in acceleration can affect the agent more than might be intuitively expected. Also check my answer to this post on simple equations of motion with constant acceleration.
Update:
Your turns should look like this, where the player can only set a = .001, or 0.000 or -0.001:
    a    v    l
 0.001 .001 .001
 0.001 .002 .003
 0.001 .003 .006
 0.001 .004 .010
 0.001 .005 .015 now motor turned off, so a = 0.000
 0.000 .005 .020
 0.000 .005 .025 now retro-rockets fired (ie braking applied)
-0.001 .004 .029
-0.001 .003 .032
-0.001 .002 .034
-0.001 .001 .035
-0.001 .000 .036 now motor turned off again
 0.000 .000 .036 etc.

When you increase the acceleration by .001 each time, you are in fact using constant jerk, as I suspected earlier.

Yes, I think the problem is the OP's understanding of acceleration.  Though I wouldn't cut the acceleration down, or it'll exacerbate the problem

@Attackfarm: Disagree strongly with the last part. The problem is that the velocity is becoming unreasonably high, which only happens because acceleration is either too great, or applied for too long. For example, even Usain Bolt takes 60m to reach full speed. Short of applying a drag proportional to v^2, only by scaling back acceleration can the distances travelled be scaled back.

But he mentions specifically that "it eventually changes direction", and the hard-coded value is 1/1000.  Unless every value he uses is incredibly small, what he's finding is pressing the "down" key constantly until the ship finally reverses, at which point the acceleration is so high that the reversed velocity is similarly high.

That sounds like the equations of motion are incorrect, and OP is providing control of jerk instead of acceleration. (Jerk is rate of change of acceleration, the third derivative of distance instead of the second.)

What Attackfarm stated is correct. There is a reversal, though by that time, the velocity is far too high. I edited my original question, which I believe now states the real problem. I'm really just using things I learned from the book I mentioned. For example, he explicitly states that one should use very small values for acceleration.

How small or large the value just depends.  On the coordinate system used, on whether you want it occurring in small amounts every update or in bursts of force, etc.  That's why I suggested tweaking it in real time to balance it.

Have you thought about adding negative velocity and using a ternary statement to decide what to add?
if(keys.up != keys.down) {
  acceleration.add(0, keys.up ? 0.001 : -0.001);
  velocity.add(acceleration);
  location.add(velocity);
}

EDIT:
What platform are you using? I've never seen a vector class that couldn't go negative.

Sorry, I may have phrased that badly. The Vector class can do that just fine. The problem is the resulting behavior, where the object continues to move up for example, even if the down key is pressed. It eventually changes direction but by then it's at nearly uncontrollable speeds.

You might want to edit your question to reflect your new question, if the behavior, and not the logic of subtracting vectors, is the real problem.

So, the .add method doesn't take negative numbers?
If it does, it's just a matter of adding a negative acceleration to velocity. Otherwise, you really have no choice but to check.
EDIT: I think I understand your problem now. Vectors can't be negative correct? If so, you'd probably be better off having acceleration be two scalars. This way, I assume they can be negative and you can just add each component.

The .add() method takes numbers as well as a vector object. It is really nothing fancy and should actually take negative values just fine. Adding a negative value should be the same as subtracting a positive one, right? However, as soon as I use negative values, the vectors continue to increase or decrease exponentially, leading to a pretty much uncontrollable object. It's on c9.io, I can post the address if you don't mind the horrible state of code. :)

Yes, adding a negative number is the same as subtracting a positive number. Doing it this way SHOULD be fine. What's with this line though? acceleration.mult(0);

Okay, now I know what's going on.
When you mult acceleration by 0, you're getting rid of it for good. That's not the idea behind acceleration. It's meant to keep going even when you're not pressing a button. Like a falling object, it keeps getting faster and faster, and doesn't continue at the same speed. What you want to do is get rid of that mult line, and make the opposite direction invoke a negative value. This will give you the acceleration effect.

That's also from said book. I'm using this project pretty much as a playground. This particular line is supposed to set the accerlaration to zero. It does have a slight effect but it's not really related to this problem.

If you want to move at a constant speed, you'll want that line for both key presses. If you want acceleration, however, you'll need to do as I explained above.

I actually just saw your comment. Sorry. I have removed that line and used a negative value like so. The problem, however, is still present. I also made sure that the addition of negative values works as expected, which it does. So the problem must be somewhere in the implementation I'm using, not in the vector class itself.

I see several things wrong with your code.  However, before trying to list them here, let me just show how I would rewrite your main loop:
// reset acceleration to default value
acceleration.set(0, 0);  // or, equivalently, acceleration.mult(0);

// adjust acceleration based on keys pressed
if (keys.up) {
    acceleration.add(0, 0.001);
}
if (keys.down) {
    acceleration.sub(0, 0.001);
}

// move ship according to Newton's laws
velocity.add(acceleration);
location.add(velocity);

ship.move(location.getX(), location.getY());

The main differences between this and your code are that:

The acceleration is not retained between update steps, but is reset to its default value (which I've assumed to be zero, but you could e.g. include gravity in that value) on every iteration.  This default value is then modified based on the player's controls.
The velocity and location of the ship are updated on every iteration, not just when the player presses a key: in the absence of player interaction, the ship should continue on its inertial trajectory.  Of course, since the default acceleration is zero, the velocity only changes if the player presses some keys (and thus the inertial trajectory is a straight line), but that would change if you included gravity.

Note that I've assumed that you want the ship to accelerate upwards when the up key is pressed and downwards if the down key is pressed, regardless of its orientation.  Depending on what kind of game you're making, you may instead want to add or subtract the ship's heading vector (normalized and scaled by a constant) instead of the fixed vector (0, 0.001) to the acceleration.

Also, there are a couple of improvements you could make to you physics simulation (i.e. the lines velocity.add(acceleration); and location.add(velocity);).  One is to account for the fact that the velocity has changed during the timestep in your location update, by taking the average of the old and new velocity:
// move ship according to Newton's laws...
velocity.add(acceleration);
location.add(velocity);
// ...including the correction for the gradual change in velocity
acceleration.mult(0.5);
location.sub(acceleration);

This makes the trajectories physically exact (under constant acceleration), and, in particular, ensures that, with appropriate scaling, they won't be affected by changes in the simulation time step.  However, to really make use of this feature, you need to actually involve the timestep in the calculations.  This would be easiest to do if your vector class included a multiply-and-add method:
// move ship according to Newton's laws...
velocity.muladd(acceleration, timestep);  // velocity += acceleration * timestep
location.muladd(velocity, timestep);      // location += velocity * timestep
// ...including the correction for the gradual change in velocity
location.muladd(acceleration, -timestep*timestep/2);

If not, you'll just have to do it by hand, e.g. like this:
// velocity += acceleration * timestep
acceleration.mult(timestep);
velocity.add(acceleration);

// location += (velocity - 0.5 * acceleration * timestep) * timestep
var displacement = velocity.clone();
acceleration.mult(0.5);
displacement.sub(acceleration);
displacement.mult(timestep);
location.add(displacement);

Note that this will mess up the acceleration vector (by multiplying it with 0.5 * timestep²), so you shouldn't use it for anything after this.

Now that is a thorough answer. Thank you. :) I've pretty much fixed the problem thanks to Attackfarm though you are right, the code is pretty messy. When dealing with something completely new, I usually don't care too much about looks or structure as I can simply rewrite it when I get a better understanding of how to do things properly. For example, now that it works, I will write a gameObj class and most of this will be wrapped in the gameObj.applyForce(v); function. Thanks again for your help. It's much appreciated. :)


text:
XNA Collision is quircky/wobbly, how to improve?
I am sorry if this was already answered but I couldn't find the answer.
So I am doing a tile based platformer and when I was making collision I had quiet a struggle I looked here and googled for answers but they all seems to be overcomplicated for such a simple task/game.
I did come up with this code and it works almost fine:
Rectangle boundRect = new Rectangle((int)position.X, (int)position.Y,
            (int)(sprite.Texture.Width * scale), (int)(sprite.Texture.Height * scale));

        Vector2 previousPosition = position;
        Vector2 previousVelocity = velocity;

        if (boundRect.Intersects(collider))
        {
            velocity = Vector2.Zero;
            position = previousPosition - previousVelocity;
        }

It works almost as good as I want, axcept few things. When I constantly move (i.e.) to left of a collider object(tile) my player sprite is shaking, if thats right word to use, for like 1-3 pixels from edge of object, also in this state I can't move any other direction (i.e. jumping up) till I stop my current movement.
So my question is basicly: "Can I improve this while keeping simplicity, or I need to use better(more complex) approach?"
P.S. Sorry for my English, it is not my native language.

You are going to need to do your move/collision in two steps, once for the horizontal direction, and another time for the vertical direction.

Move Horizontal
Check for horizontal collision - adjust position if needed
Move Veritcal
Check for veritcal collision - adjust position if needed

Doing the collision check like this should solve your stuttering issue.  Checking both directions at once is fine for collision detection, however, when dealing with collision response it is best to do each direction individually.

Thanks very much, I think that helped! This is how I did it now:
link I also extended Rectangle a bit but thats not my code I find it somewhere on internet

If it's wobbling like you describe, then the game is drawing both before the collision occurs, and after the collision occurs.  Make sure your Update function moves all of your objects first, and then handles collisions before that same Update call returns.  That way, only the result of all collisions is drawn.

@RedPanda I agree.  It seems you are checking for collision before you move your object on screen.

@Jon yeah big thakns guys, I did checked it before moving, but thats resolved only half of the problem. I still can't figure why I can't move in other direction when colliding and moving in other direction at same time.

I think the reason your sprite is shaking is because you're moving it back from the object based on previousVelocity. I'm assuming that when you press or hold the movement, it sets the velocity. If this is true, then I think what's happening is:

Your player is moving towards an obstacle.
Player's next move intersects obstacle. (boundRect.Intersects(collider))
You move player in the opposite direction. (position = previousPosition - previousVelocity;)
Player is holding down button and velocity gets set again since the player is not against the obstacle.
GOTO 1

Hence, your player would appear to bounce back and forth.
So, what you need to do is make the player go backwards to the point where they are resting against the obstacle instead of the full velocity. Then, ensure that when they have the button pressed down, the velocity doesn't get set if they are against something or it doesn't get set if there is an obstacle within the initial movement range (i.e. position + velocity).