# Question
Title: XNA is only rending the bottom half of video; how to fix it?
When running an XNA game any Video objects & related Texture2D's are not being drawn properly. Only the bottom half of the videos are being drawn. the video still plays, and before/after any videos are played all other textures are properly drawn to the correct screen sizes.

Video Class from Microsoft.XNA.Framework.Graphics

```
using Microsoft.Xna.Framework.Graphics;
using System;

namespace Microsoft.Xna.Framework.Media
{
    // Summary:
    //     Represents a video.
    public sealed class Video
    {
        // Summary:
        //     Gets the duration of the Video.
        public TimeSpan Duration { get; }
        //
        // Summary:
        //     Gets the frame rate of this video.
        public float FramesPerSecond { get; }
        //
        // Summary:
        //     Gets the height of this video, in pixels.
        public int Height { get; }
        //
        // Summary:
        //     Gets the VideoSoundtrackType for this video.
        public VideoSoundtrackType VideoSoundtrackType { get; }
        //
        // Summary:
        //     Gets the width of this video, in pixels.
        public int Width { get; }
    }
}

```

Here is some of the code that would affect video textures and playback. please ignore any variable name differences and assume they are right in my working code. If you can think of anything that would be affecting the drawing of the videos that is not included in the following code let me know and i will see if i have something similar in my code and add it here. Again the **issue is: videos being played are cut in half only the bottom half of videos are being drawn**, any input that helps me find a solution to the issue is greatly appreciated.

```
namespace Picodroid
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public partial class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        GraphicsDevice device;

        .....

        DateTime developerDuration; // Video Duration

        .....

        int screenWidth;
        int screenHeight;
        float screenScale;

        .....

        Video developerVideo;
        Texture2D developVideoTexture;
        bool developer = true;

        // Constructor
        public Game1(int resolutionValue, int soundFxValue, int musicValue)
        {
            this.resolutionValue = resolutionValue;
            this.soundFxValue = soundFxValue;
            this.musicValue = musicValue;

            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
        } // End Constructor

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here

            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            device = graphics.GraphicsDevice;

            // current screen resolution

            float resolutionAdjustment;

            if (resolutionValue == 0)
                resolutionAdjustment = 1.0f / 3.0f;
            else if (resolutionValue == 1)
                resolutionAdjustment = 2.0f / 3.0f;
            else
                resolutionAdjustment = 1;

            if (device.DisplayMode.Width * resolutionAdjustment > 1920)
            {
                graphics.PreferredBackBufferWidth = 1920;

                float maxWidth = graphics.PreferredBackBufferWidth;
                float realWidth = device.DisplayMode.Width;
                float realHeight = device.DisplayMode.Height;
                float useHeight = (maxWidth / realWidth) * realHeight;

                graphics.PreferredBackBufferHeight = (int)useHeight;
            }
            else
            {
                graphics.PreferredBackBufferWidth = (int)(device.DisplayMode.Width * resolutionAdjustment);
                graphics.PreferredBackBufferHeight = (int)(device.DisplayMode.Height * resolutionAdjustment);
            }

            graphics.IsFullScreen = true;
            graphics.ApplyChanges();

            // screen
            screenWidth = device.PresentationParameters.BackBufferWidth;
            screenHeight = device.PresentationParameters.BackBufferHeight;
            screenScale = device.PresentationParameters.BackBufferWidth / 1920f;

            base.Initialize();
      } // End Initialize

      /// <summary>
      /// LoadContent will be called once per game and is the place to load
      /// all of your content.
      /// </summary>
      protected override void LoadContent()
      {
           .....

           developerVideo = Content.Load<Video>("developer-100-audio-720");
           developerVideoTexture = Content.Load<Texture2D>("videoTexture");
           videoPlayer = new VideoPlayer();

           .....
      } // End LoadContent

      .....

      /// <summary>
      /// Allows the game to run logic such as updating the world,
      /// checking for collisions, gathering input, and playing audio.
      /// </summary>
      /// <param name="gameTime">Provides a snapshot of timing values.</param>

      // Note: Refer to Flow Chart and Update Method Hierarchy for details
      protected override void Update(GameTime gameTime)
      {

           .....

           if (developerDuration == DateTime.MinValue)
           {
                videoPlayer.Play(developerVideo);
                developerDuration = DateTime.Now;
           }

           .....

           base.Update(gameTime);
      } // End Update

      /// <summary>
      /// This is called when the game should draw itself.
      /// Drawing code goes here
      /// </summary>
      /// <param name="gameTime">Provides a snapshot of timing values.</param>

      // Note: Refer to the Draw Method Hierarchy for details
      protected override void Draw(GameTime gameTime)
      {
           float elapsedTime = (float)gameTime.ElapsedGameTime.TotalSeconds;

           GraphicsDevice.Clear(Color.Black);

           if (developer)
           {
                // Only call GetTexture if a video is playing or paused
                if (videoPlayer.State != MediaState.Stopped)
                     developVideoTexture = videoPlayer.GetTexture();

                float proportionalHeight = 1080f * screenScale;
                float heightDifference = screenHeight - proportionalHeight;

                if (heightDifference != 0)
                     heightDifference /= 2;

                // Draw the video, if we have a texture to draw.
                if (developVideoTexture != null)
                {
                     spriteBatch.Begin();
                     spriteBatch.Draw(developVideoTexture, new Vector2(0, heightDifference), null, Color.White, 0, Vector2.Zero,
                                 screenScale * 1.5f, SpriteEffects.None, 0);
                     spriteBatch.End();
                }
           }

           .....

           base.Draw(gameTime);
     } // End Draw
}

```

# Answer
> 1 votes
In stardrive, some videos are also displayed like this. It is caused by a bug in a Windows Update. (And I think stardrive also use XNA.)

You just have to uninstall this update (and deactivate the auto update mode). This will solve your problem.

# Answer
> 0 votes
If using windows 7 uninstall microsoft update: KB2803821

This also effects windows xp and windows vista. It is the same KB# for vista. Microsoft know about this issue. Not sure when they will have a fix. The security flaw they were fixing was in the rendering of video files.

---
Tags: c#, xna, video
---


# Question
Title: Component-based programming with child objects
I am presently working on a game in Unity3d and have come to a cross road regarding scripting for repetitive child objects. Should these child objects handle its own scripting for best practice?

For example, I have a parent game object, Game Board, that spawns repetitive child objects, Tiles, on the board. Right now, I let these child objects handle its own position on the board and its own animation when the tiles move. However, I can just as easily do this with the parent object's scripting class.

The reason I chose to let the child object do so is because I believe that child objects should be as independent to the parent object as much as possible. But since these are repetitive child objects, I start to wonder if it is just as easy to do all the scripting in the parent object. This way I decrease the number of class instances in the child objects.

According the component-based programming, which method is recommended?

# Answer
The "recommended" method here is going to depend heavily upon what your tiles are actually used for/doing. As Sean says, there's no explicit need to treat the tiles as components if they aren't behaviorally distinct. I.e., are tiles just a visual backdrop for the real action, as in chess?

That said, since you mention the tiles "moving," it seems unlikely that this represents a traditional physical board game. In that case, you'll want to **err on the side of clarity** \- if it makes sense *to you* (and to any other devs on the project) to treat the tiles as components, do so. The overhead from additional scripts whirring away isn't generally significant \[citation needed\], but you can optimize away from that later if it becomes necessary.

*(In my own games, I haven't yet noticed any kind of performance hit from running many hundreds, even thousands, of component-y scripts. I keep them light. Raw draw calls and unnecessary instantiations have had a much larger impact on frame rate. Even then, I do lump together some methods/data for clarity and ease of implementation.)*
> 0 votes

---
Tags: unity, component-based
---


# Question
Title: what is more expensive 2D sprites or 3D models?
Me and my friends are programmers.We decided to try ourselves in game design. As we don't want to find ourselves in debts, we decided to avoid investors. We want to develop and publish a couple of simple 2D games to test the ground. So we collected some humble funds to pay artists and for some other stuff like Unity.

The question is: what is more expensive - 2D sprites or 3D models for 2D games (not mega visual rich)? The question is adressed to artists and modelers and to everyone who has expirience hiring them. Thanks in advance!

# Answer
> 9 votes
As always, it depends.

Game art is a very deep field, so in my opinion you should find a well rounded artist partner to help you, instead of hiring people to do do specific jobs.

Regarding 2D vs 3D, in fact, as Quacks says, creating a 3D model is much more complex than creating a 2D drawing, and therefore more expensive.

However, *animating* in 2D is increasingly more complex than in 3D as the amount of frames increases, because you have to make a complete new drawing for each frame, while in 3D you it is much simpler. Also, making changes, and creating variations of existing data is easier in 3D than it is in 2D.

In fact, I'd dare say that a very compelling reason why fully animated 2D games are not as common today as they were say, in the 90s, is that 2D is simply too expensive.

However, this also greatly depends on the game you're making. Graphical data for an action platform game is probably cheaper in 3D, while for a puzzle game it may be cheaper in 2D.

Nevertheless, remember that you will need 2D assets regardless of whether your game is 2D or 3D, for the menus, GUI, web/box art among many others.

Also, keeping all of the art consistent and interesting is a very complex task, which is why I recommend you to get a well rounded art director, or become one yourself.

Regarding costs, the skills associated with making 2D graphics are vastly different from those required for 3D, and there are no standards in pricings, so your best bet is probably to ask for estimates. However, knowing what to ask for is difficult by itself, which is yet one more reason to get yourself an art director.

# Answer
> 3 votes
2D is cheaper; much cheaper. Reasons why:

* Significantly less work is required in the 2D pipeline
    + "just" draw the frames (or the skeletal pieces if using 2D skeletal animation) and the character is ready to drop in
    + No need for multiple materials for normals/lighting/etc.
    + Animations can be much simpler (few frames, no IK) but still look great in 2D
    + 3D has many parts, usually handled by separate specialized artists in bigger projects
        - Concept artist
        - Modeler
        - Rigger
        - Animator
        - Texture painter
        - Lighting and FX
        - Potentially a whole team just for VFX (particles and the like)
        - Usually separate teams for character vs environment art
    + 2D art for one character is typically all done by the same person
        - Maybe separate artists for characters vs environments
        - More artists more directly correlates to more content
* The level of expertise is much less overall in 2D
    + Hence you need less people in the pipeline
    + 2D artists are cheaper on average, especially when accounting for skill level
    + There are less things (like lighting) to have to handle
* Programmer/designer time is *significantly* cut down in 2D
    + With 3D you need to do with a larger number of external tools/integrations
    + Engine support to handle the assets exported is much more complicated
    + Physics is way easier, which does impact art and design requirements
        - Hit box definitions
        - Physics materials
        - Character controllers (animation combinations and transitions)
        - You need *significantly* more animations just for a basic 3D model to not look like crap
        - You need animation blending, animation trees, etc. in 3D
    + There is significantly more project-specific training required of both programmers and artists regarding the engine and supported features
        - Not all 3D models are created equal, nor are all 3D engines
        - Meshes, textures, materials, animations, etc. all generally must be made a certain work to work with a particular engine
* Tool investment is cheaper in 2D
    + Consider the investment of ZBrush, Max, PhotoShop at a bare minimum for 3D
        - The Free alternatives will typically cost you more in training in my experience, both programmer (for plugins/APIs) and artist
    + If you outsource you don't pay for this directly, but it does contribute to higher fees for 3D work
    + 2D has a lot of cheap or free tools, and Flash and PhotoShop often being the only big ones
        - Those aren't even needed for the retro sprite work
* Art consistency is somewhat easier to achieve in 2D
* Iteration is easier in 2D
    + Much easier and more reliable to preview sprites out of engine
    + Sprites can be started before the engine is up
    + Fewer people in the pipeline means more rapid changes to a model
* 2D gameplay is simpler
    + Designers and programmers spend more time on actual gameplay

The last time I saw a company cost analysis on this stuff I saw six-figure numbers for the differences between 2D and 3D for just a few dozen characters. You can maybe do better, especially if you're not operating at a AAA scale, but I really doubt you'll get 3D cheaper and not have it be completely unusable garbage.

Notice how many indie and hobby games have gone 2D. It's simpler way easier and cheaper all around.

# Answer
> 0 votes
2D sprites should be significantly cheaper than 3D models.

The main bulk of the work on 2D sprites would involve creating a sprite sheet (each frame of the sprite's animation) and that's about it.

3D models however require a lot more attention, especially when they need to be animated. Textures, rigging, animation and possibly normal maps are going to require a lot of time and specialized skills.

Source: I used to work for game company in production. Our concept artists could create a beautiful piece of work much faster than it took 5 people working on getting a single character model in game (granted they were probably more complex than what you are looking to do, but even basic models take time).

---
Tags: 2d, 3d, sprites, models, costs
---


# Question
Title: Procedual terrain generation and biomes/predetermined variation
So I already have some (currently 2D possibly 3D later) simplex noise generation going, and with some experimenting I can make a map for plains, hills, mountains, etc

The problem now is I want to combine those together to create a larger more interesting map. For each "pixel" in the height map I provide/generate a biome type which has a bunch of parameters to define how the height value is calculated etc. i.e. I want to be able to say mountains here, river through there, flood plains next to it, etc and have them blend together.

The problem is this leaves nasty borders since between them even the simplex input values change suddenly (due to the x/z scaling being different, perhaps not the best way?). I considered just doing like a post process to smooth out the height values along the borders, but this would still leave often steep (and uninteresting near constant gradient) slopes since I could have a valley one side and a mountain peek the other side.

I am sure there must be a better fairly standard way to do this, but have not found much searching around, at least for this sort of noise function (midpoint displacement can be seeded with initial values at a low resolution, but doesn't seem viable if not generating the entire map at once)

```
double getHeight(int x, int z, Biome biome)
{
    double nx = x;
    double nz = z;
    nx *= biome.xzNoiseScale();//e.g. 1/64
    ny *= biome.xzNoiseScale();
    double noise = fbm(nx, nz, biome.noiseOctaves(), biome.noiseLacunarity(), biome.noiseGain());
    return biome.baseHeight() + noise * biome.heightVariation();
}

double fbm(double x, double z, int octaves, double lacunarity, double gain)
{
    double amp = 1;
    double freq = 1;
    double sum = 0;
    for (int i = 0; i < octaves; ++i)
    {
        sum += amp * noise(x * freq, y * freq);
        amp *= gain;
        freq *= lacunarity;
    }
    return sum;
}

```

# Answer
I don't know how "standardized" any of the techniques out there are, as PCG is still a nascent field. That said, I immediately thought of this excellent generation-with-biomes article when I read your question:

Source and demos included, even. What a guy. It doesn't seem like it would be particularly hairy to work your "paint the biomes" approach into it, either, though you'd need to port from Actionscript.

There are a lot of resources out there, most of which can be found from this one link:

The PCG Wiki linked therein can be a bit chaotic to navigate, but it has a lot of great links if you're persistent. Can never have too many resources when it comes to designing PCG algorithms!
> 2 votes

# Answer
There are two possible approaches i can think of.

---

**1.) use many differently scaled FBM noises**

Just add the FBM values of many differently scaled FBM noises together

*Note* Why do you use doubles, its unlikely that you do have mountains with a height of some light seconds.

```
class NoiseData
{
    NoiseData(float SpartialScale, float HeightScale, float Octaves)
    {
       ...
    }

    public float SpartialScale;
    public float HeightScale;
    public float Octaves;
}

NoiseData []Noises = {new NoiseData(100.0f, 5000.0f, 1), new NoiseData(12.0f, 500.0f, 1), new NoiseData(5.0f, 10.0f, 2), new NoiseData(0.5f, 1.0f, 3)};

float getHeight(float X, float Z)
{
    float ReturnHeight;

    ReturnHeight = 0.0f;

    foreach( CurrentNoise in Noises )
    {
        ReturnHeight = ReturnHeight + fbm(X/CurrentNoise.SpartialScale, Z/CurrentNoise.SpartialScale, CurrentNoise.Octaves, ?, ?)*Currentnoise.HeightScale;
    }
}

```

Now you can call getHeight to calculate the height of a point in your 2d plane.

Do decide on the returned height and the neightbor bioms which biom you want to generate, not the other way around.

To decide which Biome to generate for a given sector you can take the following things into account:

* neightbor biome(s)
* height/height variance
* ...

---

**2.) Use another technique than FBM noises for basic height generation**

To generate the height of a hill you could use as the function the Gaussian function.

You then can use many of these functions added together to get the height of one point in space.

It is also possible to add FBM noise over this for more variation.
> 0 votes

---
Tags: procedural-generation, terrain
---


title: Approach to AI in Entity Systems

text:
# Question
Title: Approach to AI in Entity Systems
We are making game using Entity Systems. And we with my colleague have different opinions about what approach is better when doing AI.

Basically, he thinks that everything should be a system, where I'm not.

That is his way:

```
Systems:
 - Sensor System (look for a target)
 - Pathfinding System (find a path to a target which will be colliding between agents with high probability)
 - Attack System (attack target if in attack range)
 - Movement System (advance path to target, resolve colliding if can't advance)

```

There is my proposal:

```
Systems:
 - Attack System (find a target with hp > 0, write to Target component and attack if in range)
 - Movement System (find a path to target (if there isnt already) and advance)

Utility classes:
 - Sensor
 - Pathfinding

```

There is problem with first approach. For example, 10 units all choosed one target and attacked it (simly because it was closer). But in reality 3 units are sufficient to kill that target in an instant. So, why other 7 should attack this target too? When they choosed their target they doesn't known yet that 3 unit would suffice. They know now that target hp \<= 0 but they can't choose another, because Sensor System finished his work already. If we want to fix it then problem will be in unreasonable complexity of Sensor system. Where in latter approach we simply wouldn't select target if hp already \<= 0.

Similarly, in first approach pathfinding will find paths which are colliding between them. When one unit taken grid cell another can't take it. That means he must forget his path. But he can't build a new, because Pathfinding system already finished his work. So, he advances one cell in direction of target. In latter approach, we will build path in respect to new positions of units.

Maybe there are another problems in both approaches which we couldn't foresee. So, please say something if you know.

Which way are better (both clear code and good AI)? Maybe both are wrong then please advice what is right way to make it.

# Answer
> Systems:
>
> * Sensor System (look for a target)
> * Pathfinding System (find a path to a target which will be colliding between agents with high probability)
> * Attack System (attack target if in attack range)
> * Movement System (advance path to target, resolve colliding if can't advance)

You most likely have a system for Attack/Movement already, considering your AI isn't going to be the only one Moving/Attacking so don't create new ones just for AI. The mecanisms are the same for playing characters or AI players.

Every AI entity should be responsible for its own decisions. With that in mind, I'd add an AI component to AI entities and *maybe* a system to handle that component (it depends if your engine has behavior on components or only in systems). That component/system pair is responsible for **making decisions and emitting commands**.

Pathfinding is really a global resource that is typically accessed in the same way by every moving entity. In that regard, I'd be on your side and make it a helper class/function. The idea is that systems should be used to update components, not provide arbitrary functionality unrelated to components.

As for sensors, I also disagree with making a system for them unless **you absolutely have to** limit the amount of information available to your AI artificially. For example, if actual players can write AIs for your game, you probably want to set what their agent knows or not so a system to achieve that and prepare a context or a component would be justified. In your case though, you should just query the world around you for the information you need.

In short:

* Add a component/system for AI and make it responsible for making decisions and emitting commands by leveraging your already (hopefully) existing movement and attack mecanics
* Make pathfinding a globally accessible resource, not a system
* Don't abstract understanding your agent's surroundings with a "sensory" layer, just plain old query the world directly

As for your friend, he means well but sometimes we have to be reminded of pragmatism. Not everything has to fit the paradigm perfectly :)
> 4 votes

---
Tags: ai, entity-system
---


# Question
Title: Should I use text files for my save data?
My question is whether or not I should use text files to save my game data. I have some basic concerns over doing this:

1. There's really no way to protect the data, and thus, the user could screw up everything if they touched it and I don't want that to happen.
2. It's probably not the most efficient way to store my data (There will be a lot of it)

I know how to parse/write to text files effectively, though, so for prototyping they have been fantastic. I just want to look to the future for what I should be thinking about switching to so it doesn't punch me in the face near the end of development.

If I shouldn't use text files, what should I use? I need something C++ compatible.

# Answer
> 28 votes
For now, since you're just beginning, text files are probably OK. There's a couple of concerns in your question that I'll address.

1. Protecting the data isn't as crucial as you probably think. If your game is multiplayer, you'll have the data saved server-side anyways. If your game is single player, so what if players modify the data? If they break something it's really their fault and they can re-install.
2. Performance is also something else that we often fail to plan properly. You shouldn't really optimize until you actually **measure** a performance issue. My guess is that you'll probably have an amount of data that isn't *that* big and that text files are going to be just fine.

That being said, your best bet is to abstract your data saving and loading routines as best you can. For example, you can have a base class, say `DataWriter`, and then provide different implementations of its different methods. A very basic example would look like:

```
class DataWriter {
  virtual void save(GameState state) = 0;

  virtual ~DataWriter() { }
};

class TextFileDataWriter : public DataWriter {
  virtual void save(GameState state) {
    //write to text file
  }
};

class DatabaseDataWriter : public DataWriter {
  virtual void save(GameState state) {
    //write to database
  }
};

```

When you eventually profile your game and realize the performance bottleneck is in the file writing routine, you can provide another implementation of that class (for example to write to a database instead) with minimal changes to calling code.

# Answer
> 3 votes
The word Game Data can mean many things, for example

* Gamestate
* Configuration files
* Maps, textures, sounds, scripts, animation data, ...
* Localisation
* GUI layout data
* more i didn't think of

For each category you can take another approach.

For example you could use *SQLite* for Localisation stuff, binary for Maps, textures, sounds and so on.

For configuration stuff you should use easy to change xml files.

As always, the correct answer is "it depends".

There exists many xml parsers with a c++ binding and a c++ binding for SQLite exists too.

# Answer
> 0 votes
You could save out your data as a binary blob and stream the data back in when you come to accessing that file. This would solve both your issues. Just make sure that the serialisation code is exactly the same as the de-serialisation.

Streaming in the binary blob is relatively fast and also prevents the user from seeing the data and changing it.

You can achieve all this by using the standard library streams.

---
Tags: c++, serialization
---


# Question
Title: Calculate mipmap level in a loop with varying iteration?
How can I calculate the correct mipmap level in a shader? It needs to be used in a loop which runs a variable number of times so the compiler will not allow me to use Sample or the derivative functions, instead I have to use SampleLevel and manually specify a level. I tried a simple distance based one but that doesn't look very good and doesn't fix all the problems (such as looking at them at a sharp angle), I thought I could use the dot product of the normal with the direction the pixel is going but I'm still not sure on the correct thresholds etc or if there's a better way.

# Answer
> 1 votes
Quote

`I tried a simple distance based one but that doesn't look very good and doesn't fix all the problems (such as looking at them at a sharp angle)`

this implies that you need Anisotropic filter and it needs the derivaives...

So you need to calculate the derivatives manually.

One apprach is to render the texture coordinates into a texture and calculate the derivative from that (you need to render the object id in a texure too and use it to differenciate between the objects in the derivative calculation).

See here and GPU-Gems for some appraches how to filter anisotroph.

# Answer
> 0 votes
Since you're running this in a loop, and since it runs a variable number of times, you may be able to do something like the following:

* Sample from *all* mipmap levels before entering the loop, and store them in an array of float4s.
* Enter the loop.
* Calculate the mipmap level you wish to use inside the loop.
* Use that as an index into the array; the integral part of the level gives the array index to use, and the fractional part can be used as an interpolation factor between that and the next level down if you wish.

This may even be faster than the theoretical case where you may be allowed to sample inside a loop. Say, if your texture has 10 mip levels and your loop runs on average more than 10 times; you're able to get the desired result with only 10 texture lookups rather than an average of more than 10.

Of course it will break down if you don't know how many mip levels you're going to have in advance, but you should tune your content so that doesn't happen.

---
Tags: shaders, hlsl, directx11
---


# Question
Title: Whats the best way to expose current settings to your classes?
Just as the title states, whats the best way to expose current settings like resolution to my classes? (I know this might have been asked, but I couldn't find anything)

I was thinking of the service-locator design pattern, but I am unsure, as I read that it can be abused easily.( I mean it might not fit this particular use-case )

# Answer
Just make them global until you determine that it's a detriment to your system.

Read this: http://c2.com/cgi/wiki?DoTheSimplestThingThatCouldPossiblyWork

Don't add complexity unless you're getting some benefit out of it.
> 10 votes

---
Tags: c++, architecture, design-patterns
---


# Question
Title: How to set a global alpha-blending value in Direct3D 9?
Is it possible to set an alpha value **globally** in Direct3D 9, which modulates the pixel alpha values of every subsequent draw?

I would like to let a whole scene fade in/out. I know that for example `ID3DXSprite::Draw()` lets you set this in the `Color` parameter, but I'm using pixel shaders to draw 2D circles and rectangles as well, so I would have to pass the alpha value to each of them.

# Answer
> 2 votes
With shaders and ordinary alpha blending I don't think this is possible. If you wanted to *replace* all the alpha values in the scene by a global constant, you could use `D3DBLEND_BLENDFACTOR` and `D3DBLEND_INVBLENDFACTOR`. But it sounds to me like you want to *multiply* each pixel's alpha value by a global constant. This is best done in the pixel shader.

That being said, fading out the alpha of every scene element may not be what you actually want to do. It will produce a strange effect as opaque objects will become transparent during the fade. For instance, an object hidden behind a wall will be briefly visible during the fade, as the wall and the object are both partly transparent.

If you want to fade to a constant color (black, white, etc.), a better approach may be to just render a full-screen pass of that color over the entire scene, rather than altering the alpha values of anything in the scene. If you want to fade to a different scene (like a dissolve) then the second scene should be drawn into an offscreen render target, then drawn on a full-screen pass over the first scene.

---
Tags: directx9, alpha-blending
---


title: OS X OpenGL 3.2 Core (Black Screen)

text:
# Question
Title: OS X OpenGL 3.2 Core (Black Screen)
I want to render a Quad via VAO, IBO and VBO but nothing is drawn. I'm using glDrawRangeElements in OS X OpenGL 3.2 Core context. The screen is completely black without any error. GLFW3 is used to create window and context.

Window opening/Context creation code

```
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
_mainWindow  = glfwCreateWindow(width, height, title, monitor, NULL);
if(_mainWindow == NULL)
{
    return false;
}
_mainWindowWidth  = width;
_mainWindowHeight = height;
glfwSetKeyCallback(_mainWindow, _onKeyEvent);
glfwMakeContextCurrent(_mainWindow);

glewExperimental = GL_TRUE;
glewInit();

_openGLVersion = reinterpret_cast<const char*>(glGetString(GL_VERSION));

```

Shader sources (compiled successfully). Custom FragColor is binded.

```
_vertexShaderSource =
            "#version 150 core\n"
            "in vec3 in_Position;\n"
            "in vec3 in_Normal;\n"
            "in vec2 in_TexCoord;\n"
            "uniform mat4 ModelViewProjection;\n"
            "void main()\n"
            "{\n"
            "   gl_Position = ModelViewProjection * vec4(in_Position, 1.0);\n"
            "}\n";
_fragmentShaderSource =
            "#version 150 core\n"
            "out vec4 FColor;"
            "void main()\n"
            "{\n"
            "   FColor = vec4(1.0, 1.0, 1.0, 1.0);\n"
            "}\n";

```

Vertices

```
Vertex* vertices = new Vertex[6];

vertices[0].nz = 1.0f;
vertices[1].nz = 1.0f;
vertices[2].nz = 1.0f;
vertices[3].nz = 1.0f;
vertices[4].nz = 1.0f;
vertices[5].nz = 1.0f;

vertices[1].y  = height;
vertices[1].v0 = 1.0f;

vertices[2].x  = width;
vertices[2].y  = height;
vertices[2].u0 = 1.0f;
vertices[2].v0 = 1.0f;

vertices[4].x  = width;
vertices[4].u0 = 1.0f;

vertices[5].x  = width;
vertices[5].y  = height;
vertices[5].u0 = 1.0f;
vertices[5].v0 = 1.0f;

_mesh->setVertices(vertices, 6);
vertices = NULL;

Uint16* indices = new Uint16[6];

indices[0] = 0;
indices[1] = 2;
indices[2] = 3;
indices[3] = 0;
indices[4] = 1;
indices[5] = 3;

_mesh->setIndices(indices);
indices = NULL;

```

Buffer update (checked the data, it seems to be correct)

```
// Update VBO
if(_vertexBufferObjectID == 0)
{
        glGenBuffers(1, &_vertexBufferObjectID);
}
glBindBuffer(GL_ARRAY_BUFFER, _vertexBufferObjectID);

float* data = new float[_vertexCount * sizeof(Vertex) / sizeof(float)];
Uint64 begin = 0;
for(Uint32 i = 0; i < _vertexCount; i++)
{
    begin = i * 8;
    data[begin]     = _vertices[i].x;
    data[begin + 1] = _vertices[i].y;
    data[begin + 2] = _vertices[i].z;
    data[begin + 3] = _vertices[i].nx;
    data[begin + 4] = _vertices[i].ny;
    data[begin + 5] = _vertices[i].nz;
    data[begin + 6] = _vertices[i].u0;
    data[begin + 7] = _vertices[i].v0;
}

glBufferData(GL_ARRAY_BUFFER, sizeof(Vertex) * _vertexCount, &data[0], GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);

delete[] data;
data = NULL;

// Update IBO
if(_indexBufferObjectID == 0)
{
    glGenBuffers(1, &_indexBufferObjectID);
}
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _indexBufferObjectID);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(Uint16) * _vertexCount, &_indices[0], GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);

// Update VAO
if(_vertexArrayObjectID == 0)
{
    glGenVertexArrays(1, &_vertexArrayObjectID);
}
glBindVertexArray(_vertexArrayObjectID);

glBindBuffer(GL_ARRAY_BUFFER, _vertexBufferObjectID);
// Vertices
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glEnableVertexAttribArray(2);

glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), ((char*)NULL + (0)));
// Normals
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), ((char*)NULL + (12)));
// TexCoords
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), ((char*)NULL + (24)));

glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _indexBufferObjectID);

glBindVertexArray(0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);

```

Rendering code

```
glUseProgram(material->_programID);
GLuint mvp = glGetUniformLocation(material->_programID, "ModelViewProjection");
glUniformMatrix4fv(mvp, 1, false, glm::value_ptr(camera_mvp));

glBindVertexArray(node->_mesh->_vertexArrayObjectID);

// Draw
glDrawRangeElements(GL_TRIANGLES, 0, 3, node->_mesh->_vertexCount, GL_UNSIGNED_SHORT, NULL);
glBindVertexArray(0);

```

Note: camera\_mvp is Orthographic

```
0.00333333_0___________0 0
0__________0.00333333__0 0
0__________0__________-1 0
599________599_________0 1

```

Program Linking

```
_programID = glCreateProgram();
glAttachShader(_programID, vertex_shader);
glAttachShader(_programID, fragment_shader);

glLinkProgram(_programID);
glGetProgramiv(_programID, GL_LINK_STATUS, &result);
glGetProgramiv(_programID, GL_INFO_LOG_LENGTH, &loglen);

if(loglen > 0)
{
    char* log = new char[loglen];

    glGetProgramInfoLog(_programID, loglen, 0, log);
    _lastInfoLog = log;

    delete log;
    log = NULL;
}

if(result == GL_FALSE)
{
    glDeleteProgram(_programID);
    glDeleteShader(vertex_shader);
    glDeleteShader(fragment_shader);
    return false;
}

glUseProgram(_programID);
glBindAttribLocation(_programID, 0, "in_Position");
glBindAttribLocation(_programID, 1, "in_Normal");
glBindAttribLocation(_programID, 2, "in_TexCoord");
glBindFragDataLocation(_programID, 0, "FColor");
glUseProgram(0);

glDeleteShader(vertex_shader);
glDeleteShader(fragment_shader);

```

# Answer
> 4 votes
I pasted together a running version here (just for demo purposes, I hacked around your existing names and structures)

Like I said, your indices were wrong. How you got your MVP matrix I don't know, but it still looks wrong, maybe you transposed it or printed it out transposed.

Also, the way you used `glBindAttribLocation()` and `glBindFragDataLocation()` is slightly wrong, you need to either call it before linking or link the program again after calling it.

These are your vertecies visualized:

```
1_______2&5
|      /|
|     / |
|    /  |
|   /   |
|  /    |
| /     |
|/______|
0&3     4

```

and you tried to draw 0,2,3 and 0,1,3. As you see that would draw triangles with no area as I explained to you.

---
Tags: c++, opengl, rendering, graphics-programming, vbo
---


title: Safest place to store data

text:
# Question
Title: Safest place to store data
What is safest possible way to store data? Specific directory? (De-)hashing method? Specific permissions?

Let say I have file `*.txt` file; the only `*.txt` file. I have there important data. What can I do with this file to make it as safe as possible for further use. For Windows Vista and newer (7/8/Blue). I could use it to see if game is really bought, not cracked etc. .

# Answer
Really, the safest way to store data is on a remote server. By safe, I mean, no one can really touch the data except for the ways you allow the data to be accessed.

A good question to ask yourself is, is my data worth protecting?

If this game was a simple single player game with no contact with the outside world (eg. online high scores, online multiplayer), why bother protecting that data?

If the game is online in some way, then don't bother storing sensative data locally.

**If your goal is to prevent people stealing your game, then have it look online for validation and store keys and IP Addresses on your servers**. That way you can see *who* is using your game. If this is done, be aware that ISP's sometimes hand out random IP's in their massive pools of IP addresses.
> 1 votes

---
Tags: data, storage
---


# Question
Title: Wavefront mesh: determine which face a point belongs to?
I have a 3D mesh Wavefront .obj file.

Is there any algorithm that takes an arbitrary point coordinates as input and determines which face of the mesh that point belongs to ??

The mesh is rendered on the screen, then the user clicks on it, I want to determine which part of the mesh the user has clicked on ?

Here's the code using LibGDX:

```
Vector3 intersection=new Vector3();
Ray ray=camera.getPickRay(x, y);
//vertices is an array that hold the coordinates of the mesh
boolean ok=Intersector.intersectRayTriangles(ray, vertices, intersection);

```

Thanks

# Answer
For each face in the mesh: test for a ray-triangle intersection using a ray that goes through the pixel the user clicked on.

You can compute the ray using gluUnproject (or the equivalent math). Unproject two points with winX and winY set to where the user clicked: one with winZ=0.0 at the near plane, and one with winZ=1.0 at the far plane. These two points form a line you can use to test for triangle intersections.
> 1 votes

# Answer
OBJ format is not meant to reflect how you store things in memory and operate on data. The fact that you're using an OBJ format is hence not relevant. You need to be loading your data into an appropriate in-memory format that makes the operations you need efficient.

In the most general case you store a list of `Triangle` objects and iterate over each to do a ray-triangle test. You can optimize this heavily by using a smarter data structure, such as a model-local BSP tree (or some other spatial partitioning as appropriate for the kinds of shapes you're using).
> 1 votes

---
Tags: libgdx, 3d-meshes, raycasting, obj
---


# Question
Title: what kind of technique is used in android game rendering like Pou
Hi I want to create a game which is graphicaly similar like Pou, I just do not know how is is rendered, if it is using opengl or just bitmaps at canvas? I want nothing serious, so i think opengl is to heavy tool for that. Just some animal, with moving eye and mounth... http://developer.android.com/training/building-graphics.html -- is where i am looking for the answer.

thanks

# Answer
> 9 votes
For drawing body of main character, this application use Canvas and 2D drawing primitives like `curves`, `lines`, `circles` :

1. The main body is drawn using a `cubic bezier curve`. This one is "deformed" real-time to give illusion it's "alive". Same goes for mouth.
2. Eyes are draw using circles.

More information about 2D primitives used by the application here : http://developer.android.com/reference/android/graphics/Path.html

The game doesn't use any custom format to store 2D primitives, all these drawings calls are hard-coded in different methods. Depending which outfit player has selected, the game choose the corresponding method. Methods use several inputs (elapsed time, tilt device orientation, touch gestures, character status, etc...) and simple math (eg : `easing functions`, ...) to do animations and rendering.

This is for drawing the main "deformable" part (body, eyes, mouth, ...).

---

For all the other items that requires more complex shapes (like hats, ears, glasses, eyebrows, suit, moustache, ...), the game simply use bitmaps :

They are draw on the top of main character. They are not "deformable" like the rest but are `scaled`, `rotated` and `translated` to always follow main character body.

Most other parts of the application (eg : icons) also use bitmaps.

source : I made an analysis on the inner workings of the game using an `android emulator`.

---
Tags: android, rendering
---


title: How to get map tiles to line up nicely?

text:
# Question
Title: How to get map tiles to line up nicely?
When I first created my code, there were quite a few cases where I would get horizontal and vertical gaps between tiles when displayed. I put this down to rounding issues with `float`s and just moved on to other things. Now that I've revisited the issue, I can't seem to get it working properly, even after trying my hardest to eliminate places where this sort of issue might happen. It seems to only happen when I place the camera at certain positions, which is why I think it's likely to be a `float` issue. If anyone could help me with the correct way to draw the tile layout, it'd be much appreciated.

This is my drawing method for the map:

```
public override void Draw(GameTime gameTime, SpriteBatch spriteBatch)
{
    var topLeft = Camera.ScreenCoordinateToWorld(new Vector2(0, 0));
    // Readjust the position of the topLeft element so we get the actual
    // drawing position for the tile here
    topLeft = new WorldCoordinate(topLeft.X - 1, topLeft.Y - 1,
                                  -TileSize / 2, -TileSize / 2);
    var topLeftDrawPosition = topLeft.DrawPosition;
    var screenWidthInTiles = Game.GraphicsDevice.Viewport.Width / TileSize + 1;
    var screenHeightInTiles = Game.GraphicsDevice.Viewport.Height / TileSize + 1;

    for (var y = topLeft.Y; y <= topLeft.Y + screenHeightInTiles; y++)
    {
        for (var x = topLeft.X; x <= topLeft.X + screenWidthInTiles; x++)
        {
            if (x < 0 || y < 0 || y >= MapData.Count || x >= MapData[y].Count)
            {
                // Ignore out of range tiles to avoid exceptions
                continue;
            }

            var tile = MapData[y][x];
            var drawPosition = topLeftDrawPosition +
                               new Vector2((x - topLeft.X)*TileSize,
                                           (y - topLeft.Y)*TileSize);
            Tileset[tile].Draw(spriteBatch, drawPosition);
        }
    }

    base.Draw(gameTime, spriteBatch);
}

```

Broken:

Semi-working:

# Answer
One method I've discovered to fix this is to use a two-pass approach; first render the tiles onto a texture, then render the texture in the correct place. This seems to be mildly more expensive, as you'd expect, but does the job perfectly.

```
public override void LoadContent()
{
    MapSprite = new RenderTarget2D(Game.GraphicsDevice, ScreenWidthInTiles * TileSize, ScreenHeightInTiles * TileSize, true, Game.GraphicsDevice.DisplayMode.Format, DepthFormat.Depth24);
    MapSpriteBatch = new SpriteBatch(Game.GraphicsDevice);

    base.LoadContent();
}

public override void Draw(GameTime gameTime, SpriteBatch spriteBatch)
{
    var topLeft = Camera.ScreenCoordinateToWorld(Vector2.Zero);
    // Readjust the position of the topLeft element so we get the actual drawing position for the tile here
    var topLeftTile = new WorldCoordinate(topLeft.X - 1, topLeft.Y - 1, -TileSize / 2, -TileSize / 2);
    Vector2 drawPosition;

    Game.GraphicsDevice.SetRenderTarget(MapSprite);
    Game.GraphicsDevice.Clear(Color.Black);

    MapSpriteBatch.Begin();

    for (var y = topLeftTile.Y; y <= topLeftTile.Y + ScreenHeightInTiles; y++)
    {
        for (var x = topLeftTile.X; x <= topLeftTile.X + ScreenWidthInTiles; x++)
        {
            if (x < 0 || y < 0 || y >= MapData.Count || x >= MapData[y].Count)
            {
                // Ignore out of range tiles to avoid exceptions
                continue;
            }

            var tile = MapData[y][x];
            drawPosition = new Vector2((x - topLeftTile.X)*TileSize,
                                        (y - topLeftTile.Y)*TileSize);
            Tileset[tile].Draw(MapSpriteBatch, drawPosition);
        }
    }

    MapSpriteBatch.End();
    Game.GraphicsDevice.SetRenderTarget(null);

    // Render the result into the right place. First push the sprite up into the top left corner
    drawPosition = Camera.Position.DrawPosition - Game1.ScreenCentre -
                    // The account for the offset of the camera
                    topLeft.Offset -
                    // And account for centering issues
                    new Vector2(TileSize*1.5f);
    spriteBatch.Draw(MapSprite, drawPosition, null, Color.White, 0.0f, Vector2.Zero, 1.0f, SpriteEffects.None, 1.0f);

    base.Draw(gameTime, spriteBatch);
}

```
> 8 votes

# Answer
It looks like the TEXTURE WRAP mode is wrong. You want to set it to CLAMP. See Texture address mode.
> 2 votes

# Answer
This problem happens because you are working with Vector2, this is, float values. So when XNA draws a sprite in a non integer coordinate, tends to adjust it by antialiasing the sprite.

To fix this, just make sure you convert your floats to integers before drawing it:

```
        var drawPosition = topLeftDrawPosition +
                           new Vector2((int)((x - topLeft.X)*TileSize),
                                       ((int) (y - topLeft.Y)*TileSize));

```

Regards
> 0 votes

---
Tags: xna, 2d
---


title: Raycasting in Unity3D?

text:
# Question
Title: Raycasting in Unity3D?
I have a game object on screen represented by a cube (but say it was a quad or something else all the same).

How do I raycast to check intersections? Keeping in mind I may not be raycasting fora physical object, just a gameobject of any sort.

Another question I have is, how can you raycast in Unity3D just to check against an intersection against anything in general (say the first gameobject to be hit)?

# Answer
> 2 votes
If you want to stay with Raycasting, when you load your object, keep track of the faces in some way. Then raycast to the triangles instead of the whole object. This greatly improves your accuracy of your raycast, also built in an algorith that improves the raycasting technique

# Answer
> 2 votes
Raycasting in Unity is applied against colliders only, not gameobjects. In fact, gameobjects are nothing other than a storage of transform info. If you want raycasting against meshes (MeshRenderer on a gameobject) you can use a meshcollider.

Raycasting, especially against meshes are very expensive so, basic colliders are designed for performance. Meshcolliders are expensive too but the cost can be reduced by using Convex flag = true. It generates a simplified mesh from the original mesh but you should make sure if it's close enough to your original mesh.

Without a mesh collider, you can't use the built-in raycast functions. You can implement your own function working against the real meshes (The mesh in MeshRenderer component) but you don't gain any benefit by doing this. Because raycasting is implemented for you in unity already.

Just add a meshcollider to every object you want to raycast against. By the way, you can use the layer system to be able to filter some objects out when you are raycasting.

---
Tags: c#, unity, raycasting
---


# Question
Title: XNA 2D Spritesheet drawing rendering problem
I'm making a tile-based game, using one spritesheet containing all tile graphics.

Each tile has a size of 32x32 pixels.

The main problem is: when I draw the tile to the screen, if the tile position x and y are not rounded or if scale is activated in spriteBatch.Draw() method (scale != 1.0f), I get some lines of adjacent tiles on the spritesheet into the current tile drawed.

I already tried setting SamplerState to PointClamp, removing AntiAlias, but still doesn't work.

Here I'll show images of some tests that I made, with a test sprite sheet that I've created (I made a 9x9 spritesheet, with each sprite of size 32x32 containing a unique solid color).

Tests:

SpriteSheet used:

---

Already tried to remove anti-alias, set PointClamp as sampler state, but still getting this issue, XNA keeps drawing part of the adjacent pixels of the texture on the screen.

What I want is to get the correct area of the tilesheet texture (as seen in the first test, that gets just the yellow pixels).

**My question is: Is there any way that I can fix this, WITHOUT adding tile spacing or any other modification involving the tilesheet?**

Maybe disabling a texture filtering that is done by XNA, or something like that.

# Answer
> 1 votes
From my experience, this seems like you aren't setting your SamplerState to PointClamp correctly. This is indicated by the "blending" at the top left corner. Have you tried rendering on different hardware?

First, **Your texture isn't a power-of-two** Although some wouldn't agree, I always use textures^2. On some older hardware it was a requirement. I would suggesting sizing up to 128x128 (4\*32, 4\*32)

Second, have you tried setting GraphicsDevice.SamplerState\[0\] directly? (source)

# Answer
> 1 votes
Based on the images you're showing, it is very clear that the renderer is interpolating, so you have to disable this interpolation. This has little to do with half pixels.

Now, I'm not really knowledgeable in XNA, but a quick google of "xna nearest neighbor interpolation" shows that there are at least two places you can try to disable interpolation:

This one suggests using `PointClamp` as a parameter for `SpriteBatch.Begin()`, while this other one suggests setting it at `GraphicsDevice.SamplerStates`.

You mention you tried setting the sampler state to `PointClamp`, so how about trying at `SpriteBatch.Begin()`?

# Answer
> 1 votes
I had exactly the same problem that User24092, and I tried all those suggestions with no result. Finally the solution suggested by Panda Pajama made the trick!

Just set the PointClamp sampler state when you begin the spriteBatch:

```
spriteBatch.Begin(SpriteSortMode.Immediate, null, SamplerState.PointClamp, null,null);

```

It worked like a charm!

# Answer
> 0 votes
The best way to fix this is to round your X and Y values before drawing them.

The "usual" way I handle this in XNA is to keep X and Y internally as a `float`, and to expose them externally (eg. to `SpriteBatch`) as an `int`. You should, of course, use `Math.Floor` to get you the correct tile.

The code would look something like this:

```
float x, y = 0f;
// ...
public int X { get { return (int)Math.Floor(this.x); } }
public int Y { get { return (int)Math.Floor(this.y); } }
spriteBatch.Draw(this.texture, new Vector2(this.X, this.Y), Color.White);

```

# Answer
> 0 votes
I know it may be a bit extreme, but try to apply a pixel shader with filter point to force that the exact pixels are rendered. I'm really curious with this problem.

```
Texture Sprite;
sampler SamplerSprite = sampler_state {
    texture = <Sprite>;
    filter = POINT;
};

float4 Ps_Main(float2 coord : TEXCOORD0) : COLOR {
    return tex2D(SamplerSprite, coord);
}

technique Tech_0 {
    pass Pass_0 {
            pixelshader = compile ps_2_0 Ps_Main();
    }
}

```

---
Tags: xna, 2d, textures, spritesheet, lines
---


# Question
Title: What is the correct and most efficient approach of streaming vertex data?
Usually, I do this in my current OpenGL ES project (for iOS):

**Initialization**:

* Create two VBO's and one IndexBuffer (since I will use the same indices), same size.
* Create two VAO's and configure them, both bound to the same Index Buffer.

**Each frame**:

1. Choose a VBO/VAO couple. (Different from the previous frame, so I'm alternating.)
2. Bind that VBO
3. Upload new data using `glBufferSubData(GL_ARRAY_BUFFER, ...)`.
4. Bind the VAO
5. Render my stuff using `glDrawElements(GL_***, ...)`;
6. Unbind the VAO

However, someone told me to avoid uploading data (step 3) and render immediately the new data (step 5). I should avoid this, because the glDrawElements call will stall until the buffer is effectively uploaded to VRAM. So he suggested to draw all my geometry I uploaded the previous frame and upload in the current frame what will be drawn in the next frame. Thus, everything is rendered with the delay of one frame.

Is this true or am I using the good approach to work with streaming vertex data?

(I do know that the pipeline will stall the other way around. Ie: when you draw and immediately try to change the buffer data. But I'm not doing that, since I implemented double buffering.)

# Answer
Since you've mentioned iOS in your question, I'm going to refer you to Apple's guidelines, particularly at here: Use Double Buffering to Avoid Resource Conflicts.

Note that they comment: "Although shown for textures, this solution works for almost any type of OpenGL ES object".

In OpenGL ES 3.0 you would have glMapBufferRange, which is a better solution for streaming, but in the absence of that I would say to run with Apple's own current guidelines.
> 1 votes

---
Tags: ios, opengl-es
---


title: Finding vectors with two points

text:
# Question
Title: Finding vectors with two points
We're are trying to get the direction of a projectile but we can't find out how

For example:

\[1,1\] will go SE

\[1,-1\] will go NE

\[-1,-1\] will go NW

and \[-1,1\] will go SW

we need an equation of some sort that will take the player pos and the mouse pos and find which direction the projectile needs to go.

Here is where we are plugging in the vectors:

```
def update(self):

    self.rect.x += self.vector[0]
    self.rect.y += self.vector[1]

```

Then we are blitting the projectile at the rects coords.

# Answer
> 2 votes
To compute a direction you just need subtraction, and ideally normalisation.

```
self.vector = (mouse.position - player.position).normalize()

```

Note that your loop update should take the velocity and time between two frames into account:

```
self.rect.x += speed * timestep * self.vector[0]
self.rect.y += speed * timestep * self.vector[1]

```

# Answer
> 0 votes
A vector is a position in space relative to other vectors, and by using Pythagoras and some Trigonometry, we can determine the vectors direction and distance in relation to a target vector.

For the projectile, you are going to need to determine the length of its flight path from the start to the end vector and the angle to which you must launch that projectile.

To find the magnitude(direction): Say we have two vectors in R2(2D Cartesian coordinate system): P(3,4) Q(6,8) we must subtract each of the corresponding X and Y terms, then subtract those two elements, square them, then take the root of the whole equation, this is illustrated as follows:

sqrt((6-3)^2-(8-4)^2) which equates to roughly: 2.6458 (Euler angles)

Now we have the distance between the two vectors, it is time to generate the angle:

Tan((8-4)/(6-8)) Which roughly equates to: 1.285

So now rotate your projectile to 1.285 degrees and then offset the projectile for a distance of 2.6458.

Albeit not a complete solution, you can do this check each time the target moves and update the destination of the projectile, you will however, need to find a suitable method to transition between angles, otherwise the result may look choppy.

---
Tags: vector, python, pygame
---


title: JMonkey - Create health bar?

text:
# Question
Title: JMonkey - Create health bar?
**How can I create a health bar in JMonkey? Is there some documentation that can help?**

I am working on a game, specifically “Battleship”, using the JMonkey Engine (JME3). I want to add health bars on each ship. For the main ship, “the player”, I want to have a fixed-place health bar in the top-left corner of the screen. For the enemy ships, I want to add a health bar that moves with each enemy ship.

While trying to figure out a solution to this idea, I found that everyone was talking about using “BillboardNode”, to create a health bar. On knowing this, I started to search on what a “Billboard Node” means and tried to find any documentation that can explain how to use it. But, with no luck. I don’t know if I’m missing something, but I can’t find any documentation to help.

I did find a code that creates a health bar:

https://code.google.com/p/jme-simple-examples/source/browse/JMESimpleExamples/src/com/robotfight/Main.java?spec=svn5a70b9fc75bde6b7213e0d098e263660b5db290a&r=5a70b9fc75bde6b7213e0d098e263660b5db290a

But when I try to use it in my code, it doesn’t work. So there must be something that I am missing!

This is the code that I tried to use in my game:

```
        BillboardControl billboard = new BillboardControl();
        Geometry healthbar = new Geometry(“healthbar”, new Quad(4f, 0.2f));
        Material mathb = mat.clone();
        mathb.setColor(“Color”, ColorRGBA.Red);
        healthbar.setMaterial(mathb);
        Ship.attachChild(healthbar);
        healthbar.center();
        healthbar.move(0, 7, 2);
        healthbar.addControl(billboard);

```

# Answer
> 2 votes
Essentially, a billboard is just a quad - a single rectangular plane - that is constantly oriented so it faces the camera. JME3 has a control that can do the orientation bit for you, `com.jme3.scene.control.BillboardControl`.

In the code sample you provided, the Material mat is cloned for use as the material of the billboard. If you aren't creating this material somewhere already, you need to do so (or just create mathb). I'm guessing you've also created Ship somewhere. Other than that, I can't see anything wrong with this piece of code.

---
Tags: java, jmonkeyengine, billboarding
---


# Question
Title: How to know in OPenGL ES android that one object crosses another?
I have 2 objects on the screen:

**static:**

**non-static:**

*non-static* object moves randomly over the screen.

How do I know that *non-static* Object cross the "+" (static).

Both objects I draw by using followed code:

```
private void updateScreenData(float screenWidth, float screenHeight){
    // takes screen Height and Width
    this.mScreenWidth = (screenWidth > 0) ? screenWidth : 1f;
    this.mScreenHeight = screenHeight;
    wRatio = 10f/mScreenWidth;
    hRatio = mScreenHeight/10f;
}

protected void drawTarget(GL10 gl){
    gl.glPushMatrix();
    try {
        float transx =  shiftX + (wRatio * (x));
        float transy =  shiftY +(mScreenHeight*wRatio) - (wRatio * (y)) - 1/hRatio;

        gl.glTranslatef(transx, transy, 0.0f);

        //###########  draw ##############

        gl.glBindTexture(GL10.GL_TEXTURE_2D, textures[0]);

        gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, floatBufferArray[mFrame]);

        //update();

        gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
        gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
        gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertexBuffer);
        gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, vertices.length / 3);
        gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
        gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY);

        //###############################

    } catch (NullPointerException e) {
    }
    gl.glPopMatrix();
}

public void loadTextures(GL10 gl) {
    Log.e(LOG_TAG, "loadTextures");

    InputStream is;

    is = mContext.getResources().openRawResource(_SRC);

    Bitmap bitmap = BitmapFactory.decodeStream(is);

    try {
        is.close();
        is = null;
    } catch (IOException e) {
    }

    gl.glGenTextures(TEXTURE_COUNT, textures, 0);

    gl.glBindTexture(GL10.GL_TEXTURE_2D, textures[0]);
    gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR);
    gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_LINEAR);
    GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0);

    bitmap.recycle();

}

```

Any ideas?

What do I need to compare in both Objects?

**\[EDIT\]**

I see my question is not so clear, so i'll try once more.

Since my cross image stays at the middle of screen (`screenWidth/2` and `screenWidth/2`) I know the coordinates, it do not change. But second Object changes.

**How can I fetch out coordinates (aka x,y) from dynamic object?**

# Answer
One of the simplest and fastest ways is to compare the bounding boxes of the two, and see if they intersect/overlap. This is usually fairly trivial.

In your case, it seems like you have a "hit zone" in the middle of your crosshairs. I would alternatively check if the bounding box of that inner area overlaps the skulls, and if it does, that's a valid hit.

You can see this question's answers for some ways to calculate overlap/intersection..
> 1 votes

---
Tags: android, opengl-es
---


title: Wall penetration

text:
# Question
Title: Wall penetration
I have a terrain with geometry that is fairly ridged. I needed to make sure the player didn't enter the world geometry, so I used sphere-triangle intersections (after narrow down of which tris to test using AABBs on chunks of the terrain).

This works *fine*, the player smoothly appears to "roll off" the terrain when you walk into it.

What I do is detect the penetration distance of the sphere into the terrain, then just push the player *back* in the direction of the terrain face. That clears him of the world geometry.

# Method 1:

### Push the bounding sphere of the player back in the direction of the normal of the wall he hit, until he exits the wall.

**However**. This has had the awkward side effect of occassionally *pushing the player into another face* (when the player is near the meeting of 2 faces). The result is this nasty bounce-shake between the two walls and the player gets stuck until he changes direction (turns around).

Initially I tried to solve this problem by:

* "Cancel" previous move by translating player back along his "last move" vector the exact distance he moved if he touches a wall

+ But this causes walls to feel "sticky". You will get "caught" on walls if you use this, if any component of your velocity enters a wall (so you cannot "slide" by running diagonally into the wall).
* Pushing the player back along his "last move" vector *only far enough to clear the wall*. This looks better at first, but converges to the *same* sticky walls problem as "fully cancelling the move" if the player is *already touching the wall*, but is trying to slide along it by running diagonally into it

# Method 2:

### Cancel or partially cancel the move by pushing the player back along the vector from which he came, until he exits the wall he *deepest* hit

So it **seems** I was on the right track with the first approach (push in wall's normal direction). What I'm going to try next is a hybrid:

* Look for wall intersection
    + If one is found, push him back along the normal of the wall, then CHECK FOR A WALL COLLISION AGAIN (apply Method #1)
        - If a 2nd wall collision is found, **cancel the move until he exits the wall** (apply Method #2)

Am I on the right track here? Is there a better way to solve this?

# Answer
> 1 votes
Method #1 **does** work, but performance is **a lot** better if you use the **interpolated normal** of the face (instead of the face normal, as I had been using).

But you can still get sporadic behavior with this. The "weird bounce" behavior occurs *mostly when a sphere "chomps"* into the side of a triangle (instead of "kissing" the triangle from above)

So I found there were actually 3 cases to handle distinctly to avoid sporadic bouncing behavior:

## 1. "Kissing" intersections (normal intersections like you'd expect).

For these you push off in the interpolated normal direction (use barycentric coordinates to determine the interpolated normal from the vertex normals -- you have the barycentric coordinates from the sphere-tri test anyway)

## 2. "Chomping Edge" intersections

## 3. "Chomping Corner"

For chomping edge and chomping corner, *don't* use the normal direction, that will push your sphere WAY off in the wrong direction. Instead you need the closest pt on the tri to the sphere center, and to push the sphere OFF the triangle *in the direction from the closest pt on the tri to the sphere center*.

A couple of other notes:

* I only select **one tri** to push back on each frame.
* The tri I select (of all the tris intersected) is the tri with the **closest tri centroid to the sphere centroid**. Choosing the tri with the deepest penetration distance *does not seem to be a good choice*.

# Answer
> 3 votes
Here's one quick nice trick implemented in the latest Physics SDK: if you have a ball experiencing multiple collisions, then use impulses to resolve collisions.

1. find the number of contact points (contact point = {pair, position, normal} )
2. divide the ball into `n` balls with the same center of mass (basically sharing the same position and volume, of course not colliding with each other), but having the initial sphere's mass divided by `n`
3. now simply compute for each sphere the necessary impulse required to push it out of the wall
4. when all contact points are solved by finding appropriate impulses, just add those impulses together and apply them to your big sphere
5. Inside a frame, to assure convergence, you can perform 4 such iterations to find a solution (relaxation).

Nvidia Physics researchers claim it's even jitter free :).

# Answer
> 2 votes
You could add one invisible wall to prevent players from trying to squeeze into these areas. So instead of bouncing between two walls at an acute angle, they could bounce off three walls with obtuse angles between them. That would avoid your feedback problem without additional collision logic. But to the player, it would appear that they simply can't move any farther into the joint of the two visible walls.

# Answer
> 0 votes
The "canceling" you described earlier should work, just you need to separate the movement between the axes and check both seperatedly. E.g. a collision on the X-axis shouldn't cancel the movement on the Y-axis and vice versa.

This also applies to the bouncing, hitting a wall should just invert the movement on the X-axis and not affect the movement on the Y-axis at all.

---
Tags: collision-detection, terrain, bounding-spheres
---


title: Blender and the smoothing effect

text:
# Question
Title: Blender and the smoothing effect
I just started using blender again and I'd like to know if smoothing your model out adds a performance hit to your game?

By smoothing I mean when you hit ctrl+X (number from 1-9). The number of vertices stay the same, but the model gets considerably smoother the higher the number goes, i'm wondering if it's secretly adding tons of vertices in order to do this and would be a performance hit, or if it's doing something else that isn't a big deal to the performance of your game. Thanks.

# Answer
> 1 votes
It dependes what kind of smoothing.

I don't know about new versions of Blender, so I don't know the functionality you are talking about, but it sounds like it is keeping the mesh the same but using it as a base mesh for a high resolution smooth surface. The number of vertices are the same, but a high res smooth surface is constructed at as a preprocessing stage while rendering.

However, (although I don't think you are talking about this) setting smoothing on a mesh's material can mean fewer vertices, since shared vertices can be reused (if the position, normal and uv coordinates are the same).

So to summarise:

**Any kind of subdivision smoothing -\> more vertices**

**Setting material smoothing flag -\> fewer vertices**

However, if you are using subdivision, when you export it may just export the base mesh. You may need to apply the subdivision modifier to be able to export the smooth geometry. Why don't you just look at the number of vertices and number of triangle when you export?

# Answer
> 0 votes
Summarizing:

* Ctrl-x adds a sudbivision smoothing modifier. You can see it in modifiers well after the press of aforementioned key.
* It will either have an negative impact on performance (in the case where
export applies subdivision) or will not (when subdivision is not
applied). But in the latter case you will have an unsmoothed mesh in result. If you want to smooth mesh without vertices number change, you may use vertex smooth in edit mode.
* Number of vertices you see in the top window is a number of vertices before modifier application, so think of them as of "control
vertices", not the resulting mesh vertices, so the number of vertices is not the same, in fact.
* Whether modifiers are applied or not is controlled in export settings, usually.

# Answer
> 0 votes
# Yes, it does reduce performance

What you are actually talking about is subdivision surfaces. This generates more geometry to give the mesh enough geometry to round itself out. To see how this modifier affects your mesh.

> Subdivision Surface (Subsurf in short) is a method of subdividing the faces of a mesh to give a smooth appearance, to enable modeling of complex smooth surfaces with simple, low-vertex meshes.

You do ***not*** want to subsivide meshes for use in realtime applications for obvious reasons. If you are interested in getting smooth looking meshes, you can use the **Smooth** modifier instead as this moves vertices rather than adding more.

> ...The number of vertices stay the same, but the model gets considerably smoother the higher the number goes...

The number of vertices do not remain the same, look in the header and you will see that the vertex count has gone up, set your model to flat shading and you will also see all the new faces as the levels fo up.

Also, you can subdivide up to *6* levels in Blender. The view level is the one you see in the viewport and the render level is the one you see in the game engine or render etc.

---
Tags: performance, blender
---


title: Early Z-test / depth-test in DirectX 11

text:
# Question
Title: Early Z-test / depth-test in DirectX 11
As a DirectX noob i'm trying to wrap my head around depth buffers and specifically how pixel shaders are called for obscured pixels.

From what i understand, the rasterizer calls the pixel shader for each pixel that is covering the primitive beeing drawn, then later in the output merger stage, the output merger checks the depth buffer and either discards, writes or blends the pixel in the back buffer.

This seems wasteful though if i'm rendering a simple opaque object in front of a very complex one, so it seems it would be useful to have the rasterizer check the depthmap Before even calling the pixel shaders for the complex object.

Doing research i've found references to early Z test / conservative Z testing and so on, but there also seems to be very little documentation about it. i looked for a way to configure that on the rasterizer state desc object, but i only found anything like that on the OM state desc.

It also seems like this was possible to set with SetRenderState in DX9 (i have no experience with DX9 either though)

From my research it seems like this is something some hardware just does if i render objects front to back, is that correct? How can i even tell? With all the Control DirectX gives you it seems weird that there is no control over this, as it seems to be a good optimization :)

Any info or references on this is appriciated

# Answer
It's completely automatic, so long as you don't do anything that might implicitly disable it.

Early Z and such are *hardware* optimizations, meaning that they're things hardware *might* do and are allowed to do or not to do as the result of early Z has no effect on the rendered image other than speed. It's similar to how a compiler or even CPU is allowed to transform or reorder your code so long as it doesn't change the actual output (assuming you don't rely on some specific result from undefined behaviour). This is the so called "as-if" rule, which is a formal part of some language specifications and just an informal/implicit rule of most other languages and APIs. Your role as an API users is simply to avoid doing things that might stop the hardware from using its optimizations rather than explicitly opting in or opting out.

For each pixel (fragment), the rasterizer will have already computed a "default" depth. This depth value is tested *before* the pixel shader is run. If the depth test fails (the pixel is obscured) then the pixel shader is not run. All automatic.

This is disabled if you do things like modify the depth output semantic in the pixel shader. In this case, the rasterizer doesn't know what depth to use until *after* it runs the pixel shader, so it can't do early Z culling.

A related topic is hierarchical Z. With this feature, the GPU takes advantage of the fact that most pixels drawn are part of a larger primitive and all other pixels nearby will be part of that same primitive and be at a relatively similar depth. Also, the primitive being drawn typically either fully obscures other primitives drawn or is itself fully obscured. Hierarchical Z breaks the scene into sub-regision, recursively, in an approach reminiscent of mipmaps (might even be the same thing on some hardware). In each lower layer of this hierarchy, the Z buffer stores only the furthest depth value (assuming you're using the standard depth scheme). Before testing a specific pixel's depth, the hierarchy is traversed downward. If any part of the hierarchy fails, the GPU knows that any pixel in that entire chunk would obscure the pixel being processed so it is culled. The hierarchy allows less depth value updates, tighter memory access, and so on, which account for sometimes significant drawing advantages. This feature is again free so long as you don't use weird depth setups or draw in crazy ways that would subvert the assumptions the algorithm is based on.
> 4 votes

---
Tags: directx, directx11, optimization, depth-buffer
---


# Question
Title: Directional light shader not behaving as expected
I coded my first glsl shader which manage diffuse and specular effects of a directional light. This is the fragment shader.

```
#version 120

//matrix
uniform mat4 model_matrix;

//directional light position in world coordinates
uniform vec3 light_position;
uniform vec3 eye;

//send to fragment shader
varying vec4 color;
varying vec4 normal;
varying vec4 vertex;

void main()
{

    float light_diffuse_intensity;
    float light_specular_intensity;
    float light_mod;

    vec3 world_normal;
    vec3 world_vertex;
    vec3 world_reflec;
    vec3 vertex_to_light;
    vec3 vertex_to_eye;

    world_normal = (model_matrix * normal).xyz;
    world_vertex = (model_matrix * vertex).xyz;

    vertex_to_light = light_position - world_vertex; //vector from vertex to light
    vertex_to_eye = eye - world_vertex; //vector from vertex to eye
    world_reflec = 2 * dot(vertex_to_light, normalize(world_normal.xyz)) * normalize(world_normal) - vertex_to_light; //reflection of vertex_to_light

    light_diffuse_intensity = dot(normalize(vertex_to_light), normalize(world_normal.xyz)); //computing angle between light and normal
    light_specular_intensity = dot(normalize(vertex_to_eye), normalize(world_reflec)); //computing angle between eye and reflection

    if (light_diffuse_intensity > 0){
        light_mod = light_diffuse_intensity;
        light_specular_intensity = pow(light_specular_intensity, 8.0);
    }
    else{
        light_specular_intensity = 0;
    }

    gl_FragColor = vec4(mix(color.rgb * light_diffuse_intensity, vec3(1.0,1.0,1.0), light_specular_intensity), 1.0);

}

```

As you can see from the screenshot below, in the first screen, where I look at the sphere from the direction of the light, the border of the sphere is white because of the specular effect. However if the shader were correct it should not look like that. It should be white only in the middle of the sphere.

In the second screen, I look at both the sphere and the source of the directional light (the yellow sun) and everything looks just fine.

I cannot find the error in my shader, could someone help please?

Thank you very much!

# Answer
> 2 votes
### One solution

Use an odd number in your power function (or some other function that keeps the sign of your previous specular intensity):

```
light_specular_intensity = pow(light_specular_intensity, 9.0);
light_specular_intensity = pow(light_specular_intensity, 7.0);

```

There may be other ways to perform the math such that you may still use an even power.

### The problem

Your power function is (mathemtically) creating a phantom light behind the ball, and that's the reflection you're seeing along the edge. For clarity, I've added some parenthesis to this line:

```
world_reflec = 2 *
    (
        dot(vertex_to_light, normalize(world_normal.xyz))
        * normalize(world_normal)
    )
    - vertex_to_light; //reflection of vertex_to_light

```

When the camera aligns with the light, for the pixels on the edge, `dot(vertex_to_light, world.normal.xyz)` will yield nearly zero. So the value of `world_reflec` will be rough equal to `-1 * vertex_to_light`. And because `vertex_to_eye` and `vertex_to_light` are nearly equal, that means that this line:

```
light_specular_intensity = dot(normalize(vertex_to_eye), normalize(world_reflec));

```

...will yield a value of `light_specular_intensity` of almost `-1`. And then this line:

```
// (light_diffuse_intensity > 0) == true
light_specular_intensity = pow(light_specular_intensity, 8.0);

```

...will strip off the negative and give you a value near `1`. That causes specular illumination.

---
Tags: opengl, shaders, glsl, lighting
---


# Question
Title: Direct3D11 + Assimp imported model corrupted/failed
I use Assimp library to import vertex and index data from model file.

I don't know how to correctly create index buffer from mFaces array of aiMesh. Or something wrong, because i my model is incorrect.

I have already experienced successful mesh rendering, if verticies and indicies are defined manually in code (x5 vertices triangle and indicies).

Here is my code.

```
// Loading TRIANGULATED vertex/index buffers:

// Load verticies:
m_uVertexCount = pMesh->mNumVertices;
CBasicEffect::sVertex * verticies = new CBasicEffect::sVertex[m_uVertexCount];
for(UINT i = 0; i < m_uVertexCount; i++)
{
    CBasicEffect::sVertex v;
    v.Pos = Vector3FromAi(pMesh->mVertices[i]);
    v.Color = XMFLOAT4(1,1,0,1);//test
    verticies[i] = v;
}

D3D11_BUFFER_DESC bd;
ZeroMemory( &bd, sizeof(bd) );
D3D11_SUBRESOURCE_DATA InitData;

// Create vertex buffer:
bd.Usage = D3D11_USAGE_DEFAULT;
bd.ByteWidth = sizeof( CBasicEffect::sVertex ) * m_uVertexCount;
bd.BindFlags = D3D11_BIND_VERTEX_BUFFER;
bd.CPUAccessFlags = 0;
InitData.pSysMem = verticies;
if( FAILED(pModelOf->GetDevice()->GetDevice()->CreateBuffer(&bd, &InitData, &m_pVertexBuffer)) )
    ;//...

// Load indicies:
m_uIndexCount = pMesh->mNumFaces * 3;
UINT* indices = new UINT[m_uIndexCount];
for (UINT face = 0; face < pMesh->mNumFaces; face++)
    for (UINT idx = 0; idx < 3; idx++)
        *indices++ = pMesh->mFaces[face].mIndices[idx];

// Create index buffer:
bd.Usage = D3D11_USAGE_DEFAULT;
bd.ByteWidth = sizeof( UINT ) * m_uIndexCount;
bd.BindFlags = D3D11_BIND_INDEX_BUFFER;
bd.CPUAccessFlags = 0;
InitData.pSysMem = &indices;
if( FAILED(pModelOf->GetDevice()->GetDevice()->CreateBuffer(&bd, &InitData, &m_pIndexBuffer)) )
    ;//...

```

**UPDATE:** Now i see my model. But it is loaded incorrecty: https://i.stack.imgur.com/Z9liR.jpg (originally it is scene with 5 primitives).

My render code:

```
// <Clean render target view and depth stencil view>

ID3D11Buffer* pVertexBuffer = pMesh->GetVerticiesBuffer();
    ID3D11Buffer* pIndexBuffer = pMesh->GetIndexesBuffer();

    // Set buffers and topology mode
    UINT stride = sizeof( sVertex ), offset = 0;
    m_pDevice->GetContext()->IASetVertexBuffers( 0, 1, &pVertexBuffer, &stride, &offset );
    m_pDevice->GetContext()->IASetIndexBuffer(pIndexBuffer, DXGI_FORMAT_R32_UINT, 0);
    m_pDevice->GetContext()->IASetPrimitiveTopology( D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST );

    // Shaders:
    m_pDevice->GetContext()->IASetInputLayout( m_pVertexLayout );
    m_pDevice->GetContext()->VSSetShader( m_pVertexShader, NULL, 0 );
    m_pDevice->GetContext()->VSSetConstantBuffers( 0, 1, &m_pConstantBuffer );
    m_pDevice->GetContext()->PSSetShader( m_pPixelShader, NULL, 0 );
    //m_pDevice->GetContext()->PSSetConstantBuffers( 0, 1, &m_pConstantBuffer );

    // Draw:
    //m_pDevice->GetContext()->Draw( pMesh->GetVertexCount(), 0 );
    m_pDevice->GetContext()->DrawIndexed( pMesh->GetIndexCount(), 0, 0 );

```

//

# Answer
Well i dont know how, but i have solved my problems and for now i can load and render my model (except i need to work on shaders now:P ). Probably my error was in import pre/post-process flags of assimp. Now they are:

```
    unsigned int processFlags =
aiProcess_CalcTangentSpace         | // calculate tangents and bitangents if possible
aiProcess_JoinIdenticalVertices    | // join identical vertices/ optimize indexing
//aiProcess_ValidateDataStructure  | // perform a full validation of the loader's output
aiProcess_Triangulate              | // Ensure all verticies are triangulated (each 3 vertices are triangle)
aiProcess_ConvertToLeftHanded      | // convert everything to D3D left handed space (by default right-handed, for OpenGL)
aiProcess_SortByPType              | // ?
aiProcess_ImproveCacheLocality     | // improve the cache locality of the output vertices
aiProcess_RemoveRedundantMaterials | // remove redundant materials
aiProcess_FindDegenerates          | // remove degenerated polygons from the import
aiProcess_FindInvalidData          | // detect invalid model data, such as invalid normal vectors
aiProcess_GenUVCoords              | // convert spherical, cylindrical, box and planar mapping to proper UVs
aiProcess_TransformUVCoords        | // preprocess UV transformations (scaling, translation ...)
aiProcess_FindInstances            | // search for instanced meshes and remove them by references to one master
aiProcess_LimitBoneWeights         | // limit bone weights to 4 per vertex
aiProcess_OptimizeMeshes           | // join small meshes, if possible;
aiProcess_SplitByBoneCount         | // split meshes with too many bones. Necessary for our (limited) hardware skinning shader
0;

```

Mesh (vertices, indices and normals) load code, with D3D11 buffers initialization:

```
// D3D buffer resources:
D3D11_BUFFER_DESC       buffDesc;   ZeroMemory( &buffDesc, sizeof(D3D11_BUFFER_DESC) );
D3D11_SUBRESOURCE_DATA  buffData;   ZeroMemory( &buffData, sizeof(D3D11_SUBRESOURCE_DATA) );
CDevice* pDevice = pModelOf->GetDevice();

// Create vertex array:
m_uVertexCount = mesh.mNumVertices;
sVertex * vertices = new sVertex[m_uVertexCount];
for(UINT v = 0; v < m_uVertexCount; v++)
{
    sVertex point;
    point.Position = AiToVector4(mesh.mVertices[v]);
    //point.Color = VectorSet4(1,0,0,1);
    point.Normal = AiToVector4(mesh.mNormals[v]);
    vertices[v] = point;
}

// Create D3D vertex buffer:
buffDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
buffDesc.Usage = D3D11_USAGE_DEFAULT;
buffDesc.ByteWidth = sizeof(sVertex) * m_uVertexCount;
buffData.pSysMem = vertices;
if( FAILED(pDevice->GetDevice()->CreateBuffer(&buffDesc, &buffData, &m_pVertexBuffer)) )
    throw new CException(ERR_DX, "Create vertex buffer failed.");

// Create index array:
m_uIndexCount = mesh.mNumFaces * 3;
UINT* indices = new UINT[m_uIndexCount];
for (UINT face = 0; face < mesh.mNumFaces; face++)
    for (UINT idx = 0; idx < 3; idx++)
        indices[face*3+idx] = mesh.mFaces[face].mIndices[idx];

// Create D3D index buffer:
buffDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;
buffDesc.Usage = D3D11_USAGE_DEFAULT;
buffDesc.ByteWidth = sizeof(UINT) * m_uIndexCount;
buffData.pSysMem = indices;
if( FAILED(pDevice->GetDevice()->CreateBuffer(&buffDesc, &buffData, &m_pIndexBuffer)) )
    throw new CException(ERR_DX, "Create index buffer failed.");

```
> 4 votes

---
Tags: c++, directx, directx11, assimp
---


title: Definition of graphics needed

text:
# Question
Title: Definition of graphics needed
It is not isometric, neither is it pure 2D. What is this graphics view called?

# Answer
If you don't consider it as simply *perspective* (ie if the view is actually *orthographic*) then it would be called an oblique projection. See this discussion on Ultima 7's perspective/projection.
> 1 votes

---
Tags: graphics
---


# Question
Title: How does level design work in 2D Java games with multiple levels?
I'm building a small platformer game with multiple levels, similar to old-school Mario, and I was wondering how devs created levels. This is my first game, so I'm pretty new to design & such. I've seen people use Paint.NET or Photoshop to create a level where certain colors in the world represent various tiles & such, that are rendered throughout the level. For instance, a red block in the world on a blue background would represent a tile that a player can jump on, and would be rendered so when the game is started. Is this an effective way of designing levels, or is there a better way? Please explain your process.

# Answer
> 0 votes
For such a task you create/use an level editor. In the editor you can do all sorts of things, place tiles, lace enemies, program/link/load scripts, set effects, ...

I actually don't know any standard 2d Level Editor.

Creating a Level Editor is no simple task but here are some hints how to get started:

* keep it for the beginning simple, use your cursor keys for navigation in the world and some other keys to set the tiletype of the currently selected position
* later you can create a "simple" GUI to choose stuff to insert / change

just keep it simple so you don't waste too much time if you decide to throw it away.

# Answer
> 0 votes
I have created a level editor for a 2d top-down rpg. The principles are exactly the same for a 2d side-scroller like mario.

Here is what I did.

I created an 4 arrays of numbers. Each array represents a layer and each number in the array represents a tile. A tile is simply a square chunk of pixels. The location of the number in the array represents the location on the screen the tile should be drawn to. So with an array of size \[10\]\[10\], setting \[5\]\[5\] to the number 1 would draw, let's say grass, to the center of the screen.

When you create your map editor, you'll want to display all the available tiles the user can use to paint the level. When a user selects a tile in the map editor there should be some indication that the tile has been selected and the tile should have a number associated with it.

When the user clicks somewhere on the screen, you detect which area he clicked on and send the tile's number to the array responsible for the layer he's drawing on. that way you fill each array with tile numbers so that when you render the map, you only need to iterate through each array and draw the tile based on the tile number and position in the array.

You'll need to determine how large you want your levels to be. For a sidescroller you'll want a very wide 2d array, maybe something like ground\[50\]\[500\] for the ground layer.

To implement layers, simply draw them in order. It may be something like ground, background, player sprite, foreground foreground2. The player sprite will then draw on top of the ground and background layers and the two foreground layers will cover the sprite.

---
Tags: java, level-design
---


# Question
Title: How to position two objects relative to each other
I am trying to make a modular vehicle editor similar to Kerbal Space Program. The user selects an initial vehicle part which is spawned in the center of the "work area". To add another part to the initial one, the user clicks and drags a part from a list onto the "work area" and then drags that part towards the initial one. When a node on the new part is close enough to a node on the initial part, the new part snaps onto the initial one. The user can then click to confirm the connection or drag it somewhere else. For a visual example.

The spawning of the parts I have no problem with.

For moving the parts in the environment I have an invisible plane that is parallel to the camera and rotates to always face the camera. I then draw a ray from the mouse to the plane and update the parts position to the location where the ray hits the plane.

When the new part is in the correct position I will add I make it the child object of the part I want to connect it to.

The problem occurs with positioning the new part relative to the part I want to attach it to. I'd like to make it like Kerbal Space Program where when the connecting node of the new part is within range of the connecting node of the part I'm attaching to, the new part's position snaps to the part I'm attaching to.

# Answer
> 1 votes
If your nodes are placed on the edges of your objects, that makes this a little easier. It's simple vector math for aligning the two objects.

You have two points, `A` and `B`. These points are the positions of your nodes, or points on the edges you want to snap together.

Simply calculate the difference in them. This difference is the amount you want to move your part so that `A` and `B` are the same point.

As you can see in the image above, the yellow line is the distance between the points and the red line is the amount you need to move the dark grey part to align them. These are the same lines.

---
Tags: unity
---


title: Textures not rendering with VBOs

text:
# Question
Title: Textures not rendering with VBOs
After having used display lists for my programs since I started learning OpenGL, I've finally decided to switch to VBOs after experiencing a considerable amount of lag when I started work on a new game. I've nearly finished with my transition, but I'm still having a bit of trouble with rendering the textures to the screen. The way I'm working it is this: I have several sprites of the same dimensions for each type of "block" in the game (it's a Terraria port) which are loaded into the game via a convenience method, then after they're all loaded, they're compiled into a virtual texture atlas via Graphics2D, converted to a Slick texture, and their relative coordinates are saved to a HashMap. However, when it comes time to grab the textures out of the HashMap and render them, the game simply doesn't. Here's part of my code for adding a block to the VBO (this is executed 4 times per block, once for each corner):

```
// top left
// vertex
values.add(Float.valueOf((float)b.getLocation().getPixelX()));
values.add(Float.valueOf((float)b.getLocation().getPixelY()));
// light
values.add(Float.valueOf((float)b.getLightLevel() / 15));
values.add(Float.valueOf((float)b.getLightLevel() / 15));
values.add(Float.valueOf((float)b.getLightLevel() / 15));
// texture
values.add(tX);
values.add(tY);

```

(Note: *values* is a list which is later converted to an array.) Then comes my code for rendering the VBO:

```
public static void render(){
    glPushMatrix();
    glTranslatef(MineFlat.xOffset, MineFlat.yOffset, 0);
    glBindTexture(GL_TEXTURE_2D, BlockUtil.atlas.getTextureID());
    glVertexPointer(2, GL_FLOAT, 28, 0);
    glColorPointer(3, GL_FLOAT, 28, 8);
    glTexCoordPointer(2, GL_FLOAT, 28, 20);
    glDrawArrays(GL_QUADS, 0, vertexArray.length / 7);
    glBindTexture(GL_TEXTURE_2D, 0);
    glPopMatrix();
}

```

The blocks are properly rendered with the correct lighting, but they lack any sort of texture. Any suggestions as to how to get the code working? I apologize if the answer is obvious, but I still consider myself a bit of an OpenGL noob, especially in the area of VBOs.

One last thing; I should mention that I'm not using any shaders in my current game.

EDIT: I seem to be a bit mistaken. Upon experimenting with the code by manually setting all texture coords, I discovered that the game simply converts the texture to a uniform color by averaging the RGB value of all pixels. I didn't recognize this before because the color of most blocks is grey. I recall having this problem before with display lists, but that was quite a while ago, and so I don't remember how I resolved it.

SECOND EDIT: Screenshots of the expected and actual result, respectively: https://i.stack.imgur.com/3t4r4.png https://i.stack.imgur.com/edv8v.png

# Answer
> 1 votes
I figured out my problem myself, and found it was due to a very simple mistake: I added a red pixel to the top left corner of one texture, and discovered it was the only one being rendered. I got the idea from this thread. It's because I forgot to cast the image width to a float, so when divided by 16, it would yield zero.

---
Tags: opengl, java, lwjgl, vbo
---


title: Tile based map player movement

text:
# Question
Title: Tile based map player movement
I'm doing a tile based 2d rpg in pygame. The problem I'm working on right now is character movement... I am already able to create a map by using multidimensional arrays and a 'camera' follows the player. My problem is now the collision detection... The player should only move one tile at the time so I can easily get his position in tile coordinates and check if he's collided. But I don't know how to do that! At the moment, if a key is pressed, the player moves four pixels in a direction every frame. But that makes tile based collision detection nearly impossible. The player has the size of one tile and yeah, my question is, how can I make the player move only one tile (but NOT every frame since then he would move 32 pixels every single frame.) I know this question was asked before : Pygame Tile Based Character movement speed but this wouldn't work for me, because you had to press the key EVERY TIME you want to move one tile. I use booleans so the player moves as long as the key is pressed.

# Answer
> 1 votes
To solve your problem check every frame if the button is pressed, if so increment the position.

To have the snapping effect you need to round down your position to tileX position like with this code `(int)(PosX/TileSizeX)`.

If your player can move backwards just decrement the position if the other button is pressed.

---
Tags: tiles, pygame
---