Tuesday, June 30, 2015

node.js - How to keep track of players nearby other players in an MMO


I'm confused how to handle the players in my MMO server (using Socket.IO but I think this should apply to any MMO).


Suppose there are 2 players in my server that are far away from eachother. I will call them A and B in this example.


The server launches. No clients are connected.


A joins and is added to the server's active playerlist.


Every second A gets a list from the server with the active players nearby to update their positions. Since there are none online currently, the list is empty.


B joins, far away from A. The server adds B to the active playerlist. Since A cannot see B yet, the list that A receives from the server is still empty.


B is moving towards A and comes within visual range.



What to do now for A? Send an event to A that B has come within range? How can the server know that A was informed of B being nearby? Does this mean I have to maintain a list on the server which player can see another?


Here's what I was doing before with my previous project: I never told the clients that a player was in range, instead the server just sent a list every second of players that are nearby and let the client do the rest. This way, the client keeps track which unit is added and which is not. Is this the best approach, or am I missing something?



Answer



Nic explained this to me briefly yesterday. Check out the explanation on his blog.


http://nic-gamedev.blogspot.com/2011/11/mmo-architecture-creating-ghosting.html


grammatical number - “Everybody goes crazy”. Is the sentence correct?


What kind of verb should be placed after 'Everybody' - singular or plural?


Is it necessary to place 's/es' after a verb?


For example, which of the following sentences is correct?





  1. "Everybody goes crazy"




  2. "Everybody go crazy"





Answer



Everybody is singular, therefore it takes singular verb forms, and "everybody goes crazy" is correct. "Everybody go crazy" would only be correct for a command, as the third-person singular imperative form of "go" is "go".


xna - HLSL pixel inside a view (cascaded shadowmapping)



I'm figuring out shadowmapping in HLSL (see also this question). I understand that I need projection matrices for each cascading shadowmap.


I use this code to create the projections:


    Matrix CreateLightViewProjectionMatrix(LightProjectionDistance distance)
{
// Matrix with that will rotate in points the direction of the light
Matrix lightRotation = Matrix.CreateLookAt(Vector3.Zero,
-_lightDir,
Vector3.Up);

BoundingFrustum cameraFrustum = new BoundingFrustum(_view);

switch (distance)
{
case LightProjectionDistance.Close:
cameraFrustum = new BoundingFrustum(_view * _projectionClose);
break;
case LightProjectionDistance.Medium:
cameraFrustum = new BoundingFrustum(_view * _projectionMedium);
break;
case LightProjectionDistance.Far:
cameraFrustum = new BoundingFrustum(_view * _projectionFar);

break;
}

// Get the corners of the frustum
Vector3[] frustumCorners = cameraFrustum.GetCorners();

// Transform the positions of the corners into the direction of the light
for (int i = 0; i < frustumCorners.Length; i++)
{
frustumCorners[i] = Vector3.Transform(frustumCorners[i], lightRotation);

}

// Find the smallest box around the points
BoundingBox lightBox = BoundingBox.CreateFromPoints(frustumCorners);

Vector3 boxSize = lightBox.Max - lightBox.Min;
Vector3 halfBoxSize = boxSize * 0.5f;

// The position of the light should be in the center of the back
// pannel of the box.

Vector3 lightPosition = lightBox.Min + halfBoxSize;
lightPosition.Z = lightBox.Min.Z;

// We need the position back in world coordinates so we transform
// the light position by the inverse of the lights rotation
lightPosition = Vector3.Transform(lightPosition,
Matrix.Invert(lightRotation));

// Create the view matrix for the light
Matrix lightView = Matrix.CreateLookAt(lightPosition,

lightPosition - _lightDir,
Vector3.Up);

// Create the projection matrix for the light
// The projection is orthographic since we are using a directional light
Matrix lightProjection = Matrix.CreateOrthographic(boxSize.X, boxSize.Y,
-boxSize.Z, boxSize.Z);

return lightView * lightProjection;
}


Where the view matrices are like this:


        float aspectRatio = (float)graphics.PreferredBackBufferWidth / (float)graphics.PreferredBackBufferHeight;
_projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4,
aspectRatio,
1f, 500.0f);
_projectionClose = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4,
aspectRatio,
1f, 20.0f);
_projectionMedium = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4,

aspectRatio,
20.0f, 100.0f);
_projectionFar = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4,
aspectRatio,
100.0f, 500.0f);

In my Pixelshader I try this:


diffuse = input.Color;
float4 lightingPosition = mul(input.WorldPos, LightViewProjClose);
if (lightingPosition.x > -0.5 && lightingPosition.x<0.5 && lightingPosition.y>-0.5 && lightingPosition.y < 0.5)

{
diffuse = float4(1,0,0,1);
}

lightingPosition = mul(input.WorldPos, LightViewProjMedium);
if (lightingPosition.x > -0.5 && lightingPosition.x<0.5 && lightingPosition.y>-0.5 && lightingPosition.y < 0.5)
{
diffuse = float4(0,1,0,1);
}


lightingPosition = mul(input.WorldPos, LightViewProjFar);
if (lightingPosition.x > -0.5 && lightingPosition.x<0.5 && lightingPosition.y>-0.5 && lightingPosition.y < 0.5)
{
diffuse = float4(0,0,1,1);
}

return diffuse;

Now I expected to see the picture colored in red (close), green (medium) and blue (far) bands. However it seems only the close range is actually colored and the medium and far distances are not triggered. I did set the parameters like this:


_myEffect.Parameters["LightViewProjClose"].SetValue(CreateLightViewProjectionMatrix(LightProjectionDistance.Close));

_myEffect.Parameters["LightViewProjMedium"].SetValue(CreateLightViewProjectionMatrix(LightProjectionDistance.Medium));
_myEffect.Parameters["LightViewProjFar"].SetValue(CreateLightViewProjectionMatrix(LightProjectionDistance.Far));

I'm getting frustrated as I'm trying to figure this out for the past couple of days with almost no progress. What am I missing? How can I get the pixel shader switch between the correct light projections so it can pick the right cascaded shadowmap?


Edit, after tweaking this is my shader code:


float4x4 World;
float4x4 View;
float4x4 Projection;
float4x4 LightViewProjClose;
float4x4 LightViewProjMedium;

float4x4 LightViewProjFar;


float3 LightDirection1 = float3(-1.5, 0.45, 0);
float4 LightColor1 = float4(1, 1, 1, 1);
float3 LightDirection2 =float3(1,1,0.2);
float4 LightColor2 = float4(0.2, 0.2, 0.25, 1);


float4 AmbientColor = float4(0.15, 0.15, 0.15, 0.15);

float DepthBias = 0.001f;

texture ShadowMap;
sampler ShadowMapSampler = sampler_state
{
Texture = ;
};

struct VertexShaderInput
{

float4 Position : SV_POSITION;
float4 Normal : NORMAL0;
float4 Color : COLOR0;
};

struct ShadowVertexShaderInput
{
float4 Position : SV_POSITION;
float4 Normal : NORMAL0;
float4 Color : COLOR0;

};

struct VertexShaderOutput
{
float4 Position : SV_POSITION;
float4 Normal : TEXCOORD0;
float4 Color : COLOR0;
float4 WorldPos : TEXCOORD2;
};


struct CreateShadowMap_VSOut
{
float4 Position : POSITION;
float4 Color : COLOR0;
};

VertexShaderOutput VertexShaderFunction(VertexShaderInput input)
{
VertexShaderOutput output;


float4x4 WorldViewProj = mul(mul(World, View), Projection);

// Transform the models verticies and normal
output.Position = mul(input.Position, WorldViewProj);
output.Normal = input.Normal;
output.Color = input.Color;

// Save the vertices postion in world space
output.WorldPos = mul(input.Position, World);


return output;
}

float4 PixelShaderFunction(VertexShaderOutput input) : COLOR0
{
// Color of the model
float4 diffuseColor = input.Color;

// Intensity based on the direction of the light
float diffuseIntensity1 = clamp(dot(input.Normal.xyz, LightDirection1.xyz), 0, 1);

float diffuseIntensity2 = clamp(dot(input.Normal.xyz, LightDirection2.xyz), 0, 1);

// Final diffuse color with ambient color added
float4 diffuse = saturate((diffuseIntensity1 * LightColor1 + diffuseIntensity2 * LightColor2) * diffuseColor);

// Find the position of this pixel in light space in the close projection
float4 lightingPosition = mul(input.WorldPos, LightViewProjClose);
lightingPosition.xyz = 0.5 * lightingPosition.xyz / lightingPosition.w;
if (lightingPosition.x > -0.5 && lightingPosition.x<0.5 && lightingPosition.y>-0.5 && lightingPosition.y < 0.5)
{

lightingPosition = mul(input.WorldPos, LightViewProjClose);
// Find the position in the shadow map for this pixel
float2 ShadowTexCoord = 0.5 * lightingPosition.xy /
lightingPosition.w + float2(0.5, 0.5);
ShadowTexCoord.y = 1.0f - ShadowTexCoord.y;

// Get the current depth stored in the shadow map (red component for close)
float shadowdepth = tex2D(ShadowMapSampler, ShadowTexCoord).r;

// Calculate the current pixel depth

// The bias is used to prevent floating point errors that occur when
// the pixel of the occluder is being drawn
float ourdepth = (lightingPosition.z / lightingPosition.w) - DepthBias;

// Check to see if this pixel is in front or behind the value in the shadow map
if (shadowdepth < ourdepth)
{
// Shadow the pixel by lowering the intensity
diffuse *= float4(0.5, 0.5, 0.5, 0);


};
}

lightingPosition = mul(input.WorldPos, LightViewProjMedium);
lightingPosition.xyz = 0.5 * lightingPosition.xyz / lightingPosition.w;
if (lightingPosition.x > -0.5 && lightingPosition.x<0.5 && lightingPosition.y>-0.5 && lightingPosition.y < 0.5)
{

lightingPosition = mul(input.WorldPos, LightViewProjMedium);
// Find the position in the shadow map for this pixel

float2 ShadowTexCoord = 0.5 * lightingPosition.xy /
lightingPosition.w + float2(0.5, 0.5);
ShadowTexCoord.y = 1.0f - ShadowTexCoord.y;

// Get the current depth stored in the shadow map (green component for medium)
float shadowdepth = tex2D(ShadowMapSampler, ShadowTexCoord).g;

// Calculate the current pixel depth
// The bias is used to prevent floating point errors that occur when
// the pixel of the occluder is being drawn

float ourdepth = (lightingPosition.z / lightingPosition.w) - DepthBias;

// Check to see if this pixel is in front or behind the value in the shadow map
if (shadowdepth < ourdepth)
{
// Shadow the pixel by lowering the intensity
diffuse *= float4(0.5, 0.5, 0.5, 0);
};
}


//do the same trick using the 'far' matrix.
lightingPosition = mul(input.WorldPos, LightViewProjFar);
lightingPosition.xyz = 0.5 * lightingPosition.xyz / lightingPosition.w;
if (lightingPosition.x > -0.5 && lightingPosition.x<0.5 && lightingPosition.y>-0.5 && lightingPosition.y < 0.5)
{
lightingPosition = mul(input.WorldPos, LightViewProjFar);

// Find the position in the shadow map for this pixel
float2 ShadowTexCoord = 0.5 * lightingPosition.xy /
lightingPosition.w + float2(0.5, 0.5);

ShadowTexCoord.y = 1.0f - ShadowTexCoord.y;

// Get the current depth stored in the shadow map (blue component for far)
float shadowdepth = tex2D(ShadowMapSampler, ShadowTexCoord).b;

// Calculate the current pixel depth
// The bias is used to prevent floating point errors that occur when
// the pixel of the occluder is being drawn
float ourdepth = (lightingPosition.z / lightingPosition.w) - DepthBias;


// Check to see if this pixel is in front or behind the value in the shadow map
if (shadowdepth < ourdepth)
{
// Shadow the pixel by lowering the intensity
diffuse *= float4(0.5, 0.5, 0.5, 0);
};
//diffuse = float4(0, 0, 1, 1);
}
return diffuse;
}



CreateShadowMap_VSOut ShadowCloseVertexShaderFunction(VertexShaderInput input)
{
CreateShadowMap_VSOut output;

output.Position = mul(input.Position, mul(World, LightViewProjClose));
output.Color = float4(output.Position.z / output.Position.w,0,0,1);

return output;

}
CreateShadowMap_VSOut ShadowMediumVertexShaderFunction(VertexShaderInput input)
{
CreateShadowMap_VSOut output;

output.Position = mul(input.Position, mul(World, LightViewProjMedium));
output.Color = float4(0,output.Position.z / output.Position.w, 0, 1);

return output;
}

CreateShadowMap_VSOut ShadowFarVertexShaderFunction(VertexShaderInput input)
{
CreateShadowMap_VSOut output;

output.Position = mul(input.Position, mul(World, LightViewProjFar));
output.Color = float4(0,0,output.Position.z / output.Position.w, 1);

return output;
}


float4 ShadowPixelShaderFunction(CreateShadowMap_VSOut input) : COLOR0
{
return input.Color;
}

technique MyTechnique
{
pass Pass1
{
VertexShader = compile vs_4_0_level_9_3 VertexShaderFunction();

PixelShader = compile ps_4_0_level_9_3 PixelShaderFunction();
}
}

technique ShadowTechniqueClose
{

pass Pass1
{
VertexShader = compile vs_4_0_level_9_3 ShadowCloseVertexShaderFunction();

PixelShader = compile ps_4_0_level_9_3 ShadowPixelShaderFunction();
}
}
technique ShadowTechniqueMedium
{

pass Pass1
{
VertexShader = compile vs_4_0_level_9_3 ShadowMediumVertexShaderFunction();
PixelShader = compile ps_4_0_level_9_3 ShadowPixelShaderFunction();

}
}
technique ShadowTechniqueFar
{

pass Pass1
{
VertexShader = compile vs_4_0_level_9_3 ShadowFarVertexShaderFunction();
PixelShader = compile ps_4_0_level_9_3 ShadowPixelShaderFunction();
}

}

The "close" shadows seem to work. However the 'medium' and 'far' shadows are still not working. The result looks like this:


Close shadows look nice though


What am I doing wrong here?




shaders - Unity / How do I change the color of an object based on its depth?



The objective here is to change the color of the nearest object. (the nearer the object, the more "colorful" the object gets rendered; and the farther away, the more "grey" the object gets rendered), so far away objects are completely grey and close objects are in full color.


How I'm thinking about this so far:


You know, every frame, there is this certain float value, which determines if a pixel should be drawn or not. (aka z-buffer)


Can anyone tell me the variable - name of it? Or how can I access it? Can I even access it?


Edit:



The GPU is comparing two values: the depth of the new fragment you're drawing (a) and the depth value of whatever's already been drawn in that spot of the depth buffer (b).


Typically if b <= a it skips drawing the fragment because it's behind whatever's already been rendered previously.



I think I need both (a) and (b) variables - since I always need the nearer one.



Im not sure though... I think its also fine if I could only access the (b) and check every frame if the previous b was smaller.




architecture - Timestamps as ids in an entity manager?



I've built my own entity manager, as I found out some days ago, it is very similar to the Artemis framework.


For now, I just use integers as entity ids. Behind the scenes, there is a simple integer counting up every time a new entity is created so that the ids are handed out in incrementing order by the manager.


But recently I faced the problem that I cannot load multiple savegame files into the same scene. The issue here is that two savegames could use the same entity id for different things, causing a conflict when being load into the same scene.


Anyhow, the ability to load multiple savegames is useful to keep separated player data (his skills, inventory, custom items and tools he crafted) with scene data (rocks, trees, players in a town) and data from mods (cool new weapon pack).


So I need unique ids among every savegame file that will be created at all, without them knowing about each other. The idea that came to my mind is using timestamps as entity ids instead of consecutive integers.


(Since multiple entities might be created in the same millisecond, the timestamp should contain microseconds. And to play safe there could be also a mechanism to suffix a consecutive number if multiple entities are created in the same microsecond. To be honest I don't know how fast modern CPUs are and if they could do that, but I guess they can.)


Since I haven't heard of other people doing that, I assume that there is a trade-off. What are the disadvantages of using timestamps as entity ids? I think the performance hit will be minor and be can neglect that point.



Answer



Timestamps are a terrible thing to use for IDs, even with a high-precision timer 2 entities do not necessarily have to have a different ID (think how little time can have passed between 2 calls to CreateEntity()). Also you cant fit time into a simple 32bit integer. If you're going to load entities from two different sources there is a much easier fix. Load the first set of entities, find the highest ID and add this number to all IDs in the second set while loading.


Also, since you're talking savegames I'm not sure how ever 2 entities can have the same ID even though they are saved in multiple files. If they contain a saved state from the same game then all IDs should be unique.



Other scenarios you mention, like weapon packs and stuff should be wired by factory methods, which assign each component from the weapon pack fresh IDs while loaded. Wiring everything together instead of relying on predefined IDs.


xna - Slopes in 2D Platformer


I'm dealing with Slopes in a 2D platformer game I'm developing in XNA Game Studio. I was really tired of trying without success, until I found this post: 45° Slopes in a Tile based 2D platformer, and I solved part of the problem with the bummzack answer.


Now I'm dealing with 2 more problems:


1) Inverted slopes:


The post says:


If you're only dealing with 45 degree angles, then it gets even simpler:


y1 = y + (x1 - x)



If the slope is the other way round, it's:


y1 = y + (v - (x1 - x))


My question is, what if I'm dealing with slopes with less than 45 degree angles? Does y1 = y + (v - (x1 - x)) work?


2) Going down the slope:


I can't find a better way to handle the "going down through the slope" situation, considering that my player can accelerate its velocity.


Edit: I was about to post a image but I guess I need to have more reputation he he he... What I'm trying to say with "going down" is like walking towards the opposite direction, assuming that if you are walking to the right, you are incrementing your Y position because you are climbing the slope, but if you are walking to the left, you are decrementing your Y position.




Monday, June 29, 2015

Complex Game AI for Turn-based Strategy Games


I'm doing some research for a turn-based Strategy game project and looking for good resources on this topic. The game is a typical war game where countries can fight each other, deploy units and have these units move around on a hexagonal tilemap, attack each other, etc.


I'm particularly interested in how the AI of Civilization V is organized! According to Wikipedia the game uses four different AI systems for different layers of the game's AI:



  • tactical AI controls individual units

  • the operational AI oversees the entire war front

  • the strategic AI manages the entire empire

  • the grand strategic AI sets long-term goals and determines how to win the game



Conceptually this looks like it makes a lot of sense to achieve a complex AI and it makes me curious to find out about how these different AI systems work (and work together). The tactical AI is probably the most easy to understand since it handles the decision-making for a single unit (move, attack, repair, retreat, etc.) but I think the other AI systems are where it really gets interesting. For example what does the operational AI do and how does it do that? I'm sure these are best-kept secrets by Firaxis Games but it would be cool to get some discussion started on this to find out more about it.


Also if anyone knows any good books that handle turn-based strategy game AI it would be great to know. Obviously this is a sparsely seeded topic on the web. I got "Programming Game AI by Example" but that book is more about single agent behavior AI than high-level goal-oriented AI.



Answer



Whilst I agree with DampeS8N's opening paragraph (i.e. game AI only needs to be smart enough to make the player think that it's smart), I feel that this question needs a little more elaboration. The data structures in use could be FSMs for all levels, but that doesn't really answer the question as to how the individual systems work.


Disclaimer: I have hardly played the Civilization games so my understanding of the gameplay is limited. If there are any obvious errors, I do apologise. Please correct me, and I'll gladly edit.


I'll be taking quotes from the original IGN Article.


1. Tactical AI



At the lowest level, the tactical AI uses the forces at hand to win a battle on a local scale.




This is probably the most standard part of the subsystem. There are limitless ways to carry this out from using FSMs, Behaviour Trees (or even performing random actions, depending on the difficulty of the AI).


However, since this is a turn based game, similar to Risk, I think what is more likely happening is that each unit is assigned a score. There are then multipliers attached to this score depending on different variables (allegiances, terrain bonuses, etc).


The outcome is then calculated by something like this:


If (AI unit score >> (much greater) enemy unit score) Then Completely destroy enemy unit
If (AI unit score > (somewhat greater) enemy unit score) Then Partially destroy enemy unit
If (AI unit score < (somewhat less) enemy unit score) Then Partially destroy AI unit
If (AI unit score << (much less) enemy unit score) Then Completely destroy AI unit

It makes sense that the AI will try and maximize this score when in battle.



Add in an epsilon value (e.g. small random chance of failure/success) and you've got a pretty decent looking AI (no one wants a perfect opponent, that's just not fun!).


2. Operational AI



One step up from that, the operational AI picks which battles to fight and makes sure that the necessary forces are available.



I think there are a couple of points to this:



  • Evaluating current strength

  • Reinforcement of units

  • Evaluating which fights to pick/avoid



Evaluating Current Strength - This just screams Influence Map to me. It can be easily represented on a hex grid. As this subsystem is combat oriented, the influence values can be representative of the strength values of each unit in the vicinity. If you have a massive army focused in a small area of hexagons, the influence value will be huge and the operational AI will take this into account when evaluating fights to pick. Don't forget, the influence values of opposing armies will also be calculated. This allows the operational AI to predict potential incoming threats.


Reinforcements of units - By receiving information on opposing factions from the influence map, the AI can determine which units are under the most threat. The AI can then issue a command to close-by units to go and reinforce the threatened parties.


Evaluating which fights to pick/avoid - A couple of situations can occur here. If the AI detects a unit is under threat AND there are no nearby units to help it could a) decide to sacrifice the unit (if they're just lowly infantry, instead of an irreplaceable general, for example) or b) Order the unit to retreat. Conversely, if the AI detects a weak enemy unit near an army, it could order the units to take this enemy out.


Here's a decent paper that makes use of influence maps in Real Time Strategy games.


3. Strategic AI



Moving even higher, the strategic AI manages the empire as a whole, focusing on where to build cities and what to do with them.



"Where should I build a city?" just sounds like position evaluation. Chess programs and other games use it to determine the desirability of a given position. For example:



Hex A: Close to resources, on high terrain, close to allies, close to enemy Hex B: Far from resources, on mid level terrain, medium distance from allies, far from enemy


The position evaluation function could take these three factors like so:


Score = Proximity to resources (closer yields a higher score) + 
terrain elevation (higher yields higher score) +
proximity to allies (closer is better) +
proximity to enemies (farther is better)

And whichever hexagon has the higher score, will be where the city is built. More information on evaluation functions can be found here.


I reckon the strategic AI also has a bunch of pseudo-prebaked strategies in the game depending on the type of victory the AI is going for.


4. Grand Strategic AI




At the top of the ladder is the grand strategic AI, which decides how to win the game.



I think this is probably the simplest of the bunch, and it gives the impression that it's more impressive than it really is. In a game such as this, there will only be a finite number of victory types. The article mentions a Conquest victory, assuming that there are also Alliance victories, etc, it could be as simple as randomly picking one of the types and then pass it onto the other systems.


EDIT: Of course as pointed out by DampeS8N, the type of map could dictate the best victory condition to go for, in which case it could be hardcoded by the designers or some sort of evaluation function factoring in different variables.


Summary
I think what's really important to note about this kind of system is that the way the subsystems are layered, they don't actually need to be communicating a great deal with eachother. It looks to be a top-down architecture with the components loosely coupled. From a technical design point-of-view it's clean and it's flexible and probably takes its inspiration from Emergent Behaviour and/or the Subsumption Architecture.


I really do apologise for the length of this post, it's turned into a bit of a beast :(


Either way, I hope it helps!


2d - How do I incorporate .tmx files into my game?



Ok, so I have made a .tmx file for my first level, but I am unsure how I would load it into my game. Currently I am iterating through an internal array to set the blocks, but I need to know how to load the .tmx file into the code.


Here is my World.java:


import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import javax.imageio.ImageIO;
import java.io.*;

class World {
Image ground;

Block[] blocks = new Block[46];
int map[][] = {
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},

{0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1},
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1},
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1},
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1},
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1},
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1},
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1},
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1},
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},

{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
};
World() {
int enc = -1;
for (int i = 0; i < map.length; i++) {
for (int j = 0; j < map[i].length; j++) {
if (map[i][j] == 1) {

enc++;
blocks[enc] = new Block(j * 32, i * 32, 32, 32, 1);
} else if (map[i][j] == 2) {
enc++;
blocks[enc] = new Block(j * 32, i * 32, 32, 32, 2);
}
}
}
}
}



prepositions - Adj + (of) a + noun construction


I'd like someone to explain me this contruction. How often and how is it used?


For example:



It is not that big (of) a deal.



and



He is not that good (of) a husband.




Are these examples grammatically correct? Are there any other similar constructions to this one? Also, I'd apreciate if told me the "degree of formality" with this construction and when it should or shouldn't be used.


Thanks in advance.



Answer



Yes, they are grammatically correct.


While I wouldn't call it common, it's not at all obscure a construction. Making them up off the top of my head:



(After seeing the HR department stuffing pink slips in envelopes, the layoffs were) not that much (of) a surprise.


(Being told she looked like his mother was) not that charming (of) a compliment.


("Buy five get one free" is) not that much (of) a discount.


(And it's) not that great (of) a deal (either).



(He's) not that fluent (of) an English speaker.


(He's a fine programmer, but he's) not that much (of) a sys admin.


(emacs is a fine operating system, but it's) not that great (of) a text editor.


(After last season's use of the fashion, it's) not that fresh (of) an idea.



In almost all cases, it's used to connote disappointment. It's a way of saying that something did not meet a standard, particularly one that seems self-evidently pertinent because it has to do with proposition of what the thing is in the first place: an inadequate sale can barely be said to be a sale at all. If I can get a can of peas at store X for $0.50, the fact that store Y has them 20% off their regular price of $1.00, i.e. $0.80, will make me think, "Well, store Y, I suppose it is technically a sale, but I'm having trouble going along with your proposition that it's a sale to the point of thinking of it as one, because the savings of this sale are so inadequate to compete with store X that, it's not that much of a sale."


It's only very slightly informal, but I can't think of a way to use the expression of disappointment in something (which this almost always is, unless used ironically) that doesn't risk offending someone. You'll want to be careful using it, constraining yourself to employing where you really do mean to let someone know that something is inadequate, and when you're prepared for the sort of reaction that can provoke.


Interestingly, you have the classic exception at the top of your list: "Not that big of a deal", which is used to reassure that something hasn't given offense or caused distress.


phrase usage - "reflect" vs "reflection on" or "reflection of"



The bride's elegant dress reflected her good taste.


The bride's elegant dress is a reflection on her good taste.


The bride's elegant dress is a reflection of her good taste.



Would you tell me if they mean the same thing?


If they would mean the same thing, what about the following question--link--? or I mean how could we distinguish such a distinction between these functions?


Similarly, what about these:




A student's grades reflected her teacher


A student's grades are a reflection on her teacher


A student's grade are a reflection of her teacher



When, where or in which situation don't they mean the same? How can we distinguish such a distinction?




What's the meaning of "check out"?


This is a comment made by a poster on an article about texting:



It seems to me that by texting during class or at meetings, you are in no position to assess whether the topic under discussion is worth your time and attention or not. You're not paying attention. You've already mentally checked out.



What does checked out mentioned above mean? I've looked it up in the dictionaries, but wasn't able to find a definition that's relevant to the context.



Answer




Literally it refers to "checking out of a hotel." It's something you do when you leave the hotel. Once you've checked out, you're gone.


This can be used figuratively in a few ways. The basic metaphor is that once you've checked out, you're gone. It could mean several things:




  1. Death. It's what you do when you leave this mortal life behind. Once you've checked out, you're gone.




  2. Senility. If you're still here physically but mentally you've checked out, then your body is still here but your mind is gone.





In your example, it's like #2 but perhaps without the sense of permanence. Physically speaking, you're sitting in class or you're at a meeting, but mentally speaking you're not there at all. It doesn't appear to suggest actual senility in this case, though—it's just being used to describe a lack of attention. This seems to me like a slightly more extended use of the metaphor.


sentence construction - The summer training or (just) summer training


Should we use the summer training or just summer training in the paragraph. As per me training is a noun and before singular noun we have to use an article and I am using the because I am talking about a specific training for engineers, I also know that before very common nouns we avoid articles, like bed, school, bus, university, so if you say we should use summer training then please give me a valid reason.



Company(name) has been providing the summer training for engineers since 2010. We have been giving completely professional atmosphere for engineers to complete the summer training with practical knowledge. Our each faculty has a great experience in the education field. We make sure you get all the important resources to make your summer training a learning and an enjoyable summer training. You may call or email us to get your confirmation about the training.




Thanks in advance.



Answer



Though both StoneyB's answer and FumbleFinger's comment have already discussed the four "the"s in your question, I would like to provide additional information about articles, in hope that it'd be useful.


Using articles properly is difficult for learners, especially the learners who speak languages that do not have articles. Thus, it's very useful for these learners (myself included) to know the "two basic rules" listed in Practical English Usage by Michael Swan, under entry 62.1:




  • To say 'You know which I mean', we put the before a noun.
    I've been to the doctor. (You know which one: my doctor.)
    Have you fed the dogs? (You know which ones I mean.)

    Could you pass the salt? (You can see the salt that I want.)

  • When we can't say 'You know which I mean', we:

    • put a/an before a singular countable noun (see 65).
      There's a rat in the kitchen!
      I need an envelope.

    • put no article with a plural or uncountable noun.
      She's afraid of rats.
      I need help.






In short, ask yourself "Does the reader know which I mean?",



  • If YES, use the before that noun. (Have you fed the dogs?)

  • If NO, ask yourself "Is it a singular countable noun?"

    • If YES, use a/an before that noun. (I need an envelope.)

    • If NO, use no article before that noun. (She's afraid of rats.)





Please note that these two basic rules, though cover most typical cases, are not complete. There are lots of exceptions and the real practices are so complex as StoneyB wrote.




Following the two basic rules, and knowing that training is uncountable and field is countable, it's now easier to see why the first "the summer training"(1) in your question is incorrect.



Company(name) has been providing the summer training(1) for engineers since 2010. We have been giving completely professional atmosphere for engineers to complete the summer training(2) with practical knowledge. Our each faculty has a great experience in the education field(3). We make sure you get all the important resources to make your summer training a learning and an enjoyable summer training. You may call or email us to get your confirmation about the training(4).



It's because you've never mentioned this summer training before, so the reader has no idea "which summer training" you mean. Writing "the summer training" in your first sentence will make it sound like your summer training is the "only" summer training in the world.



The other two "training"s: "the summer training"(2) and "the training"(4) are acceptable because "summer training" has already been mentioned in (1), so the reader now knows which "summer training" or "training" you are talking about. However, "this" might be a better choice, as StoneyB explained.


The part "the education field"(3) needs "the", because the word field is a countable noun, which means you need an article. To pick between "an education field" and "the education field", you might need to consider if "education fields" makes sense. (If you think you can say "an education field", you should also be able to imagine several "education fields".) And since "education fields" might not make much sense in your case, it's better to write "the education field".--Think of it like this: "It's a field. Which field? It's the education field."


c# - Creating placement grid in Unity


I'm fairly new to C# and Unity, so I don't really know much about it.


I want to create an RTS like game where you have a huge grid that the whole world is placed on. Then you can place houses, walls etc on the tiles just like a lot other RTS games (i.e. Age of Empires, Stronghold Series etc).


How would I go about this in Unity? I could imagine having some Terrain/World manager that handles all the models and objects that you can interact with etc. And probably a lot of prefabs too with the different items, soldiers and so.


So if anyone have any smart way of doing this or maybe a link to a tutorial explaining, then the help would be greatly appreciated.




negation - "No, I didn't see him" vs "Yes, I didn't see him"


Bob didn't come to office today.


I was asked "Didn't you see Bob today?"


Should I say "Yes, I didn't see him today" or "No, I didn't see him today"?



Answer




"Didn't you see Bob today?" means that the person asking the question assumes that you saw Bob. The negation works like a tag question, so the sentence basically means the same as "You saw Bob today, didn't you?"


So, the appropriate response should be as if the tag question were omitted.



Speaker 1: any of… "Didn't you see Bob today?" or "You saw Bob today, didn't you?" or "You saw Bob today?" (The three formulations of the question are mostly equivalent.)


Your appropriate response: "No, I didn't see him today."



Sunday, June 28, 2015

architecture - Creating a database with special items, like in Diablo


I am in the middle of creating a browser game. I need to add 'special items' like in Diablo, but simpler. Item names are fixed (e.g. 'ring of power'), so only their attributes change.


In my game there are different towns. Each town may trade a different set of items with randomized characteristics. For instance, in Town A a 'ring of power' will have better attributes than the same item in Town B (and, thus, it will cost more).


My question is how to construct the database to handle this.


After constructing the database I will create a small script that will assign a different subset of items in each town. Each item with random attributes and a price that reflects its value.


I can make the script; what I need help on is creating the database.




Answer



You can think about items as a pair of names with description and attributes (including the price)
You can do a table 'items': ID, descid, attrid


You can make the two others like this:
'item_descriptions': ID, name, desc
'item_attributes':


ID, strength, intellect, agility, price


This would split up the description part and the, let's say, value part of the item.


Edit:
I would, as said in a comment, now recommend the following structure:



'items': ID, descid, strength, intellect, agility, price
'item_descriptions': ID, name, desc


The item is in a table with the attributes, because every attribute set should be unique.


The description is in another table, because you wanted to have the same description for different attributes.


And one thing in addition:
I strongly recommend to use memcached! With it you don't have to query the database all the time. Memory is much faster.


Is the article "a" justified in "they are wearing a cape"



You can't cast aspersions on someone just because they are wearing a cape.



Shouldn't it be capes instead of a cape? "a cape" means one cape, "they are" implies it is a group of people, a group of people can't wear one cape.


The only way I see it grammatically correct is when they stands for "he or she" to avoid sexism. Like in the sentence I saw in one video game: "The player doofos killed you with their AK47."



Answer



You actually have the answer to your question, within your question.


Let me split the sentence : You can't cast aspersions/ on someone/ just because /they are/ wearing a cape.



Note: I have not split this sentence according to any grammatical convention, I just split it up for the purpose of the discussion.




  • In the sentence you are talking about "someone" and well "someone " is singular, so your sentence is talking about a general, unknown him/her.




  • Since we are talking about a singular him/her, the usage "a cape" is correct.




  • Now, how does "they are" which implies a group of people fit into this sentence? Well let me introduce you to 'Singular they '. It is somewhat similar to the usage of 'you'

    eg: you are strong - Singular reference
    you guys stink - referring to a group of people but it is the same 'you'



  • Similarly 'they' can be used in singular and plural forms, and in your question, they is singular. Talking of singular they, I remember an example,
    when we were kids, we used to make fun of our teacher behind their back and giggle. Every time this happens, the teacher would shout " If anybody thinks they are so smart, you teach the class I will listen!" (huh, fun times).

  • Well in the above sentence 'they' is used in singular context again.


If you want to become a "Singular They Expert" you gotta check this out.


There is another more complicated concept to this "Singular They" called as epicene but explore at your own risk. I dont want do discuss further about epicene as I am not very knowledgeable with the grammatical nuances of an epicene.


Edit: I agree with @sgryzko 's comment, maybe the example I originally gave needs a little modification. The example suggested by @mplungjan is definitely an improvement - "When we were kids, we used to make fun of each and every teacher behind their back and giggle".



A phrase for describing the reaction of an element to an action


I have this sentence:




In our software we ask the user to specify some elements by clicking on the HTML element



My purpose for the sentence:
Suppose you move the mouse over some elements and the border of each element under the mouse gets highlighted as the mouse enters it.



  • The element is not highlighted before the mouse enters it

  • The element gets highlighted as the mouse enters it


If I say "highlighted element", one can't know if it was highlighted before or it gets highlighted as the mouse enters it.



Which phrase can be used instead of "highlighted" to convey this only-present-not-past-tense relation?




Saturday, June 27, 2015

What preposition is correct 'sleep on the bed' or 'sleep in the bed'


Are both expressions correct? If yes, do they have different meanings? It seems to me that I came across both of them in books, but I'm not sure.



Answer



They are both correct, but convey slightly different ideas.



I will sleep on a bed.



Implies that I will sleep on the piece of furniture I refer to as a bed. As opposed to sleeping on the couch or sleeping on the floor.




I will sleep in a bed



Specifically conveys the idea that I will be inside the bedclothes, typically underneath a blanket or duvet.


modal verbs - Difference between (might, might have and could have)


Consider:



He might go to Beijing last month.


He might have gone to Beijing last month.



He could have gone to Beijing last month.



Any difference in meaning?



Answer



1.



He might go to Beijing.



Expresses a possible future action. Therefore the use of last month is impossible. You must use a time expression that goes with the future, for example:




He might go to Beijing next month.



2.



He might have gone to Beijing last month.


He could have gone to Beijing last month.



Both express a possible situation in the past.



→ He might have gone to Beijing last month.




According to context could mean:




  • There's a possibility he went to Beijing last month, I'm not sure perhaps he did something else.




  • I know he went some place last month, I don't exactly remember where, it could be Beijing. (sentence stress on "to Beijing" when spoken)





  • I know he went to Beijing sometime or other, it could be last month but I'm not sure. (sentence stress on "last month" when spoken)





→ He could have gone to Beijing last month.



There was a possibility for him to go to Beijing last month but he didn't go.


textures - How to handle font loading?


I need to display text in my game, who doesn't.


I had originally thought that I could just statically render all the text I would need to images and use those. I'm starting to think that is a bad idea. I figure I'll have to internationalize it in the future, and the game has score counters and such which cannot be statically rendered. It looks like I'll need to use a more dynamic approach.


So my question.


How do games usually handle font loading?



  • Load the TTF directly and render it to a texture atlas.

  • Pre-bake the TTF into an image with a configuration file storing locations and kerning.




Answer



This is what you're looking for:


http://www.angelcode.com/products/bmfont/


Used by numerous games, from indies to AAA titles, to create bitmap fonts from TTFs


Using this tool or something similar is probably the most common way to implement font rendering in a game. Other options do exist (e.g. rendering vector fonts directly with something like FreeType), but the simplicity and performance of bitmap fonts usually makes them the obvious choice


(Note that Valve's distance-field stuff is super-sweet for extreme magnification of text, such as the examples of decals in an FPS, but of little or no benefit for UI text, which is often being scaled down from the source texture, or maybe scaled up just a little)


mandative - Different uses of subjunctive





  1. It is necessary for Mary to go home.




  2. It is necessary that Mary go home.





  3. It is necessary that Mary goes home.





I am wondering, what's the difference between their meanings?




3d - SharpDX/D3D: How to implement and draw fonts/text


I am playing with SharpDX (Direct3D for .NET) without using "Toolkit", already finished with basic rendering 3D models. But now i am wondering how to program/create fonts for game (2D), or how to simple draw variable text to output with Direct3D? (it is not as SharpDX question as common Direct3D question, how to start with game GUIs? And what should i do to program simple GUI's like menu for a game (generally i understand that it's shaders).




android - 2D collision detection


Let's assume I'm using this character.


bird
(source: iconbug.com)


How would you implement collision detection for it? Using a bounding box doesn't seem to be a good approximation, because the bird's shape is nowhere near a square.



I was thinking of having a sort of quad tree data structure inside the object that represents portions of the image. Each leaf could be either false (in case it covers the white/transparent space outside the bird) or true (in case it represents an area of the bird i.e. beak, eye etc). Then somehow test the only obstacle in the scene for collision with the bird.


But my problems in my approach are:



  1. I don't know how to initialize the quad tree.

  2. Once the quad tree is initialized, I'm not sure how to traverse & use it once the obstacle is within the coordinates of the image.


How would you do collision detection with non-squarish characters?


LE: The other approach I've seen was to use multiple bounding boxes. For example I'd have one or a few bounding boxes for the beak, then a few of them for the hair or the tail. But it can get tedious. If this is a valid approach in my case, how would I generate those bounding boxes? I doubt I'd have to have them hardcoded in my program.


LE2: I care about fairly precise collisions. I can't imagine how a single bounding box or circle can at least approximate decently that shape, so this approach won't work.



Answer




Circle collider. Good enough for it I would say unless you're doing something fancy with certain parts being affected by physics or the colliding looking unnatural, and even if you need to split it up into several parts I have one thing to say to you:


Don't overcomplicate it.


You don't need a full quad tree structure for this. Just have several boxes or circles in a straight array, and then intersect with all of them. This can't possibly be performance critical enough and you won't gain that much from using a quad tree.


Friday, June 26, 2015

udk - How can the Unreal Development Kit be used with Android?


I've read the UDK will support Android development, I checked the download page on the site and found nothing related to Android.


also read that Dungeon Defenders Android game was built with Unreal engine.


so is there a way to use the UDK with Android ?



Answer



I think that only the licensees have the access to android part of udk as the below page clearly mentioned about this


Android support is available to full UE3 source licensees. If you are developing a UDK title and wish to explore moving from UDK to UE3 in order to target additional platforms, please contact the sales team at Epic to discuss our competitive terms and licensing options.


http://udn.epicgames.com/Three/MobileHome.html



But if you want to confirm you can probably ask this on there development forums to the people who have there games out there.


Here is the link to epics forum.


Meaning of “it does not do (to do something)”


This is about the meaning of Dumbledore's quote “it does not do to dwell on dreams and forget to live”


From the Time article, "10 of the Most Magical Harry Potter Quotes to Inspire You":



"It does not do to dwell on dreams and forget to live"


enter image description here


Book: Sorcerer’s Stone


Who said it: Albus Dumbledore


Context: Upon finding Harry gazing longingly into the Mirror of Erised — which shows anyone who looks into it their deepest desire — Dumbledore tells Harry that he is going to move the mirror before warning him not to go searching for it again. The headmaster’s words are a reminder that dwelling on what might have been in the past or what could be in the future distracts from living in the present moment.




There is a clip on YouTube here (said around 3:47).


But what is the grammar behind those words? Is there a phrase "it doesn't do" meaning "it's not good to"?




prepositions - Question concerning a prepositional phrase


In the prepositional phrase : "Who did you give your number to?" Is the TO at the end of the sentence absolutely necessary?



Answer



The verb give participates in something called the Dative Alternation:



I gave the book to him.

I gave him the book.



Both of these sentences can be used with the same meaning. Levin gives the following examples of verbs that participate in the Dative Alternation:



  • give-type verbs: give, hand, lend, loan, rent, sell, . . . 

  • send-type verbs: send, mail, ship, . . . 

  • throw-type verbs: fling, flip, kick, lob, slap, shoot, throw, toss, . . .


But the example I've given above is very simple. If we make things more cognitively complex by making the example interrogative, then we find a strong preference for the version that is explicitly marked by a preposition. Why?


In Cognitive complexity and increased grammatical explicitness in English, Günter Rohdenburg outlines his Complexity Principle, "explicitly marked phrases are preferred over zero-marked counterparts in cognitively complex environments". Following this principle, it seems many speakers have a strong preference for including to in the interrogative version:




Who did John give the book?
Who did John give the book to?



I personally find both versions grammatical, but I think you'll find that people usually choose to include this preposition in real life examples.


How to implement rotating rectangle around circle in libGDX Box2D?


I want to implement rotating rectangle around cicrle in such way, that circle has no rotation, and rectangle has, and I could myself control rotation of this rectangle (I mean set its angular velocity). All object's are Box2D Body objects. Here is picture, what I want to have:


enter image description here



In my case rectangle touches circle, but I think it doesn't matter.


At first I tried to do it with two Fictures for same Body, but there was a problem with rotation: I couldn't have one ficture with rotation and another without.


I think, it should be somehow connected, but I don't know what exactly Joint I should use.


I tried to use DistanceJoint, but there was a problem, that I couldn't control Rectangle: when I even linear velocity of rectangle to 0 in render() method it continued to rotate.


Maybe are there another solutions?


P.S. It's important, that Cicrle should be DynamicBody, not StaticBody.



Answer



You can achieve this using a RevoluteJoint to anchor the "motor" to a point in the world, and a WeldJoint to anchor the rotating box to the "motor".


In my example I've used two static bodies, one for the circle that shouldn't move, and one for a small box inside the circle that will serve as the anchor point in the world.


The dynamic rotator Body is attached to the anchorBody using the RevoluteJoint and then the box (which is also dynamic) is welded to the rotator (which serves as the engine) using a `WeldJoint'.



The result looks like this; Rotating boxes! Sorry about the artifacts, the gif capture seems to be broken.


Full source for the above looks like this;


package com.bornander.androidstudiosandbox;

import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;

import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.BodyDef;
import com.badlogic.gdx.physics.box2d.Box2DDebugRenderer;
import com.badlogic.gdx.physics.box2d.CircleShape;
import com.badlogic.gdx.physics.box2d.FixtureDef;
import com.badlogic.gdx.physics.box2d.PolygonShape;
import com.badlogic.gdx.physics.box2d.Shape;
import com.badlogic.gdx.physics.box2d.World;
import com.badlogic.gdx.physics.box2d.joints.RevoluteJointDef;

import com.badlogic.gdx.physics.box2d.joints.WeldJointDef;

public class MyAndroidStudioSandboxGame extends ApplicationAdapter {
World world;
OrthographicCamera camera;
Box2DDebugRenderer renderer;

@Override
public void create () {
camera = new OrthographicCamera(100, 100);

camera.position.set(0,0,0);

world = new World(Vector2.Zero, true);

renderer = new Box2DDebugRenderer();

Body visibleCircle = createCircle(5, 0, 0);
visibleCircle.setType(BodyDef.BodyType.StaticBody);

Body anchorPoint = createBox(2, 2, 0, 0);

anchorPoint.setType(BodyDef.BodyType.StaticBody);

Body rotator = createBox(4,4,0,0);
rotator.setType(BodyDef.BodyType.DynamicBody);

Body box = createBox(4,4,8,0);
box.setType(BodyDef.BodyType.DynamicBody);


RevoluteJointDef revoluteJointDef = new RevoluteJointDef();

revoluteJointDef.initialize(anchorPoint, rotator, anchorPoint.getWorldCenter());
revoluteJointDef.enableMotor = true;
revoluteJointDef.motorSpeed = 20;
revoluteJointDef.maxMotorTorque = 50;

WeldJointDef weldJointDef = new WeldJointDef();
weldJointDef.initialize(rotator, box, rotator.getWorldCenter());

world.createJoint(revoluteJointDef);
world.createJoint(weldJointDef);


}

private Body createBox(float w, float h, float x, float y) {
BodyDef nodeBodyDefinition = new BodyDef();
nodeBodyDefinition.type = BodyDef.BodyType.DynamicBody;
nodeBodyDefinition.position.set(10, 10);

PolygonShape shape = new PolygonShape();
float density = 1.0f;

shape.setAsBox(w / 2.0f, h / 2.0f);

Body body = world.createBody(nodeBodyDefinition);
body.setUserData(this);
body.setTransform(x, y, 0);
final FixtureDef nodeFixtureDefinition = createFixtureDefinition(shape, density);

body.createFixture(nodeFixtureDefinition);
shape.dispose();


return body;
}

private Body createCircle(float r, float x, float y) {
BodyDef nodeBodyDefinition = new BodyDef();
nodeBodyDefinition.type = BodyDef.BodyType.DynamicBody;
nodeBodyDefinition.position.set(10, 10);

CircleShape shape = new CircleShape();
float density = 1.0f;

shape.setRadius(r);

Body body = world.createBody(nodeBodyDefinition);
body.setUserData(this);
body.setTransform(x, y, 0);
final FixtureDef nodeFixtureDefinition = createFixtureDefinition(shape, density);

body.createFixture(nodeFixtureDefinition);
shape.dispose();


return body;
}

private static FixtureDef createFixtureDefinition(final Shape shape, final float density) {
final FixtureDef nodeFixtureDefinition = new FixtureDef();
nodeFixtureDefinition.shape = shape;
nodeFixtureDefinition.friction = 1;
nodeFixtureDefinition.density = density;
nodeFixtureDefinition.restitution = 0.1f;
return nodeFixtureDefinition;

}



@Override
public void render () {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

world.step(Gdx.graphics.getDeltaTime(), 4, 4);

camera.update();

renderer.render(world, camera.combined);
}
}

intellectual property - Safe to advertise without a trademark?


Alright, I'm currently thinking about registering my game with Steam's new Greenlight program. Only problem is I don't have a trademarked title yet and I read the government's registration process can take a little while. (and $$ I don't have at the moment) So naturally, this got me wondering if it is a sound idea to proceed without one.


So my question is are there any serious pitfalls I should worry about if I start advertising without a trademarked title? (Assuming it doesn't infringe upon anyone else's property of course)




c++ - What's a way to implement a flexible buff/debuff system?


Overview:


Lots of games with RPG-like statistics allow for character "buffs", ranging from simple "Deal 25% extra damage" to more complicated things like "Deal 15 damage back to attackers when hit."


The specifics of each type of buff aren't really relevant. I'm looking for a (presumably object-oriented) way to handle arbitrary buffs.



Details:


In my particular case, I have multiple characters in a turn-based battle environment, so I envisioned buffs being tied to events like "OnTurnStart", "OnReceiveDamage", etc. Perhaps each buff is a subclass of a main Buff abstract class, where only the relevant events are overloaded. Then each character could have a vector of buffs currently applied.


Does this solution make sense? I can certainly see dozens of event types being necessary, it feels like making a new subclass for each buff is overkill, and it doesn't seem to allow for any buff "interactions". That is, if I wanted to implement a cap on damage boosts so that even if you had 10 different buffs which all give 25% extra damage, you only do 100% extra instead of 250% extra.


And there's more complicated situations that ideally I could control. I'm sure everyone can come up with examples of how more sophisticated buffs can potentially interact with each other in a way that as a game developer I may not want.


As a relatively inexperienced C++ programmer (I generally have used C in embedded systems), I feel like my solution is simplistic and probably doesn't take full advantage of the object-oriented language.


Thoughts? Has anyone here designed a fairly robust buff system before?


Edit: Regarding Answer(s):


I selected an answer primarily based on good detail and a solid answer to the question I asked, but reading the responses gave me some more insight.


Perhaps unsurprisingly, the different systems or tweaked systems seem to apply better to certain situations. What system works best for my game will depend on the types, variance, and number of buffs I intend to be able to apply.


For a game like Diablo 3 (mentioned below), where nearly any bit of equipment can change a buff's strength, the buffs are just character stats system seems like a good idea whenever possible.



For the turn-based situation I'm in, the event-based approach may be more suitable.


In any case, I'm still hoping someone comes along with a fancy "OO" magic bullet which will allow for me to apply a +2 move distance per turn buff, a deal 50% of damage taken back to the attacker buff, and a automatically teleport to a nearby tile when attacked from 3 or more tiles away buff in a single system without turning a +5 strength buff into its own subclass.


I think the closest thing is the answer I marked, but the floor is still open. Thanks to everyone for the input.



Answer



This is a complicated issue, because you're talking about a few different things that (these days) get lumped together as 'buffs':



  • modifiers to a player's attributes

  • special effects that happen on certain events

  • combinations of the above.



I always implement the first with a list of active effects for a certain character. Removal from the list, whether based on duration or explicitly is fairly trivial so I won't cover that here. Each Effect contains a list of attribute modifiers, and can apply it to the underlying value via simple multiplication.


Then I wrap it with functions to access the modified attributes. eg.:


def get_current_attribute_value(attribute_id, criteria):
val = character.raw_attribute_value[attribute_id]
# Accumulate the modifiers
for effect in character.all_effects:
val = effect.apply_attribute_modifier(attribute_id, val, criteria)
# Make sure it doesn't exceed game design boundaries
val = apply_capping_to_final_value(val)
return val


class Effect():
def apply_attribute_modifier(attribute_id, val, criteria):
if attribute_id in self.modifier_list:
modifier = self.modifier_list[attribute_id]
# Does the modifier apply at this time?
if modifier.criteria == criteria:
# Apply multiplicative modifier
return val * modifier.amount
else:

return val

class Modifier():
amount = 1.0 # default that has no effect
criteria = None # applies all of the time

That lets you apply multiplicative effects easily enough. If you need additive effects also, decide what order you're going to apply them in (probably additive last) and run through the list twice. (I'd probably have separate modifier lists in Effect, one for multiplicative, one for additive).


The criteria value is to let you implement "+20% vs Undead" - set the UNDEAD value on the Effect and only pass the UNDEAD value to get_current_attribute_value() when you're calculating a damage roll against an undead foe.


Incidentally, I wouldn't be tempted to try and write a system that applies and unapplies values directly to the underlying attribute value - the end result is that your attributes are very likely to drift away from the intended value due to error. (eg. if you multiply something by 2, but then cap it, when you divide it by 2 again, it'll be lower than it started with.)


As for event-based effects, such as "Deal 15 damage back to attackers when hit", you can add methods on the Effect class for that. But if you want distinct and arbitrary behaviour (eg. some effects for the above event might reflect damage back, some might heal you, it might teleport you away randomly, whatever) you'll need custom functions or classes to handle it. You can assign functions to event handlers on the effect, then you can just call the event handlers on any active effects.



# This is a method on a Character, called during combat
def on_receive_damage(damage_info):
for effect in character.all_effects:
effect.on_receive_damage(character, damage_info)

class Effect():
self.on_receive_damage_handler = DoNothing # a default function that does nothing
def on_receive_damage(character, damage_info):
self.on_receive_damage_handler(character, damage_info)


def reflect_damage(character, damage_info):
damage_info.attacker.receive_damage(15)

reflect_damage_effect = new Effect()
reflect_damage_effect.on_receive_damage_handler = reflect_damage
my_character.all_effects.add(reflect_damage_effect)

Obviously your Effect class will have an event handler for every type of event, and you can assign handler functions to as many as you need in each case. You don't need to subclass Effect, as each one is defined by the composition of the attribute modifiers and event handlers it contains. (It will probably also contain a name, a duration, etc.)


Thursday, June 25, 2015

Money - Countable or Uncountable noun


This page suggests that we use much with only uncountable nouns whereas the use of many/several is limited to countable nouns only. So I conclude that money is uncountable noun as I've heard people saying phrases like



So much money!



But, We do count the money in our daily life then why is it that money is considered an uncountable noun instead of countable? What if I say



I have $500 to spend




Wouldn't the money be considered countable in this case?


Edit The question may be considered duplicate of the suggested question but, in my opinion, the question on that link itself is not answered properly.



Answer



Sugar is uncountable: grains of sugar are countable.


Air is uncountable: oxygen molecules are countable.


Money is uncountable: dollars are countable.


Sometimes we want to use a collective term for stuff that you use to buy things with- that's money. When you want to start quantifying (counting) it, you have to use a currency- dollars, dinars, yen, euros.


grammar - What's the right form of verb in this sentence?


I found this sentence in the delivery note.



Above mentioned Goods received in good condition.
We are not responsible for the Goods after the delivery.

Receiver's signature.



My question why do we use the verb "received" and not "were received" or "have been received"?




java - Sphere-Sphere intersection and Circle-Sphere intersection


I have code for circle-circle intersection. But I need to expand it to 3-D. How do I calculate:



  • Radius and center of the intersection circle of two spheres

  • Points of the intersection of a sphere and a circle?


Given two spheres (sc0,sr0) and (sc1,sr1), I need to calculate a circle of intersection whose center is ci and whose radius is ri.

Moreover, given a sphere (sc0,sr0) and a circle (cc0, cr0), I need to calulate the two intersection points (pi0, pi1)
I have checked this link and this link, but I could not understand the logic behind them and how to code them.


I tried ProGAL library for sphere-sphere-sphere intersection, but the resulting coordinates are rounded. I need precise results.



Answer



Sphere-Sphere Intersection


Let's start with the more obvious one - sphere-sphere. It's almost identical to the circle-circle case in 2D. We can project down on any plane containing the line between the spheres' centers to get an identical 2D picture:


Reducing the problem to 2D


Here the first sphere has center c_1 and radius r_1, the second c_2 and r_2, and their intersection has center c_i and radius r_i. Let d = ||c_2 - c_1||, the distance between the spheres.


Edge Cases:


As was pointed out previously, if r_1 + r_2 < d then there is no intersection at all. The spheres have a separation between them.



If r_1 + r_2 == d, then the intersection is a single point, located a distance of r_1 on the line from c_1 to c_2, or: c_i = c_1 + (c_2 - c_1) * r_1/d


This can also happen from the other side, if d + min(r_1, r_2) = max(r_1, r_2). In this case, the single point of intersection lies on the larger sphere, at c_i = c_larger + (c_smaller - c_larger) * r_larger/d


Finally, if one circle is entirely encompassed within the other, such that d + min(r_1, r_2) < max(r_1, r_2), then once again there is no intersection.


Edge case examples


Typical intersections


Okay, now the meaty bit.


Let's define c_i = c_1 + h * (c_2 - c_1), for some value of h. Note that h can be negative or greater than one in the case where one circle encompasses the center of the other. Fortunately, the signs will "just work," so we don't need to add any special case logic for this condition.


The remaining, interesting cases


We can express r_1 and r_2 in terms of r_i, h, and d using Pythagorean Theorem, then solve the system of equations to find h:


$$\require{cancel} \begin{array}{r|l} (hd)^2 + r_i^2 = r_1^2 & \left((1-h)d\right)^2 + r_i^2 = r_2^2\\ h^2d^2 - r_1^2 = -r_i^2 & \left(1 - 2h + h^2 \right)d^2 - r_2^2 = -r_i^2 \end{array}\\ \begin{align} \cancel{h^2d^2} - r_1^2 &= d^2 - 2hd^2 + \cancel{h^2d^2} - r_2^2\\ 2hd^2 &= d^2 + r_1^2 - r_2^2\\ h &= \frac 1 2 + \frac {r_1^2 - r_2^2} {2 d^2} \end{align}$$



h = 1/2 + (r_1 * r_1 - r_2 * r_2)/(2 * d*d)

We can sub this into our formula for c_i above to find the center of the circle of intersections. Then, reversing one of our earlier Pythagorean relations:


r_i = sqrt(r_1*r_1 - h*h*d*d)

So, now we have the center and radius of our intersection. Now we can revolve this around the separating axis to get our full circle of solutions. The circle lies in a plane perpendicular to the separating axis, so we can take n_i = (c_2 - c_1)/d as the normal of this plane.


Our glorious intersection


After choosing a tangent and bitangent t_i and b_i perpendicular to this normal and each other, you can write any point on this circle as:


p_i(theta) = c_i + r_i * (t_i * cos(theta) + b_i sin(theta));


Because of the Hairy Ball Theorem, there's no one universal way to choose the tangent/bitangent to use. My recommendation would be to pick one of the coordinate axes not parallel to n_i, and set t_i = normalize(cross(axis, n_i)), and b_i = cross(t_i, n_i) or somesuch.




Sphere-Circle Intersection


A circle, being flat/2-dimensional, can only intersect with things within its own plane. So, the first thing is: find out where that plane intersects our sphere.


Slice


Given a circle with center & radius c_c and r_c, respectively, in the plane with (unit) normal n, and a sphere with center & radius c_s and r_s...


The plane of the circle cuts the sphere d = dot(n, c_c - c_s) units from the sphere's center. Again, this can be negative if the normal is pointing toward the sphere's center, but the signs will work out.


If abs(d) > r_s then there is no intersection. Our plane passes above/below the sphere entirely.


If there is an intersection, it will be between our original circle and a new one formed where this plane meets the sphere, with center c_p = c_s + d*n.


If d == r_s then this is the sole point of intersection with the plane; otherwise we have a circle whose radius r_p we can find with Pythagorean Theorem:



r_p = sqrt(r_s*r_s - d*d)

And now we've reduced the problem to circle-circle, which we already know how to solve. Checking the distance/radii involved according to the edge cases above will let us take care of the non-intersecting and single point of intersection cases.


Looks familiar


If the two circles do overlap by more than one point, we can use the formulae from the Sphere-Sphere check to find c_i and r_i as before.


Instead of a full circle of intersection points though, we'll have only the two points lying in the plane of the circle.


To express these points, we can define a tangent vector in the plane,


t = normalize(cross(c_p - c_c, n))

Then our intersection points are:



p_0 = c_i - t * r_i

p_1 = c_i + t * r_i

And we're done. :D


I hope that helps!


Wednesday, June 24, 2015

physics - How do I change the speed of an object without changing path travelled?


I have a ball which is being thrown from one side of a 2D space to the other. The formula I am using for calculating the ball's position at any one point in time is:


x = x0 + vx0*t
y = y0 + vy0*t - 0.5*g*t*t


where g is gravity, t is time, x0 is the initial x position, vx0 is the initial x velocity.


What I would like to do is change the speed of this ball, without changing how far it travels. Let's say the ball starts in the lower left corner, moves upwards and rightwards in an arc, and finishes in the lower right corner, and this takes 5s. What I would like to do is change it so the ball still follows the same curve and finishes in the same position, but takes 10s or 20s to do so.


How can I achieve this? All I can think of is manipulating t but I don't think that's a good idea. I'm sure it's something simple, but my maths are pretty shaky.



Answer



Actually, you're correct -- without switching equations, the only way you have of altering speed without altering the path is to manipulate t.


For the given x0 and y0, you need to record t0. Then:


rate = 0.25 // run path at one-quarter speed

t' = (t - t0) * rate


x = x0 + vx0*t'
y = y0 + vy0*t' - 0.5*g*t'*t'

Essentially what you are doing is slowing down time for the ball's path, without slowing down anything else.


physics - Frame-rate independent friction on movement in 2d game



I have been trying to implement a simple physics system for a 2D space game I am making. I have it pretty much working, but I have encountered an issue with the way I apply friction. I have tried several different ways of solving it, with different guides found online, but my math skills are lacking and it's difficult for me to translate the solutions to fit my problem.


I made a unit test that shows my problem:


            //Simulate a low FPS.
//Accelerate body1 with 100 pixels/second, for a deltaTime of 1 (A single frame that took 1 second)
body1.accelerate(100, 1);
//Performe the physics with the dame deltaTime.
body1.doPhysics(1);

//Simulate a higher fps.
//Accelerate body2 10 times, with 100 pixels/second for a deltaTime of 0.1 (A single frame that took 1/10'th of a second.

for(int j=0; j< 10; j++) {
body2.accelerate(100, 0.1);
body2.doPhysics(0.1);
}

Debug.Log("Straight movement result "+body1.getPosition()+" --- "+body2.getPosition());

Which gives the result: "Straight movement result [0.0, 50.0] --- [0.0, 39.31200662855]"


My acceleration does not seam to be a problem. I have a unit test like the other one, to test the acceleration, and it shows no problems.


public void accelerate(double acceleration, double deltaTime) {

Vector2f accel = new Vector2f(0, (float)(acceleration));

//If power is negative, we want to go backwards.
if(acceleration < 0)
accel.setTheta(angle+90 - 180);
else
accel.setTheta(angle+90);

velocity.x += (accel.x * deltaTime);
velocity.y += (accel.y * deltaTime);

}

In the doPhysics method, is where I calculate the friction. If I remove the friction calculations, the two values printed from the unit test are equal.


private static final float friction = 1.0f;//0.96f;

private void doPhysics(double deltaTime) {
//Save the velocity before applying friction.
Vector2d velBefore = new Vector2d(velocity);

//Then apply friction, with deltaTime.

velocity.x -= (velocity.x * friction) * deltaTime;
velocity.y -= (velocity.y * friction) * deltaTime;

//And then calculate the average of the friction before and after friction and factor in deltaTime
double realVelX = ((velBefore.x + velocity.x) * 0.5) * deltaTime;
double realVelY = ((velBefore.y + velocity.y) * 0.5) * deltaTime;

//Add the calculated velocity.
position.x += realVelX;
position.y += realVelY;

}

I hope someone can see what I am doing wrong. I would really like my physics to be frame-rate independent and simple enough for me to understand.




path finding - How can I generate a 2d navigation mesh in a dynamic environment at runtime?


So I've grasped how to use A* for path-finding, and I am able to use it on a grid. However, my game world is huge and I have many enemies moving toward the player, which is a moving target, so a grid system is too slow for path-finding. I need to simplify my node graph by using a navigational mesh.


I grasp the concept of "how" a mesh works (finding a path through nodes on the vertices and/or the centers of the edges of polygons).


My game uses dynamic obstacles that are procedurally generated at run-time.


I can't quite wrap my head around how to take a plane that has multiple obstacles in it and programatically divide the walkable area up into polygons for the navigation mesh, like the following image.


navigational mesh


Where do I start? How do I know when a segment of walk-able area is already defined, or worse, when I realize I need to subdivide a previously defined walk-able area as the algorithm "walks" through the map?



I'm using javascript in nodejs, if it matters.



Answer



@Stephen - Long Comment - That paper looks like it might be worth a read when I have some time. Basically what I would have suggested is something along the lines of the Hertel-Mehlhorn Algorithm which is mentioned in the paper (a reference for this specific algorithm can be found here http://www.bringyou.to/compgeom/) with the addition of subdividing the map sides (outside boundary of the play area) some number of time to reduce the occurrences of multiple small triangles formed in the corners. Those small triangles can be problematic as they can end up being smaller than the thing you’re preforming path-finding for. The Hertel-Mehlhorn is for the reduction of the polygons produced by a triangular partitioning if you’re interested here is more on triangulation: http://www.personal.kent.edu/~rmuhamma/Compgeometry/MyCG/PolyPart/polyPartition.htm.


Also, if you’d rather not reinvent the wheel, I think this library will actually do everything you need: http://code.google.com/p/polypartition/. It preforms the triangulations and reductions with one of a number of different options including Hertel-Mehlhorn. It’s an MIT License which means it can be used for closed-source and commercial projects if that is an issue.


If you do decide to keep working on your own implementation, I’d love to see what you come up with.


Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...