# Question
Title: Confusion about systems implementation of ECS
For reference I am mostly imitating the architecture in this tutorial, the "Entity System" section: http://www.raywenderlich.com/24878/introduction-to-component-based-architecture-in-games

NOTE: the tutorial is in objective-c but I am using C++. Also, I only code the "happy case" for now because I am not sure if this is the architecture I am going with; I am simply experimenting.

Quick background: every time a system's update() function is called, the relevant system calls a helper method in EntityManager, getEntitiesWithProperty(), that returns a vector of all entities which possess a component(s) type that the system operates on.

```
template <class T>
std::vector<unsigned int> getEntitiesWithProperty()
{
    std::vector<unsigned int> ret;
    auto key = std::type_index(typeid(T));
    std::unordered_map<unsigned int, PProperty*> map = data[key];
    for(auto i = map.begin(); i != map.end(); i++)
    {
        ret.push_back(i->first);
    }
    return ret;
}

```

The system then iterates through this vector, calling yet another helper method in EntityManager per each element in the entity vector. This method returns a pointer to the component that is associated with the particular entity that is being iterated over, and the system performs its logic on the entity:

```
void SRender::update(EntityManager& entM, float frameTime)
{
    auto ids = entM.getEntitiesWithProperty<Image>();
    for(auto i = ids.begin(); i != ids.end(); i++)
    {
            Image* img = entM.getProperty<Image>(*i);
            draw(img);
    }
}

```

After I implemented this ECS I "stress-tested" it by simply drawing 300 sprites at differing x and y values, and was only able to get around 80 average fps doing absolutely nothing besides rendering.

I then altered the SRender system class and update method so that, instead of calling getEnt..() every frame, it only calls it upon system initialization and every time the EntityManager's component data structure changes size (i.e. entity deleted or created), and stores a vector of relevant components locally within the system as a member variable, like so:

```
   class SRender : public SSystem
   {
       private:
           ...
           std::vector<Image*> components
   }

```

Without update() calling the helper function every frame, rendering the same 300 sprites every frame I get an increase of 150 average fps. 1k sprites yield 100 fps; 20 fps faster the prior implementation.

My problem with this new approach is that there is no longer a separation of data from function, and that there are more pointers to deal with spread over systems instead of all being contained within the EntityManager, and it overall is just messier to deal with and more bug prone. But I don't know how else to increase performance. NOTE THAT there is nothing flawed from a performance standpoint regarding my rendering pipeline; I did the same initial test WITHOUT actually rendering anything, but simply iterating over each element returned by the helper method, and the fps was exactly the same (around 80 fps average) as it was making draw calls.

What other approaches can I take to improve performance? I have seen other ECS approaches doing the same thing as in the tutorial (returning relevant data structures from the entity manager on every update() call), so I don't understand why my implementation of it has poor performance. Maybe I am overlooking something, or misunderstanding the tutorial (I'm unfamiliar with objective-c)?

# Answer
You have various implementation issues and some misunderstandings either about C++ or what ECS is supposed to do.

```
template <class T>
std::vector<unsigned int> getEntitiesWithProperty()
{
    std::vector<unsigned int> ret;
    auto key = std::type_index(typeid(T));
    std::unordered_map<unsigned int, PProperty*> map = data[key];
    for(auto i = map.begin(); i != map.end(); i++)
    {
        ret.push_back(i->first);
    }
    return ret;
}

```

This is probemsome. You're allocating a whole new `vector` every time you call this method as you're not reusing or caching the result vector. You're allocating a whole new `unordered_map` in each call, too, since you're not using a reference.

```
void SRender::update(EntityManager& entM, float frameTime)
{
    auto ids = entM.getEntitiesWithProperty<Image>();
    for(auto i = ids.begin(); i != ids.end(); i++)
    {
            Image* img = entM.getProperty<Image>(*i);
            draw(img);
    }
}

```

And here you're making yet another copy, in the line starting with `auto` since `getEntitiesWithProperty` does not return a reference. With C++11 you wouldn't be making a copy, but you're still allocating/filling a new vector every time.

Memory allocations alone can have a *significant* impact on performance, not to mention all the copying; these might be your problem. In general *avoid copies* anywhere you possibly can without compromising your ability to maintain the code.

> After I implemented this ECS I "stress-tested" it by simply drawing 300 sprites at differing x and y values, and was only able to get around 80 average fps doing absolutely nothing besides rendering.

If you're doing rendering, this is a bad benchmark. You have no way to tell if your ECS is inefficient or your rendering is inefficient (80 FPS is not unheard of for a naive sprite renderer on some hardware still in common use). Do a nullary update loop (do no work in your update method) to check only your object system's efficiency.

class SRender : public SSystem { private: ... std::vector components }

This eliminates half the point of what an ECS was originally about. You have a nice contiguous `vector` which is just holding pointers to `Image`s that could be strewn all over memory. You get very little performance benefit to this and might as well be using another significantly simpler component-based design (which I'd recommend *anyway*, but that's a different subject). This should be something like `std::vector<Image>` along with a free-list. Or, if you really want to use pointers/iterators, `std::deque<Image>`. That way all the `Image` instances are in contiguous memory and can be quickly iterated over and updated in a cache-friendly way.

Yes, Artemis is effectively doing the same thing you're doing in terms of memory access inefficiency (it's in Java and has no choice, since Java has no way to contiguously allocate objects last I checked), but that's a (significant) problem with Artemis, not something to emulate.
> 4 votes

# Answer
I just put my component cache inside of EntityManager. Systems don't need to know where the components come from. Implementation relies on a dictionary with the key being type of component - not sure if that is possible in C++.
> 0 votes

---
Tags: architecture, performance, entity-system, entity-component
---


# Question
Title: Does HDR rendering have any benefits if bloom won't be applied?
At the moment I use an image based light in my game for environment lighting. I sample a sky cubemap to get diffuse and specular lighting. At the moment I use a HDR rendering pipeline - the skybox uses 16 bits of storage. I draw to a 16 bit rendertarget, then at the end use a tonemapping operator to scale the values into the 0.0 - 1.0 range to be drawn to the backbuffer.

Recently I noted that most of my rendering pipeline was basically made pointless when I removed the bloom postprocessor. Nothing is actually done with the higher dynamic range values - they just get processed down to lower dynamic range values at the final stage of post processing.

Would I be right in saying that I might as well just use a low dynamic range pipeline and manually tonemap my skyboxes in Photoshop? This would make the pipeline much simpler. Is there any reason other than bloom why I might want to have HDR data?

# Answer
There are many places where HDR makes a difference besides providing source data to base a bloom filter on. Essentially, anyplace where lighting values are scaled or added together is going to look different, and will be more realistic / physically correct when done in HDR.

One of the most obvious places where it matters is with **environment reflections**. As you may know, most non-metal materials have a very low specular reflection at normal incidence - like 2% to 5%. So the reflection will only be 2% to 5% as bright as the environment it's reflecting. If you don't have an HDR environment (including sky, light sources, etc. with realistic brightness levels), this will lead to unnaturally dark, washed-out-looking reflections. With an HDR environment, the reflection looks natural and maintains contrast despite the low overall specular level.

Here's an example I rendered using a gray sphere with a 5% spec and an environment map from one of Paul Debevec's HDR light probes. There is no tone mapping or bloom in this image.

This problem shows up with any shiny surface; cars, glass windows, and water are common cases. You can hack around this a bit by scaling or otherwise altering an LDR cubemap, but the benefit of an HDR cubemap is that it "just works" regardless of material or lighting environment.

---

Aside from reflections, HDR is important just for **light accumulation** to function correctly. When you have a scene with multiple sources of light, perhaps ambient and directional, or several converging spotlights, etc., there can be places where the total amount of light goes over 1.0, even if none of the individual lights has a brightness over 1.0. It improves the visuals if you use tone mapping to reign in the excess brightness smoothly, rather than simply saturating to 1.0 and clipping anything over that.

Here's an example from Uncharted 2 (this image can be found on slide 126 of John Hable's GDC talk). As you can see, without tone mapping, the areas on the character's cheek and forehead where the lighting gets too bright show an unpleasant yellow tinge (due to the red and green channels saturating before the blue) as well as complete loss of detail in the saturated region.

---

Finally, one more place where HDR shows up is postprocessing effects like **motion blur and depth of field**. Although it can be expensive, doing your whole postprocess chain in HDR leads to much more realistic results. Here is an example of what happens with motion blur:

When doing a blur, bright areas of an HDR image will remain bright and hard, while in an LDR image they will soften and dim. As shown above, the HDR postprocessing is a better simulation of what would happen in a real camera, so it looks more "filmic".

So there's much, much more to HDR lighting and rendering than just bloom.
> 54 votes

---
Tags: skybox, hdr
---


# Question
Title: Java collision detection with rectangles
I'm trying to get the collision between two squares. I've made a `Rectangle` object that overlays each one and updates the position every tick.

Then I made a collision method that checks whether they are intersecting or not. It just uses `rectangle1.intersects(rectangle2);`

That works fine, and it detects the collision, however I can't move when it detects it.

This is my move and collision method at the moment.

```
public void move(int xa, int ya, Player opponent) {
    if (collision(opponent)) {
        return;
    }

    this.x += xa;
    this.y += ya;

}

public boolean collision(Player opponent) {
    if (rectangle.instersects(opponent.rectangle) return true;
    return false;
}

```

The detection and stuff works fine, but I can't move. I see why I can't, because the method is returning before it moves anything, but I'm just completely lost for whatever reason on where to go with it. I'm sure it's an easy fix and I'm just not seeing something.

# Answer
> 1 votes
There are a couple ways you can go about solving this. They vary in complication and difficulty.

What I suggest starting with is testing your move before you actually move the rectangle, or move the rectangle back if there's a collision. Basically, your problem is that the rectangle moves to a position where it is colliding with something:

```
          --------                 --------
          |      |                 |      |
--------  |      |            -----|--    |
|      |  --------    -->     |    --|-----
|      |                      |      |
--------                      --------
        (1)                        (2)

```

And then it stays there, unresponsive to the collision. When you run `move` under condition `(2)`, the rectangles are still considered to be colliding and no move will be carried out, even if that move resolves the collision.

If you prevent it moving there in the first place, then it's free to continue moving in other directions. Code would look something like the following:

```
public void move(int xa, int ya, Player opponent) {
    this.x += xa;
    this.y += ya;

    if (collision(opponent)) {
        this.x -= xa;
        this.y -= ya;
    }
}

```

This method can lead to odd collisions though, depending on the velocity at which your rectangle moves. If it attempts to move 10 units but a collision occurs in 9, then it's prevented from moving in a direction even though it isn't flush against the colliding object.

To solve that, things get a little more complicated. To give an overview, you determine the magnitude of penetration along the direction one rectangle was traveling, and back it up along that direction to the point where it's no longer colliding. If the rectangle can bounce, an even more detailed implementation will determine where the rectangle should be considering that it collided mid-timestep. If you're interested on how to get started on those options, I recommend reading through Metanet Software's collision detection tutorials.

# Answer
> 1 votes
I like using a simplified version of the SAT (separating axis theorem).

Basically, You collapse your 2D rectangles down to a cardinal axis (eg: X or Y) by flattening the 2D point to a 1D point. Then, you simply look for an overlap. If you do this in both axis, you can be sure that there's an actual intersection.

This is pretty handy when you've got a number of objects in the "scene" as you can very quickly determine possible intersection of a number of objects.

---
Tags: java, collision-detection
---


# Question
Title: Java: See if Mouse is hovering/clicking Sprite
The game I am developing is in which you defend the Cell from the Viruses, and I need the sprites to have a `MouseListener` for when the mouse clicks on that `sprite`, it will get destroyed, and I cannot figure out how to get the location of the mouse and apply it to the sprite.

Basically, I need to grab the location of the `mouse` and the `sprite`, and when the user clicks it will reset the `sprite`.

I have tried to do debugging with this, so like if the mouse hovers the location of the sprite it will print a message "Hovering" but it just doesn't work.

For my update method, I added:

```
if(MouseInfo.getPointerInfo().getLocation() == this.getLocation()) System.out.println("SAME LOCATION");

```

I even got it to print out the location of the sprite and the mouse, and I aligned them both to `0`,`0` and it still didn't work.

CONCLUSION:
How do I check if the location of the mouse is the same as a sprite, and then print out a message to the console?

# Answer
If I understand your approach and problem correctly, you should use the following algorithm:

```
Obtain the minimum and maximum coordinates of the sprite.
Obtain the position of the mouse pointer.
Test both axes within a range.

```

The first requires the dimensions of the sprite and it's position. Let's say its position is relative to the top-left of the sprite. Pseudo-code would look like this (my Java is rusty):

```
int minx = this.getPosition().x();
int miny = this.getPosition().y();
int maxx = minx + this.getWidth();
int maxy = miny + this.getHeight();

int mousex = MouseInfo.getPointerInfo().getLocation().x();
int mousey = MouseInfo.getPointerInfo().getLocation().y();

if ((mousex >= minx && mousex <= maxx) && (mousey >= miny && mousey <= maxy) {
    System.out.println("Clicked on the sprite.");
    // Some reset code.
}

```
> 1 votes

---
Tags: java, game-design, mouse
---


title: Profiling the GPU of a tablet

text:
# Question
Title: Profiling the GPU of a tablet
We are working on a tablet game in Unity Pro (for the first time). Unity's profiler works great for probing the CPU, but the tablet's GPU isn't supported in the profiler, so we have no idea where the rendering bottlenecks are.

Are there any other means of profiling the GPU of an android tablet? (We are working with a Samsung galaxy tab 2 10.1 ) How do other mobile devs do this?

We are basically looking for any ways of getting info from the gpu as we're running the game. Benchmarking software wouldn't help; we don't need benchmark scores.

Cheers!

# Answer
> 2 votes
One of our team mates found Imagination: http://www.imgtec.com/powervr/insider/powervr\_presentations/profiling\_tools\_android.asp

It is a set of profiling tools for Andorid. You can configure this to your tablet and profile the GPU.

Would be better if Unity supported this on its own, but still, this gets the job done thoroughly.

---
Tags: android, unity, mobile, gpu, profiler
---


# Question
Title: XNA - Where should I start playing a song?
I am just wondering where is the best place to start playing the background song for a game. In the loadContent() method, Draw(), or Update() methods or when I initialize it?

I am trying to make it so that the song starts playing at the same time the screen appears.

# Answer
In "real" XNA is it safe to do so in any of the methods you listed, although **I would recommend `BeginRun`** myself, which is called *once*, immediately before the first call to `Update`.

```
protected override void BeginRun()
{
    MediaPlayer.Play(song);
    base.BeginRun();
}

```

MonoGame has historically implemented the startup sequence with subtle differences to the real XNA. But in this case it's *probably* quite safe to treat it like XNA. (I think at one stage it didn't even have the `BeginRun` method in `Game` \- hopefully that's been fixed.)

It's totally reasonable and safe to simply do this:

```
bool songStarted = false;

protected override void Update(GameTime gameTime)
{
    if(!songStarted)
    {
        MediaPlayer.Play(song);
        songStarted = true;
    }

    // ...
}

```

Which may seem over-done in this context, but starts to make more sense when you need to have greater control over music playback (eg: starting a song at the beginning of each level).

Finally, you may be tempted to implement the above check by checking the `MediaPlayer.State` property each frame (instead of your own boolean). I strongly recommend **not doing this**, as (at least in XNA) this is a slow, blocking operation that can significantly slow down your game.
> 2 votes

---
Tags: xna, c#, xna-4.0, monogame
---


title: Do you plan before or improvise?

text:
# Question
Title: Do you plan before or improvise?
**\- Transferred to chat -**

Lately I have found myself browsing Unity3D's asset store and in the complete projects and I was thinking if it is more effective

* to get for example an infinite runner template and start building up,
* or to think and plan ahead everything and then start working on it.

> Let's assume that this was not for your job or main job to make everyone think clearer and without barriers

For me both choices have their pros and cons.

***Freestyle / improvisation style***

Pros:

* can be more creative and more fun
* might be more successful
* better for one man bands / solo projects

Cons:

* time consuming
* might be unsuccessful
* not efficient when working in teams

**Plan ahead style**

Pros:

* better time management
* clear goals
* no missdirections
* more professional

Cons:

* can be less fun
* greater failure

The real question here is mostly to share your experience and the results you had if you ever worked over in any of these 2 ways described, and how you handled the situation regarding the work flow in each way.

# Answer
When you are working together with others, you definitely should write concept documents to make sure everyone knows where the project is going. You might have a vision, your partners might have a vision, but it might not be obvious at first that it isn't necessarily the same one.

But even when you work alone, thinking before you act is usually a good idea. Planning your software architecture beforehand and always keeping your planned features in mind while programming usually results in better and more maintainable code than just hacking together stuff as you go.

But never forget that the requirements of a game are much less set in stone than when you develop business software. Business software is made to solve a specific problem, so they usually have a long list of requirements to fulfill. The only requirement a game has to fulfill is being fun to play. But what is fun to play?

It's hard to tell which concepts will be fun and which won't. Experience and gut feeling help, but in the end you need to play a game to know if it works, and to play a game you need to develop it first. That means that a certain flexibility is always required in game development process. When you realize that a game feature you developed isn't as fun as you thought it was, you should be prepared to revise your concept document and see how you can remove or redesign the feature. Adopting some form of agile software development process, like Scrum for example, can help to organize the development of a project where the concept is not set in stone.
> 1 votes

---
Tags: game-design, project-management
---


# Question
Title: Need help thinking of a way to code a text parser
Apologies if this has been asked before, or if it is a bit too simple for this forum.
I'm new to C++ and as one of my first projects I have decided to try a textual adventure. Step 1: the text parser.
Note that I am aware that there are libraries out there that will make this for you, but I want to code it from scratch to learn what is going on :)

So! I've gotten to the point where I add the user's input to a `vector`, so that I can handle each word individually. However, I cannot for the life of me figure out a "handler" that does not hard-code everything. I want to create a `map` through which to associate the `string`, for example "Go", to the relative action handler. Something like this:

```
map<string, ActionHandler> actionMap;

actionMap["Go", GoActionHandler];

```

GoActionHandler would be a `struct` of ActionHandler type, and I would put in ActionHandler or the general messages/actions/reactions, and then in GoActionHandler I'd elaborate on the possible "Go" actions. But, one thing at a time... The code above does not compile, as ActionHandler is not a "type". Considering that for now I am just focusing on having a (scalable!) program that reacts differently based on the word entered, could someone help me by showing me **real** code? I've found online people making examples in pseudocode, but I'm to big of a noob to then know how to execute what they are talking about, even though I understand the logic.
So could anyone dumb this down and point me in the right direction? How do I include in my `main()` a way to call a `struct`/function based on the a `string` contained in a `vector`? (eg. `string` "Go" in `vector[0]`?)

# Answer
> 2 votes
Hope I've written it clear enough, so it could answer all your questions. (I put several keywords in the comments that you can look up if you don't understand something I did)

```
#include <iostream>
#include <map>
#include <vector>

using namespace std;

// Interface for all handlers
class AbstractHandler {
public:
    // this as an abstract method (pure virtual) which every handler must override
    // with its own implementation
    virtual void doAction() = 0;
};

// This class will handle the word "Go", it implements the abstract handler
class GoActionHandler : public AbstractHandler {
public:
    // here we override the pure virtual method of the abstract handler,
    // and replace it with our own implementation (in this case, we print "Go!")
    virtual void doAction() {
        cout << "Go!" << endl;
    }
};

int main() {
    // this is the vector we'll put words in
    vector<string> words;

    // we map a string to an action handler. The value (second template argument)
    // is a pointer to an abstract handler (we need to do this to take advantage
    // of polymorphism)
    map<string, AbstractHandler*> actionMap;

    // here we map the string "Go" to the GoActionHandler
    actionMap["Go"] = new GoActionHandler;
    // ... populate with additional handlers ...

    // ... populate your vector with words ...
    words.push_back("Go");

    // iterate over words in vector, activate handler for each word
    for (vector<string>::iterator iter = words.begin(); iter != words.end(); ++iter) {
        // retrieve handler for current word from action map. We supply the map with
        // a key (word) and get in return an action handler. We don't know which one
        // is it, but we know it inherit the basic handler
        AbstractHandler* handler = actionMap[*iter];

        // this is where we leverage polymorphism
        handler->doAction();
    }

    // cleanup dynamically allocated handlers
    for (map<string, AbstractHandler*>::iterator iter = actionMap.begin(); iter != actionMap.end(); ++iter) {
        delete iter->second;
    }

    return 0;
}

```

---
Tags: c++, text-based
---


title: Is a game view "stack" really a Stack?

text:
# Question
Title: Is a game view "stack" really a Stack?
Given the academic definition of a Stack as "A data structure where items are added in a FILO manner and accessed in such a way that only the top item may be examined or removed to be modified."

Game view implementations that call them "stacks" where each view is `pushed` onto the top or `popped` off the top and *each view below it is visible* seems to violate the above definition. The first part is valid, views are only added/removed from the top but the fact that each other view in the stack is still visible from top-down seems to violate the principle that only the top is accessible for examination or modification.

That said, are these implementations actually Stacks in the data structure sense of the word or just wrapped fully accessible arrays with fancy methods called `pop` and `push` added to them?

# Answer
> are these implementations actually Stacks in the data structure sense of the word or just wrapped fully accessible arrays with fancy methods called pop and push added to them?

That depends on how you implement your scene stack. I have used stacks that were `std::stack` and I have used fancy wrappers for vectors due to the need to check other scenes. So it boils down to the specific needs of a game, both are valid and are used out there.
> 8 votes

# Answer
Imagine for a second that you have a bunch of plates.

You can *stack* plates, by putting them one on top of the other. To add a plate to the stack, we push it on top. To remove a plate from the stack we pop it off the top. We can however reach into the stack and take out any plate, its just harder and requires lifting all the other plates out of the way.

The important thing to note is that, when you stack a bunch of plates, the plates you've stacked are still there, they don't become non-plates once you stack them. The stack really defines the *way we access the plates*. Also, you can in most cases *peek* at a plate within the stack. (a bit like tipping the stack up so we can see what plate has what written on it).

We're more concerned with *access* patterns, than overall implementations. And using a stack implies you're going to use it a particular way, rather than how it was implemented.

So yes, it's still a stack, regardless of implementation. It's about access patterns.
> 4 votes

# Answer
Stack is indeed nice way to do implement screen manager. However, it really depends on you, what you want for it. I had to create little bit different kind of solution, because of few problems that arise, with single stack.

Stack is nice, because if you automatically route input to top view and draw it too, it makes developing a game, very fast process. There is few problems thou. What if you create GUI view, that should be drawn on top, but should not take input away from the actual game screen? What if you create popup view, that darkens game world and shows some panel/window with information, still allowing game to be drawn and update, but no input. Because of this kind of problems, my screen manager has multiple stacks. I have Gui stack, gamescreen stack, background service stack and few others. My view has flags, that are set when it's instantiated. Flags can be Update, UpdateAndDraw, NoUpdateDraw,BackgroundService,PopUp,GUI etc. With these, my manager automatically pushes and pops stuff in out from stacks.

TL;DR; Yes, it really can be stack. Problems come when you wanna restrict running of certain view, either by stopping update or drawing, it forces you to design some controlling system.
> 1 votes

# Answer
It is a stack data structure from the user interaction perspective. They have to get rid of the window on top to access the next window down, and clicking a button may open a new window on top of the current one.

As far as the implementation goes maybe, maybe not. A stack would probably be the easiest to get up and running but wouldn't look as neat as it could without some kludges. So I would start with a stack to keep it simple but go with something else of better visuals later.
> 1 votes

---
Tags: viewport
---


title: Pygame 2d map error

text:
# Question
Title: Pygame 2d map error
I'm writing a Legend of Zelda like game in pygame.

I have this code for loading a map from a text file.

```
#Load maps
f = open ("map1","r")#This file is a text file containing only: 1
map01 = f.read()

terrains = [{"sprite": dirt}, {"sprite": mountian}, {"sprite": water}]

themap = [[-1 for x in range(150)] for y in range (150)]

for x in range (0,150):
    for y in range (0,150):
        themap[x][y] = terrains[map01]#if I replace map01 here with a number or random.randint(0,2) it works as expected

    for x in range (0, 150):
        for y in range (0, 150):
            screen.blit(themap[x][y]["sprite"], [x * 16, y * 16])

```

But that gives me:

```
$ python map.py
Traceback (most recent call last):
  File "map.py", line 17, in <module>
    themap[x][y] = terrains[map01]
TypeError: list indices must be integers, not str

```

Ok I'm making this a bit clearer I want to make a file called map1 that looks like this

```
1, 2, 1, 0 etc.

```

I can make a random screen with random.randint:

and I can make it a solid texture:

but I can't figure out how to predefine a map.

# Answer
Ok I managed to fix it myself so I'll go ahead and put what I got.

Instead of loading a text file I made a map\_data.py file and put a two dimensional array inside. then I imported the array in my main file:

```
from map_data import map1

```

and then I changed this line to:

```
for x in range (0,150):
    for y in range (0,150):
        themap[x][y] = terrains[map1[x][y]]

                                    /\
                     I had random.randint(0, 2) here before.

```
> 0 votes

# Answer
The `read()` function in this line:

```
map01 = f.read()

```

doesn't do any format checking to try determine what the text is. It just returns raw bytes as a string. You need to convert it to a number explicitly:

```
map01 = int(f.read())

```
> 4 votes

---
Tags: maps, python, pygame
---


# Question
Title: 2D shooting problem on Java using arrayList
I'm trying to shoot missiles according to a direction which a player is facing at. A missile goes towards right iff the player is facing towards right and shoot for instance. It is working but when missiles which moving towards for example left still on a screen and new ones are shot towards right, the missiles which moving towards left turn back and start moving towards right as well. I'm trying to treat each missile as an object for this shooting problem but seems not working. Is there any way to fix this?

In MainPanel class I have followings;

```
public void run() {
    while (true) {
        move(); // move the player

        player.update(); // update the player's conditions

        if (firePressed) {
            fire();
        }
        if (shots.size() > 0) {
            for (int i = 0; i < shots.size(); i++) {
                shots.get(i).move();// get a first shot and move it
            }
        }

        repaint();
}

```

and

```
private void fire() {
    // create a shot and store it in arraylist
    shots.add(new Shot(this));
    for (int i = 0; i < shots.size(); i++) {
        // set shot's direction according to that of player's
        shots.get(i).setDir(player.faceDirection);
        if (shots.get(i).isInStorage()) {
            Point posX = player.getPos();
            shots.get(i).setPos(posX.x - player.getWidth() / 8, posX.y);
            return; // break?
        }
        // shots.get(i).
    }
}

```

in Shot class I have

```
// Move the shot
public void move() {
    if (isInStorage()) { // if the shot are in the storage
        return; // do nothing
    }

    if (direction == LEFT){
        x -= SPEED;
    } else if (direction == RIGHT){
        x += SPEED;
    }

    if (x < 0 || x > panel.WIDTH) { // when a shot went outside the screen range
        panel.shots.remove(0);
    }
}

// Set the shot direction and return its direction
public int setDir(int dir){
    if (dir == LEFT){
        direction = LEFT;
    } else if (dir == RIGHT){
        direction = RIGHT;
    }
    return direction;
}

```

# Answer
Yes, stop changing the missile's direction whenever you fire a new shot:

```
for (int i = 0; i < shots.size(); i++) {
    // set shot's direction according to that of player's
    shots.get(i).setDir(player.faceDirection); //reset the direction for each missile

```

You're looping through each shot and re-setting its direction to that of the players. If you don't want the shots to change direction, remove that line.

Just create the shot and add it:

```
Shot newShot = new Shot(this);
newShot.setDir(player.faceDirection);
shots.add(newShot);

```
> 1 votes

# Answer
i acheived this with a program i wrote called "rotating" availible for referance at Nathan's Computer Knowledge

how i acheived this was to attach a line to the top of my image (the x, y coordinate) to the center of the image using the getWidth() getHeight() methods. that way when i rotated the image which was a space ship, the line would point in the dirrection of the front of the space ship, which could later be used to tell which dirrection to fire the missiles, so the animation will display a space ship firing missiles.

you also need to rotate your image and make your ship or whatever front of the image whatever your image is the front needs to be pointing to the top right of the or i mean the top of top left.

this teqnique as far as i know only works with images rotating that are not moving , it may work with space ships but your ship might be deformed haha but i think it would look fine.

the next thing you need to do is get the slope of the lines, and figure out which dirrection it is facing.

i achieved something similar to this at point a to point page

how now that i think about it, i might be trying to answer the wrong question. but if you ever need to get a image or an object from anywhere on the screen to anywhere on the screen i would really reccomend that point a to point b page listed above. it is difficult to explain the answer but i have acheived this myself for a program that didnt have user input, in other words a "stationary" object rotating and shooting in a 360' dirrection , displaying animation as a cannon shooting cannon ball s , that was the first or the second link i listed the first one, which may be somewhat helpful to your question.

to clarify, you need to (as described above) rotate your image in a paint program (disclaimer: your image will show as rotated to the left 50%), add a line line2d.double(yourimage.getx(), yourimage.gety(),yourimage.getwidth() / 2, yourimage.getheight() / 2);, from the top left (x, y) to the center (as described above), then you need to get the slope of the line, figure out which dirrection your line is facing in an 8 quadrent circle, which i have done (the last two steps) i have done at the page listed above, the first page "Nathan's computer knowledge" you may use my program "rotating" as a reference to achieve the last two steps which are long and complicated, but if you look at my program you should be able to see how i did it, and the page has a runnable jar zip folder attached working on windows for download demonstration visual and the source and the source and images are included.

i think that is it, you could have rotation code set up to a key listener as well.

good luck to you, if you have any questions or comments or would like to contact me, please reply via email that is listed on the about me page or should be listed.

Best regards, Nathan Nelson

one of the links i was trying to post it looks like it got the wrong url acctually i think i might have fixed it its called "rotating" on the nathanscomputerknowledge website it should be listed in the navigation onthe left side of the screen. acctually it is called "rotating cannons shooting cannon balls in a runnable jar"

also: when you get the slope of the line and the quadrent number, you have to increments the x or the y value depending on which quadrent you are in, and the y and the x value by the slope of the line. keeping looking at "rotating" if you get lost and watch the program in your ide to see what it does, then you will know how to do what it's doing by looking at the code, which may solver your problem or similar problems.

take note: this teqnique works in a 360' radius not just a 8 quadrent vector (circle)
> 0 votes

---
Tags: java, 2d
---


# Question
Title: Finding the monitors orientation in XNA for Windows
Just to be clear this is *not* for Windows Phone 7. =)

I've got some interesting requirements for a project and I'm having trouble trying to find the information I need.

I have two monitors. The default monitor is landscape. The second monitor is portrait.

Right now I save the width and height and then change `Graphics.PreferredBackBufferWidth` and `Graphics.PreferredBackBufferHeight` to the values returned from `GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Width` (1920) and `GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Height` (1080) right before toggling to full screen. This works fine on the monitor in landscape mode. The monitor in portrait however scales 1920x1080 to fit onto the 1080x1920 screen.

I'm looking for either a way to determine that the monitor is in portrait mode or have the `CurrentDisplayMode.Width` and `CurrentDisplayMode.Height` return the portrait appropriate values.

I've been rifling through the XNA Framework documentation and googling like mad and not finding anything helpful.

# Answer
> 3 votes
You can just check if the width of the screen is less than the height - if this is the case, then you definitely have a monitor in portrait mode.

---
Tags: xna, windows, orientation
---


# Question
Title: How can I make the "Strength" attribute more attractive to Wizard/Caster classes in a RPG game?
I have a game where, among many attributes, is Strength and Constitution. In Ultima Online, Strength was used for hit points. However, I would like to avoid this- as Hit Points are so incredibly important, every class will want to have a lot of them in any game you play. In almost all MMORPG's and in many RPG's, players stack constitution almost as much as their primary attribute.

I have a plethora of ways in which INTELLIGENCE helps a WARRIOR type. It is the problem of the attribute STRENGTH helping a WIZARD type that is giving me so much difficulty.

Strength can more easily be an important statistic for Warrior and Rogue types, as they are both melee damage- and players tend to love stacking high damage. However, Strength is all but useless to a Wizard who casts spells from afar, and relies on Intelligence as their damage attribute.

What can I do to strength, to make it more appealing to wizard types, or any class that does not perform any melee combat?

Correct me if I am wrong, but I do not feel as though Spells/Magic should be more powerful because someone has more physical muscles and capacity to lift more. It makes sense to give Magic more power if the caster had a lot of fortitude or a overall healthy body, but that is already defined as Constitution.

I want to make Strength as attractive as Intelligence, to Wizard types than in stereotypical RPG's.

I was able to find balance between a "Dumb Brute Warrior" vs "Intelligent Warrior". How can I find a balance between a "Buff Conan Wizard" vs "Intelligent but Frail Wizard" without introducing melee combat?

Adding unique gameplay features or altering the traditional RPG style of play is more than welcome.

# Answer
> 21 votes
One way I can think of to make strength important to a mage, would be to have strength decide the maximum weight a player can carry, and have some (or all?) Spells require reagents that take space and consume weight.

Or make a heavy staff necessary to cast the more powerful spells, which you can only wield if you're strong enough.

That way, if you want to cast lots of spells, you have to spend some attribute points in strength to carry all the stuff you need.

Crossposting seems to be discouraged, but you may get other perspectives if you ask at the rpg stackexchange site.

# Answer
> 29 votes
You do not give deep details about what you already have, but starting on an empty canvas, I would say that intelligence shall be used to determine the complexity of the spells being able to be cast by the wizard, while strength may be used to determine the number of spells being able to be cast by unit of time.

This way, an intelligent but weak wizard, may be able to launch a powerful spell, but will need more rest time to launch additional ones; on the other hand, a strong but stupid wizard can systematically launch basic spells, which may be useless against powerful foes.

Wizards will tend to be able to launch powerful spells, but eventually will feel the need to grow in strength to launch them more often.

# Answer
> 15 votes
Casting requires mental discipline but also requires large amounts of energy to flow through the body. Holding the body in the right position and directing the flow with precision requires physical strength to hold the arms and the head and the fingers just "so" while huge energies are flowing through them. If your muscles are not strong you have to take it very slowly and carefully, the more physical strength you have, the more you can rely on your body to hold the necessary position while you channel the energies.

Which is to say that strength affects casting speed and channeling rate.

Maybe

# Answer
> 13 votes
**Get rid of Strength**

Just because every other CRPG since the inception of computer games has ripped off D&D's original poorly-conceived attribute system doesn't mean that you have to as well.

You can fix the issue of Strength being useless for casters by simply not having Strength. Or don't have it for casters. Some alternative stat concepts that don't just copy D&D's poor design include:

1. Show only relevant stats to the class. There can be a handful of "always relevant" core stats like Constitution and Dexterity, but then Strength could only be shown to warrior-like classes while Intelligence is only shown to magic-user classes and Charisma is only shown to rogue-like classes. The issue goes away if Mages don't use Strength and players aren't even prompted to think about what Strength might do if it isn't there.
2. Remove all "concrete" stats and use only more abstract measurements. Use Health, Dodge, Melee Damage, Magic Power, etc. Few people are going to wonder why a Fighter has a low Magic Power or why it does almost nothing or how to increase it. (Maybe it affects potions or magic items somehow, if you want.) This plays in well with how actual players think anyway - nobody cares if a character's Strength is high, they only care how the character's DPS compares with the average for the character's common/important attacks. If the stats you show are simply the DPS for the main attacks, one whole layer of the stats is removed (simplifying the game).

**Change your mechanics**

Your game doesn't have to use attributes the same way early D&D and the MUD/CRPG/MMORPGs have been doing.

You can fix the use of Strength by making it directly relevant to the things a player does, rather than trying to find hackneyed secondary attributes to derive from Strength.

1. Change which cue you take from D&D: follow in the 4th Edition footsteps and make these attribute relevant to *abilities* rather than classes. The Mage has a wide variety of spells and you can find ways to make different spells use different abilities easily. A Fireball for instance doesn't have to just be a projectile that automatically flies out in a straight line and explodes at the precise desired distance, but rather it can be a small rock-sized ball of fire that must be physically hurled at the target and explodes in a huge conflagration on impact. Strength will be useful for how far one can hurl a Fireball, while Dexterity will be useful to determine how accurate one's throw is in a lore-friendly way.
2. Go even further and reduce the concept of class. Again ripping off D&D, pay close attention to the multi-classing system of 3rd Edition. The character gains a level and the player can put that level in a class of his choosing, allowing him to be a 4th-level Fighter and 2nd-level Mage. The *depth* of character abilities is tied to a class level but (unlike D&D) you should have the *power* of character abilities tied to class level (or a slightly more complicated function of all class levels). It's no good to be a 10th level character with only the melee strength of an 8th-level Fighter and the magic power of a 2nd-level Cleric; such a combination usually ends up being far too weak. However, being able to fight like a 10th-level Fighter but with less special abilities to choose from while also being able to use a small handful of Cleric abilities at 10th-level lets the character remain useful and simply results in trading in some abilities for others. In such a system a Wizard would find Strength useful because he can still toss in some levels of Fighter and be able to hold his own in combat while he's not casting or is out of spells.

# Answer
> 5 votes
You could take each non-magical stat, and make it have a secondary but useful function to spells.

A simple approach might be to allow access to certain thematic (and powerful) spells only if the character reaches certain secondary stat values.

For instance, for Strength, you could decide that thematically applies to the ability to magically absorb physical energy, and grant better defensive spells for the mage, such as telekinetic shields, defence against dragon breath etc. Or you could tie it to apply it to travel magic, and only strong mages could levitate and fly. The thematic best fit will depend on which magics are available in your game world, and which might already be taken by the other already-good matches amongst the stats.

You will also want a reasonable collection of "universal" magic which any wizard has access to, of course.

# Answer
> 4 votes
> I have a plethora of ways in which INTELLIGENCE helps a WARRIOR type. It is the problem of the attribute STRENGTH helping a WIZARD type that is giving me so much difficulty. (...) What can I do to strength, to make it more appealing to wizard types, or any class that does not perform any melee combat?

Big text:

# Don't do this.

Stat systems, like the one D&D has, are designed to be a specialisation system: pick a couple of stats out of those available, and excel at them. Strength was *created* for physical characters to specialise in, and to appeal to only them. Intelligence, on the other hand, was created pretty specifically for intelligent characters and casters to specialise in.

It is problematic to use a system designed for specialisation, offer a caster stat that all casters would rightly want to specialise in, and then also try to make it a generalised system where all other stats benefit them. It's problematic because it's going against what this sort of specialisation system was made for: specialising.

There is **no reason** to make Strength beneficial to Wizards as well. They **don't need** to find it useful. You **do not need** to make it useful to them.

Instead of putting useful effects on Strength to make it appealing where it would otherwise not be, place those useful effects on a stat that is already helpful to a caster, and let them specialise.

## Learn from where this goes wrong: D&D's Monk, and M.A.D.

Editions of D&D from the start up to and including 3.5e included a *Monk* class which suffered from a huge problem: every single stat, for them, was highly desirable in one way or another. Every stat influenced a significant part of things they would be doing regularly.

This is called M.A.D.: Multiple Attribute Dependency. M.A.D. is *very* bad news for every class that suffers from it, because of one reason: it was impossible to be good at all of those attributes. The Monk had to spread its resources thin and be mediocre or bad at all of them, just to not be absolutely terrible at any of them - or else let a huge part of their class suffer. In a game where virtually every other class could happily specialise, put everything into 2-3 stats, and become *extremely good* at particular things, the Monk *suffered*.

In 4e, they finally fixed the Monk: by making him rely on only 2-3 stats, like *every other class*.

Don't make your Wizards spread their resources thin. If Strength is a crap attribute, nobody will invest in it. If it's half-decent, everyone will wish you'd put its positive features on something they *actually wanted*, like Constitution or an equivalent.

# Answer
> 3 votes
Well aside from making it an encumbrance issue re. reagents and suchlike (which could be an interesting mechanic I guess), if you're going the class-based route (I have to admit, I do have a soft spot for class-based systems) then another way of doing it might be to have certain spells or category of spells rely on an amplification of the caster's own strength

* So for example a spell that allowed the caster to remotely rend an enemy limb from limb, would really be amplifying their own physical strength in order to give the desired effect - this actually gives you a pretty simple way to calculate resistance as well as it's comparing two strength scores.
* In this way a caster with low physical strength just wouldn't be able to make as much use of that kind of spell as a more phsyically strong caster, but can compensate by being able to use higher intelligence to cast more complex spells.
* You could rationalise this by having the higher intelligence requirements for "complex" spells such as a healing spell because they require more of an intellectual understanding of the biology of the subject, etc.
* Or you can mix and match and just make a small damage modifier for spells with a physical component that uses str instead of int for those types of spells.
* Possible con: A caster who is building their strength to be able to take advantage of that mechanic is probably more likely to be offensively combat oriented, so you *are* starting to veer off into classic/cliche "spell-sword" territory a bit with the above approach, but that could be cool to...the Asha'man from WOT for example..

# Answer
> 3 votes
If we take strength as being a measurement of physical prowess, then you may want to consider how casting and magic wielding impact the caster physically.

Some spells could come at a physical cost as well as a magical/mental one. For example, a fireball could burn the casters hands incurring slight physical damage which is offset by strength/toughness.

Some spells may require a steady hand and firm stance to cast. For example, a spell which can push back an enemy may also push the caster as well or the accuracy of a thrown fireball might be affected by strength.

You could have strength/endurance affect the tiring/recovery rate of the caster which could reduce casting chance / effectiveness of cast as fatigue increases. Allowing them to cast more spells, quicker over a period of time.

You could have some spells be an extension of the strength of the caster and thus strength would provide an effectiveness modifier. For example, the strength of a spell with a knock back effect or even the effectiveness of a jump spell.

Strength could affect the total amount of power the caster can wield at a given time. i.e. a stronger caster can allow more energy to flow through them at one time. Intelligence would allow you control it to cast the spell, but the strength would allow you to cast bigger spells that require more mana to cast. This way spells can have an intelligence and strength requirement to cast.

Strength could also affect encumbrance which would allow the mage to carry better armor (which might be better for enchanting with magic buffs) and also allow them to carry more totems, items, staffs etc.

If strength affects hp, then you could have a fail cost to casting. If the caster fails at casting then maybe they take damage. Thus discouraging weaker casters from even attempting the really big spells.

# Answer
> 3 votes
There are a lot of good responses in here but I'd like to throw something in that is less an answer and more a different way to get at the question.

From the player's perspective character building is about sacrifice. They have a limited pool of resources they have to choose how to divide up. Your job as the designer is two-fold:

**Make each choice clear to the player**

The player should know that by choosing stat A over stat B what they are gaining and what they are sacrificing. Summarizing the suggestions in the other answers this means the player should know that by choosing intelligence over strength they are choosing something like spell slots, damage or complexity over something like carrying capacity which may be important for spell reagents, weapons or armor. In particular this choice could manifest in the form of either being able to cast 7th-level room-clearing spells like cloud kill versus having the physical capacity to carry around those 10 kg solid-gold gauntlets of fire damage +40.

**Make each (reasonable) build functionally equivalent**

Each (reasonable) build needs to be able to make it through the game. The player can't be suddenly stymied by a magically resistant foe or physically impenetrable barrier because he chose to spend his stat points poorly. Even more difficult for you, a balance must be struck between showing the player what they could have done had they chosen differently and beating them over the head because they chose badly.

At the heart of your question is "how I can I not punish my player who wants to play as a high strength wizard". This is a good question that you have to consider for each class and stat you choose include in the game. In this case you can reward them with heavy stat-boosting gear or the ability to do physical feats that give them other ways of solving problems (can't take on the guards? climb the trellis to a window). On the other hand punish them with an inability to cast the most complex spells (perhaps shadow-door could have also got them past those guards) either at all or with as much frequency or efficacy as they otherwise could.

Just make sure the player understands the options they are presented with. Don't put the rewards on such a high shelf that the player will be locked into one progression before they realize they have made a choice. Put a few spells in the early game with relatively high intelligence requirements for the expected level and a few items or barriers with high strength requirements so the player gets a flavor of the choice they are making.

# Answer
> 2 votes
I don't know how much this could apply to your game but you could look into simplifying your stats to a minimum.

In the end, a mage attacks, a knight attacks, a rogue attacks, etc... The problem I've faced with rpgs is that they quickly become these weird number games where:

* is 50 strength and 60 sword better than 60 strength and 50 sword?
* Does equipping 2 swords change anything if each attack uses only one of the swords at a time?
* Does a 60 strength mage deal the same damage with a sword than a 60 strength knight with the same sword?

I think you could look into not having explicit classes and narrowing your stats to something like: attack, defense, evade, magic, and physical where a combination of attack and magic would mean more magic power and a combination of defense and physical means more defense against physical attacks.

This will force players towards having more balanced characters because if you're a mage, you want to add some stats to physical or else you can get one shot killed by any enemy that deals physical attacks. This will have a side effect that your mage won't be bad at physical attacks given that the attack stat was increased for magical attacks.

This kinda makes sense if you have a scenario where your mage has attacks that work great at a distance but are poor in close combat. So, if the enemy gets too close, your mage could possibly pull out a sword and have a chance to defend himself. (like Gandalf in the Lord of the Rings, he actually uses a sword to fight the orcs)

The problem then becomes: then why not just make a magical warrior and that's it?

Well, part of the solution will have to come from design, as in, how does the character level up (or gain exp) and how much a character can improve in any given domain.

Another part of the solution could come by having your characters gain affinity at using certain weapons and talents (like FF12 or Skyrim). The more you use swords, the better you are at using swords. So a mage who has never used a sword before has the same abilities at using a swords than a knight who has never used a swords with equal stats.

This solution could lead you to question why stats? If you've played any of the Metroid games (i know they're not rpgs in the way we think of rpgs but bear with me), you don't need any stats to improve. It's just, unlock better weapon and better armor. So, when you come across weaker enemies, your better armor does the job of better defense and you get less hurt by the weaker enemies. So, if you learn, say, the "fireball" spell, you don't need to know whether you have 60 magic or not to know if it's powerful. If you've been using magic and have been using that spell for a while, then, yes it's powerful.

This kinda all sounds like Skyrim I guess. But if you want an actual class system with this, you can have a scenario where you character must, say, learn spells from the magic school and pass the tests and only then graduate as a wizard which could grant you some points in magic and maybe an item or two. (and the same would be true for the other classes)

Sorry for the long answer but I hope my random ideas (which obviously aren't mine cuz I've invented nothing) help.

(If you have disregarded the preceding, consider flaming swords... strength could then be useful to your wizard this way).

# Answer
> 2 votes
> "A sound body leades to a sound mind"

When your sick and weak you cant think right and become sluggish. For a wizard this matters because if he cant concentrate he cant channel/chant/focus his spells.

I never use a single stat for anything it it always combinations of stats, this makes it harder to ignore any one stat I have found.

I would use strength combined with various other stats to effect the following:

Cool down of spells - those fireballs might have quite the recoil and a buff mage will handle it better

carrying capacity – you an only loot what you can carry as well as penalties for weight limits such as slower movement.

susceptibility – its far harder to poison a peak athlete that a brittle old wizard, the athlete will recover quicker as well.

# Answer
> 1 votes
I could see a strength attribute being important to a summoner type wizard. Have a school of spells that create ghost warriors who are patterned off the caster their strength is equal to the casters strength etc. Then just have a bunch of different types of summons to fill out the school; shield bearers, swordsmen, werebeasts, archers etc. If you wanted it to still be playable as a high int wizard have int determine how many you can keep up simultaneously.

# Answer
> 1 votes
I think the problem you may be facing is the muddying of a skill based system with a one that uses archetypes. Ultima Online that you mention, did not attempt to define Archetypes available for play.

Wizardly talents are generally defined by intelligence and mental attributes. Fighting is a skill more defined by physical attributes. So while you were free to select from a base template of stats, you were also free to create a hybrid between two common styles of play. Your toon was a collection of stats, skills, and abilities that were generally unique.

A common build in Ultima Online was the Tank Mage. Giving additional strength to the mage did not improve his spell casting abilities but it did allow him to wear more protective armor as a trade-off. At the same time a fighter could choose to give up some fighting prowess for the ability to cast a spell that enables him to escape trouble if need be. Neither were clearly defined archetypes.

Strength and Intelligence are pretty universally understood by players. I would not go to far out of my way to benefit a mage choosing strength or a fighter using intelligence if you are using archetypes. This feels like redefining each attribute and only serves to confuse the player. If however, you are using a skill based approach then the player is probably expecting to give up one for the other when they make that choice. The player can build a character that fits their particular playstyle.

Would you reward a mage rushing in to hand to hand combat? No more than your Fighter with no points in Ranged Combat would fare with a bow. Remember, the players fun will derive from them trying out their own differing choices from available options. Sometimes they will conquer the enemies and sometimes they will fail. Failing along the way makes Victory all the more sweeter though in the end.

# Answer
> 0 votes
Well, from what I've understood, strength is related to the character's health and damage, and with that said, you want health to matter in your caster class as much as possible so the player isn't just casting spells from afar without ever losing health.

One solution I can think of is to have your character's enemies "magical defense" attribute grow a little bit, making them harder to kill by magical classes. This will force the fight to last long enough so the foe can actually get in melee range and damage the caster. By using the magic defense attribute it wouldn't unbalance PvP or any other thing in game, and casters could remain pretty strong with enemies with regular defense.

Also, an interesting idea could be to have all casters have a very limited pool of "mana" to cast spells, and introduce a basic attack (melee or ranged) which doesn't consume any "mana" but is strong enough to be considered as a viable secondary damage dealing source.

With these ideas put to practice, you'd be fighting a lot more in the close range, forcing you to run-and-shoot to save as much health as possible before the foe is beaten.

As for scaling up the damage dealt to enemies, I think the old method of separating physical damage and magical damage works as a charm in many cases!

Hope it helps.

# Answer
> 0 votes
Just based on your exact words, I had an idea:

"Buff Conan Wizard" vs "Intelligent but Frail Wizard"

The less intelligent wizard might be from a race like orc / goblins etc. and represent a more shaman like / religious type of magic.

But on the other hand an intelligent wizard might focus more on researching spells and complicating rituals and stuff.

Now that I think of it again this is nothing new and most of the games probably mix it like this. But if you per se want to have the strength modifier playing a big role in spellcasting then I would go with that way.

I would probably mix the shaman's / priest's spellcasting ability with strength (like Defensive Casting from DnD 3.5 ability).

# Answer
> 0 votes
There are plenty of ways to incorporate strength into a magic spell. Imagine trying to tame a giant dragon or lift anything of substance without some strength. While, intelligence may be the factor that indicates what spells someone might be able to learn, why not consider magic a way of channelling a skill you already have.

* **Strength** means you can lift big things, add magic and you can lift adnd control huge things.
* **Constitution** helps you heal yourself easier, magic means you can heal yourself and *others*!
* **Charisma** allows you to charm others and make them act more favourably, add magic and you can appear to shapeshift or even control their minds.
* **Dexterity** makes you more agile, and magic means you become invisible, can teleport or phase through objects.

In this way, intelligence is important, while ensuring that other skills are still relevant for a wizard, as intelligence opens the door to magic that extends your skills beyond the "humanly possible"

---

**For example, consider 2 wizards who specialise in telekenesis having a fight** \- Alice and Bob, while Bob has dumped most of his points into INT, while Alice put quite a few points into STR as well as INT.

Bob lifts and throws a giant boulder at Alice. Alice is able to use her spell to slow and hold the rock. Her strength prevents her from getting thrown like a rag doll.

She retaliates, throwing the rock back. Bob stops the boulder, relative to himself, however he hasn't the strength to fight the inertia of a one ton of rock comng his way, he is flung off a cliff face, and on the fall down considers a more balanced build on his next play-through.

# Answer
> -1 votes
In Diablo II strength was a prerequisit for some items. Some caster builds were highly reliant on items with min str requirement. Only those who seek to use the build would invest in STR - though.

# Answer
> -2 votes
Diablo 3's route is to have variations on stats depending on the class. Depending on the class the stat is an attack damage modifier in addition to the regular modifier. For example, Barbarians would have their strength attribute directly affect Damage in addition to its property of adding to the Armor stat. For all other classes it only added the armor value.

Having a wizard that could actually get hit once and not explode into little bits would be an attractive attribute.

---
Tags: game-design, level-design, character, statistics
---


title: Detecting key press only once in Libgdx

text:
# Question
Title: Detecting key press only once in Libgdx
Have a question on keyboard inputs. Currently I am using this method to read my input, `Gdx.input.isKeyPressed(Input.Keys.A)`, it is working fine. But I do realized at times there are multiple instances of A being pressed when I only press once. And I understand that the method had to be placed in the `render()` method for it to work. Is the problem due to the refreshing?

My question is, how can I only detect 1 instance of "A", when A is pressed for once.

# Answer
> 1 votes
LibGdx library provided an InputProcessor Interface, I think you are better to implement the InputProcessor and you should set Screen's input processor to the class you made, see tutorials that dermetfan user made on youtube http://www.youtube.com/user/dermetfan/videos

however you may would like to use different methods, also check DeviceInfo of LibGdx for checking devices.

# Answer
> -1 votes
store the current keys state, get the new ones and

```
if(newInput.isKeyPressed(Input.Keys.A) && oldInput.isKeyUp(Input.Keys.A))

```

---
Tags: libgdx, input, keyboard
---


# Question
Title: Game Architecture doubt on variable access
Im having a hard time figuring out a solution to a problem that seems it should be easy to answer but since i cant come up with a good solution I bid your knowledge:

In my game i have a state manager which deals with either the game is at the menu state, level1 state, level2 state, etc etc, every different screen condition is a state that is, and in my level state i created a base level class so i can extend the level1, level2, etc levels.

In the base level class, it is where i declare my common level variables, like Player, the Tilemap, the array of enemies (mobs), the CollisionManager etc. (this might be what i am doing wrong...) and i wanna add explosions to the game, which will occur at least when i shoot explosive barrels (and the barrels really arent the problem because since they are created in the beggining of the level, i can just add an array of barrels and set the argument of the barrel to receive the array of explosions pointer so the barrel just adds a new explosion when the time comes) and when explosive bullets hit the wall.

Now my problem is specially the bullets, because explosive bullets are created by the mobs which might use a rocket launcher (including the player) and i dont really think sending the array of explosions to every mob that might shoot explosive bullets is good architecture, so my question is how i solve this problem or even better how i improve my architecture in a whole to avoid problems like these.

P.S. As a side note regarding how the mobs shoot bullets, every mob has a Weapon, which is a class that extends in the several weapons the game might have, from pistols to lasers and flamethrowers, which are all functional and working lovely. This means, though, that if id send the explosions array to the mob that will use rocket launcher, i would then have to send that pointer to the weapon, and from weapon to every bullet that the weapon spawns, so the bullets are the ones adding the explosions to the array when the time comes. This train-like passing of the array is what is bugging me and what i strive for a solution.

P.S.S. Although every advice is very appreciated, answers telling me to use Aggregation of Components Architecture are, at the moment, "ignored" because im trying to correctly use the traditional Hierarchical approach for this game, i might use component architecture in a future game though, it seems pretty neat : )

# Answer
> 1 votes
Use factories and messages. The weapon does not need to directly insert a bullet into an array. It need only send out a message saying "Create bullet type Explosive at position X,Y going in direction U,V with speed S" and then a message handler on a factory system can listen for the CreateObject message and then spawn the correct type of object with the correct parameters.

This completely decouples the need for any individual object to know how other objects are stored, managed, etc. It allows more genericism as you can now use strings, enums, or external data to denote the type of object to create rather than needing to explicitly instantiate one.

The problem has nothing to do with using hierarchies of types or components. It has to do with the tight coupling you're creating between object types, behaviors like gun firing, and the lack of messaging or abstract factories. All that the weapon needs to know is a general idea of what it fires and which position and velocity to spawn it at. The actual spawning of the object can and should happen elsewhere.

This can even be fully data-defined. You can make your Bullet class have a field that denotes what type of explosion it spawns, Weapon can define which Bullet it fires, etc. Then you can trivially create a new weapon that fires a slow-moving green bullet that explodes in a rain of acid or some such. Not need to recode, no need to recompile. Easy to mod, easy to update in a nice designer-friendly tool, etc. Yes, components make this even easier, but the really important part is the data-driven design.

# Answer
> 0 votes
Small nitpick: you say "array of explosions" but I'd rather that be encapsulated in an ExplosionManager.

So your bullets need to create explosions, but you don't like passing the ExplosionManager from mob to weapon to bullet ("train-like passing").

How about making ExplosionManager a globally-accessible singleton? Of course we can google "why are globals bad?" and "dependency injection" to learn why this isn't ideal, but I mention it anyway.

How about if the Bullet class has a static pointer to an ExplosionManager? You could set this pointer in one place in code (so you don't have to pass an ExplosionManager to every Bullet instance).

How about a bullet just does "new Explosion()" and each Explosion is responsible for adding itself to the manager/array? This just shifts the problem from Bullet to Explosion so it's not really a solution. However, I kinda like it because the fact that Explosions are kept in a big array seems like an implementation detail that users of the Explosion class shouldn't have to care about.

---
Tags: java, architecture
---


# Question
Title: Optimizing performance of a heavy fragment shader
I need help optimizing the following set of shaders:

Vertex:

```
    precision mediump float;

uniform vec2 rubyTextureSize;

attribute vec4 vPosition;
attribute vec2 a_TexCoordinate;

varying vec2 tc;

void main() {
    gl_Position = vPosition;

    tc = a_TexCoordinate;
}

```

Fragment:

```
precision mediump float;

/*
 Uniforms
 - rubyTexture: texture sampler
 - rubyTextureSize: size of the texture before rendering
 */

uniform sampler2D rubyTexture;
uniform vec2 rubyTextureSize;
uniform vec2 rubyTextureFract;

/*
 Varying attributes
 - tc: coordinate of the texel being processed
 - xyp_[]_[]_[]: a packed coordinate for 3 areas within the texture
 */

varying vec2 tc;

/*
 Constants
 */
/*
 Inequation coefficients for interpolation
 Equations are in the form: Ay + Bx = C
 45, 30, and 60 denote the angle from x each line the cooeficient variable set builds
 */
const vec4 Ai = vec4(1.0, -1.0, -1.0, 1.0);
const vec4 B45 = vec4(1.0, 1.0, -1.0, -1.0);
const vec4 C45 = vec4(1.5, 0.5, -0.5, 0.5);
const vec4 B30 = vec4(0.5, 2.0, -0.5, -2.0);
const vec4 C30 = vec4(1.0, 1.0, -0.5, 0.0);
const vec4 B60 = vec4(2.0, 0.5, -2.0, -0.5);
const vec4 C60 = vec4(2.0, 0.0, -1.0, 0.5);

const vec4 M45 = vec4(0.4, 0.4, 0.4, 0.4);
const vec4 M30 = vec4(0.2, 0.4, 0.2, 0.4);
const vec4 M60 = M30.yxwz;
const vec4 Mshift = vec4(0.2);

// Coefficient for weighted edge detection
const float coef = 2.0;
// Threshold for if luminance values are "equal"
const vec4 threshold = vec4(0.32);

// Conversion from RGB to Luminance (from GIMP)
const vec3 lum = vec3(0.21, 0.72, 0.07);

// Performs same logic operation as && for vectors
bvec4 _and_(bvec4 A, bvec4 B) {
    return bvec4(A.x && B.x, A.y && B.y, A.z && B.z, A.w && B.w);
}

// Performs same logic operation as || for vectors
bvec4 _or_(bvec4 A, bvec4 B) {
    return bvec4(A.x || B.x, A.y || B.y, A.z || B.z, A.w || B.w);
}

// Converts 4 3-color vectors into 1 4-value luminance vector
vec4 lum_to(vec3 v0, vec3 v1, vec3 v2, vec3 v3) {
    //    return vec4(dot(lum, v0), dot(lum, v1), dot(lum, v2), dot(lum, v3));

    return mat4(v0.x, v1.x, v2.x, v3.x, v0.y, v1.y, v2.y, v3.y, v0.z, v1.z,
            v2.z, v3.z, 0.0, 0.0, 0.0, 0.0) * vec4(lum, 0.0);
}

// Gets the difference between 2 4-value luminance vectors
vec4 lum_df(vec4 A, vec4 B) {
    return abs(A - B);
}

// Determines if 2 4-value luminance vectors are "equal" based on threshold
bvec4 lum_eq(vec4 A, vec4 B) {
    return lessThan(lum_df(A, B), threshold);
}

vec4 lum_wd(vec4 a, vec4 b, vec4 c, vec4 d, vec4 e, vec4 f, vec4 g, vec4 h) {
    return lum_df(a, b) + lum_df(a, c) + lum_df(d, e) + lum_df(d, f)
            + 4.0 * lum_df(g, h);
}

// Gets the difference between 2 3-value rgb colors
float c_df(vec3 c1, vec3 c2) {
    vec3 df = abs(c1 - c2);
    return df.r + df.g + df.b;
}

void main() {

    /*
     Mask for algorhithm
     +-----+-----+-----+-----+-----+
     |     |  1  |  2  |  3  |     |
     +-----+-----+-----+-----+-----+
     |  5  |  6  |  7  |  8  |  9  |
     +-----+-----+-----+-----+-----+
     | 10  | 11  | 12  | 13  | 14  |
     +-----+-----+-----+-----+-----+
     | 15  | 16  | 17  | 18  | 19  |
     +-----+-----+-----+-----+-----+
     |     | 21  | 22  | 23  |     |
     +-----+-----+-----+-----+-----+
     */

    float x = rubyTextureFract.x;
    float y = rubyTextureFract.y;

    vec4 xyp_1_2_3 = tc.xxxy + vec4(-x, 0.0, x, -2.0 * y);
    vec4 xyp_6_7_8 = tc.xxxy + vec4(-x, 0.0, x, -y);
    vec4 xyp_11_12_13 = tc.xxxy + vec4(-x, 0.0, x, 0.0);
    vec4 xyp_16_17_18 = tc.xxxy + vec4(-x, 0.0, x, y);
    vec4 xyp_21_22_23 = tc.xxxy + vec4(-x, 0.0, x, 2.0 * y);
    vec4 xyp_5_10_15 = tc.xyyy + vec4(-2.0 * x, -y, 0.0, y);
    vec4 xyp_9_14_9 = tc.xyyy + vec4(2.0 * x, -y, 0.0, y);

    // Get mask values by performing texture lookup with the uniform sampler
    vec3 P1 = texture2D(rubyTexture, xyp_1_2_3.xw).rgb;
    vec3 P2 = texture2D(rubyTexture, xyp_1_2_3.yw).rgb;
    vec3 P3 = texture2D(rubyTexture, xyp_1_2_3.zw).rgb;

    vec3 P6 = texture2D(rubyTexture, xyp_6_7_8.xw).rgb;
    vec3 P7 = texture2D(rubyTexture, xyp_6_7_8.yw).rgb;
    vec3 P8 = texture2D(rubyTexture, xyp_6_7_8.zw).rgb;

    vec3 P11 = texture2D(rubyTexture, xyp_11_12_13.xw).rgb;
    vec3 P12 = texture2D(rubyTexture, xyp_11_12_13.yw).rgb;
    vec3 P13 = texture2D(rubyTexture, xyp_11_12_13.zw).rgb;

    vec3 P16 = texture2D(rubyTexture, xyp_16_17_18.xw).rgb;
    vec3 P17 = texture2D(rubyTexture, xyp_16_17_18.yw).rgb;
    vec3 P18 = texture2D(rubyTexture, xyp_16_17_18.zw).rgb;

    vec3 P21 = texture2D(rubyTexture, xyp_21_22_23.xw).rgb;
    vec3 P22 = texture2D(rubyTexture, xyp_21_22_23.yw).rgb;
    vec3 P23 = texture2D(rubyTexture, xyp_21_22_23.zw).rgb;

    vec3 P5 = texture2D(rubyTexture, xyp_5_10_15.xy).rgb;
    vec3 P10 = texture2D(rubyTexture, xyp_5_10_15.xz).rgb;
    vec3 P15 = texture2D(rubyTexture, xyp_5_10_15.xw).rgb;

    vec3 P9 = texture2D(rubyTexture, xyp_9_14_9.xy).rgb;
    vec3 P14 = texture2D(rubyTexture, xyp_9_14_9.xz).rgb;
    vec3 P19 = texture2D(rubyTexture, xyp_9_14_9.xw).rgb;

    // Store luminance values of each point in groups of 4
    // so that we may operate on all four corners at once
    vec4 p7 = lum_to(P7, P11, P17, P13);
    vec4 p8 = lum_to(P8, P6, P16, P18);
    vec4 p11 = p7.yzwx; // P11, P17, P13, P7
    vec4 p12 = lum_to(P12, P12, P12, P12);
    vec4 p13 = p7.wxyz; // P13, P7,  P11, P17
    vec4 p14 = lum_to(P14, P2, P10, P22);
    vec4 p16 = p8.zwxy; // P16, P18, P8,  P6
    vec4 p17 = p7.zwxy; // P17, P13, P7,  P11
    vec4 p18 = p8.wxyz; // P18, P8,  P6,  P16
    vec4 p19 = lum_to(P19, P3, P5, P21);
    vec4 p22 = p14.wxyz; // P22, P14, P2,  P10
    vec4 p23 = lum_to(P23, P9, P1, P15);

    // Scale current texel coordinate to [0..1]
    vec2 fp = fract(tc * rubyTextureSize);

    // Determine amount of "smoothing" or mixing that could be done on texel corners
    vec4 AiMulFpy = Ai * fp.y;
    vec4 B45MulFpx = B45 * fp.x;
    vec4 ma45 = smoothstep(C45 - M45, C45 + M45, AiMulFpy + B45MulFpx);
    vec4 ma30 = smoothstep(C30 - M30, C30 + M30, AiMulFpy + B30 * fp.x);
    vec4 ma60 = smoothstep(C60 - M60, C60 + M60, AiMulFpy + B60 * fp.x);
    vec4 marn = smoothstep(C45 - M45 + Mshift, C45 + M45 + Mshift,
            AiMulFpy + B45MulFpx);

    // Perform edge weight calculations
    vec4 e45 = lum_wd(p12, p8, p16, p18, p22, p14, p17, p13);
    vec4 econt = lum_wd(p17, p11, p23, p13, p7, p19, p12, p18);
    vec4 e30 = lum_df(p13, p16);
    vec4 e60 = lum_df(p8, p17);

    // Calculate rule results for interpolation
    bvec4 r45_1 = _and_(notEqual(p12, p13), notEqual(p12, p17));
    bvec4 r45_2 = _and_(not (lum_eq(p13, p7)), not (lum_eq(p13, p8)));
    bvec4 r45_3 = _and_(not (lum_eq(p17, p11)), not (lum_eq(p17, p16)));
    bvec4 r45_4_1 = _and_(not (lum_eq(p13, p14)), not (lum_eq(p13, p19)));
    bvec4 r45_4_2 = _and_(not (lum_eq(p17, p22)), not (lum_eq(p17, p23)));
    bvec4 r45_4 = _and_(lum_eq(p12, p18), _or_(r45_4_1, r45_4_2));
    bvec4 r45_5 = _or_(lum_eq(p12, p16), lum_eq(p12, p8));
    bvec4 r45 = _and_(r45_1, _or_(_or_(_or_(r45_2, r45_3), r45_4), r45_5));
    bvec4 r30 = _and_(notEqual(p12, p16), notEqual(p11, p16));
    bvec4 r60 = _and_(notEqual(p12, p8), notEqual(p7, p8));

    // Combine rules with edge weights
    bvec4 edr45 = _and_(lessThan(e45, econt), r45);
    bvec4 edrrn = lessThanEqual(e45, econt);
    bvec4 edr30 = _and_(lessThanEqual(coef * e30, e60), r30);
    bvec4 edr60 = _and_(lessThanEqual(coef * e60, e30), r60);

    // Finalize interpolation rules and cast to float (0.0 for false, 1.0 for true)
    vec4 final45 = vec4(_and_(_and_(not (edr30), not (edr60)), edr45));
    vec4 final30 = vec4(_and_(_and_(edr45, not (edr60)), edr30));
    vec4 final60 = vec4(_and_(_and_(edr45, not (edr30)), edr60));
    vec4 final36 = vec4(_and_(_and_(edr60, edr30), edr45));
    vec4 finalrn = vec4(_and_(not (edr45), edrrn));

    // Determine the color to mix with for each corner
    vec4 px = step(lum_df(p12, p17), lum_df(p12, p13));

    // Determine the mix amounts by combining the final rule result and corresponding
    // mix amount for the rule in each corner
    vec4 mac = final36 * max(ma30, ma60) + final30 * ma30 + final60 * ma60
            + final45 * ma45 + finalrn * marn;

    /*
     Calculate the resulting color by traversing clockwise and counter-clockwise around
     the corners of the texel

     Finally choose the result that has the largest difference from the texel's original
     color
     */
    vec3 res1 = P12;
    res1 = mix(res1, mix(P13, P17, px.x), mac.x);
    res1 = mix(res1, mix(P7, P13, px.y), mac.y);
    res1 = mix(res1, mix(P11, P7, px.z), mac.z);
    res1 = mix(res1, mix(P17, P11, px.w), mac.w);

    vec3 res2 = P12;
    res2 = mix(res2, mix(P17, P11, px.w), mac.w);
    res2 = mix(res2, mix(P11, P7, px.z), mac.z);
    res2 = mix(res2, mix(P7, P13, px.y), mac.y);
    res2 = mix(res2, mix(P13, P17, px.x), mac.x);

    gl_FragColor = vec4(mix(res1, res2, step(c_df(P12, res1), c_df(P12, res2))),
            1.0);
}

```

The shaders receive a 2D texture and are meant to scale it beautifully across a high-res 2D surface (the device screen). It is an optimization of the SABR scaling algorithm in case it matters.

It already works, and performs OK on very high-end Android devices (like LG Nexus 4), but it is really slow on weaker devices.

The Android devices that really matter to me are Samsung Galaxy S 2 \ 3, with Mali 400MP GPU - which perform horribly with this shader.

So far I've tried:

1. Eliminating varyings (advice from ARM's Mali guide) - did minor improvement.
2. Overriding mix() functions with my own - did no good.
3. reducing float precision to lowp - didn't change anything.

I measure performance by calculating render time (before and after eglSwapBuffers) - this gives me a very linear and consistent measurement of performance.

Beyond that, I don't really know where to look or what can be optimized here...

I know that this is a heavy algorithm, and I am not asking for advice on what alternate scaling methods to use - I've tried many and this algorithm gives the best visual result. I wish to use the exact same algorithm in an optimized way.

**UPDATE**

1. I found that if I do all the texture fetches with a constant vector instead of dependent vectors I get a major performance improvement, so this is obviously a big bottleneck - probably because of the cache. However, I still need to do those fetches. I played with doing at least some of the fetches with vec2 varyings (without any swizzling) but it didn't improve anything. I wonder what might be a good way to efficiently poll 21 texels.
2. I found that a major part of the calculations is being done multiple times with the exact same set of texels - because the output is scaled by at least x2, and I poll with GL\_NEAREST. There at least 4 fragments that fall on exactly the same texels. If the scaling is x4 on a high-res device, there are 16 fragments that fall on the same texels - which is a big waste. Is there any way to perform an additional shader pass that will calculate all the values that don't change across multiple fragments? I thought about rendering to an additional off-screen texture, but I need to store multiple values per texel, not just one.

**UPDATE**

1. I also noticed that the CPU is almost unused while the GPU is a big bottleneck. Any advice on how to leverage some CPU power and transfer logic from the GPU to the CPU in this situation?

# Answer
> 2 votes
> I wonder what might be a good way to efficiently poll 21 texels.

The answer is the efficient way is the way that is not polling 21 texels. Sorry to be obvious but mobile devices may not have the necessary bus width to support such kernels. You need to optimize by reducing the size of the texture plugged in the sampler so that caching will cover a larger kernel radius.

Also, you could forget about your disk kernel and use a two passes algorithm using a vertical kernel, and another one using a purely horizontal, this way you pass from "2D" to "1D" so to speak, and reduce drastically the number of samplings as well as improving cache performance thanks to linear access.

Vertical fetches should not affect cache performance thanks to the Z storage textures should be arranged in GPU memory. cf http://en.wikipedia.org/wiki/Z-order\_curve

---
Tags: shaders, opengl-es, glsl, opengl-es2, fragment-shader
---


title: What constitutes satire?

text:
# Question
Title: What constitutes satire?
For business reasons, I would like to know what constitutes satire in a game.

Also, is there a better place to ask questions like this on the business side of game development?

# Answer
I think that it would be better to ask on a different forum, but in answer to your question:

Satire is basically ironic humor (usually sarcastic). Satire in a game can be shown in a couple different ways. You can do it visually, by poking fun at a certain stereotypes of a culture (e.g. Have a american person eating a cheeseburger) or it can be verbally. Verbal satire is easy to make, (just look at south park) and is usually a lot funnier. It involves making fun of anything really, from celebrities to culture. (e.g. South Park)
> 0 votes

# Answer
To complete RageGolem10's answer, you need to add billboard messages. The ones you can see as false commercials, or wall grafitis, like "the cake is a lie". Duke nukem had some with false movie posters, like sister act III. You can criticize real life things by mocking them using one single in game image. This is more indirect than speech, because speech is necessarily encountered, so the user is 100% focused on it when it happens. Maybe at the exception of NPC speaking to each other like half life, or mass effect, which is more indirect.
> 0 votes

---
Tags: legal, business
---


# Question
Title: Atmospheric scattering sky from space artifacts
I am in the process of implementing atmospheric scattering of a planets from space. I have been using Sean O'Neil's shaders from http://http.developer.nvidia.com/GPUGems2/gpugems2\_chapter16.html as a starting point.

I have pretty much the same problem related to fCameraAngle except with SkyFromSpace shader as opposed to GroundFromSpace shader as here: http://www.gamedev.net/topic/621187-sean-oneils-atmospheric-scattering/

I get strange artifacts with sky from space shader when not using `fCameraAngle = 1` in the inner loop. What is the cause of these artifacts? The artifacts disappear when fCameraAngle is limtied to 1. I also seem to lack the hue that is present in O'Neil's sandbox (http://sponeil.net/downloads.htm)

Camera position X=0, Y=0, Z=500. GroundFromSpace on the left, SkyFromSpace on the right.

Camera position X=500, Y=500, Z=500. GroundFromSpace on the left, SkyFromSpace on the right.

I've found that the camera angle seems to handled very differently depending the source:

In the original shaders the camera angle in SkyFromSpaceShader is calculated as:

```
float fCameraAngle = dot(v3Ray, v3SamplePoint) / fHeight;

```

Whereas in ground from space shader the camera angle is calculated as:

```
float fCameraAngle = dot(-v3Ray, v3Pos) / length(v3Pos);

```

However, various sources online tinker with negating the ray. Why is this?

Here is a C# Windows.Forms project that demonstrates the problem and that I've used to generate the images: https://github.com/ollipekka/AtmosphericScatteringTest/

**Update:** I have found out from the ScatterCPU project found on O'Neil's site that the camera ray is negated when the camera is above the point being shaded so that the scattering is calculated from point to the camera.

Changing the ray direction indeed does remove artifacts, but introduces other problems as illustrated here:

Furthermore, in the ScatterCPU project, O'Neil guards against situations where optical depth for light is less than zero:

```
float fLightDepth = Scale(fLightAngle, fScaleDepth);

if (fLightDepth < float.Epsilon)
{
    continue;
}

```

As pointed out in the comments, along with these new artifacts this still leaves the question, what is wrong with the images where camera is positioned at 500, 500, 500? It feels like the halo is focused on completely wrong part of the planet. One would expect that the light would be closer to the spot where the sun should hits the planet, rather than where it changes from day to night.

The github project has been updated to reflect changes in this update.

# Answer
I don't have working code right now, as I am transitioning my engine but these were my working parameter settings:

```
// Inited in code
float innerRadius = sphere.Radius;
float outerRadius = innerRadius*1.025f;
float scale = 1.0f/(outerRadius - innerRadius);
float scaleDepth = outerRadius - innerRadius;
float scaleOverScaleDepth = scale/scaleDepth;

Vector4 invWavelength = new Vector4(
    (float) (1.0/Math.Pow(wavelength.X, 4.0)),
    (float) (1.0/Math.Pow(wavelength.Y, 4.0)),
    (float) (1.0/Math.Pow(wavelength.Z, 4.0)),
    1);

float ESun = 15.0f;
float kr = 0.0025f;
float km = 0.0015f;
float g = -0.95f;
float g2 = g * g;
float krESun = kr * ESun;
float kmESun = km * ESun;
float epkr4Pi = epkr4Pi = (float)(kr * 4 * Math.PI)
float epkm4Pi = epkr4Pi = (float)(kr * 4 * Math.PI)

```

This was the shader:

```
struct AtmosphereVSOut
{
    float4 Position : POSITION;
    float3 t0 : TEXCOORD0;
    float3 c0 : TEXCOORD1; // The Rayleigh color
    float3 c1 : TEXCOORD2; // The Mie color
    float4 LightDirection : TEXCOORD3;
};

// The scale equation calculated by Vernier's Graphical Analysis
float expScale (float fCos)
{
    //float x = 1.0 - fCos;
    float x = 1 - fCos;
    return scaleDepth * exp(-0.00287 + x*(0.459 + x*(3.83 + x*(-6.80 + x*5.25))));

}
// Calculates the Mie phase function
float getMiePhase(float fCos, float fCos2, float g, float g2)
{
    return 1.5 * ((1.0 - g2) / (2.0 + g2)) * (1.0 + fCos2) / pow(1.0 + g2 - 2.0*g*fCos, 1.5);
}

// Calculates the Rayleigh phase function
float getRayleighPhase(float fCos2)
{
    return 0.75 + (1.0 + fCos2);
}

// Returns the near intersection point of a line and a sphere
float getNearIntersection(float3 vPos, float3 vRay, float fDistance2, float fRadius2)
{
    float B = 2.0 * dot(vPos, vRay);
    float C = fDistance2 - fRadius2;
    float fDet = max(0.0, B*B - 4.0 * C);
    return 0.5 * (-B - sqrt(fDet));
}

AtmosphereVSOut
AtmosphereFromSpaceVS(float4 vPos : POSITION )
{
    // Multiply the camera position vector in world space by the
    // World Inverse matrix so that it gets transformed to
    // object space coordinates
    float4 vEyePosInv = mul(vEyePos, mWorldInverse);

    // Compute a ray from the vertex to the camera position
    float3 vRay = vPos - vEyePosInv.xyz;

    // Transform the Light Position to object space and use
    // the result to get a ray from the position of the light
    // to the vertex. This is our light direction vector
    // which has to be normalized.
    float4 vLightDir = mul(vLightPosition,mWorldInverse) - vPos;
    vLightDir.xyz = normalize(vLightDir.xyz);
    vLightDir.w = 1.0;

    // From the vRay vector we can calculate the
    // "far" intersection with the sphere
    float fFar = length (vRay);
    vRay /= fFar;

    // But we have to check if this point is obscured by the planet
    float B = 2.0 * dot(vEyePosInv, vRay);
    float C = cameraHeight2 - (innerRadius*innerRadius);
    float fDet = (B*B - 4.0 * C);

    if (fDet >= 0)
    {
        // compute the intersection if so
        fFar = 0.5 * (-B - sqrt(fDet));
    }

    // Compute the near intersection with the outer sphere
    float fNear = getNearIntersection (vEyePosInv, vRay, cameraHeight2, outerRadius2);

    // This is the start position from which to compute how
    // the light is scattered
    float3 vStart = vEyePosInv + vRay * fNear;
    fFar -= fNear;

    float fStartAngle = dot (vRay, vStart) / outerRadius;
    float fStartDepth = exp (scaleOverScaleDepth * (innerRadius - cameraHeight));
    float fStartOffset = fStartDepth * expScale (fStartAngle);
    float fSampleLength = fFar / samples;
    float fScaledLength = fSampleLength * scale;
    float3 vSampleRay = vRay * fSampleLength;
    float3 vSamplePoint = vStart + vSampleRay * 0.5f;

    // Now we have to compute each point in the path of the
    // ray for which scattering occurs. The higher the number
    // of samples the more accurate the result.
    float3 cFrontColor = float3 (0,0,0);
    for (int i = 0; i < samples; i++)
    {
        float fHeight = length (vSamplePoint);
        float fDepth = exp (scaleOverScaleDepth * (innerRadius - fHeight));
        float fLightAngle = dot (vLightDir, vSamplePoint) / fHeight;
        float fCameraAngle = dot(-vRay, vSamplePoint) / fHeight;
        float fScatter = (fStartOffset + fDepth * (expScale (fLightAngle) - expScale (fCameraAngle)));

        float3 cAttenuate = exp (-fScatter * (vInvWavelength.xyz * kr4PI + km4PI));

        cFrontColor += cAttenuate * (fDepth * fScaledLength);
        vSamplePoint += vSampleRay;
    }

    // Compute output values
    AtmosphereVSOut Out;

    // Compute a ray from the camera position to the vertex
    Out.t0 = vEyePos.xyz - vPos.xyz;

    // Compute the position in clip space
    Out.Position = mul(vPos, mWorldViewProj);

    // Compute final Rayleigh and Mie colors
    Out.c0.xyz = cFrontColor * (vInvWavelength.xyz * krESun);
    Out.c1.xyz = cFrontColor * kmESun;

    // Pass the light direction vector along to the pixel shader
    Out.LightDirection = vLightDir;

    return Out;
}

PSOut
AtmosphereFromSpacePS(AtmosphereVSOut In)
{
    PSOut Out;

    float cos = saturate(dot (In.LightDirection, In.t0) / length (In.t0));
    float cos2 = cos*cos;

    float fMiePhase = getMiePhase(cos,cos2,g,g2);
    float fRayleighPhase = getRayleighPhase(cos2);

    float exposure = 2.0;
    Out.color.rgb = 1.0 - exp(-exposure * (fRayleighPhase * In.c0 + fMiePhase * In.c1));
    Out.color.a = Out.color.b;

    return Out;
    }

```

Let me know if it still does work. If you need any other help I'll try to dig around my code. I think I used two spheres to do the rendering: one for the surface and one for the atmosphere.
> 1 votes

# Answer
some thought tracks : check the precision of your floats. at space scales, most all the times float32 is not enough. Check dpeth buffer if you have primitive rendering, like a sphere under your scattering shader.

These artifacts, can be found in raytracing as well, these are usually secondary rays intersection with the primary surface jittering from float precision issues.

EDIT: at 1000 (all integers are representible fully until 16 million in float32 representation, thanks to the 24 bits mantissa), the next number for a float32 is 1000.00006103 so your precision is still pretty good at this range.

however if you were to use meter ranges, to see a planet a this distance would mean values of 100,000,000 and the next is 100000008 : 8 meters of precision at 100,000km.

this would cause camera jumps if you were to try to move around a satelite for example, and the rendering of the satellite itself would bo all broken if the zero of your world is the center of the planet. if it is the center of the star system then it is even worse.

look up flavien brebion (Ysaneya) and the game infinity quest for earth. He has interesting dev journal of gamedev and his forum where he explains how star system distances are impossible to manage using absolutes.

He also mentions the depth buffer problem at those kind of ranges, and is one of the first, if not the first, to introduce logarithmic z scales. http://www.gamedev.net/blog/73/entry-2006307-tip-of-the-day-logarithmic-zbuffer-artifacts-fix/ a much more complete here: http://outerra.blogspot.jp/2012/11/maximizing-depth-buffer-range-and.html

Software test bed: good idea, it is a excellent way of authoring shaders so you can debug what is going on step by step. just check your values lines by lines, and if something look weird you can investigate. I didn't see in the code you posted the part where the camera angle is used in the shader, so I'm a bit puzzled about this part though.
> 0 votes

---
Tags: xna, c#, procedural-generation, planet
---