# Question
Title: When mapping the surface of a sphere with tiles, how might you deal with polar distortion?
It's easy to deal with the way locations interact on a clean Cartesian grid. It's just vanilla math. And you can kind of ignore the geometry of the sphere's surface for a bunch of it if you want to just truncate the poles or something. But I keep coming up with ideas for games where the polar space matters. Geo-coded ARGs and global roguelikes and stuff.

I want square(ish?) locations -- reasonably representable by square tiles of the same size across the globe, anyway.

This has to be a solved problem, right?

What are the solutions?

ETA:

At the equator -- and assuming that your square locations are reasonably small, it's close enough to true that you can get away with having one square in the rows north and south of the most equatorial row. And you could probably get away with that by just hand-waving the difference up to like 45-degrees or so. But eventually, you need to have fewer squares in a pole-ward circumferential row. If I reduce the length of the row by one and offset the squares by 1/2 then they're just like hexes and it's relatively easy to do the coding to keep track of the connections. But as you get pole-ward, it gets more and more extreme.

Projecting the surface of the world onto the surface of a cube is tempting. But I figured there must be more elegant solutions already in use.

If I did the cube thing (not dissecting it further through geodesy) Are there any pros and cons related to placing the pole at the center of a face or at the vertex of three sides?

# Answer
> 5 votes
I think you are looking for a geodesic grid. Lots of people approximate the earth with a cube:

Carlos A. Furuti has lots of maps of earth that fold up into a cube

You may also be interested in the The Peirce quincuncial projection which maps the whole Earth to one or two squares.

The icosahedron (Dymaxion map ; "What is the best way to pixelize a sphere?" ) gives slightly less distortion, but is more complicated.

# Answer
> 11 votes
I've always wanted to see a game where the spherical map used a regular polyhedron of some some sort instead of playing the world on a torus. This technique is called Dymaxion map.
<sub>(source: grunch.net)</sub>

I would recommend an Icosahedron. Plop the current triangle so it's aligned on one edge of a square. When the player moves off the triangle, pull up the next triangle and map it identically again. The player's coordinates would then be remapped to the new section. So each section of your map has its own coordinate system. Also you'll need to draw the background for the 3 adjacent and 9 semi adjacent sections. I don't think the user would be able to determine how it's implemented if it's well done.

Here is an example of how this might work.

Of course after reading this you'll probably use the classic torus map and I'll be waiting to see a true polyhedral universe.

# Answer
> 6 votes
If you create a sphere using a geodesic base, the polar area is treated no different than any other region in terms of vertex spacing which facilitates uniform uv mapping.

Most modeling apps allow you to create a sphere primitive using a geodesic design.

# Answer
> 5 votes
There is no way to "map" a sphere with squares (or rectangles) and have them all join up at "common" vertices.

However, would it be feasible to generate the "local view" on demand? The problem space isn't really stated in the question, but if I were working on something where I wanted a city view but wanted to be able to spin the world, I might temporarily just map a grid onto a "flat enough" section of the world. The origin of the grid would be wherever your local center was, and the normal at that point matches the normal of the surface of the planet.

Then, when one walks off of the grid, a new one is generated on demand.

This may or may not work for the OP, but for some it might be useful.

# Answer
> 4 votes
Take a cube, with the distance between the vertices and the center of the cube equal to the desired radius. You have a sphere made out of 6 quads.

Now in each step, take every quad, divide it into 4, and move the new 5 vertices (one in the center, and 4 on the edges -- warning, they are SHARED) away from the center so that they like on the desired radius.

No, this method is not perfect, but at least it's a more or less equal distribution over the sphere.

# Answer
> 2 votes
I'm operating several PTZ network cameras from Sony, model SNC-RX570N, for the purposes of tracking moving objects in the sky and triangulating to obtain true 3D tracks. One of the aspects of initial setup is to define unattended "tours", for which waypoints must be chosen. There are a restricted number of such programmable waypoints, and I want to cover the entire hemisphere (the "celestial sphere") from horizon to zenith, leaving no gaps.

So I asked myself the question "What are the minimum number of waypoints that I need for full coverage (no gaps)?". I've discovered that I actually can't fully figure this out.

The camera has endless pan (360 deg) and 0-90 deg tilt, so theoretically it's possible to achieve complete coverage. The camera display, intended for computer use, is 4:3 aspect ratio rectangular. Rough horizontal FOV at 1x zoom is 58 deg.

There are two ways of representing the problem, depending on which projection one chooses: \- rectilinear like Mercator, whereby the horizon is "the equator", and the zenith is "the pole", dilated across over 360 deg of pan. \- polar, whereby the horizon is the circle's circumference and the zenith is the circle's centre.

I find polar the easiest way to approach the problem. I can carve up the circle into horizontal FOV sized pie slices, and this tells me I need 7 waypoints around the circle with that 58 deg H-FOV. So far so good. The inner radius is simply the tilt or V-FOV, which is 3/4 of 58 deg. So far so good - I've covered the outermost parts of the circle.

But it gets trickier as we approach the zenith. I'll assume that one of my waypoints is exactly at zenith. How do I map my view rectangle onto the region around the centre of the circle? Is that shape a rectangle, an ellipse, a pincushion, or what? How do I fill in the middle bit between the nice neat outer coverage and this odd shape at zenith? Flummoxed.

I note that the solid angle of a hemisphere is 2\*PI steradians, and that of my FOV at 1x zoom is 0.762 st, meaning I need a minimum of 9 tessellations. I suspect the answer is higher than 9.

# Answer
> 1 votes
With the dymaxion max you've got hexagons laid out in triangles on a flat surface but because the map isn't really flat they are pentagons. If you want to allow the player to keep their orientation when they walk over certain portions you'll need to separate the location maps from how they are actually stored. For things like buildings you could store a little map of rectangle vectors and then just do a harsh job of drawing them at whatever orientation you needed.

You wouldn't need to always make the interior look like there had been a recent Earthquake because I think the average player shouldn't even bat their eyes about entering a door to the north east but entering into a screen with the front door oriented due south and the whole building on a regular grid.

Though if you are going to just store buildings and important sites like that then you've done all the work for a soccerball pattern anyway. The end result is that you're storing the world as some non-square pattern and then forcing it into such a grid wherever the player is at.

There's another alternative though- if you don't give them all that precise an indication of the sphere, like if you just gave them a low precision compass to tell them which of the four orthogonal directions was closest to North, then you could get away with just doing 90 degree rotations for whatever location the player went to. Given the assumed graphics level it isn't as if you have to worry about a tall building obscuring some doorway. So long as they knew if they were near the poles or not they shouldn't get too upset about the compass changing on them, unless the NPCs around there told them to go North East or they try to actually go to specific latitude and longitude coordinates.

# Answer
> 1 votes
You're asking a question that people who make maps have been asking for a *long* time :)

Most definitely go read up on Map Projectsions to get some insights and ideas that might help. The challenge of representing the surface of a sphere on/with a flat 2D plane has been something people have been thinking about for a long long time.

Short answer is, no you can't do it. That's why when you look at maps of the world, some parts are distorted and some parts aren't. Usually it's the poles because most maps are about non-polar areas.

As other answers have said, the answer is to either use a different shape (hexes or triangles for example), or dynamically generate your map on the fly for the user's current viewpoint.

Square tiles are pretty easy to manage no question, but I don't think creating a tiling hex map is that hard.

Here is an older article from GameDev.net you might find useful. It's about doing isometric and hexagonal tiles on a grid.

http://www.gamedev.net/reference/articles/article747.asp

Googling "tiling hex map" will give you a lot of hits, some useful some not.

# Answer
> 0 votes
If you want to make a worldwide grid, I suggest you divide the planet in countries or continents, and make a square grid properly centered on each. Let the ocean cover the seams.

---
Tags: tessellation, maps
---


title: Is there an MMO-related research body?

text:
# Question
Title: Is there an MMO-related research body?
I'm trying to find a research resource for MMOs -- preferrably where people send papers to be published, have conferences, etc. If nothing else, just a repository of articles would be nice. Is there a site like that? I'm assuming it would be a subconference of a bigger group.

# Answer
> 4 votes
Such a thing does not really exist; games are not a very established subject in academia (except for graphics, although there is a trend towards that changing, perhaps) and what "research" is done that specifically pertains to the MMO field is likely done internally by studios developing them and thus would probably be considered a trade secret and kept undisclosed.

Your best bet is probably the LOGIN conference.

---
Tags: mmo
---


title: How should one person do game audio?

text:
# Question
Title: How should one person do game audio?
Most game development (game design, art, programming, etc.) can be done by one person with relatively little equipment: A game designer needs a pencil and paper, an artist Photoshop or Paint, a programmer a laptop and compiler.

Sound is different: External noises are a big problem, sound effects can't be made with instruments, and small mistakes easily produce disaster.

I can see how large companies with big studios and budgets do this.
**How can I do this as a one-person indie?**

Should I synthesize everything? Record sounds and buy some crazy program for editing them?

# Answer
First, read this question:

Second, there are *so many* musicians and sound designers of all skill levels (and expecting various degrees of compensation from free to standard rates) wanting to join on with a project. If you're having trouble finding somebody, you just need to find more internets. ModDB, GameDev.net, forums for specific engines/tools that have tried to form a general game development community. Seriously consider giving working with somebody a shot. You'll both learn a lot.

If you're wanting to be a one-man developer, then you can take a sound editor, microphone, and samples and synths, and now you're a sound guy. It's another art/craft to learn, no different in that regard to drawing/modeling/other-graphic-art, game design, and programming. Use the tools Valryon mentioned (SFXR and Audacity) to get started. Also look into:

* Wavosaur \- A freeware sound editor
* Reaper \- A very inexpensive DAW (digital audio workstation, used for producing music from audio recordings and midi) and Ardour, a FOSS alternative for Linux and OS X
* KVRAudio.com for free basic VSTs (often playable directly in Reaper and other DAWs
* Modplug, Renoise, SunVox, and Buzz are music trackers for old-school-style game music composition
* Links for the lazy: Audacity and SFXR

For learning about sound, you should be aware of some of its physical properties and how we are able to digitally represent it.

To start making music, you should learn about music theory and how to produce music.
> 64 votes

# Answer
There are many sound banks on the Internet providing sound effects or musics for games. It can be free or not, in all formats and quality you want. An example: Findsounds

You can mix those samples, or modify them to create new sounds. A fridge sound can be transformed in a spaceship laser sfx. Some softwares are quite easy to use to do that, such as Audacity.

If you are into retro/chiptune sound effects, there is an awesome software to make those kind of sfx : SFXR. You will spend some hours getting what you want but you can make everything with it.

Another solution is to record on your own. You need a mike and a lot of imagination (like this bread landing in the bath producing an octopuss being scratched sound...). But results may not be terrible.

Finally you can do all your sound effects with your mouth, the result may be.. unexpected!
> 26 votes

# Answer
As a one-man developer, I've got something quite interesting - I invested a few months into writing a piece of software which autonomously generates music. This doesn't work for everyone, of course, but it is really, really, helpful, since some music in the style of the game really helps me get into developing. If you're not a musician, then consider looking at other algorithmic composition programs.
> 4 votes

# Answer
I've been making music longer than I've been making games...But I just make all of my music and sound effects in Milky Tracker and FL Studio. That works for me since all I need are 8/16-bit style sound effects for my games.
> 0 votes

---
Tags: sound, sound-effects
---


# Question
Title: Is WS-Security or REST+SSL a scalable authentication platform?
I'm trying to find a solid architecture for authenticating users against a database. I have a game client, which I plan to serve up a request with. The transport doesn't really matter, but at this point I'm thinking HTTP and leveraging either SSL or WS-Security to ensure the encryption of data over the wire.

I'd like to avoid middle-man attacks if possible so I'm leaning towards WS-Security even though I know it costs more in terms of overhead.

On the service side, I'd like to use an authentication framework such as Apache Shiro to authenticate users against a MySQL database. I'm not sure if I can leverage the session features or not, as I haven't looked that for into it, but it'd be great if I could.

It will probably be a mix of storing some session information in the database and if I can leverage Shiro's session features then that's a bonus.

My real question is about the handshake between the client and server. If I use WS-Security isn't all that taken care of for me? Does that alone make the overhead worth it?

If not, what should I do here? I want to make sure all of the requests from the client are authenticated but I also don't want to have to jump through hoops to make it happen. Would something as simple as HTTP digest authentication work here?

One constraint I have is access to libraries. If it's not free and can't be used in a commercial product then I can't leverage it. My client is going to be written in C++ and I can use whatever language makes it easiest (I'm leaning towards Java) to make it happen on the server side.

I plan on adding support for users to purchase in-game items through micropayments down the road, so this handshake mechanism definitely needs to be secure.

I keep hearing people suggest REST + SSL, and to examine Amazon's Signing and Authenticating REST Requests page. Is that a viable alternative? If I used that and something like Apache Shiro would I have a winner?

# Answer
SSL is not vulnerable to MITM, unless the client machine has malicious root CA certificates installed (in which case you can't do anything at all as you might as well assume that the entire client is compromised). If you get a certificate from a proper CA like Verisign you will be assured that any communications with your server will be secure (except in academic situations like quantum computing). If you use an encrypted channel during the authentication phase you can use whatever serialization/communication paradigm you want (REST, Protobuf, etc.).

In other words all you need to do at the end of the day is make sure that the passwords are salted and hashed in your DB, preferably double-salted so that your client 'remember password' functionality can store a salted hash on the hard-drive; instead of a clear-text password.

Alternatively you could look into:

* SRP which doesn't need to occur over a secure medium.
* Mutually-authenticated TLS/SSL (using a client certificate). The nice thing with this is that it enables offline (LAN) scenarios as clients can authenticate with each-other without the presence of your authentication server.

WS-Security is primarily geared toward federated services, i.e. cross-enterprise, (as are most of the WS-I extensions) - which is probably not a concern for you. At any rate the WS-Security has the associated overhead of SOAP (and the underlying frameworks/marshalling needed to handle SOAP calls). SOAP is a very heavy protocol and is probably an **very** poor choice for game development. I would avoid this entirely.
> 1 votes

---
Tags: c++, authentication
---


# Question
Title: Proper audio formats in low resolution without gaps for a game
I'm a music composer and I have to give my first job for a game. They are working in Objective C in Xcode, it's a game for iPhone/iPad.

I need to know the proper audio format to give programmers since .mp3 or .aac **make gaps at the start and end of the loop** and .Wav or .Aiff are too heavy.

I'm working in Windows7 with Sony Sound Forge and Audacity.

# Answer
This is up to your programmers. If they don't know, they are confused. The programmers decide what type of compression is acceptable and you decide within that compression what the sample rate will be.

For instance.

* **WAV** is never used by a sane person in IPhones because of their uncompressed size. Though it is never in a final game, some programmers will compress themselves so this is a possible format.
* **MP3** is a likely candidate if they are ok with slightly larger files than what is possible but require instant loading of music. So no runtime decompressing is allowed.
* **OGG** is what I prefer but it has some overhead if you want to decompress it on load. A lot of IPhone developers will prefer this because a general goal is to get your file size under 20MB if possible. In my case, 18 of that is reserved for everything besides music. The problem with OGG is the decompression time can take a little bit. So for this you generally have a MP3 file of a short loop to play until the main loop is decompressed.

All of these possibilities require some knowledge of audio on their parts. If they don't understand that, it's your job unfortunately to explain the differences. Otherwise, give them a lossless clip and have them figure it out.

NOTE: Keep in mind a lot of audio software adds gaps on purpose. These gaps are to zero out the wave on the clip. If you had the amplitude at anything over zero when your clip starts, the speakers will pop. Sometimes the software overcompensates and adds an unloopable gap. Open the clip in a raw wave editor like audacity and cut out the extra space and make sure you still start and end at zero amplitude.
> 5 votes

# Answer
Unless they have requested otherwise the proper format to give to the programmers is lossless at the sampling rate and bit depth you have used for composition. Choosing a format and making it play properly is not your job. You could do the encoding, but only if the receiver know what he wants.

This is pretty global for all game content, you don't ship jpegs around internally either.
> 3 votes

# Answer
I suggest giving them lossless. It should be up to the developers to convert to the format they need.

FYI, in iOS, AC3 doesn't have gaps during looped playback, and I believe MP3 no longer does either. (Source: game I'm working on w/CocosDenshion as my audio engine.)
> 0 votes

---
Tags: audio
---


# Question
Title: NullReferenceException problem when loading savegame in XNA 4.0
I want to enable my program to load "savegames", and I followed the tutorial on MSDN, but when I run my code, I get the NullReferenceException error. I use an xml file as my savegame data container, and it works, but at this point I have to rebuild my game every time I make some changes to that xml file, and I want to be able to do it during run-time. The xml file is stored in my Content folder. This is the code of my load method:

```
   public void Otvori()
        {

            IAsyncResult rezultat = device.BeginOpenContainer("OtvaranjeDemo", null, null);
            rezultat.AsyncWaitHandle.WaitOne();

            container = device.EndOpenContainer(rezultat);
            rezultat.AsyncWaitHandle.Close();
            if (!container.FileExists(imeDatoteke))
            {
                container.Dispose();
                return;
            }
            Stream stream = container.OpenFile(imeDatoteke, FileMode.Open);
            XmlSerializer serializer = new XmlSerializer(typeof(PostavkeStanice));
            PostavkeStanice postavke = (PostavkeStanice)serializer.Deserialize(stream);
            stream.Close();
            container.Dispose();
        }

```

The compiler throws me the error at this line "IAsyncResult rezultat = device.BeginOpenContainer("OtvaranjeDemo", null, null);"

Since this is a method in a game library, I thought it had something to do with variable definition scope, but I declared the variable in the game wide scope, and I use this method inside the Update method, so that should not be the problem? Do you have any ideas? Thanks

# Answer
You need to get a device first using StorageDevice.BeginShowSelector In the Async callback of that method, you can assign the device to your variable. Only then can you call methods on it.
See Getting a StorageDevice Asyncronously (MSDN).

---

I suggest using the EasyStorage helper classes that encapsulates a lot of the setup of loading/saving.
> 2 votes

---
Tags: xna-4.0
---


# Question
Title: Best way to do buttons for an OpenGL ES iPhone game
I'm making a simple 2d game in OpenGL ES and I want to add movement buttons to it. What's the best way of going about this? In previous projects I've simply added UIButtons to the view but I hear there are performance implications in doing so with OpenGL ES so I'm wondering what the possible alternatives are if so.

# Answer
> 6 votes
If you can detect the user tapping on the screen, and know how to draw a simple textured 'quad' (two textured triangles or a triangle strip/fan) then the simplest button is just a combination of the two.

Draw a quad on the screen, texture it with your button's image, then do a simple bounding box test to see if the user has tapped inside it.

Be careful researching about 'OpenGL GUIs' and the like, it can get horrifically complex very quickly. Write your game with the simplest thing that works rather than setting out to design your own GUI library.

# Answer
> 2 votes
I don't want to sound snarky, but have you actually profiled the performance of using a UIButton? Sometimes the simplest answer is the more appropriate. If the full on UIView is too much, maybe just using Core Graphics alone on a CAShapeLayer is good enough and would be less code. Don't just throw out all the stuff Apple gives you, leverage what's there when it makes sense.

---
Tags: opengl, iphone, opengl-es, objective-c
---


# Question
Title: Any problems with Event usages within XNA on Xbox/Phone
This is a slightly vague one but I am currently looking at a couple of areas of my current framework, such as spatial partitioning and UI based menus, and with UI menus it makes sense to have an event based system so you can tell if the user has clicked on it etc... its like your own small version of winforms.

However for some other areas it got me thinking that I could expose a lot of evens for other things, such as when an object moves so it could be re-allocated in a spatial tree of some kind if needed, or if it needed to calculate a collision it could return an event.

Anyway I quite like using events everywhere as it decouples you from having to know about who needs to know what, however I was wondering if there were any hidden gotchas with using events on the Xbox/Phone. I read a few older posts that mentioned that there are performance penalties with events on non PC platform (i.e Link)

So is this still an issue or has XNA and the .net implementation on these machines improved in this area, as it would be nice to add events of all kinds to high level entities, like Player.HealthChanged, Creature.AnimationStateChanged etc, but I dont want to go exposing these for usage if there is a major performance overhead with doing so...

# Answer
> 2 votes
On all platforms there is a small overhead to calling a function though an event compared to just calling the function. This overhead is pretty small and its only related to calling the event so the longer the event the less significant the impact.

A smart use of events can actually help performance as you are only working when necessary. Its the usual cost/balance issue you will always run into with programming. If you keep you events low in number and have them do a significant amount of work it should actually help performance. There are a couple of gotchas though.

* Pileup

You might needs to make a way to prevent events such as a button press from getting spammed. I know when I get frustrated I keep smashing what ever button button didn't do what I want.

* Inconsistent running speed

If you have an event that triggers something hefty, maybe run an A\* algorithm, you can make you game stutter assuming the workload varies enough to be noticed by the user. Though with XNAs 60hz update speed you have to exceed the time of a cycle to cause this.

Also making the events asynchronous with BeginEvoke and EndEvoke can get you another performance gain, it takes some intentional designing around but might be worth it in your case.

I've worked with the XBox but not WP7; however, looking at the most resent Performance Considerations from Microsoft I see nothing about events being particularly slow.

---
Tags: xna, events, .net
---


# Question
Title: How do I use setFilmSize in panda3d to achieve the correct view?
I'm working with Panda3d and recently switched my game to isometric rendering. I moved the virtual camera accordingly and set an orthographic lens. Then I implemented the classes "Map" and "Canvas".

A canvas is a dynamically generated mesh: a flat quad. I'm using it to render the ingame graphics. Since the game itself is still set in a 3d coordinate system I'm planning to rely on these canvases to draw sprites. I could have named this class "Tile" but as I'd like to use it for non-tile sketches (enemies, environment) as well I thought canvas would describe it's function better.

Map does exactly what it's name suggests. Its constructor receives the number of rows and columns and then creates a standard isometric map. It uses the canvas class for tiles. I'm planning to write a map importer that reads a file to create maps on the fly.

Here's the canvas implementation:

```
class Canvas:
def __init__(self, texture, vertical=False, width=1,height=1):

    # create the mesh
    format=GeomVertexFormat.getV3t2()
    format = GeomVertexFormat.registerFormat(format)
    vdata=GeomVertexData("node-vertices", format,  Geom.UHStatic)

    vertex = GeomVertexWriter(vdata, 'vertex')
    texcoord = GeomVertexWriter(vdata, 'texcoord')

    # add the vertices for a flat quad
    vertex.addData3f(1, 0, 0)
    texcoord.addData2f(1, 0)
    vertex.addData3f(1, 1, 0)
    texcoord.addData2f(1, 1)
    vertex.addData3f(0, 1, 0)
    texcoord.addData2f(0, 1)
    vertex.addData3f(0, 0, 0)
    texcoord.addData2f(0, 0)

    prim = GeomTriangles(Geom.UHStatic)
    prim.addVertices(0, 1, 2)
    prim.addVertices(2, 3, 0)

    self.geom = Geom(vdata)
    self.geom.addPrimitive(prim)

    self.node = GeomNode('node')
    self.node.addGeom(self.geom)

    # this is the handle for the canvas
    self.nodePath=NodePath(self.node)

    self.nodePath.setSx(width)
    self.nodePath.setSy(height)

    if vertical:
        self.nodePath.setP(90)

    # the most important part: "Drawing" the image
    self.texture=loader.loadTexture(""+texture+".png")
    self.nodePath.setTexture(self.texture)

```

Now the code for the Map class

```
class Map:
def __init__(self,rows,columns,size):
    self.grid=[]
    for i in range(rows):
        self.grid.append([])
        for j in range(columns):

            # create a canvas for the tile. For testing the texture is preset
            tile=Canvas(texture="../assets/textures/flat_concrete",width=size,height=size)
            x=(i-1)*size
            y=(j-1)*size

            # set the tile up for rendering
            tile.nodePath.reparentTo(render)
            tile.nodePath.setX(x)
            tile.nodePath.setY(y)

            # and store it for later access
            self.grid[i].append(tile)

```

And finally the usage

```
    def loadMap(self):
        self.map=Map(10, 10, 1)

```

this function is called within the constructor of the World class. The instantiation of world is the entry point to the execution.

The code is pretty straightforward and runs good. Sadly the output is not as expected:

Please note: The problem is not the white rectangle, it's my player object. The problem is that although the map should have equal width and height it's stretched weirdly. With orthographic rendering I expected the map to be a perfect square.

**What did I do wrong ?**

**UPDATE:**

I've changed the viewport. This is how I set up the orthographic camera:

```
    lens = OrthographicLens()
    lens.setFilmSize(40, 20)
    base.cam.node().setLens(lens)

```

You can change the "aspect" by modifying the parameters of setFilmSize. I don't know exactly how they are related to window size and screen resolution but after testing a little the values above seem to work for me.

Now everything is rendered correctly as long as I don't resize the window. Every change of the window's size as well as switching to fullscreen destroys the correct rendering. I know that implementing a listener for resize events is not in the scope of this question. However I wonder why I need to make the Film's height two times bigger than its width. My window is quadratic !

Can you tell me how to find out correct setting for the FilmSize ?

**UPDATE 2:**

I can imagine that it's hard to envision the behaviour of the game. At first glance the obvious solution is to pass the window's width and height in pixels to setFilmSize. There are two problems with that approach.

1. The parameters for setFilmSize are ingame units. You'll get a way to big view if you pass the pixel size
2. For some strange reason the image is distorted if you pass equal values for width and height.

Here's the output for setFilmSize(800,800) You'll have to stress your eyes but you'll see what I mean

# Answer
> -1 votes
`setFilmSize` doesn't set the aspect ratio, it sets the size of your screen, like `glOrthof` in OpenGL.

More specifically, it sets the the resolution of the viewport. 3D coordinates are arbritary, so it should look good if you set it to the same value as the window's size. (So 1 unit will be equal to 1 pixel.)

This isn't a hard and fast rule of course. If you have a 3D setting such that 1 unit is 1 foot, then setting your film size to 800x600 will give a 800ft x 600ft view in your scene.

---
Tags: python, isometric, panda3d
---


# Question
Title: Where to hire someone to make a trailer?
Developers are found on coding forums, artists are found on art forums, etc... but where to find someone who is good at making trailers? Is there some community of "trailer makers"? Should I look for someone in a game enthusiasts forum? Any hints where to look at? ...let me also mention that we have very low budget, and a volunteer would be even greater.

# Answer
> 2 votes
Are there any universities around your area? If so, consider hiring a student in an appropriate field. Many schools also have a classified ad site where you can post an offer.

Trailers are not very difficult to make, so not going with an established professional is a relatively small risk. These students will likely be looking to build a portfolio, so make sure you tell them that you're willing to recommend them if you're satisfied with the job.

Much of this will also depends on what, *exactly*, needs to be done. Do you already have the gameplay footage? Do you have the music? Is it just a matter of stitching clips together and adding music? Do you need a voiceover?

Being specific is helpful here. The absolute worst thing you can do is to just say "make a trailer for this game." Ideally, you already have a mental image of what the finished product looks like. Put these ideas down on paper in the form of a detailed descriptive document, complete with sketches.

---
Tags: trailer
---


# Question
Title: Could a large number, such as 255.000255 be converted to it's RGB channels in a Shader language?
If I had a Vertex Shader constant holding one float value, like:

```
255.000255

```

**Where:** The first 3 numbers are actually red (255), next three are green (000), then the last three are blue (255).

... Could I separate those values and pass them to a vertex-variant register for the Fragment Shader? I'm thinking it would involve a combination of opcode operations such as: fractional, subtraction, and multiplications?

Perhaps there is a simpler way to pass all 3 color-channels in one register value and extract them back in separate channels (within a low-level language)?

**\- UPDATE -**

Alright trying to clarify my question a bit. The flow of execution would be:

* In Flash (in my case), pass the value 0xff00ff (Magenta) to a free Vertex Constant register of FLOAT\_1 (so it only uses one field of that register).
* In AGAL, the Vertex-Shader would decompile the field's value into 3 separate values (R, G, B, \[A will be taken care of with another constant\]).
* Still in the Vertex-Shader, pass those 3 separate values to a Variant that will be used by the Fragment Shader (example: mov v0.rgb, vt0.rgb).
* In the Fragment Shader, draw the interpolated color of the Variant.

Really, all I'm asking is happening in the Vertex-Shader. Then again, now that I know large numbers consisting of more than 7 digits won't work, a value of 0xFFFFFF won't fit! (16777215 = 8 digits = shit outta luck!).

Maybe it's just not worth the hassle. But if someone knows a work-around the limitation, that would be cool. (Heck... maybe it could be split into two fields instead?)

# Answer
Usually shader languages come with special types that hold multiple values. For example GLSL has `vec2`, `vec3`, and `vec4` types which hold 2, 3 or 4 float values... these types are ideal for something like RGB or RGBA values.

I don't know which shader language you use, but from your other question I'm guessing it's AGAL (Flash shader). There you use register and every register is 128bits wide. So it can hold 4 float values, which you can access like this:

```
register.r // first component (red)
register.g // second component (green)
register.b // third component (blue)
register.a // fourth component (alpha)

```

If that's not a possibility, you could probably just use an integer and bitwise operations to get the color values. Eg something like this

```
uint color = 0xff6633;
red = (color >> 16) & 0xff;
green = (color >> 8) & 0xff;
blue = color & 0xff;

```
> 4 votes

# Answer
No, you can't.

Floating-point numbers have a *floating* decimal point. So while you may write them as "255.000255", the float is stored exponentially: "2.55000255x102".

As you may know, 32-bit floats only store 6-7 decimal digits of precision. 2.55000255 has nine digits. So you can kiss the last 255 goodbye.

Now, you *can* store it as an integer. In DX10/OpenGL3.x-class hardware and better, you have sufficient bit manipulation capabilities to pack 3-4 floating-point values into a 32-bit unsigned integer, and then restore them in the fragment shader. However...

I'm going to assume that by "vertex-variant register for the Fragment Shader", you mean "pass a value from the vertex shader to the fragment shader, which will be interpolated across the primitive in question." Well, that's a problem. Because linearly interpolating that 32-bit unsigned integer does *not* give rise to a reasonable value. At least, it doesn't do a proper blend between colors.

So unless you want to pass an un-interpolated value (or pass 3 uninterpolated values and do the interpolation yourself per-fragment), this is not possible.
> 3 votes

---
Tags: flash, shaders, color, floating-point, agal
---


# Question
Title: Am I liable if my game damages someone's computer?
Do i really have to tell somewhere in my game documents that "there is no warranty for this software for any damage" etc? I see it a lot in almost every program, if not all, but is it really necessary, can someone sue me if i forgot to add that line of text and their GFX card burns out when they play my graphics-intensive game? (because that has actually happened to me few times, i didnt sue anyone though).

(Someone can fix my tags, couldnt add new tags because of low score.)

# Answer
> 5 votes
As one example, under UK law it's clear that if you fail to exercise reasonable care in what you do, and it causes harm, then you can be held liable for the damage caused. (Especially in a business -\> customer relationship, or similar, where there is some sort of contract.)

The bad news is that disclaimers don't tend to count for much in the UK (or in most non-US jurisidictions from what I've heard). So you may as well put them in, for the places where it does help, while bearing in mind that they don't nullify all your responsibility in others.

What you can do to protect yourself might involve setting the customer's expectations - for example, if your site says you are a one-man team making games in your spare time, and you aren't charging AAA prices for your game, then it's unlikely a judge would think it unreasonable for you to have more bugs than most other software of a similar nature.

# Answer
> 21 votes
I assume that you're based in the U.S.

I'm not a lawyer, and I imagine that these kinds of things vary from state to state, but here's what I know. Common sense dictates that you should verify all of this, however.

First, you can always be sued. A civil suit can be levied for any claim of damages exceeding $20. This is a *constitutional* provision, so it doesn't vary from state to state. Whether or not the plaintif will win is another question entirely.

I used to fix computers when I went to college and I got scared once that a client would try to sue me. I had an informal disclaimer (i.e., a document that was signed by the client that essentially stated I was not liable for any and all damages), but I didn't know what such things were worth. Fortunately, I did MMA with a guy who was a practicing corporate attorney. He told me the following:

* Such terms of agreement, though not legally binding, go a hell of a long way in determining a tort in a civil suit. In other words, having a EULA should help insulate you from litigious worries.
* The only thing that you can't really disclaim is *negligence*. In other words, if you screw up someone's computer because of a blatantly careless error, or if the client can convince the judge/jury that you didn't have reasonable quality control in place (e.g., absence of a bug tracker), you could be liable.

This friend of mine also said that while it's extremely difficult to disclaim negligence, it doesn't hurt to try. Just explicitly state that you disclaim all responsibility from any adverse effects of installing, executing, or uninstalling the software, including those arising from negligence.

I hope this helps!

---
Tags: legal
---


# Question
Title: Open source component-based game engines?
> **Possible Duplicate:**
> Are there existing FOSS component-based frameworks?

What open source game engines with component-based design of game objects do you know? And which best of them? I mean best not in Graphics or Physics, but best in context of Behaviour, Messaging, etc.

This question is the result of inspiration by another question

Thank you!!!

# Answer
> 1 votes
CraftyJS meets your criteria - component based and open source. It is a Javascript based 2D game/graphics engine.

http://craftyjs.com

---
Tags: c#, c++, component-based
---


# Question
Title: How do character/object interaction animations work in isometric games?
I am planning an isometric business simulation game where the player sees an office with the usual furniture such as desks, whiteboards etc.

Characters (Staff/NPC's) within the game should interact with these objects by performing some pre-defined tasks such as typing on the keyboard at the desk or writing on the whiteboard etc.

What I am interested in, specifically, is the following scenario:

Character moves across the office (1) to his desk (2) and sits down and starts to type (3).

From what I understand I would have a sprite sheet for the character movement (1) and a static sprite for the desk (2) but I don't quite understand how the third step would be handled?

Is there a combined sprite that contains both desk and character? I assume not, otherwise I would need to have a sprite sheet for every desk and character combination.

How is this normally handled?

**EDIT:**

Here is a specific example animation from the game Theme Hospital. You can see the video here.

As far as I can see the animation is split into several steps.

**Step 1 - Character moves between desk and chair.**

This suggests that chair and desk are in fact separate sprites.

**Step 2 - Character sits down animation**

Notice how in the very last frame the chair is closer to the desk.

**Step 3 - Desk animations**

**Step 4 - Stand up animation**

Is the same as sit down but played in reverse.

**Step 5 - Move away**

Use normal move animation to move away.

The questions I have is how are these animations best separated and how would a graphic artist usually provide these animations?

Is the character sitting and typing on the desk actually three different sprites (desk, character and chair)? Does anyone know any example sprites of similar animations?

**EDIT 2:**

I guess my biggest concern is that I have the right expectations on how the sprites will actually look like. I can't draw them myself so I will have to pay someone to do it and I assume there is some kind of best practice way to do these kind of animations?

# Answer
Short answer? Dont combine sprites.
That is, if you combine, you'll have to have the animation for every single combination. Seems strange if you just want one chair. But lets pretend your office could be expanded in the middle game, where the chairs now have a sprite nicer. Would you just add a chair sprite, or will you recombine and add all the animation of every employer again?

Lets make some calcs.

Pretend you have 6 sprites on a employer sitting typing animation, you have 5 different chairs, and 10 different employers type.

If you just draw the employer on top of the chair, this would take 10 * 6 + 5 sprites, 65 sprites.
If you combine, and make every combination, this would take 10 * 6 * 5 sprites, that is, 300 sprites. Will be such a pain for you to make a spritesheet this large for just a simple animation!

EDIT:

Well, if you dont know how to, it would be better to define your chair as a background, and the staff as active sprites. Easier for you.

```
Background.draw();
Foreach(employer i in staff)
    I.draw();

```

That should keep your staff separated from your chais(background) Also, update the frames of the staff animation indepently too.

EDIT2:

I saw your edit and your samples. I would keep the same approach. All different sprites. The chair would go in front of the character anyway!

To move the chair closer, update its position to some pixels up and left, or do this on the sprite itself.

Do you understand about Z align? that should play a lot of things...

You can see that some parts of the chair stays behind the character, others appear in front. So how is this possible if it is just one sprite? Z align!

Two ways to achieve the effect. Keep a mask(Not that easy) or divide your sprite in two.

I'll just mention the second method, as I dont have much time now. You should cut your chair sprite, in the parts that would be in the front, and what will be behind. Then put them in the same position. easy! What plays is the Z Align here, The parts behind should be drew behind, the character in the middle and the front chair parts in the front.

I don't know which lib/api/sdk/toolset you're using. But the most do this way: use a z Align factor that determines what is behind or what is in front or What is drew first go behind, what's drew last go in front. So you should keep this in mind.
> 8 votes

# Answer
An alternative idea would be to include a Depth/Z Buffer image with your sprites similar to how 3D APIs (OpenGL) ensure polygons don't overlap. For a basic sprite game it could just be a bunch of 0/1 bits (black and white bitmap) (although you could use more levels of depth if you want).

If you have a combined 'deskchair' sprite and want the chair to appear in front of any other sprites (ie people) on that square you would make the Z-Buffer version of the char 'black' while the desk would be 'white'.

When you render the dynamic sprite (a person) on that tile it would check to see what color is in the depth buffer. For pixels that are 0 (black) you skip drawing the person sprites pixels and just leave the chair ones there.

Rather than check every pixel 1 at a time, a simpler way to do the check would be to multiply the sprite pixels by the depth buffer value since the closer depth would be 0 and cancel out the. Then of course you have to colorkey (unless you have a alpha color channel).

This of course adds overhead (although you could skip it for anything that doesn't need multiple depth levels like a deskchair). You also need to sync your animations (ie the person would have to match up with the desk chair anim). It doesn't give you the same flexibility of just having a whole bunch of separate sprites.
> 2 votes

---
Tags: animation, sprites, isometric
---


# Question
Title: Where to start when building a 3D terrain editor?
I'm looking to build (for start) a simple tool, that could raise, lower, smooth and texture the terrain.

So, what are the things I have to go through in order to make such terrain editor?

And maybe there are valuable resources available on subject?

Yes, forgot to mentioned, that I'm interested in a 3D terrain editor.

# Answer
For a 'classic' 3D terrain editor, the steps could be those:

Generate a mesh (e.g a grid of squares, every square made of two triangles), all vertices are shared between triangles (so that there is only one normal per intersection).

This should be made a 3DMesh and rendered in your program.

Make a tool to raise and lower (smaller and bigger) parts of the grid (you need to calculate where on the mesh the mouse cursor is and modify the meshes vertices, but only up and down).

Create a big texture (like 1024x1024x4 or better) and texture it with what is called a splat-map:

Make it possible to paint it (with R,G,B OR Alpha, not pink for example) and to choose textures replacing those ugly primary colours (Red,Blue, Green, Alpha), or moreover, be represented by them:

The shader (that you will need to create) should multiply those nice textures (say stone, grass, ...) with the intensity in the splatmap (the ugly one) and then mix together the whole so it looks, for example (with like only 2 colours), like this:

Sorry for the big images, I whipped together this at work...
> 25 votes

# Answer
The first thing is to be clear on the data structure of your terrain, and what you want from an editor. Is it a mesh? An array of heights? Some sort of Minecraft-style voxel system? Do you need to be able to add mesh terrain features like trees and buildings? Manually, automatically or both? I could go on, but you get the idea.

A basic terrain editor isn't that difficult to write, but the details will vary a lot depending on the game you're making, and thus the type of terrain you want to make.
> 6 votes

# Answer
This is just mostly a follow-up to Valmond's response, but it doesn't seem short enough to add as a comment.

Once you get around to making a basic editor, you might want to experiment by generating the heightmap entirely on the GPU. This is completely optional but it's a good way of offloading work to the GPU for a constantly changing terrain. Valmond already mentioned the texture splatting being done on the pixel shader, but the vertex shader can be used as well, using a texture lookup to raise and lower the vertices in the grid. Here's a tutorial on how to accomplish this with the vertex shader. The non-shader stuff is C# and XNA specific, but the important stuff is in the shader code.

In this case, your code on the CPU side will just deal with modifying the grayscale texture stored in memory. Your mesh grid stays flat, vertices don't get updated by the CPU. Each time the texture is changed, the new texture can be passed to the GPU.

Keep in mind that not all shader models support texture sampling on the vertex shader (for instance in HLSL you need at least shader model 3.0).
> 5 votes

# Answer
You can have a look at Ogre's ETM http://www.ogre3d.org/addonforums/viewforum.php?f=16 , should give you some ideas. Artifex Terra is based on it if you want to see it in action.
> 0 votes

---
Tags: 3d, terrain-rendering, terrain, editors, map-editor
---


# Question
Title: How do I do 3d collisions in isometric game?
I've wondered how to get basic collision detection working in an isometric game. I'm using panda3d which has very comfortable support for bullet, ode and a small builtin physics framework. The problem is that these naturally don't work with flat images. I'm using dynamically generated quads as canvases in the 3d coordinate system. Every image or texture is mapped on one of these. The idea is to create tiles with images and place them in 3 dimensions to let panda3d do the rendering.

In order to place a tree on the screen I would generate one of the dynamic flat quads and map a texture with an image of the tree on it. Then I would move the quad to the desired position and everything's fine. Panda3d manages the correct rendering order.

Up to now the player object simply walks through the environment. I need to implement basic collision detection in order to solidify the trees. Browsing through previous questions I've found this one How do I handle Isometric collision detection? Unfortunately the question only targeted collisions to prevent the player from falling through the ground and allowing him to jump on platforms. This can be done comfortably with panda3d's builtin physics.

Here's a picture to show you what I want:

The ground itself is composed of a 10x10 grid of tiles. I've used the same texture for all of them. The tree is not a sprite that's rendered in 2d. It's actually a flat rectangle with a partially transparent tree texture. The white rectangle is my player object. With the standard 3d physics I could prevent the player from walking through the quad but the tree would still be perfectly flat. I thought about adding a "dummy mesh" to have 3d collisions but that would surely come pricey in terms of performance and would spoil the neat implementation of my 3d canvases.

**Is there a canonical way to get 3d collisions in an isometric game ?**

**How would you do this ? Please answer this second question on behalf of panda3d.**

I know that this is probably rather complicated. A link to a good article would be perfect. If you want to have a look at my code, you might want to read this question: How do I use setFilmSize in panda3d to achieve the correct view?

UPDATE:

Here's another picture that might depict the problem better

# Answer
ThomasEgi on the panda3d irc channel gave me some good advice. It will be best to add an additional mesh for each solid model in the scene. The graphics are rendered by the flat rectangle and its texture. The collision detection works on the new mesh. ThomasEgi suggested a small sphere, with a diameter of the trees trunk. Spheres would work best with the physics system and would be cheap on performance.

Thank you very much ThomasEgi
> 1 votes

# Answer
First, see my answer here from a couple of weeks ago. That deals with the 2D aspect.

Then for 3D, assuming you're using bounding boxes (need not be 1:1:1 side ratios), it's as easy as checking for an additional collision in Z. The general idea is this:

```
if (collides in 2D (x OR y) OR collides in 3rd dimension (z))
   resolveCollision();

```

Since this is a simple OR operation, you could do collision testing in any order you like, since the result remains that if there is a collision in any of X, Y, or Z, then a collision has occurred.

Isometry really has nothing to do with collision detection, it is just a representation of the world. My answer linked to above explains this in full.
> 1 votes

---
Tags: collision-detection, physics, isometric, panda3d
---


# Question
Title: Is it worth making component based entity system?
I've been reading about component based entity-system for couple days now and I'm not quite sure if it is worth implementing in my next game. I haven't started making the game yet, but I have bunch of ideas for it. In my imaginations the game will be very similiar to QUBE and Portal (1). 3D puzzler, no enemies, no weapons ( although there may be some "guns", just like portal has portal-gun ). The "basis" of the levels would be constructed from voxel-like data just like in QUBE, but there may be some models aswell ( although, since this is one-man project and I'm no artist, the models will be simple and there wont be many of them ).

I couldn't imagine that I'll ever have more than 20-30 different entities, if even that many.

This is a project that I expect to be working with for a long time, so I'm now trying to properly research all the possible "engine"-architectures before I actually start making the game. I want the game to be flexible and that I could easily implement more features as I progress.

Questions:

1. After reading this, do you think I should implement component-based entity system or not? If yes, why?
2. If I were to implement component-based entity system ( or in a matter of fact, any entity-system at all ), what would "terrain"/"voxel data" be? Would it be entity?

EDIT: I forgot to mention, the other option would be just simple inheritance-based entity-system. The game will be done using C# + XNA ( and WPF for the level-editor ).

# Answer
Short answer: probably

Longer answer: A component-based entity system becomes more valuable quickly as the number of distinct entity types increases, so your saying "20-30 different entities" is an important consideration. However it doesn't really take many different entities for component-based to be a big advantage. 20 different entities would certainly benefit a lot from a component-based system, although you also don't think 20 is many entities so I'm curious what exactly you consider "different".

For example, I wouldn't consider an old brass key and an electronic keycard to be different entities, but rather two instances of the same entity with different art assets assigned to the entity. Would you consider those to be different entities?

---

Another important consideration besides the sheer number of entities is their complexity. A component-based system helps a lot with complex entities, but is just unnecessary overhead for simple entities.

Going back to my keys example, I probably wouldn't bother with a component-based system for keys. I would use a component-based entity system for enemies, but then you said your game won't have enemies. What exactly are the entities you have in mind? Maybe not a full list, but at least give us a few representative examples.
> 3 votes

# Answer
Yes there are benefits in entity complexity, yada yada yada, but the real benefit of an entity component system comes not from the ease of creating new entities, or the ease of changing entire sub-systems; it comes from the ability to leverage cache-effecient algorithms. With components, for example, your physics code only needs to know about the object's position, velocity, and collision volume. It doesn't care about the model being displayed, or that it happens to be tinted green, and it doesn't have to waste space in the cache for the entire entity. Unfortunately, these benefits aren't nearly as great in C#.

Short answer : Yes, but don't half-ass it. Make your components data-only, and enforce this rigorously. Define behavior in separate modules that update all like components at once, and separate disparate data into separate components as much as possible.

For reference, http://software.intel.com/en-us/articles/how-to-manipulate-data-structure-to-optimize-memory-use-on-32-bit-intel-architecture/
> 2 votes

# Answer
You mentioned you want the game to be flexible. Do you mean that as only adding new features (better lighting, physics, etc), or also flexibility in terms of game-design? If you also want the game-design part of the development to be flexible, component-based entity systems would be pretty useful.

Unfortunately, I can't give you a competent answer to your second question.

If you choose to implement a CBS, there's two important things you need to ensure:

1. That components have a way to communicate between themselves very fast (this implies passing the right components to all other components that need them, so they are able to access them directly).
2. There's a messaging system in place so that components can inform each other when something rare happens, without having to check their state every frame for something that only happens very rarely, like sending a message when the player gets hit.
> 2 votes

# Answer
If the answer and the benefits arent't obvious to you immediately then it's probably not a good idea. Just make it work with the least amount of abstraction possible and when it's done perhaps some sort of "system" will emerge. But don't start by designing a system and then try to fit a game into it.
> 1 votes

# Answer
Based on what you have written I would say that a full on Entity/Component system may be over kill. A question to ask yourself is how deep and tangled do you see your inheritance hierarchy getting? EC Systems are good for cases where entities can take on functionality unexpectedly like if you have an RTS with flying units and ground units, and you decide you want a Mech type unit that can both fight on the ground *and* fly.

You could always split the difference. Have your game object inheritance hierarchy but if you start having functionality that does not neatly fit within it, factor that functionality out into a component. This is the approach I have been taking and have found it successful.

Anecdotally, I have found more success with having a simple GameObject hierarchy combined with components than having a "pure" EC set up with only a generic GameObject.
> 1 votes

---
Tags: xna, architecture, entity-system, component-based
---


# Question
Title: Handling polygons in multiple nodes of an Octree
I'm building a 3d software renderer for grins to learn the math and rendering concepts. I've implemented the basic drawing of polygons with some basic optimizations like back face culling and frustum culling. Its going pretty well for it being java and all (15k polygons at 30fps at 1900x1080) but I want to implement an Octree to reduce the amount of overdraw happening and correctly sort the polygons for drawing without using a z-buffer for the entire screen.

I get the basic ideas of how to partition the world and how to traverse the tree from front to back to order the polygons correctly, but I'm a bit confused on how to handle polygons that are in more than one node of the Octree.

Some example cases I'm concerned about are: A floor of 2 big polygons that intersect all of the nodes at the bottom of the Octree A polygon that extends across a node boundary I figure I should split the polygon at the node boundaries, but then do I need to check on each frame for objects that have moved in the world that need recalculation in the Octree.

# Answer
Actually, I don't think that octrees are the appropriate data structures for what you are trying to do, at least not if you are dealing with arbitrary polygons (which I assume you are). For sorting polygons (at least static ones), you may want to look into BSP (Binary Space Partitioning) trees instead, see

http://www.gamers.org/dhs/helpdocs/bsp\_faq.html

They are vaguely similar to octrees, but space is only split into two parts at each node, and the planes are not required to be axis aligned. They are fairly easy to build for an arbitrary scene (consisting of planar polygons), and you get correct front to back ordering of polygons fairly efficiently (though you may need to split a lot of polygons to achieve this).

AFAIK neither octrees nor BSP's can help you reduce overdraw directly, but a correct front to back ordering of polygons will certainly simplify the problem. If you are doing software rendering, one fairly simple possibility is the so-called "coverage buffer". See the article "The Coverage Buffer (C-buffer)" by Jacco Bikker on

http://www.flipcode.com/archives/articles.shtml

for an explanation. On that same site, you'll also find the article "Fine Occlusion Culling Algorithms", which describes several alternatives.

There is also Michael Abrash's "Graphics Programming Black book" (do a google search; presently, I'm not allowed to include more than 2 hyperlinks in a single post), which describes (among *a lot* of other things) how they dealt with this problem in Quake.

Approaches that works well both in software and hardware are beam trees (described in the flipcode.com article on "Fine occlusion culling algorithms") and portal rendering; the latter will also solve the sorting problem, if you only use convex cells. It will also handle dynamic scenes at no additional cost. A good introduction is the article series "Building a 3D Portal Engine" by Jacco Bikker, (the most relevant parts would be issue 9 and 11), which can also be found in the flipcode archives (see link above).
> 4 votes

---
Tags: culling, octree
---


# Question
Title: Things to do to port game made for iOS in Unity to Android?
I have just made my first game for iOS and submitted it to app store. I was thinking of porting my game to Android also. I would like to know things one need to do/remember to port game made for iOS in Unity to Android. How to handle different screen resolutions and pixel densities, optimizations required, etc. Any other suggestions and important things you think I should know?

EDIT: Also, should I handle builds according to device resolutions or by pixel density?

# Answer
This is all very game specific.

It all depends on how *your game* handles its UI and the size of things on screen to determine how you're going to solve the pixel density and resolution disparity issues (which should be pretty similar to how you're solving iPad vs iPhone, assuming you are).

Any optimizations you're doing for the iOS version should apply to the Android version. You really just need to get a couple of target devices and test on them.

As for specifics, if you're *not* using OpenGLES 2.0 and you are doing fixed function shader stuff you need to realize that you have fewer texture stages on Android hardware than on iOS hardware. It's generally 2 instead of 4 I think.

One thing that Android users are used to that you'll have to add is soft "back" button support. Basically check for `KeyCode.Escape` and go "back" where appropriate. I think this also includes exiting the application if you're, for example, on the main menu.
> 3 votes

---
Tags: c#, android, unity, ios
---


# Question
Title: Can I create mods for a D3D game made in C#?
There is a game currently in development in C# (using Direct3D for graphics) that I want to make mods for.

Ideally, I would like to make the mods in C#, but after that I am lost. How would I (or other people) put the finished mod into their version (client) of the game? I know that for Java this is pretty simple (as shown by all the Minecraft mods in the wild) but is it harder (or even possible) for a language like C#? Is there something special the devs have to do to make sure modding is possible?

# Answer
If the developer builds the game with the intent of supporting mods, then you can create mods through whatever means the developer has elected to support. Generally the language used to build the game and the specific technologies used to build the game (Direct3D, in this case) are not relevant to the game supporting mods in this case.

If the developer does not build the game with mod support, it's still possible to alter the game but generally you will have far fewer options and all of those options will be much more difficult. At this point it does matter what technologies the original developer used. For example, it's possible to hook (using DLL injection or hooking, for example using the Detours toolchain) function calls the game makes to the D3D interfaces and redirect them, allowing you to draw extra information on the screen.

You can also examine the game's data files and attempt to reverse engineer and modify them.

Decompiling, modifying, and reassembling the executable or its dependent DLLs is also an option but one that sits on questionable ethical and legal grounds -- I would not recommend this approach.

Your best bet would be to contact the developer and express your interest in a modding API and toolset.
> 1 votes

# Answer
Modding is something that is easy depending on language, but more how the developer designs his game.

Minecraft for example is actually decompiled, and then the necessary modifications are added by copying new files to the jar. Things like the ModLoader or Bukkit for MC make modding not only easier, but also allow for mods to be run without actually modding the files, but instead being loaded at game load.

Generally mods are implemented using Hooks, and a set of functions are given to you (the API). You can "tap into" the Hooks and have your own peice of code run. E.G, there is a OnJoin hook, with all the information about the player joining being passed to it. You as a modder can "tap into" it, and using the given API functions, do stuff when a player Joins.

As far as your question goes...

If the developers of the game give modders an API to work with, then modding is possible. Generally mods would be placed in a folder and run at game load.

If they do not, modding can still be done, but generally the game would be decompiled by another team, an API will be added over the top of the code, and that will make modding possible.

As far as actually making the mods go. You would have documentation on what language they allow; C# or Java, or scripting languages like Lua. And then using the given functions, you create your mod from that.
> 0 votes

---
Tags: c#
---


# Question
Title: Is there a simple way to do true isometric projection with an HTML5 canvas?
Is there a simple way to get a true isometric projection with the HTML5 canvas element?

# Answer
One of the properties of an isometric projection (and all axonometric projections) is that objects in the distance do not grow smaller.

Therefore, trivially, HTML5 supports isometric projections because you can just draw all your art assets that way, and overlay them to create the depth.
> 13 votes

# Answer
Edit: Revised the answer so it is more clear.

Here is a quick note on how to modify something simple like a square so that it is isometric. What I do here is run 3 draw routines. First, I draw a normal square who's center origin is the middle of the canvas (but your origin could be anywhere). Then, I make some basic calculations to turn it into an isometric polygon. This isn;t the "right" way to do this, but it should help you understand what the math in the next draw routine is doing. I then re-draw the polygon using a isometric transform, which is a short cut of sorts for doing what we did manually in the previous example.

```
   <!DOCTYPE html>
<html lang="en">
<head>
    <title></title>

    <script type="text/javascript" src="..\tccore\jquery.min.js"></script>

 <script type="text/javascript">

    var cellWidth = 30;
    var cellHeight = 30;
    var context;
    function getCellBoundaries(theCellX, theCellY) {

        //right
        var aOffset = { "offsetX": (cellWidth * -1) / 2, "offsetY": (cellHeight * -1) / 2 };
        var aCell = { "x": theCellX, "y": theCellY };
        var p1 = getScreenCoords(aCell, aOffset);

        //bottom
        aOffset = { "offsetX": (cellWidth) / 2, "offsetY": (cellHeight * -1) / 2 };
        var p2 = getScreenCoords(aCell, aOffset);

        //left
        aOffset = { "offsetX": (cellWidth) / 2, "offsetY": (cellHeight) / 2 };
        var p3 = getScreenCoords(aCell, aOffset);

        //top
        aOffset = { "offsetX": (cellWidth * -1) / 2, "offsetY": (cellHeight) / 2 };
        var p4 = getScreenCoords(aCell, aOffset);

        return { "point1": p1, "point2": p2, "point3": p3, "point4": p4 };
    }
    function getScreenCoords(Cell, offset) {

        var posX = Cell.x * cellWidth + offset.offsetX;
        var posZ = Cell.y * cellHeight - offset.offsetY;

        var xCart = (posX - posZ)
        var yCart = (posX + posZ) / 2;

        var rX = -xCart + 400;
        var rY = +yCart + 300;

        return { "x": Math.floor(rX), "y": Math.floor(rY) };

    }

    function drawIsoCellBorders (cellX, cellY) {

        var cellPoints = getCellBoundaries(cellX, cellY);
        context.beginPath();
        context.strokeStyle = "red";
        context.moveTo(cellPoints.point1.x, cellPoints.point1.y);
        context.lineTo(cellPoints.point2.x, cellPoints.point2.y);
        context.lineTo(cellPoints.point3.x, cellPoints.point3.y);
        context.lineTo(cellPoints.point4.x, cellPoints.point4.y);
        context.lineTo(cellPoints.point1.x, cellPoints.point1.y);

        console.log("Translated:");
        console.log("Bottom: " + cellPoints.point2.x+","+ cellPoints.point2.y);
        console.log("Right:" + cellPoints.point1.x +","+ cellPoints.point1.y);
        console.log("Top:" + cellPoints.point4.x+","+ cellPoints.point4.y);
        console.log("Left: " + cellPoints.point3.x+","+ cellPoints.point3.y);

        context.stroke();
        context.closePath();

    }

    $(document).ready(function () {

        context = $("#gamescreen")[0].getContext('2d');

        /*let's saw we want to draw an isometric square in the center of the page.
        Before we do that though, let;s draw a normal square in the center of the page
        so you know where some of these wild assumptions come from. To do that, we need to know
        where the square should go. We know our canvas is 800 wide and our cells are 30 wide so
        we can assume that our canvas can fit around 800/30 cells.*/
        var cells_wide = 800/cellWidth;
        var cells_high = 600/cellHeight;
        //half are our centers positions for 2d
        var xCenter = cells_wide/2 * cellWidth;
        var yCenter = cells_high/2 * cellWidth;

        var centerCellNumberX = cells_wide/2;
        var centerCellNumberY = cells_high/2;

        //to draw a square in the center of the canvas, we just draw the points.
        context.beginPath();
        context.strokeStyle = "blue";
        context.moveTo(xCenter-cellWidth/2,yCenter-cellHeight/2); //move to top left corner
        context.lineTo(xCenter+cellWidth/2, yCenter-cellHeight/2); //move to top right corner
        context.lineTo(xCenter+cellWidth/2, yCenter+cellHeight/2); //move to bottom right corner
        context.lineTo(xCenter-cellWidth/2, yCenter+cellHeight/2); //move to bottom left corner
        context.lineTo(xCenter-cellWidth/2,yCenter-cellHeight/2); //move back to top left corner
        context.stroke(); //draw and yay - we've got a little gray square in the center of our canvas
        context.closePath();

        //now, give this an isometric perspective is pretty easy, we essentially tilt the square.
        //a sort of simplified way to do this is as follows -
        //It means that we essentially draw a diamond instead of a square, and then halve the height
        //and double the width.
        //the first point, (the top of the diamond) is 1/2 the width of the square from where the top left
        //corner of a normal square would be, to the right
        //to Draw: first clear our other rect
        //context.clearRect(0, 0, 800, 600);
        context.beginPath();
        context.strokeStyle = "gray";
        console.log("Hacked:");
        context.moveTo(xCenter, yCenter+cellHeight/2); //bottom of diamond
        console.log("Bottom: " + xCenter + "," + (yCenter+cellHeight/2)); //bottom of diamond

        context.lineTo(xCenter+cellWidth, yCenter); //right of diamond
        console.log("Right:" + (xCenter+cellWidth) + "," + yCenter); //right of diamond

        context.lineTo(xCenter,yCenter-cellHeight/2); //top of diamond
        console.log("Top:" + xCenter + "," + (yCenter-cellHeight/2)); //top of diamond

        context.lineTo(xCenter-cellWidth, yCenter); //left of diamond
        console.log("Left: " + (xCenter-cellWidth) + "," +yCenter); //left of diamond

        context.lineTo(xCenter, yCenter+cellHeight/2); //back to bottom of diamond
        context.stroke(); //boom, we have an isotile and isopositioning based on some 2s cell-grid coord
        context.closePath();

        //now let's draw the same exact iso polygon but use our transform
        drawIsoCellBorders(0,0);

    });
</script>
</head>
<body>
    <canvas id="gamescreen" width="800" height="600" style="border-style: dotted; float: left;">

    </canvas>
</body>
</html>

```

An explanation of how this code works can be found here (I just found this today): http://www.kirupa.com/developer/actionscript/isometric\_transforms.htm. This explains a bit about a coordinate system similar to what we used. Unfortunately, it doesn't really explain the math, which I will do shortly (need to run).

In addition as mentioned in the previous post, some of this code is taken from http://github.com/j03m/trafficcone which is an isometric game engine for html5 that I wrote. To see how this code is used to create a full world, see Engine.js and GameWorldModelIso.js. Engine.js shows how a full grid can be drawn (drawMock3dGrid) and GameWorldModelIso.js shows how to build on the basic forumla used above to help you navigate the gameworld, place things in cells etc without having to think about the angles and such.
> 1 votes

---
Tags: mathematics, javascript, html5, isometric
---


# Question
Title: HTML5 canvas screen to isometric coordinate conversion
I am trying to create an isometric game using HTML5 canvas, but don't know how to convert HTML5 canvas screen coordinates to isometric coordinates. My code now is:

```
var mouseX = 0;
var mouseY = 0;
function mouseCheck(event) {
    mouseX = event.pageX;
    mouseY = event.pageY;
}

```

which gives me canvas coordinates. But how do I convert these coordinates to isometric coordinates? I am using 16x16 tiles.

# Answer
Check out the code examples at Andres Pagella's github repo. It's the example code that goes along with his book on isometric social games in HTML5. The book explains the math behind the transformation, or you could try and puzzle it out from one his examples, like this one.
> 1 votes

# Answer
It is probably going to depend on how you define your world grid, but the tutorials posted earlier are good. I wrote an html5 game engine and open sourced it here: https://github.com/j03m/trafficcone

Docs are still a little rough, but there are some usable/runnable examples. The Isometric game world model shows some of the code needed to do those translations.

Check out this class, it contains a bunch of helper functions designed to hide some of the complexity - but its a bit coupled to how we do things (tiles + cells):

https://github.com/j03m/trafficcone/blob/master/public/tccore/GameWorldModelIso.js

```
 getWorldCellFromScreenCoord: function (screenX, screenY) {
        var pos = this.getCell(screenX, screenY);
        pos.x = pos.x + this.cameraX;
        pos.y = pos.y + this.cameraY;
        return pos;
    },
    getCell: function (screenX, screenY) {

        var screenLocationX = screenX - this.originX;
        var screenLocationY = this.originY - screenY;

        var ym = (2 * screenLocationY - screenLocationX) / 2;

        var xm = screenLocationX + ym;
        var tw = this.cellWidth;
        var th = this.cellHeight;

        if (xm > 0) {
            xm = xm + tw / 2
        }
        else {
            xm = xm - tw / 2;
        }

        if (ym > 0) {
            ym = ym + th / 2
        }
        else {
            ym = ym - th / 2
        }

        var ty = this.rightFloor(ym / th);
        var tx = this.rightFloor(xm / tw);

        return { "x": -tx, "y": -ty };
    }

```

But this is again heavily tied to how you decide to do your coordinate system, the direction of your x/y/z axis (0-\>max or max-\>0) and if you use cells.
> 0 votes

---
Tags: javascript, html5, coordinates, isometric, html-canvas
---


# Question
Title: Commonizing cycle time across different browsers for HTML5
Is there a good (accepted) method for "fixing" the cycle time within an HTML5 canvas game implementation?

The game that I have been working on runs far quicker in Google Chrome than in other browsers such as Firefox, Opera, or IE9. To be honest, it kind of reminds me of running a game from the early 90's on a brand new machine.

# Answer
It sounds like you're looking for framerate-independent animation. If you're using a faster machine and your animations hang around for a certain number of frames, they'll appear to be moving faster. If your animations however are set to last for a certain number of milliseconds (framerate independent) then everything should appear the same on each machine.

There are exceptions to this, such as if the machine is very slow and the cycle time is longer than the expected duration of more than one frame in the animation, you may need to skip frames which can make things look not so nice.

Some searching revealed this example. Of note is the prototype for the Animation class, where the update function takes a time delta since the previous frame.

This framerate independent approach should be applied to all other concepts in the game as well such as character movement. Consider your standard walking speed to be in terms of pixels (at the current resolution) per second rather than pixels per frame.
> 4 votes

# Answer
For many games I recommend implementing game logic that updates in fixed time intervals. When updating your game, measure how much time has elapsed and then run as many game ticks as needed to update your game state to the current time.

pseudo code:

```
var gameSimulatedTime = 0;
var tickTime = 1000/60; // game logic runs at 60 ticks per second
update() {
    var newWallTime = (new Date()).getTime();
    var deltaTime = newWallTime - gameSimulatedTime;
    if (deltaTime > 1000) // If over 1 second has elapsed, ignore and only update 1 frame.
        gameSimulatedTime = newWallTime-1;

    while (gameSimulatedTime < newWallTime) {
      gameSimulatedTime += tickTime;
      updateGameStateByOneTick();
    }
}

```

Notes:

* If you browse away and come back, and or have very low frame rate, the logic squelches the huge update and just updates one frame.
* Game time is never lost.. If wall time has progressed for 1.5 ticks worth of time and then another 1.5 ticks worth the logic will correctly update the game for 3 ticks.

Pros:

* Even at low frame rates the game will update deterministically
* Some game logic is easier to implement in a simple "one step at a time" manner, instead of dealing with e.g. 17.490823ms of elapsed time.

Cons:

* Game logic may be run many times over each visual frame. If computation is expensive (e.g. A\* pathfinding) it may be preferable to update only once and provide the amount of time that should be accounted for.
* The discrete updates can cause beat patterns if e.g. the visual update is running at 45fps and game logic at 60fps. The game logic would update one tick, two ticks, one tick, two ticks, ... for each visual frame. In practice this often isn't that perceptible. Based on how expensive your update logic is, you can make the tickTime very small and greatly reduce this, e.g. tickTime = 1000/120 or even 1000/240.

If these Cons are *real* issues for your game, then move to more complicated update methods.
> 2 votes

# Answer
In: http://github.com/j03m/trafficcone (an html5 game engine I wrote) the way I approached was to use requestAnimationFrame but then also allow each sprite frame to have a speed attached to it in milliseconds. So, what you can do there is defined frame by frame the speed (so, if certain movements were to seem explosive and then slow down you can do that as well). From there, the engine tracks the last time the frame changed and handles it accordingly and uniformly.

Docs are still a little rough, but there are some usable/runnable examples. The Sprite.js and Frame.js classes might serve as good examples.

One thing I didn't do was apply this to movement :-/ where you have the same issue. Things flying around the screen on chrome but lagging on iOS. Will add that in next release.
> 0 votes

---
Tags: html5, html-canvas
---


# Question
Title: Are there any sample projects for Flashpunk?
Are there any open source games using Flashpunk? The other big flash game library Flixel has a number of example projects, are there any equivalents for Flashpunk?

# Answer
> 1 votes
You can check out http://www.brighthub.com/hubfolio/matthew-casperson/blog/archive/2010/03/19/flashpunk-tutorials.aspx. The tutorials are a little old now, but should give you somewhere to start.

# Answer
> 1 votes
this could help you:

https://github.com/Gornova/EscapeIn60Seconds

I've doing that for LD21, here the game itself:

http://www.kongregate.com/games/Gornova81/escape-in-60-seconds

# Answer
> 1 votes
For the last Ludum Dare competition there were some games that used FlashPunk:

* #1 Flee Buster - Chevy Ray (creator of FlashPunk)
* #7 McPixel - Sos
* #8 Hollow - Connor Ullman
* #27 Reach For It - Noel Berry

Once you start browsing the FlashPunk forums, these names will become familiar. Oh yeah, the forums have tutorials too.

# Answer
> 1 votes
I am probably resurrecting a very old topic, but I open-sourced a small platformer game I made for an artist on Flash Game License. The game didn't sell (as I never thought it would) but I made it for the learning experience.

Take a look here:

http://www.github.com/ericmbernier/GemCollector

Be forewarned though, the code is pretty ugly in spots, as I threw it together in a matter of days with no concern for code quality. Enjoy!

# Answer
> 0 votes
Here are some open source resources that I've found so far.

---
Tags: flash, actionscript
---


# Question
Title: How can I check for Shader Model 3 support?
Currently I am working on a 3D visualization app. A requirement of my app is that host's graphics card supports Shader Model 3. How can I check for Shader Model 3 support?

I know that these versions are supposed to support these models:

* DirectX 8.0 - Shader Model 1.0 & 1.1
* DirectX 8.0a - Shader Model 1.3
* DirectX 8.1 - Shader Model 1.4
* DirectX 9.0 - Shader Model 2.0
* DirectX 9.0a - Shader Model 2.0a
* DirectX 9.0b - Shader Model 2.0b
* DirectX 9.0c - Shader Model 3.0
* DirectX 10.0\* - Shader Model 4.0
* DirectX 10.1\* - Shader Model 4.1
* DirectX 11.0\* - Shader Model 5.0

But some graphic hardware doesn't support Shader Model 3.0 even with the proper DirectX version. So I want to *determine it by checking the hardware* not just the DirectX version.

# Answer
> 2 votes
You'll need to check the GPU capabilities through D3DCAPS (check the DirectX SDK docs if you don't know it). More than just determining the shader model, you can check for specific capabilities supported.

For a one-off check (not gonna help you at runtime) you can use GPU-Z.

# Answer
> 2 votes
If you are using D3D9, you can query for device capabilities reported by your card using the IDirect3D9::GetDeviceCaps method. This will give you a structure containing a lot of interesting information about what the hardware supports. Of interest to you concerning this problem will the fields in the resulting structure called `VertexShaderVersion` and `PixelShaderVersion` as well as possibly `MaxVertexShader30InstructionSlots` and `MaxPixelShader30InstructionSlots`. All four are described on the linked documentation page.

For D3D10 you *should* be guaranteed SM4. For D3D11 (which I'd recommend over 10, since it should be the case that you can use 11 if you can use 10) device capabilities are categorized into feature levels. If you're using the 10\_0 feature level or greater, you *should* be guaranteed SM4. Below the 10\_0 level you have some odd 10Level9 differences to take into account -- the upshot for you is that you have to use odd shader model designations like `vs_4_0_level_9_1` in some (perhaps all, we're getting into territory I haven't explored much in practice) scenarios.

You'll note that I said "should be guaranteed" in a few places. This is because, as you alluded to, it's possible for cards to lie or for there to be driver bugs that effectively render particular hardware/driver combinations "non functional" (or at least broken in a fashion you'd want to work around). This is *much* rarer these days than it used to be, but in these cases you can't really trust the hardware or driver anyhow and will have to "do it yourself." One way to do this is to simply try to create something using SM3 and see if it fails... although this will not catch all bugs/failures.

What I have done to account for that kind of issue in the past is build up a locally-maintained "feature database" API that allows me to store information about particular card/driver failures and how to fall back to safe alternative code paths when that hardware/driver combination is present on the end-user's machine. Populating this database generally requires trial-and-error and a lot of different hardware configurations, so can be difficult for the lone developer to do, unfortunately.

---
Tags: 3d, directx, hardware, requirements, shadermodel3
---


# Question
Title: What are some methods to represent train tracks?
I looked into this a while back for a small project, but didn't get too far. I'd like to create a small program that lets a user draw a train track and then allows a "train" to follow said track on a 2D plane. I'd like the track to be pretty free form and result in a nice smooth line. I played around with cubic splines and had decent results, but had a ton of trouble getting the train to follow the spline. I also had a lot of trouble creating multiple tracks and switching a train from one track to another.

Does anyone have advice, articles, or source code that can help me figure something out? Thanks!

# Answer
> 11 votes
When drawing tracks or roads, I always want to start with splines. However, the last time I was struggling with splines (as Rachel Blum mentions, smooth movement on a spline is icky both because of parameterization and distances), someone suggested to me that many real roads use circular arcs instead of splines. The constant curvature makes it *easy* to calculate distances and move at a constant velocity along them. Plus, they look good.

I started playing with roads that alternated between circular arcs and straight lines. It's similar to Will's approach but the circular arcs have variable radius. I was quite happy with this approach but didn't end up doing anything with it. Try this demo (Flash): the controls on the left are for splines and the controls on the right are for a circular arc (use the slider to control the length and the drag handle to control the angle). Make a very tight curve by dragging the end of the road to see how much nicer the circular arc looks.

Alternatively, if you want to play with grids (suggested by Iain), try drawing from edge to edge instead of square to square. Here's a demo (Java applet).

# Answer
> 8 votes
Using proper hermite splines can lead to tight corners and look rather un-train-track-like:

I've had much more pleasing results from treating the path as straight lines joining circles at the joints:

The trick is computing the inner and outer tangents of adjacent joint circles and working out the winding of each joint so you pass on the right side of it.

And, in track-laying logic, avoid path self-intersections or turn them into junctions :)

Here's a video using this approach: http://www.youtube.com/watch?v=PAVksn4btKU

# Answer
> 7 votes
You could try letting the user author the tracks using Cornu spirals. You'll find next-to-no literature about it online, because splines are the de facto way of representing curves in software. Nonetheless, they are how actual railroad tracks are pathed. Raph Levien has done a lot of work popularizing them.

# Answer
> 2 votes
You could try a grid based approach where each square can link to one or more other squares. You could then have some pieces that cover multiple squares, to create some smoother curves. Basically modular, like a train set.

# Answer
> 2 votes
I tried various techniques to implement rail tracks, and I found that sections of circles and straight lines were giving the best looking result, and the easiest math to run the train.

Unfortunately, it also made the track laying pretty complicated and not very intuitive, as small movements of the control points will send the track in a completely different direction.

The math for deciding how to lay the track becomes quite tricky, as is adding more control points.

I've got a short demo on http://www.dailymotion.com/video/xgl2kp\_openrailz-tech-demo-3\_videogames.

# Answer
> -1 votes
Maybe this will be useful:
Steering Behaviors For Autonomous Characters: http://www.red3d.com/cwr/steer/

---
Tags: mathematics
---


title: 3D rotation math/code for plane

text:
# Question
Title: 3D rotation math/code for plane
I am making a simple 3D game with plane in space. With c++ (win32). But the plane rotation is not realistic. The code I am using for the rotation is the following:

```
point3D AxisRotation(point3D point,point3D Rotation){
float sx = Sin(Rotation.x*PI/180);
float cx = Cos(Rotation.x*PI/180);
float sy = Sin(Rotation.y*PI/180);
float cy = Cos(Rotation.y*PI/180);
float sz = Sin(Rotation.z*PI/180);
float cz = Cos(Rotation.z*PI/180);
float xy,xz, yx,yz, zx,zy;
xy = cx*point.y - sx*point.z;
xz = sx*point.y + cx*point.z;
yz = cy*xz - sy*point.x;
yx = sy*xz + cy*point.x;
zx = cz*yx - sz*xy;
zy = sz*yx + cz*xy;
point.x = zx;
point.y = zy;
point.z = yz;
return point;}

```

The axis of the rotation needs to be (Roll,Yaw,Pitch). Does anyone know the code or the math for it ? Thank you. Dave

# Answer
> 1 votes
Try this: (You'll need to call this three times, once for Roll, Yaw, and Pitch). This should work, I've used it in my own game, and it has been unit-tested. Of course, if your vector/point class has its overloaded operators defined differently then it may not give similar results. Here is my vector implementation (as of a few months ago).

```
point3D RotatePointAroundAxis( const point3D& axis, const float
                               radians, const point3D& point )
{
    float matrix[3][3];

    float sn = sinf(radians);
    float cs = cosf(radians);

    float xSin = axis.x * sn;
    float ySin = axis.y * sn;
    float zSin = axis.z * sn;
    float oneMinusCS = 1.0f - cs;
    float xym = axis.x * axis.y * oneMinusCS;
    float xzm = axis.x * axis.z * oneMinusCS;
    float yzm = axis.y * axis.z * oneMinusCS;

    matrix[0][0] = (axis.x * axis.x) * oneMinusCS + cs;
    matrix[0][1] = xym + zSin;
    matrix[0][2] = xzm - ySin;
    matrix[1][0] = xym - zSin;
    matrix[1][1] = (axis.y * axis.y) * oneMinusCS + cs;
    matrix[1][2] = yzm + xSin;
    matrix[2][0] = xzm + ySin;
    matrix[2][1] = yzm - xSin;
    matrix[2][2] = (axis.z * axis.z) * oneMinusCS + cs;

    return point3D
    (
        matrix[0][0] * point.x + matrix[0][1] * point.y + matrix[0][2] * point.z,

        matrix[1][0] * point.x + matrix[1][1] * point.y + matrix[1][2] * point.z,

        matrix[2][0] * point.x + matrix[2][1] * point.y + matrix[2][2] * point.z
    );
}

```

If you're trying to rotate an entire plane then I suspect you have a rotation matrix, if you're using DirectX you could use something like `D3DXMatrixRotationRollYawPitch(&mRotation, rotation.y, rotation.x, rotation.z);` I'm not sure if that's the exact function name.

---
Tags: c++, winapi, mathematics
---