texts: Checking validation of entries in a Sudoku game written in Java

texts:
I'm building a simple Sudoku game in Java which is based on a matrix (an array[9][9]) and I need to validate my board state according to these rules:

all rows have 1-9 digits
all columns have 1-9 digits.
each 3x3 grid has 1-9 digits.

This function should be efficient as possible for example if first case is not valid I believe there's no need to check other cases and so on (correct me if I'm wrong).

When I tried doing this I had a conflict. Should I do one large for loop and inside check columns and row (in two other loops) or should I do each test separately and verify every case by it's own?

(Please don't suggest too advanced solutions with other class/object helpers.)

This is what I thought about:

Main validating function (which I want pretty clean):

public boolean testBoard() {

        boolean isBoardValid = false;

        if (validRows())
        {
            if (validColumns())
            {
                if (validCube())
                {
                    isBoardValid = true;
                }
            }
        }
        return isBoardValid;
}

Different methods to do the specific test such as:

private boolean validRows() {
        int rowsDigitsCount = 0;

        for (int num = 1; num <= 9; num++) {
            boolean foundDigit = false;

            for (int row = 0; (row < board.length) && (!foundDigit); row++) {
                for (int col = 0; col < board[row].length; col++) {
                    if (board[row][col] == num) {
                        rowsDigitsCount++;
                        foundDigit = true;
                        break;
                    }
                }
            }
        }

        return rowsDigitsCount == 9 ? true : false;
    }

I don't know if I should keep doing tests separately because it looks like I'm duplicating my code.


texts: Can I count all the allocated textures in D3D11?

texts: Is it somehow possible to get the count of all texture objects on a device?


texts: Direct3D 11: Changing fullscreen resolution does not work

texts:
In my application I can switch back and forth between windowed and fullscreen mode using IDXGISwapChain::SetFullscreenState. When the WM_SIZE is handled, IDXGISwapChain::ResizeBuffers is called in response. This works fine and when entering fullscreen mode DXGI chooses the desktop resolution.

The problem comes when I'm trying to change resolution while remaining in fullscreen. I try to change resolution by using IDXGISwapChain::ResizeTarget. The mode description I'm trying to switch to is aquired by using IDXGIOutput::GetDisplayModeList, so it should be valid. When doing the resize I get the usual blinking that happens when I enter fullscreen, but nothing has changed; the resolution is still the same and there's no WM_SIZE message being generated like in Choosing the DXGI Output and Size.

DXGI best practices also contains alot of information but it didn't help me.

I am using the DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH flag when creating the swap chain and I have also tried using IDXGIFactory::MakeWindowAssociation with the DXGI_MWA_NO_WINDOW_CHANGES and DXGI_MWA_NO_ALT_ENTER flags to no avail.

If I hardcode the swap chain to be created in fullscreen mode using a low resolution I can see the mouse cursor being jagged and larger, and this visual difference is not present when changing resolution.

Am I possibly getting the concepts wrong here? Am I supposed to get a WM_SIZE message after calling ResizeTarget? How are the display mode and back buffer related? I know that when the front buffer size is changed the back buffer should be resized to match in order to do flips instead of blits according to the links, which is why it's recommended to do the resize when the application gets the WM_SIZE message.

In a few of the similar questions I've found there are discussions about it maybe being a bug, but they all just died out with no final answer.

EDIT:
I just tried to manually call OnResize (my method actually calling ResizeBuffers and so forth) after I attempt to change resolution and the following warning shows up in the debugger (not visible before):

  DXGI WARNING: IDXGISwapChain::Present: Fullscreen presentation inefficiencies incurred due to application not using IDXGISwapChain::ResizeBuffers appropriately, specifying a DXGI_MODE_DESC not available in IDXGIOutput::GetDisplayModeList, or not using DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH.DXGI_SWAP_CHAIN_DESC::BufferDesc = { 800, 600, { 60, 1 }, R8G8B8A8_UNORM_SRGB, 0, 0 }; DXGI_SWAP_CHAIN_DESC::SampleDesc = { 1, 0 }; DXGI_SWAP_CHAIN_DESC::Flags = 0; [ MISCELLANEOUS WARNING #98: ]

The new resolution (800x600) seems to be set, but note that the Flags member is 0. Shouldn't it be 0x2? Could that be the reason the resolution doesn't have any effect? The flag is set in the swap chain description right before the swap chain is created so I don't understand how it's changed to 0.

EDIT 2:
In a tiny remark at the bottom of the DXGI_SWAP_CHAIN_FLAG documentation it says that ResizeBuffers can reset or change the flags. I took a look at my code and there it was: flag was set to zero (reading my book I must have accepted it as reusing the old flag or something). I changed it to allow mode switch and voilá, resolution changed and I got my WM_SIZE. I did however get a couple of warnings about presentation inefficiencies but that was expected, and I have plans on how to fix those.


texts: What are the typical day-to-day tasks of an entry level games programmer?

texts:
What I would like to know is: What are the daily duties of a graduate programmer in the games industry workplace? Is it mostly coding, analysing, designing, or what?

Thank you.

P.S. I am in my second year of University at the moment and am working towards specialising in games programming, specifically gameplay, tools or UI programming.


texts: How do I multiply pixels on an SDL Surface?

texts:
Okay so I'm able to put blank pixels into a surface and also draw gradient pixels rectangles,etc

But I don't know how to multiply the pixels on a surface so I was hoping someone could provide me information on this topic.

I was thinking you could get the members pixel and then * it by 2 but that didn't provide results I wanted so I'm now thinking that you have to actually get to the position in bytes in one location to the left and one location to the right and then store it in memory and then * that by 2 am I correct or what?

If so what is it that allows me to do that and how do I do that?

For those who want an explanation I need a PNG Loaded on an SDL Surface to be bigger in size through code rather then image sequence.

for example I alter the pixels on the surface in such a way to make the pixels multiply increasing the size of the png and the SDL Surface.


texts:
I wanted to create a portal.
This portal looks like a semi-transparent texture rotating on a cylinder:

At first I created such a portal using a Particle System.

Then I realized that this might be an overkill and built another portal the following way:

I put a cylinder in the scene, put the texture on it and added a script that would rotate the cylinder.

The visual result of the 2 approaches (Particle System vs. Mesh approach) is perfectly the same.

Now I wanted to test which one performs better.

Am I right to assume that I should write a script which creates 10.000 portals of type A or B in the scene and have a look at some statistics (not sure yet which / where to find them), or is there anything more convinient to test performance?

Thank you!


texts: how to handle interactive choice in the middle of the game loop?

texts:
I am programming a turn-based game, 2D tile-based, overhead view.
I have an update function and a render function running in separate threads.
When it's the player's turn, the player can e.g.

select a target tile from the map
then a popup menu with the available interactions appears
player selects interaction and the interaction gets executed

One tedious way is the following:

GameLoopUpdate():
        switch( interaction_state )
            case tile_selected:
                lookup_interactions_for_selected_tile()
                break
            case tile_and_interaction_selected()
                execute_interaction_at_tile()
                break
             default:
                break

Of course the above does not scale when the interactions get complex.

Conceptually, I would like it to be more like:

KeyListener():
    if tile is clicked
        set_tile_selected()

GameLoopUpdate():
    if tile is selected:
        interaction  = spawn_thread_interaction_selection()
        execute_interaction_at_tile( interaction )

where the spawned thread would somehow override the input listeners AND the rendering. But this looks bad as well.

Another idea (I'm starting to consider implementing this) is the following:

GameLoopUpdate():
    if it's player's turn
        set next state as PlayerState_Base
    else
        run ai turn

PlayerState_Base():
    if tile is selected
        set next state as PlayerState_TileSelected

PlayerState_TileSelected():
    if interaction is selected
        execute interaction
        set player's turn as done

where each state above would have dedicated key listener and rendering functions

Any other ideas?


texts: Generating normals from terrain heightmap

texts:
I am drawing my terrain by rendering a static quad mesh several times and then displacing vertices using a heightmap.
As such I need to generate normals. I am primarily interested in quality over speed.

What is the best way to do this? Precompute a normal-map and sample it in the pixel shader? Or generate them in the vertex shader somehow?


texts: How do I move a body using the hardware accelerometer?

texts: I want to move the ball as I move the device but I can not able to find how to use accelerometer in libGDX. I know that Gdx.input.getAccelerometerX() returns x coordinate but I don't know how to apply it to the body I have created.


texts: How do I wrap my web browser game as a standalone for Steam?

texts:
I've got a PHP/Java based game, which runs in the browser. However, I want to submit this game to Steam.

Now Steam doesn't allow web-based games unless they come in some kind of wrapper.

How can I package my web broswer game so that I could distribute it through Steam?


texts: In a MovementComponent, where should I initialize member variables?

texts:
I have a MovementComponent derived from CharacterMovementComponent

MovementComponent, attached to a Character, needs a reference to GrappleComponent, stored on the Character.

Where do I perform the GetComponentByClass call to obtain this reference to the GrappleComponent?

If this is the constructor, could I please have some information on how to override the constructor?


texts: Want to create live-voice chat between players either in unity or unreal engine

texts: I would like to create a real-time voice chat in either in unreal or unity between the players.I would like to associate and apply this voice-chat depend on username. I am saying "or" for the application because I want it to create in easiest(less programming) way. Do you know what class or script I should use? I have a limited budget so I am looking for a in-house or cheap way solution of building it.What would be the easiest way of starting this project?


texts:
I am trying to implement a sprite of 8 columns and 8 rows in OpenGL ES 2.0
I made appear the first imagen but I cant figure out how to translate the Texture matrix in OpenGL ES 2.0 , the equivalent of the code in OpenGL 1.0 that I am looking is

        gl.glMatrixMode(GL10.GL_TEXTURE);
        gl.glLoadIdentity();
        gl.glPushMatrix();
        gl.glTranslatef(0.0f, 0.2f, 0f);
        gl.glPopMatrix();

This are the matrix that I am using atm

/**
 * Store the model matrix. This matrix is used to move models from object space (where each model can be thought
 * of being located at the center of the universe) to world space.
 */
private float[] mModelMatrix = new float[16];

/**
 * Store the view matrix. This can be thought of as our camera. This matrix transforms world space to eye space;
 * it positions things relative to our eye.
 */
private float[] mViewMatrix = new float[16];

/** Store the projection matrix. This is used to project the scene onto a 2D viewport. */
private float[] mProjectionMatrix = new float[16];

/** Allocate storage for the final combined matrix. This will be passed into the shader program. */
private float[] mMVPMatrix = new float[16];

/**
 * Stores a copy of the model matrix specifically for the light position.
 */
private float[] mLightModelMatrix = new float[16];


texts: Map individual images to the surface of a sphere

texts:
I know this is a FAQ but I don't know the terms to search on. I even saw something like this with a blue globe, but now I can't find it any more!

I'm trying to make a UV map to apply to a sphere (in SceneKit, so one big image).

The map is made up of multiple photos taken with the camera pointed in different directions. You could imagine taking a series of polaroids, putting a dot of glue in the center of each one, and then sticking it to the outside of a basketball. Compare and contrast with using paper mache, which would plaster the surface smoothly - in this case it's all bumps and gaps, but that's what I want.

It's easy enough to composite each image into a single 2D map. However, when you apply that to the sphere, all the formerly linear edges end up convex - barrel distortion. I need to transform each one (to be concave) before I composite them, so that when they are applied to the sphere they return to being rectangles as seen from the center.

So... assuming I have a collection of images, the FOV angle of the camera, and the alt/az orientation when they were taken, what's the trick for mapping them into a proper UV texture to recreate the "bumpy ball" with nice linear edges?


texts: Obstacle Avoidance or Wall Avoidance for Tiles ?

texts:
I have a enemy in my game that is supposed to chase the player around the world and I thought it be a good idea for the enemy not to pass through the walls like a ghost, the levels are tile based, I've initially gone with the wall avoidance since a tile is essentially four lines, but I'm beginning second guessing the idea.

So should I go with Wall Avoidance Steering Behavior or Obstacle Avoidance Behavior ?


texts: How can I create lit-up areas during night-time in a top-down 2D game?

texts:
I am trying to implement a super simple day/night cycle. It works fine, at 9pm it gets dark, and at 6am it gets bright.

However, I am "creating" darkness by simply setting the alpha of a black Image that covers the entire screen, ie:

if(NightTime){
    Color tempColor = dayNightImg.color;
    tempColor.a = 0.5f;
    dayNightImg.color = tempColor;
    isDark = true;
}

So, in order to create the Illusion of light, I would have to be able to ignore part of this Dark Image, i.e "Light it up", for example in a circle around my character. Is there some way I can do this? Or Is my approach too simple for this effect?

Here is an example of what I want:


texts: If an object is attached to another one and you need to set its position, rotation and scale in global space, what do you do to get the local versions of these values, knowing the same values for the "parent" object?


texts: Can you decompose a rotation into a rotation around an axis and a quaternion?

texts:
I have a rotation represented by a quaternion and I want to get a rotation angle around the forward axis together with another quaternion which will together represent the original rotation.

The reason for this is that I am interpolating the rotation along a path and I want to be able to interpolate the rotation around the path in such a way that it does not have any discontinuities or sudden flips.


texts:
Apparently textButton.setScale() is not working. Even when the scale is set to 0.1, the button is displayed in it's original size.

How to properly scale a TextButton in LibGdx? The official documentation doesn't provide any details.


texts: Is it possible for automated testing applied to Angry bird

texts:
In simple case, just the first release of Angry Bird is OK

I am thinking if the testers can automated to find out all possible routes ( removing those shooting back) to get the marks stats (and also fix hidden bugs)

thx, though this may be a very simple question here


texts:
I'm trying to find a way to design a game server architecture for a real time mobile game. The design should be cost effective but still to some extend scaleable (later on).

Mobile client flow:

Connects to a distributor server which was given by DNS LB and gets grouped with x players. If y players are reached, the distributor server needs to contact a control server, which starts or uses a already running game server. The control server sends back the ip and port to the distributor server which then sends it to the grouped players.
The players then connect to the given game server. After the game the players will be send together to a new or same distributor server.

I wonder how the real server (VMs) for the game servers can be managed in a dynamic matter.
I have looked at AWS EC2 instances, but if we have 500 players with 6 players per group that play 6 hours per day, we would need ~84 EC2 t3.small (2 vCPU, 2GiB RAM) instances running. This will cost ~1,160.00 USD monthly. With this price it would be favorable to have real VMs and not dynamic cloud instances I guess?

Explanation of the components

Distributor:

Mobile clients will connect to these to get grouped with other players. It's like a lobby where players will sit until X players are reached or eg. a countdown ran out.

Control Server:

Need to take care of started server (VMs) and handle game server start requests from the distributors.

Game Server:

Is an authoritive like server client with physics etc. One game server (software) for X players in a group. Players will connect to these from the distributor after the lobby "phase".

Question:

How can this be dynamic scaleable/cost effective and is this a useable architecture?
I see one problem with the control server because it must take care of N game server vms and N distributors. But if we scale the control server, then every control server needs to know the same as every other.

(If anything is missing or can be improved, please let me know. English is not my native language so it's a bit challenging to express my goal in such a complicated topic like this)


texts:
I know that there's always a big debate on the handedness of 3D coordinate systems, but I can't seem to find any information about the handedness of 2D coordinate systems.

Usually, the X axis points to the right, but the Y axis can point up (in the case of many game engines) or down (in the case of screen coordinates and in Godot). What are the standards for these?

Which one of those is "left-handed" and which one is "right-handed"?
Are rotations always clockwise? Counter-clockwise? From X to Y? From Y to X?


texts: How to adjust position relative to resolutions?

texts: I have a lot of objects on the screen and would like at different resolutions, object's positions rendered correctly on the screen irrespective of the resolution. Is it correct to multiply the position by aspect ratio ?


texts: Can I use "Creative Comons BY-NC" licences music in my Freemium game?

texts:
According to creativecommons.org, a CC BY-NC license stands for

a creative commons license that prohibits you to use the material in "Commercial Purposes"

...and for the Commercial Purposes they have defined it in this way:

A commercial use is one primarily intended for commercial advantage or monetary compensation.
(emphasis mine)

As Freemium games can be played without spending even a penny, and the in-app purchases are only meant to accelerate the process, is this game still intended as a Commercial project with the definition given above, and thus should I ignore using such music?
My interpretation is that my use the song is not intended for a commercial purpose.


texts: Cannot import an .svg into a Unity project

texts:
I cannot import an .svg into a Unity project.

When I just move the .svg file into the Unity project Unity does not work with it and the only option Unity provides is to open the file (in my case it proposes me to open the .svg with Inkscape).

After performing a little bit of research I come to a conclusion that I need to have an SVG Package being installed into the Unity in order to import the .svg files.

But when I try to install the package I do not find it in the list of packages.

I am using a free Personal Edition of Unity. So, may it be that the option to import .svg is for paid version of Unity only?

Thank you.

Yes, it really seems that importing an .svg into Unity is only a paid feature. So, does anyone know about a way to import an .svg into Unity for free? For instance, are there other packages which help to accomplish this?

I do not see the needed package in the list of packages for preview:


texts: XNA C#: How can I prevent blurring when drawing from a RenderTarget2D?

texts:
I'm making a game and I want the end graphics to look chunky and pixellated, so I'm drawing from the spritebatch onto a RenderTarget2D which is 1/4th the size of the actual backbuffer, and then drawing from that to the backbuffer.

At first the sprites were blurred by antialiasing and I read that using SamplerState.PointWrap in the spritebatch Begin call would ease this a bit so I made that change. Everything seemed better, however the final on-screen image is still blurry and I think this is because of how it draws from the rendertarget2D to the backbuffer.

The image here is a comparison - On the left is how the output looks now and the right is how I want it to look.


texts: How to get the Exact Collision Point and ignore the collision (from 2 "ghost bodies")

texts:
I have a very basic problem with Box2D.

For a arenatype game where you can throw scriptable "missiles" at other players I decided to use Box2D for the collision detection between the players and the missiles. Players and missiles have their own circular shape with a specific size (varying). But I don´t want to use dynamic bodies because the missiles need to move themselve in any way they want to (defined in the script) and shouldnt be resolved unless the script wants it.
The behavior I look for is as following (for each time step):

velocity of missiles is set by the specific missile script
each missile is moved according to that velocity
if a collision accurs now, I want to get the exact position of impact, and now I need a mechanism to decide if the missile should just ignore the collision (for example collision between two fireballs which shouldnt interact) or take it (so they are resolved and dont overlap anymore)

So is there a way in Box2D to create Ghost bodies and listen to collisions from them, then deciding if they should ignore the collision or should take them and resolve their position? I hope I was clear enough and would be happy about any help!


texts: How do I load a model through AssimpNet into Monogame?

texts:
I am new to MonoGame and to 3d and I'm stuck on how to import a model. It seems the best way to import a mesh model and 3d animations in Monogame in Windows 8 is through AssimpNet. I can't find a basic-level tutorial on this.

I am looking for code to import in a format Blender supports (DAE, OBJ, 3DS), view the imported mesh and perform something basic like a camera rotation around it.

Is there a way to load data imported through AssimpNet into the Model object in Monogame?


texts: Box collider has different behavior in 2 clients

texts:
I'm new to Unity.
I am making my first Game and faced with problem.
I have a plane and 4 gameobject that has box collider surrounded this plane. there are a few spheres as players inside of the plane.I built the game.
I run 2 instances of the game and add force to a sphere and send this force to other client through node server. But border reflection angle differs in 2 clients. I checked value of the force in 2 clients and that is the same.
Any help would be appreciated.


texts: Weird blue shine on URP Lit shader Unity

texts: I recently started to use URP and I am noticing a weird blue like tint on shiny objects that use the URP/lot shader and I can't understand what it is and how can i remove it.


texts: How to create shockwave of objects in other shapes than circle?

texts:
Basically, I'm making a bullethell / I wanna be the guy inspired game for where I'm currently creating different methods of spawning bullets into the game. One of the few methods I've created is creating a shockwave of bullets with defined number of bullets in a circular shape. The method works excellently with a for-loop and is very simple to use.

for (double angle = (0 + rotation); angle < (Math.PI * 2 + rotation); angle += Math.PI / (numberOfBullets / 2))
{
     Bullet nextBullet = new Bullet(bulletDef, position, speed, acceleration, rotation, texturePriority, color, bulletID);
     nextBullet.speed.X = (float)Math.Cos(angle) * speed.X;
     nextBullet.speed.Y = (float)Math.Sin(angle) * speed.Y;
     nextBullet.acceleration.X = (float)Math.Cos(angle) * acceleration.X;
     nextBullet.acceleration.Y = (float)Math.Sin(angle) * acceleration.Y;
     nextBullet.position = position;
     nextBullet.isRemoved = false;
     Data.tempEntities.Add(nextBullet);
}

However, I wanted to extend this method a little further with the ability of creating shockwaves in other shapes, like Triangle, Square, Pentagon and Hexagon. I however have no specific idea of how to set this up with a for-loop.

The only lead I have so far of what I could do is calculate the amount of sides each shape have (they're all going to be equilateral as having differently long sides would be a waste of time to program) so we'll take a Triangle for example; has 3 sides. We'll decide that this triangular shockwave will shoot 6 bullets so we'll define what the first two bullets speed will be with these (probably wrongly written code).

int calculateBullets = (numberOfBullets / 3);
int divider = numberOfBullets % calculateBullets;

I tried using this in a for-loop, but it gave me OutOfMemory error without any explaination of what I did that was wrong. What would be the best way to approach this predicament? Should I still use a for-loop and how will I need to set it up? Or should I attempt to use something else?


texts: Combining pathfinding with global AI objectives

texts:
I'm making a turn-based strategy game using Java and LibGDX. Now I want to code the AI.

I haven't written the AI code yet. I've simply designed it. The AI will have two components, one focused in tactics and resource management (create troops, determine who have strategical advantage, detect important objectives, etc) and a individual component, focused in assign the work to each unit, examine its possibilites and move the unit.

Now I'm facing an important problem. The map where the action take place is a grid-based map. Each terrain has different movement cost. I read about pathfinding and I think A* is a very good option to determine a good route between two points.
However, imagine I have an unit with movement = 5 (i.e, it can move 5 tiles of movement cost = 1). My tactical AI has found an objective at a distance d = 20 tiles (Manhattan distance) from my unit.

My problem is the following: the unit won't be able to reach the objective in one turn. So the AI will have to store a list of position and execute them in various turns. I don't know how to solve this.

PS. In my unit code, I have a list called selectionMarks which stores all the possible places where the unit can go in this turn. This places are calculated recursively using a getSelectionMarks function.


texts: Exponential Variance Shadow Mapping - implementation

texts:
I use a variance shadow mapping with a "standard" light bleeding fix in my graphics engine which is based on deferred rendering.. I have a single shadow map for a directional light beacause a test scene is relatively small. Saving depth looks like this:

float moment1 = gl_FragCoord.z;
float moment2 = moment1 * moment1;
outColor = vec2(moment1, moment2);

Then I perform a separable gaussian blur on that texture.

Shadow test:

float Chebyshev(vec2 moments, float mean, float minVariance)
{
    float shadow = 1.0f;
    if(mean <= moments.x)
    {
        shadow = 1.0f;
        return shadow;
    }
    else
    {
        float variance = moments.y - (moments.x * moments.x);
        variance = max(variance, minVariance);
        float d = mean - moments.x;
        shadow = variance / (variance + (d * d));
        float amount = 0.3f;
        shadow =  clamp((shadow - amount) / (1.0f - amount), 0.0f, 1.0f); // standard light bleeding fix
        return shadow;
    }
}

vec4 shadowCoord = shadowMatrix * vec4(viewSpacePosition, 1.0f);
vec2 moments = texture(ShadowMap, shadowCoord.xy).xy;
float minVariance = 0.000001f;
float shadow = Chebyshev(moments, shadowCoord.z, minVariance);

I found a interesting technique - Exponential Variance Shadow Mapping which should provides better light bleeding fix. Here is saving depth for that technique:

float positiveExponent = 40.0f;
float negativeExponent = 5.0f
float depth = gl_FragCoord.z;
vec2 exponents = vec2(positiveExponent, negativeExponent);
depth = 2.0f * depth - 1.0f;
float pos = exp(exponents.x * depth);
float neg = -exp(-exponents.y * depth);
vec2 warpDepth = (pos, neg);
outColor = vec4(warpDepth, warpDepth * warpDepth);

How to implement a shadow test for that technique ? Here is my attempt:

float positiveExponent = 40.0f;
float negativeExponent = 5.0f;
vec2 exponents = vec2(positiveExponent, negativeExponent);

vec2 warpDepth(float depth)
{
    depth = 2.0f * depth - 1.0f;
    float pos = exp(exponents.x * depth);
    float neg = -exp(-exponents.y * depth);
    vec2 wDepth = vec2(pos, neg);
    return wDepth;
}

float Chebyshev(vec2 moments, float mean, float minVariance)
{
    float shadow = 1.0f;
    if(mean <= moments.x)
    {
        shadow = 1.0f;
        return shadow;
    }
    else
    {
        float variance = moments.y - (moments.x * moments.x);
        variance = max(variance, minVariance);
        float d = mean - moments.x;
        shadow = variance / (variance + (d * d));
        return shadow;
    }
}

vec4 shadowCoord = shadowMatrix * vec4(viewSpacePosition, 1.0f);
vec4 moments = texture(ShadowMap, shadowCoord.xy).xyzw;
vec2 posMoments = vec2(moments.x, moments.z);
vec2 negMoments = vec2(moments.y, moments.w);
vec2 wDepth = warpDepth(shadowCoord.z);
//float minVariance = 0.000001f;
//Edit
vec2 depthScale = 0.0001f * exponents * wDepth;
vec2 minVariance = depthScale * depthScale;
float posResult = Chebyshev(posMoments, wDepth.x, minVariance.x);
float negResult = Chebyshev(negMoments, wDepth.y, minVariance.y);
shadow = min(posResult, negResult);

Unfortunately it doesn't remove light bleeding. Did I do something wrong ? Maybe I should calculate two different minVariance based on the positive and negative exponents ?

Edit1:
Calculating minVariance this way:

vec2 depthScale = 0.0001f * exponents * wDepth;
vec2 minVariance = depthScale * depthScale;
float posResult = Chebyshev(posMoments, wDepth.x, minVariance.x);
float negResult = Chebyshev(negMoments, wDepth.y, minVariance.y);

gives better results but light bleeding is still quite visible.

Edit2:
Light bleeding:
EVSM with minVariance which is calculated as above gives better result than VSM without standard light bleeding fix, but to get the best result I also use standard light bleeding fix with EVSM. A light bleeding fix is performed in Chebyshev function but maybe I should add it after following calculation: shadow = min(posResult, negResult) ?

EVSM causes small artifacts on the illuminated side of the objects so I add some glPolygonOffset when saving EVSM depth.


texts: When accessing components, is it better to do so in a script or to create a reference to them in the inspector?

texts:
I am accessing the variable of one script from within another and I noticed there are multiple ways to do this, but two that are very similar.  The first is to simply find the game object and reference it within the other script like so:

void Start(){
    private int bye = 1;
    GameObject player = GameObject.Find("Meh");
    Test2 externalScript = player.GetComponent<Test2>();
    externalScript.hello *= bye;
    Debug.Log(externalScript.hello);
}

The other way is to create a global instance of the object the script is attached to and reference it within the inspector, like so:

private int bye = 1;
public GameObject player;
void Start(){
    Test2 externalScript = player.GetComponent<Test2>();
    externalScript.hello *= bye;
    Debug.Log(externalScript.hello);
}

Which way would be best in terms of performance and practice?  Would one way be better than the other when it comes to larger games and/or scripts?


texts: GL.BlendFuncSeparate(ArbDrawBuffersBlend) Enum has no members?

texts:
I want to use the function GL.BlendFuncSeparate but it seems that one of the enums used has no members.

    public enum ArbDrawBuffersBlend
    {

    }

Is there another function to call or is this a bug?


texts:
Hello i have been working on a part of my plugin that has waypoints allowing the user to create delete etc. I got to thinking after using and seeing a couple of the disguse plugins. That maybe i could create a command toggle that would show the user where the waypoints they have are! I know how to do all of this i just have no idea how to display a nameplate to the client. I know its possible because disguisecraft does it i tried looking though their code but couldent find much...

I belive to get this effect i need to send packets to the client if someone can direct me to a list of bukkit packets or even a solution to sending the client a custom located nameplate that would be fantastic! Thanks in advanced.


texts: Stop animation after definite time Libgdx

texts:
There is a button TextButton, there is also an animation spinAnimation. Neither can I understand how to implement the "fading animation" (i.e. when the button is clicked, the animation started, and gradually, after a certain time, stopped). Code Example:

@Override
public void create(){

textureAtlas = new TextureAtlas("pack.atlas");
stage = new Stage(new ScreenViewport());
sb = new SpriteBatch();

 final TextButton button = new TextButton("Start",skin , "default");
        button.setWidth(220);
        button.setHeight(50);

  button.addListener(new ClickListener(){
            @Override
            public void clicked(InputEvent event, float x, float y) {
                spinAnimation.setFrameDuration(0.5f);
                int i = 0;

            }
        });

    stage.addActor(button);

           Gdx.input.setInputProcessor(stage);
    }

@Override
   public void render() {

   elepsedTime += Gdx.graphics.getDeltaTime();
   Gdx.gl.glClearColor(0,0,0,1);
   Gdx.gl.glClear(com.badlogic.gdx.graphics.GL20.GL_COLOR_BUFFER_BIT);

   sb.begin();
   stage.act(Gdx.graphics.getDeltaTime());
   sb.draw(spinAnimation.getKeyFrame(elepsedTime,true), 50,  60

   sb.end();
   stage.draw();
    }


texts: GLFW window becomes unresponsive when asking for input!

texts: I am trying to write a simple C++ game using OpenGL. In my render loop i ask for text based input from the user but this causes the GLFW window to become unresponsive. I suspect that this happens because the window does not like it when the main thread is paused from std::cin so it behaves weirdly. If i remove the input prompt the window behaves perfectly. Can someone confirm if this is the case and what workarounds are there to fix it?


texts: Are there drawbacks to resizing mesh renderer bounds?

texts:
I had a problem yesterday where some of the meshes were not visible. I figured out the problem, which was that the mesh renderer bounds were not in the cameras field of view.
So, in order to make the mashes visible, I'm thinking of either making the bounds of the mesh renderer larger, or moving them forward so they are in the camera view.
If I do this, are there any drawbacks, like potential glitches, problems, more strain on the system, etc that might happen?


texts: 16-byte aligned matrix in DirectX9 and D3DX with Havok Physics 2012

texts:
I want to ask a question about D3DXMATRIX and D3DXMATRIXA16, and how to use them with Havok Physics.

I'm using Visual Studio 2012 on Windows 8.

I successfully created an instance of hkpWorld, added an hkpRigidbody instance with hkpSphereShape.

The class representing the sphere object has:

hkpRigidBody m_RigidBody;  // Rigidbody
D3DXMATRIX m_Transform;    // Rendering matrix

Judging from the values of m_RigidBody->getPosition(), the simulation is running without problem.
So now obviously I want to render the sphere according to its position and orientation calculated by havok.

This is how I tried to extract the matrix for rendering:

const hkTransform& t = m_RigidBody->getTransform();
t.get4x4ColumnMajor(&m_Transform._11);

Then I happily ran the program, which would break in get4x4ColumnMajor and give me this message through my error report function:

  C:\NightlyJobs\09-07-Sun-01\Source\Common/Base/Math/Vector/Sse/hkSseVector4.inl(
  1831): [0x64211C2F] Assert: pointer must be aligned for SIMD.

I took this to mean that the matrix had to be 16-byte aligned, so I changed

D3DXMATRIX m_Transform;

to

D3DXMATRIXA16 m_Transform;

This time, the problem is still there but isn't 100% reproducible.
Sometimes it runs without problem, sometimes get4x4ColumnMajor fails with above message.

Changing the matrix declaration to

_declspec(align(16)) D3DXMATRIX m_Transform;

did not help either.

So, to summarize my question:

How would I go about extracting the matrix suitable for rendering with DirectX9?
Why do D3DXMATRIXA16 and _declspec(align(16)) seem to be inconsistent about being 16-byte aligned or not, every time I run the program ?


texts:
I hope that I'm posting this correctly as I'm new to the site, feel free to correct me if I'm in the wrong spot.

As for my issue:
I'm working on an 2D side-scrolling platformer game in libGDX, and I've run into an issue that I've considered before but never received a solid answer. Here's an example of what I'm wondering about:
In games like, say, the Legend of Zelda, when the player steps on a switch, or catches a torch on fire, this can open a door or release a monster or cause a myriad of other things to happen.

Now, I imagine that this utilizes some sort of Event-trigger relationship or messaging system, but it seems that it would be insane to hardcode all of these events into the game engine itself, even when utilizing an event-based system.

The same goes for tutorial and dialog systems: the player interacts with an NPC, or some sort of in-game object, and the dialog/tutorial continues at certain points.

In my game, I will specifically need to be able to have events triggered after a character does a certain thing, and I will need to be able to have series of dialogues triggered.  I think that I know how I could hardcode these things, but I'm going to have numerous levels that I wish to develop with a level editor such as Tiled, instead of hardcoding them.  Because of this, I don't know how I would integrate events into such a system.

My questions are: what do game programmers do to avoid hardcoding these things into their games? With something like a massive quest system with tons of dialog, or numerous levels with switches and events to trigger, how are these integrated into the game?

Thank you for any answer you can give me, I'm really stumped on this one :)

P.S. If you need any more clarity on what I'm asking for, please tell me so I can give more detail if needed.

P.P.S
I saw this post Level editor event system, how to translate event to game action but I've seen on other pages that people go back and forth on whether to use a scripting language, or some sort of file format like XML or JSON, and it's very confusing...


texts: While working on a Monogame project on Linux (Arch to be exact), I found that I could not change the screen height away from the default 800 px, while I could easily, perfectly change the width to whatever I want. Has anyone ever had this issue, and is there a fix for it? I am going to try the solution that @Jon explained in this post, but I doubt it will work since this seems to be a Linux-only problem. I have installed the latest version of OpenTK and built the latest build of Monogame as of a few days ago, and have looked through the source for the Monogame OpenTKGameWindow and GraphicsDevice classes, as well as the GraphicsDeviceManager. I don't see the issue in any of those, but I might be missing something.


texts: How to load a png file without alpha premultiplying in ios?

texts:
I am making a game in which I use the alpha value, in some cases for transparency, in others for occlusion, and for HDR in others.

I'm loading the images like this (this is MonoTouch, but objective-c can be easily converted to c#):

CGImage bitmap = new UIImage(resourcePath).CGImage;
width = bitmap.Width;
height = bitmap.Height;
IntPtr pixels = Marshal.AllocHGlobal(bitmap.Width * bitmap.Height * 4);
using (var context = new CGBitmapContext(pixels, bitmap.Width, bitmap.Height, 8, bitmap.Width * 4, CGColorSpace.CreateDeviceRGB(), CGImageAlphaInfo.PremultipliedLast))
{
    var dest = new RectangleF(0, 0, bitmap.Width, bitmap.Height);
    context.ClearRect(dest);
    context.DrawImage(dest, bitmap);
    GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, width, height, 0, PixelFormat.Rgba, PixelType.UnsignedByte, pixels);
}
Marshal.FreeHGlobal(pixels);
bitmap.Dispose();

However, this butchers all my pixels by premultiplying them by the alpha value.

The reason behind this is that I'm creating CGBitmapContext with CGImageAlphaInfo.PremultipliedLast. I tried with CGImageAlphaInfo.Last, but creating the context fails. Core Graphics only works with premultiplied alpha, as explained here.

I tried using CGDataProviderCopyData, as well as pngcs. However, they both simply decode the bitmap, and don't convert the pixels to RGBA, which is relevant when you're storing 8-bit, 24-bit PNGs, or indexed PNGs (I have lots of these, which are the result of optimizing my PNG files for size).

So I'm lost. I need a way to decode PNG files in a way that they are converted to RGBA without premultiplying my colors by the alpha value. Is that too much to ask? GDI, GDI+, System.Drawing, DirectX, Mono for Android as well as PSM do it just fine...

Also, why does iOS development has to be so picky?


texts: Algorithm for drawing asteroids from, er... Asteroids game?

texts:
What would the algorithm be for generating/drawing the asteroid shapes from the original Asteroids game? Is it even an algorithm? Or would they be hard coded shapes?

Here is a screenshot to jog your memory.

Screenshot from Asteroids game http://www.heinzwerner.de/emu_asteroids.jpg

EDIT - Also found this:

alt text http://www.next-gen.biz/files/images/feature_article/2009/05/asteroids4.jpg

from the article Edge - The Making of Asteroids. Interesting read, but does not mention any specifics.


texts: Why are my game ticks longer than expected?

texts:
I was working on my game, adding stuff to it, when I noticed my ticks were in the low 50's when I had set it to do a constant 60. This is my run method.

public void run() {
    init();
    long lastTime = System.nanoTime();
    final double amountOfTicks = 60.0;
    double ns = 1000000000.0 / amountOfTicks;
    double delta = 0;
    int updates = 0;
    int frames = 0;
    long timer = System.currentTimeMillis();

    while (running){
        long now = System.nanoTime();
        delta += (now - lastTime) / ns;
        lastTime = now;
        if (delta >= 1) {
            gameUpdate();
            updates++;
            delta--;
        }

        try {
            Thread.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        gameRender();
        frames++;

        if (System.currentTimeMillis() - timer > 1000) {
            timer += 1000;
            frame.setTitle(title + "   |   " + "Frames Per Second: "
                    + frames);
            System.out.println(updates + " Ticks, " + frames + " Frames");
            updates = 0;
            frames = 0;
        }
    }
    stopGame();
}

I've tried removing all the code I added before this occurrence happened and it didn't help. Suggestions would be great!


texts: XNA 4: RenderTarget2D textures getting transparent on fullscreen

texts:
I'm generating a Texture2D object using RenderTarget2D as in the following code

public static Texture2D GetTextTexture(string text, Vector2 position, SpriteFont font, Color foreColor, Color backColor, Texture2D background=null)
{
            int width = (int)font.MeasureString(text).X;
            int height = (int)font.MeasureString(text).Y;

            GraphicsDevice device = Settings.game.GraphicsDevice;
            SpriteBatch spriteBatch = Settings.game.spriteBatch;

            RenderTarget2D renderTarget = new RenderTarget2D(device, width,
            height, false, SurfaceFormat.Color, DepthFormat.Depth24Stencil8,
            device.PresentationParameters.MultiSampleCount, RenderTargetUsage.DiscardContents);

            device.SetRenderTarget(renderTarget);
                device.Clear(backColor);
                spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.Opaque);
                if (background != null) spriteBatch.Draw(background, new Rectangle(0, 0, 70, 70), Color.White);
                spriteBatch.End();
                spriteBatch.Begin();
                spriteBatch.DrawString(font, text, position, foreColor, 0, new Vector2(0), 0.8f, SpriteEffects.None, 0);
                spriteBatch.End();
            device.SetRenderTarget(null);
            ResetGraphicsDeviceSettings();
            return (Texture2D)renderTarget;
}

It's working all fine. But when I ToggleFullScreen() (and vice-versa), the previous textures are getting transparent. However, the new textures after that are being generated correctly.

What can be the reason for this?


texts:
I am attempting to tint a texture a color but I want the texture to show under the tint. For example, I have a picture of a person but I want to tint them a light green and not change the transparency of the actual person itself.

So far I have attempted to use the SpriteBatch method setColor which takes rgba values. When I set the alpha value to .5 it will render the tinting and the texture with that alpha value. Is there any way to separate the alpha values of the tint and the texture?

I know I could draw another texture on top of it but I don't want to have two draw passes for the one texture because it will be inefficient. If there's anyway to do it in raw OpenGL that'd be great too.


texts: Unity and lots of objects. Can this way of designing levels bring problems?

texts:
Ok, question.

I've been fiddling for Unity for a while and now trying to make a cohesive game.

Up until now I've found the quickest way to design levels for me is to create a block of wall/floor to work as a "unit", and copy it lots of times.

The result is something like this

The blocks are basically just a transform + a sprite renderer + a box collider.

Now my question is: Can this approach bring problems given that it basically creates lots and lots of objects? If so what alternatives there are? Creating bigger blocks?


texts: What causes this graphics quality difference between WebGL Build and Unity 5 Editor?

texts:
The Editor version and WebGL version of my Minesweeper clone have some graphics quality differences. I chose 'Fast' option when building this deployment.

Is this the difference between 'Fast' and 'Fastest' options of Optimization Level in Build Settings, meaning that if I choose the 'Fastest' option, the WebGL deployment will be the same as Editor version, unlike below? If not, why this happens?


texts:
I'm developing a 3D visualization tool based on Unity, targeting WebGL. The user rarely interacts with the 3D scene and when he does it's only about adjusting the camera like rotating or zooming the view. I disabled vSync (QualitySettings.vSyncCount) and locked the frame rate to 30 (Application.targetFrameRate) to reduce the CPU usage at least a bit while still having an acceptable level of responsiveness when the user moves the camera around. With 30 fps I get a CPU usage of around 30%. Considering lower-end hardware this seems still too high.
In order to further decrease CPU usage, I introduced two 'modes':

Interactive: runs with 30 fps
Idle: runs with 10 fps

I wrote some lines of code to switch between those modes depending on user interaction. So when an input is detected, the application uses more fps and after a certain amount of time without any interaction, the application uses less fps again. It works pretty well so far: The app uses 30% in interactive mode and 8% to 10% of the CPU while in idle mode.
Setting the idle frame rate to 1, CPU usage is reduced to 1.5% while in idle mode. This is really great. But as expected there's a problem. Basically I locked all the Update() methods to be called only once per second. When the user interacts with the camera, the event will be processed with an expected delay of something around one second.
Now the question: How can I detect user input immediately while having the application run with a low frame rate and also immediately apply a new frame rate (say 30) without any  noticeable delay?
Originally I wanted to have some sort of on-demand rendering. I've read some posts about how people render to a texture to reduce rendering cost in less interactive scenes. But setting the frame rate dynamically seems like a cleaner solution in my opinion. I also tried to use the FixedUpdate() method to check for inputs and switch to interactive mode, but that didn't work either.
Note Also worth mentioning, this approach produces errors in the browser, indicating that the application frame rate should be 0 (not in terms of Unity's target frame rate but as in 'let the browser handle the frame rate'). While this might be a different question it's still related to this topic. Maybe someone has an answer for that as well!

Edit 1
As mentioned in the comments below, Unity provides the callbacks MonoBehaviour.OnApplicationPause and MonoBehaviour.OnApplicationFocus to detect whether the application is about to receive or lose focus.
However, the problem is this: My application nearly never loses focus. While this is a nice additional optimization it doesn't really help me too much. My problem is that the app is idle most of the time while also having focus. It's really just the user staring at the window most of the time.
Just to make some more sense: I'm targeting WebGL. Unity's sole purpose is to visualize some stuff while the user mainly interacts with some HTML controls. In the rare case he wants to interact with the 3D scene, I want to set the frame rate to say 30. The idea is "I don't re-render the scene too often as long as you don't interact".
To emphasize: In my most relevant use case the application never loses focus. This means, the only reliable indicator to determine when to switch between frame rate profiles is based on user input.
Sorry if I wasn't too clear about that :)

Edit 2
I posted this topic on the Unity Feedback Page. If you're interested, check it out and leave a vote. Maybe this request gets enough attention to get supported by the Unity developers.


texts: How is Ping-Ponging done in Stage3D & AGAL (Flash Player 11)

texts:
Does anyone know how to create a Texture feedback effect in Stage3D / AGAL?

I've just found the term "ping-ponging" in some GPU wikipage, hopefully I'm using it in the right place!

I'll share with you my sample code portion responsible for alternating between the source and destination Texture targets:

protected override function _draw():void {
        super._draw();

        var src:int =   _textureFlip;
        var dest:int =  1 - _textureFlip;

        context3D.setRenderToTexture(_texturePair[dest], false, 0, 0); //
        clear();
        context3D.setTextureAt(0, _textureNoise);
        context3D.setTextureAt(1, _texturePair[src]);
        setupConstants();
        context3D.setProgram(_programs[0]);
        context3D.drawTriangles(_quadIndices.buffer, 0, 2);

        context3D.setRenderToBackBuffer();
        clear();
        setupConstants();
        context3D.setTextureAt(0, _texturePair[dest]);
        context3D.setTextureAt(1, null);
        context3D.setProgram(_programs[1]);
        context3D.drawTriangles(_quadIndices.buffer, 0, 2);

        context3D.present();

        _textureFlip =  1 - _textureFlip;
    }

Now... if I run the bottom portion by itself (and swap _texturePair[dest] with '_textureNoise'), I can see my texture fine.

Maybe I'm forgetting something in my AGAL code, but I figured I should ask here first for any guidelines.

Is it possible I have to upload some startup data (blank rect, black, white, anything!) in my first input-texture before the very first target texture is being rendered to?

Do I need to clear the Texture targets first?
Do I need to set the blend factors between switching from BackBuffer vs. Texture Targets?

Would very much appreciate your help :)


texts: How can I detect disconnected clients in a peer-to-peer network of this topology?

texts:
I'm working on my first multiplayer game (RTS genre) and for the networking model, I'm leaning more towards a peer-to-peer model as opposed to a client-server model. I want my game to be able to handle a large number of users concurrently (around 50-100 users) in a reasonable manner.

I've come up with a proof of concept that can achieve moderate speed and moderate load balancing across the network. For it to work, one of the peers has to be designated as a central authority (i.e. the host). The host then receives updates from users through a star topology and then broadcasts the changes to other users through a tree topology, as below:

This type of network has one big problem: churn. I'm having trouble figuring out how to deal with users that disconnect from the network. If nothing is done for them, all of that user's children (and descendants) will lose connection.

How can I detect disconnected nodes in a peer-to-peer network of my expected size and remove them without harming the other, still-connected clients and without placing undue load on the designated host?


texts: Unity font API behaves differently in built game

texts:
Specifically it's Font.CreateDynamicFontFromOSFont(), use this script attached to an empty GameObject in the scene.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TestFontTexture : MonoBehaviour {

    void Start ()
    {
        var font = Font.CreateDynamicFontFromOSFont("Consolas", 12);
        font.RequestCharactersInTexture("HelloWorld", 20);
        SaveTexture2PNG("./fontTexture.png", (Texture2D)font.material.mainTexture);
    }

    void Update ()
    {

    }

    void SaveTexture2PNG(string path, Texture2D tex)
    {
        byte[] bytes = tex.EncodeToPNG();
        System.IO.File.WriteAllBytes(path, bytes);
    }
}

After click play it should create a fontTexture.png file containing character glyphs in the Assets folder, but only in editor though. In the built game it just created a completely black image.

Since it's OS concerned, I'm using Windows 7 with font Consolas installed and Unity 5.6.5f.

How to make it work in a built game?


texts: Match-3 should pieces store their location in the matrix?

texts:
I'm making a match-3 game. I have a TileManager script which stores all the tiles in a matrix, it's a singleton and it handles tile swapping and basicly everything regarding the management of tiles.
I have a variable called selectedTile. I have a method called SwapSelected which swaps the currently selected tile with the one you just clicked on. As pieces don't know their location in the matrix I can only loop through the whole thing to find them but it feels extremly stupid I just feel like there's gotta be a better way. If pieces stored their location and I kept that updated all the time that'd feel stupid too.
What could I do to make this method work nicer and more optimalized? Is there a way or there is no problem with how I do it?
    public void SwapSelected(Tile tileToSwap)
    {
        Vector3 tempPos = selectedTile.transform.position;
        selectedTile.transform.position = tileToSwap.transform.position;
        tileToSwap.transform.position = tempPos;

        Vector2Int tileToSwapPosition = new Vector2Int(-1, -1);
        Vector2Int selectedTilePosition = new Vector2Int(-1, -1);

        //OPTIMALIZE!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        for (int x = 0; x < _tileMap.GetLength(0); x++)
            for (int y = 0; y < _tileMap.GetLength(1); y++)
            {
                if (_tileMap[x, y] == tileToSwap)
                {
                    tileToSwapPosition = new Vector2Int(x, y);
                }
                if (_tileMap[x, y] == selectedTile)
                {
                    selectedTilePosition = new Vector2Int(x, y);
                }
            }

        _tileMap[selectedTilePosition.x, selectedTilePosition.y] = tileToSwap;
        _tileMap[tileToSwapPosition.x, tileToSwapPosition.y] = selectedTile;

        UpdateTileName(tileToSwap);
        UpdateTileName(selectedTile);
    }


texts: 2D Lighting Problem with Black Backgrounds

texts:
I'm currently experimenting with simple lighting in my game made with SFML and C++ (though I don't think that's relevant to the question). It's my first time messing with lighting in 2D, and my basic system is to:

Create a lightmap
Every frame, clear the lightmap and add all lights back to it (they move).
Every frame, draw the lightmap to the window on top of the game and multiply the colors from both textures (the game texture and the lightmap texture). In SFML I do this by:

window.draw(lightMap, sf::BlendMultiply);

My issue is that my lights don't show up against a black background, which doesn't seem to make sense. It's as if that specific color (and colors close to it) just can't be illuminated. Is this because of how color multiplication works? If so, is there a workaround?

Thanks!


texts:
I am a very seasoned Delphi developer (over 12 years of experience not counting my Turbo Pascal experience) and was wondering does anyone write games in Delphi?  I have seen DirectX API wrappers in Delphi that allow you to program against DirectX (even wrote a simple solitaire game with a friend), but haven't seen anything out there that shows me that I should keep up with Delphi.  I just hate to walk away from so much knowledge and Object Pascal language, but I am not seeing much as to a reason to keep going with Delphi.

I currently program in C# and thinking about XNA, but it seems to me that the dominating opinion is go C/C++ route with DirectX.

Any other Delphi developers out there struggle with this too?

Thanks,
MDV


texts: Which is the most efficient way to make the screen follow a sprite?

texts:
This is my first non-board game and I'm trying to learn a bit about 2D graphics in Java.
But I don't know, how should I efficiently implement a camera to make the screen follow the main character.
I have a position-fixed, unchanging terrain as BufferedImage on my map and other also mobile and animated entities, including the character itself.
Right now I'm using some calculations(x of character - middle of screen) each time on repaint() to draw the level on the correct position from the (0,0) coordinates. But this method does a lot of calculation and drawing, even for the fixed map.
Is there a better and more efficient way?


texts: What algorithm should I use to laid out pre-made rooms into a level?

texts:
I want to have a semi-procedural level, where rooms are pre-made but the way they're connected are proc-gen. The connections need to really exist - you can walk between rooms in hallways - not just teleported between rooms like in old games.

Each map will have a set number of rooms. Rooms should be laid into a grid(not necessary fill it) - all rooms and hallways will have the same size. Every room must lead to the exit(no dead end), except for 0 to 2 "secret room"

There can be 1 to 3 paths from start to finish; these paths may intersect. They should be relatively straight(no 180 turn or more).

There can a few rare "secret room" that are dead-end, but can only be one room depth:

              +-----+                                +-----+
              |     |                                |     |
              | End |                                | End |
              +-----+                                +-----+
                | |                                    | |
   +------+   +-----+          +------+   +------+   +-----+
   |      +---+     |          |      +---+      +---+     |
   | This +---+     |          | Not  +---+ This +---+     |
   +------+   +-----+          +------+   +------+   +-----+
                | |                                    | |
              +-----+                                +-----+
              |     |                                |     |
              |Start|                                |Start|
              +-----+                                +-----+

Is there a popular algorithm can I use to accomplish this?

One that was recommended by some people here is BSP Tree. It doesn't fit my requirement since the path it creates is too spiral, and depend on the number of corridors, it either creates too much path or too many dead-end.

The only thing I can come up with is to just add rooms one after another in random directions. There are 2 problems I can see and don't know how to solve:

How to create multiple natural paths(not just an L shape or straight line) that end up at the same location.
How to make sure the path doesn't become a spiral and block it self from advance further

Edit: I found this that that kinda resembles the structure I need, but with diagonal hallway.


texts: Any advantage of having chunks with sizes by the power of two?

texts:
With my past experience of having my little game lag because of the size of the world, I have decided that in whatever next project I might choose to create, I will split said world into chunks. Now here comes my question : Should the chunk's width, height and depth be a power of two?

For example, in a little game called Minecraft, chunks have a height of 256 and width,depth of 16. Both numbers a power of two. Is there any advantage over having the chunk simply be 100x100x100?

Minecraft was written in Java, but I'm working in Lua. Just pointing that out in case it has any relevance.


texts: ScriptableObject not working after build in Unity?

texts:
I have a GameObject with a ScriptableObject on it, stats. It works fine in editor but when I try to build I get a message,

A script behaviour (script unknown or not yet loaded) has a different serialization layout when loading.

What is wrong here?


texts:
I'm having trouble coming up with a formula/method of creating third person camera with a variable distance from the player given a specific camera pitch.

This image shows something close to my desired result:

I basically only have two requirements. The camera has to be directly calculated from a pitch. The camera should roughly follow a smooth curve between the minimum and maximum camera distance and the halfway point is around 50% of the distance (as seen by the graph in the top right of the image).

So, Option A:

I create a function online to convert a pitch directly to a camera distance and use that. http://www.timotheegroleau.com/Flash/experiments/easing_function_generator.htm

I have this working and it ends up looking close but has two distinct problems. It is rigid and doesn't allow me to edit any of the offsets or distances without having to create a whole new function and the camera at 0 degrees pitch ends up being around 15-30% of the maximum distance which doesn't feel as good as if it were closer to 50%.

Option B:

Come up with a spline, perhaps a cubic bezier, between the min and max distances and somehow project the camera on to that spline given a specific pitch. I'm not sure how I would be able to do this. The disadvantages would be that the camera distance curve would not be as smooth without some tweaking and again it would require more work if any of the distances or offsets change.

Option C:

Come up with a specific formula which I have no idea how to find. Given the min and max camera distances, the offsets, and the camera pitch, return a distance that follows a smooth camera distance curve and a mid point of roughly 50% of the max distance.

So my question is can/how do I accomplish Option B or C? Is there a better way?


texts: Getting notified about a change of a public variable in a script

texts:
I have a script attached to a GameObject.

In this script I have the variable public int Rotation

If this value is changed, I need to do some calculations.

I know that I can be notified when this value is changed in the Inspector (for example if somebody enters a different number), but I would like to be notified if this value is changed by another script.

Is that possible, or do I need do introduce a void ChangeRotation(int uNewValue) or similiar?

Thank you!


texts:
Brand new to games/graphics and I'm attempting to find a method to create a 2D liquid effect with JavaScript. Ideally I could adjust the viscosity and flow from a gas/fog effect to oil and between.

As an example, the effects in the PixelJunk Shooter trailer have stuck with me for years and I haven't ever seen another implementation with this style.

There is another question, as well, but no real implementation.

I also found a nice synopsis of ideas on gamedev so maybe that's the extent of my answer?

I'm currently using createjs but suspect I'd need another library so I'm not against using multiples.

I've looked at threejs and craftyjs but they don't seem to fit the criteria.
In order to keep with easeljs maybe I'll just check out a tutorial on how to create a particle system.

The heart of my question is really about a simple implementation rather than reading complicated mathematical presentations on the subject.  While interesting it's pretty far above my head.  Am I simply finding it's impossible to create a nice effect without some heavy lifting?

Thanks for any ideas on how this might be accomplished.


texts: How can I build an authoritative server to handle players actions taking into consideration scalability of solution

texts:
I've started with Unity3D to develop a multiplayer game similar to world of tanks, it's using authoritative server and I was able to sync movements between several clients. I'm using c# and on the networking part using sockets directly.

Currently, I have a hard time understanding how can the server perform operations such as:

Calculate if projectile shot by client A will hit client B
In addition to (1), also to see if the project did hit a static object (rock, metal...)

If we take into consideration that there could be hundred of player simultaneously, how can I approach this on the server side ? I'm looking to build myself from scratch everything in order to have a strong understanding of each puzzle piece.

On the other hand, I understood that there's the concept of headless server which is just the physics engine without rendering, however, this doesn't seem to be a scalable solution.


texts: Should I render all of my HUD views to a single SurfaceView?

texts:
I'm using a SurfaceView and canvas to implement a game HUD, title screens etc., by overlaying standard Android view widgets over my SurfaceView. This works reasonably well and maintains an acceptable frame-rate, but it is a simple game with little happening on or off screen.

I have handlers flinging messages around and runOnUiThreads everywhere. Quite cumbersome. Can I draw all my views to the one SurfaceView, controlled by the main game thread? Is there an advantage to this?


texts: Robust "soft" platform collision using SAT

texts:
We'll start with the questions, then a pile of background:

How do you rigorously and thoroughly define "soft collision" of the Mario-esque type (if I start above, or in a jump my feet apex above a "soft platform", I'll land on it)?
Can you suggest a definition in terms of object-versus-segment (or line, or ray, or whatever similar terrain boundary), in a SAT framework?
Any good examples/references for soft collision out there, even in non-SAT frameworks?
Finally, any edge/corner cases, literal or otherwise, that might not be obvious?

The background:

6+ years ago, I built a simple AABB object versus line-segment terrain collision system for $work, based heavily on N Tutorial A - Collision Detection and Response.  (This goes against my advice to never write physics/collision for production code oneself, but we had strange requirements: no FPU, blazingly fast SRAM and bus, and a relatively slow CPU.)

Over the years, we've dealt with a number of (sometimes quite literal) "corner cases", including how we deal with fast-moving objects (currently very fine-grained multisampling), order of collision resolution, et cetera.  This is the usual difficult stuff for naïve SAT, it would seem.

Recently another issue with our "soft collision" -- that is, platforms one can jump "up" through, but not fall "down" through (where "up" and "down" are relative to a unit normal off the line segment) -- has cropped up.

This has me wondering if I've "stated the problem" correctly vis a vis soft platforms.

As background, the bug in this case involved characters jumping with an arc such that their "head" just hit the bottom of the soft line segment.  Our collision system does, roughly:

early-miss if movement.dot( segmentUnitNormal ) > 0 // moving away from segment, for all segments (debatable whether this should be here, but probably largely irrelevant for this problem)
normal three-axis SAT (x-axis, y-axis, and line-axis) with miss if any axis shows separation; compute proposed projection to displace box out of segment if hit
late-miss unless 0 <= projection.dot( segmentUnitNormal ) < 1 // for "soft" segments only
finally, hit

Step #3 -- specifically the 0 == part of 0 <= -- is the issue here.  (On the other end of the range, the choice of 1 as cutoff for maximum interpenetration is arbitrary: it's based on our multisample worst case projection response.)

Amusingly, the comment above step #3 in the code says something like "Miss unless we started 'above' the segment, or if interpenetration is too deep."

The logic as stated says nothing about starting above, instead dealing only with response along unit normal.

As mentioned, the 0 case here is the issue: if the character's "head" hits the segment exactly at the peak of his jump and we compute a zero response, we'll treat that as a hit, when we'd expect to only get hits when our "feet" are at or just above the segment.

We could just exclude the 0 case here, and deal with a little "bounce" when resting on our soft platform, but then we'd have strange cases where we might not seem to be in contact with the world geometry every other frame, which has other implications for the animation system and the like.  I'd like to preserve 0 interpenetration = hit behavior.

I have a few possible solutions, mostly boiling down to things like:

"check if AABB centerpoint started on the correct side of the segment", or
"retain the directionality of the projection even if it collapses to zero length" (something like a "signed zero" here -- we already have this from our SAT calculations earlier),

...coupled with a little more care re whether we're using "computed projection along the line axis" versus "shortest computed projection" in these tests.

All of these solutions seem to be robust, in my initial tests.

But it has me wondering if I'm missing something obvious; hence the questions above.


texts:
I'm looking for image based (screen space) technique to render section cuts through arbitrary (solid) geometry. I found and studied image based CSG (Kirsch 05 / OpenCSG) but I found it to be perhaps a bit of a overkill for my case, where all I need is a section plane cut.

Above is a naive implementation using a discard in the fragment shader, but that obviously is not even half-way there as I need to close the gaps. Does anyone know of a technique/hack I could use?


texts:
I am working on packaging my game resources into a single file. I have chosen the format but I don't know whether I should use compression or not. I understand the possible pros and cons:

Compression means less installation time (happens rarely).
Compression means less game size on the disc and during downloading process.
Compression means the data should be extracted every time the game resource cache mechanism decides to cache some data in RAM from the archive.

Did I miss anything? What do other game developers usually do and why?


texts: Are there well-known algorithms for fitting a polygon to an arbitrary shape?

texts:
I'm using the Chipmunk physics engine to make the levels for a 2D C game.  I'd like to be able to fit a polygon to an arbitrary shape to serve as the collision mask.  Given a black and white collision mask for an arbitrary level object like this:

Are there any well-known algorithms for getting this:

I could then use the red polygon to create a physics object to go with the image.


texts: Specify the size of the points when building a mesh based on a point cloud

texts:
I create a mesh in Unity3D based on a point cloud in this way:

// The standard sequence for creating a mesh
Mesh mesh = new Mesh();
Vector3[] points = new Vector3[numPoints];
int[] indecies = new int[numPoints];
Color[] colors = new Color[numPoints];

// Fill in points, indecies, colors

mesh.vertices = points;
mesh.colors = colors;
mesh.SetIndices(indecies, MeshTopology.Points, 0);

I learned that it is possible to set the size of points in PSIZE through Vertex Shader.  Applied such a Shader, but without result.

Shader "VertexColor"
{
    Properties
    {
        _PointSize("Point size", Float) = 5.0
    }
    SubShader
    {
        Pass
        {
            LOD 200

            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            uniform float _PointSize;

            struct VertexInput
            {
                float4 vertex: POSITION;
                float4 color: COLOR;
             };

             struct VertexOutput
             {
                 float4 pos: SV_POSITION;
                 float4 col: COLOR;
                 float size: PSIZE;
              };

              VertexOutput vert(VertexInput v)
              {
                  VertexOutput o;
                  o.pos = UnityObjectToClipPos(v.vertex);
                  o.col = v.color;
                  o.size = _PointSize;

                  return o;
              }

              float4 frag(VertexOutput o) : COLOR
              {
                  return o.col;
              }
              ENDCG
          }
      }
}

Tell me, please, how to set the size of points correctly?


texts: How to use the float value from noise function in voxel terrain?

texts:
I'm using Unity, although this question is not really specific to that engine.

Im also using an asset from the store called Coherent Noise. It has some neat noise functionality built it.

I am using those functions to produce some noise values. I am getting a value between 0 and 1 (floats).

I have an array of blocks (for minecraft like voxel terrain) and I am confused on how to use this float value for terrain?

Do I do something like <= 0 == Solid block etc?

I am confused on how to use the floating values that the noise functions produce to use for height values of an array of say a height of 16.


texts:
I'm currently trying to develop my own little game engine (trying to understand maths in games).

I have implemented 4x4 matrices and 2d vectors (I don't need 3d since I'm aiming at orthographic projection in 2d).

I have a Camera class that has a position and a rotation angle as members.

Every time my camera moves (keyboard input), I update its view matrix.

I do it this way:

I translate the camera to its position and then create a Z-axis rotation matrix.
I multiply both and have my view matrix.

Everything looks fine, and by that I mean that translation works, as well as rotation and projection is fine too.

But my problem is that objects in my scene do not rotate around the camera position.

It looks like my objects rotate around a point that is translated by the camera too, not like objects rotate around the actual camera center.

And here is my source code: https://github.com/yann-kaiser/kyengine

I do not know if I shall tweak things in my camera transformation or if it's a model-matrix related thing or anything else; could someone explain this to me?

EDIT: Finally found the solution. I needed to first create a translation matrix to the center of the screen (translate by w/2 and h/2), then apply rotation and only then apply my position translation.


texts: Setting variable values in XNA 4.0 from an XML file

texts:
I made a program that simulates an assembly line using the XNA 4.0. I made a 3D model, and divided it into 5 positions - start, 3 workstations, and end.
These positions represent the places on the model that (in real life) would be covered by some type of sensors. Whenever an object gets to one of these positions, it triggers a method that is binded to that specific position (like "Stop", "Start", "Increment/Decrement Counter"...).

This program has to be able to load a file that describes the behavior of the entire assembly line - meaning, this file has to tell the program when and which method will be triggered (for now it is only Start/Stop methods). To do this, I created a method that serializes the class that contains bool variables (these variables determine if the position will be "active" or not - if the value is true then the object will trigger the binded method, if it is false then it will simply pass that position, without any additional actions being performed).

This is the problem I'm having:
My method successfully serializes the class, and creates the .xml file, but if I load this file as Content, it gives me the following error "There was an error while deserializing intermediate XML. Cannot find type "Postavke.PostavkeStanice"."

This is the code of my class:

using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Content.Pipeline.Serialization.Intermediate;
using System.Xml;
namespace Postavke
{

    public class PostavkeStanice
    {
        public bool radnaStanica1_Stanje;
        public bool radnaStanica2_Stanje;
        public bool radnaStanica3_Stanje;
        public bool kraj_Stanje;
        MemoryStream ms = new MemoryStream();
        public void ClassToXML()
        {

          XmlTextWriter pisac = new XmlTextWriter(ms, Encoding.UTF8);
          pisac.Formatting = Formatting.Indented;
          IntermediateSerializer.Serialize(pisac, this, "Postavke.xml");
        }

        public string XMLToXNA()
        {
            ms.Seek(0, SeekOrigin.Begin);
            TextReader citac = new StreamReader(ms);
            return citac.ReadToEnd();
        }
    }
}

Since this class is a part of Game Library, I set the dependencies so that the Game library gets compiled before the main project.
When I run the code I get the fore mentioned error. Can you tell me what I'm doing wrong
Thank you


texts: Draw wrong faces in obj model with OpenGL VBO

texts:
I am trying to draw a 3D model from an .obj file, and have met big trouble.
I think my model draws with wrong faces, but I can't understand why.

Original model:

This is my code for reading the model:

        using (StreamReader streamReader = new StreamReader("Content/Models/" + path))
        {
            while (!streamReader.EndOfStream)
            {
                List<string> words = new List<string>(streamReader.ReadLine().ToLower().Split(' '));
                words.RemoveAll(s => s == string.Empty);

                if (words.Count == 0)
                    continue;

                string type = words[0];
                words.RemoveAt(0);

                switch (type)
                {
                    // vertex
                    case "v":
                        vertices.Add(new Vector4(float.Parse(words[0], new CultureInfo("en-US").NumberFormat),
                            float.Parse(words[1], new CultureInfo("en-US").NumberFormat),
                            float.Parse(words[2], new CultureInfo("en-US").NumberFormat),
                            words.Count < 4 ? 1 : float.Parse(words[3], new CultureInfo("en-US").NumberFormat)));
                        break;

                    case "vt":
                        textureVertices.Add(new Vector3(float.Parse(words[0], new CultureInfo("en-US").NumberFormat),
                            float.Parse(words[1], new CultureInfo("en-US").NumberFormat),
                            words.Count < 3 ? 0 : float.Parse(words[2], new CultureInfo("en-US").NumberFormat)));
                        break;

                    case "vn":
                        normals.Add(new Vector3(float.Parse(words[0], new CultureInfo("en-US").NumberFormat),
                            float.Parse(words[1], new CultureInfo("en-US").NumberFormat),
                            float.Parse(words[2], new CultureInfo("en-US").NumberFormat)));
                        break;

                    // face
                    case "f":
                        foreach (string w in words)
                        {
                            if (w.Length == 0)
                                continue;

                            string[] comps = w.Split('/');

                            // subtract 1: indices start from 1, not 0
                            vertexIndices.Add(uint.Parse(comps[0]) - 1);

                            if (comps.Length > 1 && comps[1].Length != 0)
                                textureIndices.Add(uint.Parse(comps[1]) - 1);

                            if (comps.Length > 2)
                                normalIndices.Add(uint.Parse(comps[2]) - 1);
                        }
                        break;

                    default:
                        break;
                }
            }
        }

This is code is also available on GitHub - github.com/Freaky-Brainstorm/Deep.


texts:
I am making a 2D platformer in LibGDX with both Ashley and Box2D.

I have it so, that the PlayerControllerSystem watches for the jump key being pressed:

// Jumping
if (Gdx.input.isKeyPressed(Keybindings.KEY_JUMP)) {
    entity.add(new JumpingComponent());
}

This works like a charm. Every time I press the jump key the PlayerJumpingSystem fires up:

/**
* System used for the player jumping mechanism
* @author Tim
*/
public class PlayerJumpingSystem extends IteratingSystem {

    @SuppressWarnings("unused")
    private final static String TAG = PlayerJumpingSystem.class.getName();

    // Variable declaration
    @SuppressWarnings("unchecked")
    private static final Family family = Family.all(
            PositionComponent.class,
            VelocityComponent.class,
            PhysicsComponent.class,
            PlayerComponent.class,
            JumpingComponent.class).get();

    public PlayerJumpingSystem () {
        super(family);
    }

    @Override
    protected void processEntity (Entity entity, float deltaTime) {
        PositionComponent position = Mappers.position.get(entity);
        VelocityComponent velocity = Mappers.velocity.get(entity);
        PhysicsComponent physics = Mappers.physics.get(entity);

        if (velocity.y > 0) {
            // We are ascending
            physics.body.applyLinearImpulse(0, -Constants.JUMP_FORCE, position.x, position.y, true);
        }

        if (velocity.y < 0) {
            // We are descending
            physics.body.applyLinearImpulse(0, Constants.JUMP_FORCE, position.x, position.y, true);
        }

        else if (velocity.y == 0) {
            entity.remove(JumpingComponent.class);
            Gdx.app.log(TAG, "JumpingComponent removed");
        }
    }

}

It gives very weird jumping behaviour. Does anyone know how to implement jumping with Box2D in a good way? Thanks in advance!


texts: What is the role of "systems" in a component-based entity architecture?

texts:
I've been reading a lot about entity components and systems and have thought that the idea of an entity just being an ID is quite interesting.

However I don't know how this completely works with the components aspect or the systems aspect. A component is just a data object managed by some relevant system. A collision system uses some BoundsComponent together with a spatial data structure to determine if collisions have happened.

All good so far, but what if multiple systems need access to the same component? Where should the data live? An input system could modify an entities BoundsComponent, but the physics system(s) need access to the same component as does some rendering system.

Also, how are entities constructed? One of the advantages I've read so much about is flexibility in entity construction. Are systems intrinsically tied to a component? If I want to introduce some new component, do I also have to introduce a new system or modify an existing one?

Another thing that I've read often is that the 'type' of an entity is inferred by what components it has. If my entity is just an id how can I know that my robot entity needs to be moved or rendered and thus modified by some system?

Sorry for the long post (or at least it seems so from my phone screen)!


texts: How to implement the server-side game loop?

texts:
The server needs to handle the physics, because all the movement will be handled by it. So for that I need a game loop. The thing  is that the server doesn't have the render part, it's just a console.

All the posts I found on the internet were involving the render part. I'm not stupid, I know I should not take in consideration that part but then which type of loop should I use? (fixedtimestep, semi-fixed). My game functionality would resemble League Of Legends or Dota 2 functionality.

Actual questions:

1.What is the server functionality for this type of game?

2.What does the game loop look like?

Additional info: I use libGDX for the client part, and JBox2D on the server part, KryoNet for Networking and thinking of using lwjgl (only the System class) for Native timers.


texts: How to get width and height from a body in box2d?

texts: I am working on a game in Libgdx framework. I have to get width and height from a body in box2d. is their any way to get width an d height from a body in box2d??


texts: I need to remove a section of an image using a 2D mesh. Since the image is destructible (artillery game style), it would be helpful to shrink the image in memory afterward. The portion in the blue section should be kept, the portion in red is within the mesh and should be removed. Note that the image is rotated as well.


texts:
Im making a 3rd person 3D game. I have a little capsule shaped player controlled drone at the moment that moves on a flat surface. Y axis is locked. The Game object contains a script and then the child objects which are the actual body parts. If i attach a rigidbidy to the root object i get crazy results. The drone collides with something and starts to spin and then forward becomes some upward direction.

Somehow i would like to be able to use the pysics collision and ragdoll effects but still be able to maintain the keyboard movement. I guess that id have to animate the drone getting back up again when fallen.

Movement code

    void CheckForKeys ()
{
    if (Input.GetKey(KeyCode.W)) {
        transform.Translate(Vector3.forward * Time.deltaTime * walkingSpeed);
    }

    if (Input.GetKey(KeyCode.S)) {
        transform.Translate(Vector3.back * Time.deltaTime * walkingSpeed);
    }

    if (Input.GetKey(KeyCode.A)) {
        transform.Rotate(Vector3.up * Time.deltaTime * rotatingSpeed);
    }

    if (Input.GetKey(KeyCode.D)) {
        transform.Rotate(Vector3.down * Time.deltaTime * rotatingSpeed);


texts:
Any shader wizards out there have an idea of how to achieve an oily/polluted water effect, similar to this:

Ideally, the water would not be uniformly oily, but instead the oil could be generated from some source (such as a polluting drain from a chemical plant) and then diffuse throughout the water body. My thought for this part would be to keep an "oil map" as a 2D texture that determines the density of oil at each point on the water surface. It would diffuse and move naturally with the water vel;ocity at that point (I have a wave-particle simulation for dynamic waves, and am already doing something similar for foam on the water surface). However, I'm not sure how physically correct that would be, since oil might not move at the same velocity as the water.

And I have no idea how to make all those trippy colors :-). Thoughts?


texts:
I want my player to jump and i tried my best to do it and i couldn't. Basicaly my class are splitted(i have speparate player class and keyboard class) which i thought would make my life easier but didnt.

I made it so that if i press space bar, then i would fly(this is for temporarily and i wanted it to jump) and also i added gravity.

It would be great if you guys posted what to add on what class and explain what it does cause im a noob at java.

Thnx

My Player Class

package com.vescorspel.game.MyFirstGame.entities.creatures;

import java.awt.Graphics;
import java.awt.image.BufferedImage;

import com.vescorspel.game.MyFirstGame.Handler;
import com.vescorspel.game.MyFirstGame.gfx.Animation;
import com.vescorspel.game.MyFirstGame.gfx.Assets;

public class Player extends Creatures{

//Animations
private Animation animRight, animLeft;

public Player(Handler handler, float x, float y) {
    super(handler, x, y, Creatures.DEFAULT_CREATURE_WIDTH, Creatures.DEFAULT_CREATURE_HEIGHT);

    bounds.x = 32;
    bounds.y = 32;
    bounds.width = 92;
    bounds.height = 96;

    //Animations
    animRight = new Animation(100, Assets.DerpDino_right);
    animLeft  = new Animation(100, Assets.DerpDino_left);
}

@Override
public void tick() {

    //Animations
    animRight.tick();
    animLeft.tick();
    //Movement
    getInput();
    move();
    handler.getGameCamera().centerOnEntity(this);
}

private void getInput(){
    xMove = 0;
    //Gravity
    yMove = 5;

    if(handler.getKeyManager().left)
        xMove = -speed;
    if(handler.getKeyManager().right)
        xMove = speed;
    if(handler.getKeyManager().jumping)
        //this makes my player fly
        yMove = -speed;
}

@Override
public void render(Graphics g) {
    g.drawImage(getCurrentAnimationFrame(), (int) (x - handler.getGameCamera().getxOffset()), (int) (y - handler.getGameCamera().getyOffset()), width, height, null);

private BufferedImage getCurrentAnimationFrame(){
    if(xMove < 0){
        return animLeft.getCurrentFrame();
    }else{
        return animRight.getCurrentFrame();
    }
}

}

My KeyManager Class

package com.vescorspel.game.MyFirstGame.input;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

public class KeyManager implements KeyListener{

private boolean[] keys;
public boolean left, right, jumping;

public KeyManager(){
    keys = new boolean[256];
}

public void tick(){
    left = keys[KeyEvent.VK_A];
    right = keys[KeyEvent.VK_D];
    jumping = keys[KeyEvent.VK_SPACE];
}

@Override
public void keyPressed(KeyEvent e) {
    keys[e.getKeyCode()] = true;
    System.out.println("Pressed!");
}

@Override
public void keyReleased(KeyEvent e) {
    keys[e.getKeyCode()] = false;
}

@Override
public void keyTyped(KeyEvent arg0) {
}

}


texts:
I recently implemented a prelighting renderer for my XNA voxel engine, but there is now a weird alpha blending glitch. When I render to the light map, I set the graphics device's blend state to additive (though in the pixel shaders for each light I output an opaque color). When I finally render the world, I set the device's blend state to opaque, I only deal with the RGB components of colors in the shaders, and I again output an opaque color. However, the light map and the final rendering both somehow have transparency.

Edit: I believe the problem with the final rendering is caused by the light map's transparency issues. If a pixel appears to be semi-transparent in the light map, then it will appear as so in the final rendering because of how the final color is calculated.

Here is a picture of the rendered world (there is a blue directional light and a red point light at the player's position):

Here is a picture of the light map (different seed, but you get the idea):

Here is my directional light pixel shader (the point light one is similar, but [obviously] with point light calculations):

float4 PSFunc( VSOutput input ) : COLOR0
{
    // extract information
    float2 coords = GetTexCoords( input.LPosition );
    float4 normal = ( tex2D( normalSampler, coords ) - 0.5 ) * 2.0;

    // calculate the lighting value
    float3 lighting = clamp( -dot( normalize( lightDirection ), normal.xyz ), 0.0, 1.0 ) * lightColor;
    return float4( lighting, 1.0 );
}

Finally, here is my pixel shader that combines texture and lighting values:

float4 PSFunc( VSOutput input ) : COLOR0
{
    // extract lighting info (TPosition is the world position in the TEXCOORD0 channel)
    float2 coords = ProjectToScreen( input.TPosition ) + GetHalfPixel();
    float3 light = tex2D( lightSampler, coords );
    light += ambientColor; // ambientColor is a float3

    // calculate final color
    float3 tex = tex2D( spriteSampler, input.UV ).rgb;
    return float4( tex * diffuseColor * light, 1.0 );
}

Note: I do use the sprite batch to render the text, but I have a graphics state class that allows me to push and pop states (rasterizer, blend, depth-stencil, etc.), so I use that to preserve states when drawing with the sprite batch.


texts:
I am trying to instantiate an obstacles, Currency and Power up in the game. i am using same script to instantiate all. obstacles and currency are working perfectly but power ups is not generating in a game. it displays an error message

NullReferenceException: Object reference not set to an instance of an object
ElementsGeneratorss.instantiateElement (Int32 elementNumber, Vector3 v3Position, Single CurrentAngle, Vector3 hitInfoNormal) (at Assets/GameKit/C# Scripts/ElementsGeneratorss.cs:312)
ElementsGeneratorss.generateElements (Int32 elementNumber, Single fLocation, Boolean bStartPatch) (at Assets/GameKit/C# Scripts/ElementsGeneratorss.cs:225)
ElementsGeneratorss+c__Iterator1.MoveNext () (at Assets/GameKit/C# Scripts/ElementsGeneratorss.cs:115)

i used C# Script

private void instantiateElement(int elementNumber, Vector3 v3Position, float CurrentAngle, Vector3 hitInfoNormal)
{
    if (elementNumber < 0)
        return;

    Transform ObjectHandle;

    if (elementNumber < iObstacleCount)//obstacles
    {
        // for generating obstacles. its working perfectly
    }
    else if (elementNumber >= iObstacleCount && elementNumber < (iObstacleCount+iPowerupCount))//powerups
    {
        ObjectHandle = elements[elementNumber].tPrefabHandle[elements[elementNumber].iPrefabHandleIndex];
        elements[elementNumber].iPrefabHandleIndex++;
        if (elements[elementNumber].iPrefabHandleIndex >= elements[elementNumber].tPrefabHandle.Length)
            elements[elementNumber].iPrefabHandleIndex = 0;
        ObjectHandle.gameObject.SetActive(true);
        ObjectHandle.up = hitInfoNormal;
        ObjectHandle.position = v3Position;
        ObjectHandle.localEulerAngles = new Vector3(0,0,0);
        ObjectHandle.Rotate(0,CurrentAngle,0);
        ((PowerupScriptss)ObjectHandle.GetComponent(typeof(PowerupScriptss))).initPowerupScript();
    }
    else if (elementNumber == (iObstacleCount+iPowerupCount))//currency
    {
        // for generating currency. working perfectly
    }
}


texts: Using Canvas instead of Scaleform in UDK

texts:
I'm working with Unreal Script, and I need to use Canvas instead of Scaleform to create a HUD.  I've extended the game type from UTGame, and used bUseClassicHUD in the Default Properties section, but the default Scaleform HUD continues to appear.  I know for certain that I have everything configured properly to load and run the scripts, but this one line just doesn't seem to have any effect.

DefaultProperties{

// Disable the scaleform (flash) HUD in the UTGame
bUseClassicHUD = true

// Initial score value
nScore = 0

// Initial time value
m_gameTimer = 30.0

}

Is there something else I need to include?  I've done a reinstall (I'm using the July 2013 build), but to no avail.


texts: Abstracting OpenGL concepts in a OOP language (C# + OpenGL)

texts:
I have created my own C# binding for OpenGL and in doing so learned a lot about VAOs and VBOs, shaders and everything between them. Now I would like to create a game engine rendering with shader-based OpenGL. Now, I am a little bit confused on what would be the best way to abstract all those buffers and shaders to make them more easily usable. Some questions I have are:

What are the game development implications of treating the OpenGL concepts "VBO", "VAO" and "Shaders" as classes in my engine and how should they interact with each other?


texts: How to find the right direction to plug a sword into a rig's hand after projecting it?

texts:
I've downloaded BVH animations and projected it following a book. I can now see a 3D moving rig and it looks alright. The problem is, now I want to plug a sword on the hand of the rig, but I don't know which direction it should face. That is because each vertex has a rotation and an offset, so I can calculate their positions, but there is no information available about their normals. How is this done?

Pseudocode of the position finding procedure for illustration

calculate_position(bone)
     local = bone.rotation_x * bone.rotation_y * bone.rotation_z # matrices
     local[3] = bone.offset_x
     local[7] = bone.offset_y
     local[11] = bone.offset_z
     global = local * bone.parent.global
     return [global[3], global[7], global[11]]