Tuesday, January 31, 2017

android - Sprite animation in openGL - Some frames are being skipped


Earlier, I was facing problems on implementing sprite animation in openGL ES.


Now its being sorted up. But the problem that i am facing now is that some of my frames are being skipped when a bullet(a circle) strikes on it.


What I need : A sprite animation should stop at the last frame without skipping any frame.


What I did : Collision Detection function and working properly.


PS : Everything is working fine but i want to implement the animation in OPENGL ONLY. Canvas won't work in my case.



------------------------ EDIT-----------------------


My sprite sheet. Consider the animation from Left to right and then from top to bottom


Here is an image for a better understanding.


My spritesheet ... Spritesheet


class FragileSquare{


FloatBuffer fVertexBuffer, mTextureBuffer;
ByteBuffer mColorBuff;
ByteBuffer mIndexBuff;
int[] textures = new int[1];
public boolean beingHitFromBall = false;

int numberSprites = 20;
int columnInt = 4; //number of columns as int
float columnFloat = 4.0f; //number of columns as float
float rowFloat = 5.0f;
int oldIdx;

public FragileSquare() {
// TODO Auto-generated constructor stub

float vertices [] = {-1.0f,1.0f, //byte index 0

1.0f, 1.0f, //byte index 1
//byte index 2
-1.0f, -1.0f,
1.0f,-1.0f}; //byte index 3


float textureCoord[] = {
0.0f,0.0f,
0.25f,0.0f,
0.0f,0.20f,

0.25f,0.20f


};


byte indices[] = {0, 1, 2,
1, 2, 3 };

ByteBuffer byteBuffer = ByteBuffer.allocateDirect(4*2 * 4); // 4 vertices, 2 co-ordinates(x,y) 4 for converting in float

byteBuffer.order(ByteOrder.nativeOrder());
fVertexBuffer = byteBuffer.asFloatBuffer();
fVertexBuffer.put(vertices);
fVertexBuffer.position(0);

ByteBuffer byteBuffer2 = ByteBuffer.allocateDirect(textureCoord.length * 4);
byteBuffer2.order(ByteOrder.nativeOrder());
mTextureBuffer = byteBuffer2.asFloatBuffer();
mTextureBuffer.put(textureCoord);
mTextureBuffer.position(0);


}



public void draw(GL10 gl){


gl.glFrontFace(GL11.GL_CW);


gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
gl.glVertexPointer(1,GL10.GL_FLOAT, 0, fVertexBuffer);

gl.glEnable(GL10.GL_TEXTURE_2D);
if(MyRender.flag2==1){ /** Collision has taken place*/
int idx = oldIdx==(numberSprites-1) ? (numberSprites-1) : (int)((System.currentTimeMillis()%(200*numberSprites))/200);
gl.glMatrixMode(GL10.GL_TEXTURE);
gl.glTranslatef((idx%columnInt)/columnFloat, (idx/columnInt)/rowFloat, 0);
gl.glMatrixMode(GL10.GL_MODELVIEW);
oldIdx = idx;

}



gl.glEnable(GL10.GL_BLEND);
gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);



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

gl.glTexCoordPointer(2, GL10.GL_FLOAT,0, mTextureBuffer); //5
gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);

gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, 4); //7

gl.glFrontFace(GL11.GL_CCW);


gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY);

gl.glMatrixMode(GL10.GL_TEXTURE);
gl.glLoadIdentity();
gl.glMatrixMode(GL10.GL_MODELVIEW);

}

public void loadFragileTexture(GL10 gl, Context context, int resource)
{
Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), resource);
gl.glGenTextures(1, textures, 0);

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

gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_LINEAR);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR);

gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_REPEAT);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_REPEAT);


GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0);


bitmap.recycle();
}

Answer



I think that the problem is that you are getting the time from System.currentTimeMillis(). You don't know when your code will be executed so the initial value of idx is unknown. You should save a timestamp when you detect a collision then replace System.currentTimeMillis() with (System.currentTimeMillis()-timestamp)


Pseudocode:


long timestamp;
...
if(new collision detected){
timestamp = System.currentTimeMillis();

}

In this way your time will start from the moment you detect the collision and idx will always start from 0




EDIT


copy and paste this code, it's not tested but should work.


class FragileSquare{

FloatBuffer fVertexBuffer, mTextureBuffer;
ByteBuffer mColorBuff;

ByteBuffer mIndexBuff;
int[] textures = new int[1];
public boolean beingHitFromBall = false;
int numberSprites = 20;
int columnInt = 4; //number of columns as int
float columnFloat = 4.0f; //number of columns as float
float rowFloat = 5.0f;
int oldIdx;

long timestamp = System.currentTimeMillis();

lont time=0;

public FragileSquare() {
// TODO Auto-generated constructor stub

float vertices [] = {-1.0f,1.0f, //byte index 0
1.0f, 1.0f, //byte index 1
//byte index 2
-1.0f, -1.0f,
1.0f,-1.0f}; //byte index 3



float textureCoord[] = {
0.0f,0.0f,
0.25f,0.0f,
0.0f,0.20f,
0.25f,0.20f


};



byte indices[] = {0, 1, 2,
1, 2, 3 };

ByteBuffer byteBuffer = ByteBuffer.allocateDirect(4*2 * 4); // 4 vertices, 2 co-ordinates(x,y) 4 for converting in float
byteBuffer.order(ByteOrder.nativeOrder());
fVertexBuffer = byteBuffer.asFloatBuffer();
fVertexBuffer.put(vertices);
fVertexBuffer.position(0);


ByteBuffer byteBuffer2 = ByteBuffer.allocateDirect(textureCoord.length * 4);
byteBuffer2.order(ByteOrder.nativeOrder());
mTextureBuffer = byteBuffer2.asFloatBuffer();
mTextureBuffer.put(textureCoord);
mTextureBuffer.position(0);

}




public void draw(GL10 gl){
long delta = System.currentTimeMillis() - timestamp;
timestamp = System.currentTimeMillis();

gl.glFrontFace(GL11.GL_CW);

gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
gl.glVertexPointer(1,GL10.GL_FLOAT, 0, fVertexBuffer);


gl.glEnable(GL10.GL_TEXTURE_2D);
if(MyRender.flag2==1){ /** Collision has taken place*/
int idx = oldIdx==(numberSprites-1) ? (numberSprites-1) : (int)(((time+=delta)%(200*numberSprites))/200);
gl.glMatrixMode(GL10.GL_TEXTURE);
gl.glTranslatef((idx%columnInt)/columnFloat, (idx/columnInt)/rowFloat, 0);
gl.glMatrixMode(GL10.GL_MODELVIEW);
oldIdx = idx;
}else{
time = 0;
}




gl.glEnable(GL10.GL_BLEND);
gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);



gl.glBindTexture(GL10.GL_TEXTURE_2D, textures[0]); //4
gl.glTexCoordPointer(2, GL10.GL_FLOAT,0, mTextureBuffer); //5

gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);

gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, 4); //7

gl.glFrontFace(GL11.GL_CCW);


gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
gl.glMatrixMode(GL10.GL_TEXTURE);

gl.glLoadIdentity();
gl.glMatrixMode(GL10.GL_MODELVIEW);

}

public void loadFragileTexture(GL10 gl, Context context, int resource)
{
Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), resource);
gl.glGenTextures(1, textures, 0);
gl.glBindTexture(GL10.GL_TEXTURE_2D, textures[0]);


gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_LINEAR);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR);

gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_REPEAT);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_REPEAT);


GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0);


bitmap.recycle();
}

c++ - Supporting Controllers on Mac


I'm currently developing a small, cross-platform game for Windows/OSX. I have XInput support working correctly on the Windows version. I've left off Mac controller support until now and I'm struggling to find an analogous library on OS X.


Does something similar to the XInput API exist for OS X or am I on my own for that?



Answer



I've been looking into this as well and I have yet to find something as clean and simple as XInput on the Mac. A library that's commonly recommended is OIS but it seems like it's not being maintained anymore.



You can also take a look at the game pad implementation in SFML. It has game pad support for Windows, Mac and Linux. I haven't gotten a chance to take the SFML game pad stuff for a test drive yet but I've been impressed with SFML in general.


architecture - How to handle collisions without ugly conditionals and type checking?


(I asked a similar question, but this one is far more specific).


How can I handle collisions without having to do a lot of type checking and if statements?


People here suggested that when spotting a collision, the collision detector should notify both entities in the collision, and the entities themselves will encapsulate the logic to react to the collision.


I like the idea of having the entities themselves decide how to handle the collisions. However I'm not sure how to avoid doing a lot of type checking and if statements inside the handleCollision methods.



For example (in psuedocode):


class CollisionDetector{
foreach entity in entities
foreach otherEntity in entities
if(collision(entity,otherEntity)) entity.handleCollision(otherEntity);
}

class Entity{
// .. stuff omitted
void abstract handleCollision();

}

class Alien extends Entity{
// .. stuff omitted
void handleCollision(Entity entity){
// lots of ugly conditionals and type checking
if(entity instanceof Missile) die();
if(entity instanceof Alien) lifePoints -= ((Alien)entity).getDamagePoints();
if(entity instanceof Wall) setVelocity(0,0);
// .. etc

}
}

In OOP we should try to avoid type checking and employ Polymorphism. But I don't see how this can be done in this case.


Is there a way to avoid the ugly type checking and lots of conditionals? Or should I just make my peace with it? How is this most commonly done?




subjunctives - Should a verb after "any" be singular or plural?


While I'm aware of Should nouns after "any" be singular or plural? it does not quite answer my question. I have a simple sentence:



If any of the devices was not switched off, do something.



Is there supposed to be was or were? I was thinking about was since it could be rephrased as:




If any one of the devices was not switched off, do something.



But maybe that does not make any sense at all. Also, this is for a technical documentation where more formal language is preferred, not sure if that makes any difference.



Answer



"Any" can be either singular or plural depending on the context.


"I will marry any girl who answers my email." There are many possible girls out there, but I am presumably only going to marry one of them.


"Any employees who work overtime will receive a bonus." Many employees might qualify.


In your example, the word "of" makes it so that it is not clear whether it is possible for many devices to be left on. That is, if you had said, "If any device ...", "device" is singular, so clearly a singular verb is called for. If you had said, "If any devices ...", then a plural verb would be called for.


The question then is, in context, is it only possible for one device to be left on, or could many devices be left on? I'd guess many, in which case the verb should be plural.


Most Needed Open Source Project



A few questions on the site have mentioned the need for more open source projects. I agree and wonder what frameworks should be developed.


I'll start the list.



  • A geometry kernel, including serialization (JSON, binary, compressed binary), tailored for OpenGL/DirectX

  • Gesture recognition




physics - Two balls stick together in a pool game?



When multiple collisions occur between balls, sometimes they stick together. Mostly in cases of either of the balls having high velocity.




Monday, January 30, 2017

phrase usage - What does "How come" mean?


Is How come a phrase? What does it mean? Is it formal or informal? British or American?
Can I use it in anywhere?



Answer



How come is a fixed phrase with fixed uses of its own.





  1. It means, as you have divined, why, and may be used, like why, either as the head of a noun phrase, or as a bare interrogative, or as an interrogative head; but as an interrogative head it does not take ‘DO-support’—that is, it is followed by an ordinary clause in indicative form:



    And that's why I went to the party. ... And that's how come I went to the party.
    Why? .... How come?
    Why did you go to the party? ... How come you went to the party?






  2. It is never inflected: we never say How came or How has come or How comes or anything of the sort.




How come is not used in formal writing or speech; it is distinctly casual.


Are Anaglyph 3D shaders used in game engines?


I have always wanted to put on the "3d glasses" and instead of watching a 3d movie, go to my pc and play a game in real 3D. Has anyone ever tried creating a Real 3D game? Are there any shaders that would allow creating Anaglyph 3D effect in real time? How do they work? (If they exist)



http://en.wikipedia.org/wiki/Anaglyph_3D



enter image description here




Answer



Your game will need to render two viewpoints, one for the left image and one for the right image. From there, a quick search revealed the following shader created by objo on Codeplex:


sampler2D input1 : register(S0); // right image input
sampler2D input2 : register(S1); // left image input

float4 main(float2 uv : TEXCOORD) : COLOR
{
float4 Color1;
Color1 = tex2D( input1 , uv.xy);


float4 Color2;
Color2 = tex2D( input2 , uv.xy);

Color1.r = Color2.r;
Color1.g = Color1.g;
Color1.b = Color1.b;
Color1.a = max(Color1.a,Color2.a);

return Color1;
}


While created for WPF applications, you might be able to use the above as-is or with a little bit of tweaking.


There have been many games from the NES on up that have rendered an anaglyphic or other method of 3d effect.


The above code is licensed under the CPOL


Link to Codeplex article: Anaglyph ShaderEffect in WPF


ellipsis - What's the grammar of "You kiss me tomorrow, I'll bite you face off!"?


"Zootopia" around 00:23:37/01:48:32


There is a YouTube clip (by the way, is "clip" an appropriate word?):



Nick Wilde: Hey, no kiss bye-bye for daddy?
Finnick: You kiss me tomorrow, I'll bite your face off!




Question: Is "You kiss me tomorrow" subjunctive?
Does it mean "If you kiss me tomorrow"? Then why is "if" missing?
And what does "I'll" stand for? Is it "I would"?



Answer



The future simple "will" (I'll = I will) is used in English for making promises and threats.



I will sue you (threat)
I'll be careful (promise)




Finnick, the fennec fox, is threatening to hurt Nick Wilde, if the red fox kisses him the next day.


The subordinate clause in the Zootopia exchange is “You kiss me tomorrow”, by removing the "if" in the protasis, the speaker is warning Finnick that his face will be bitten off is a certainty not a probability.



I"ll bite your face off



I'll bite your face off is the main clause, it is the CONSEQUENCE based on the condition that Nick kisses Finnick.


word usage - Should the noun be in singular or plural form after "some"?


I usually use the plural form after "some."


Example:




I bought some books about France



But I would also say some source states that France is best toured in fall. Is there a specific grammar rule? May I say that in the second sentence I am really thinking at a very specific source, so singular is needed?



Answer



Some has slightly different meanings depending on whether it is used with a singular or plural noun. When you say, "I bought some books," you mean that you bought multiple books, but not how many were purchased.


With a singular noun, some is used to talk of something whose existence is known, but whose nature or identity is not.



She is in some kind of trouble.
There must be some mistake.




pronouns - One of the pirate stories that [ was / were ] written



Treasure island is one of the best pirate stories that was/were ever written.



If I use was then will this sentence become wrong? The subject treasure island is singular, I think we should use was only.


Also, one of takes a plural noun after it, so I think we should use a singular helping verb.




physics - Are collision detection always O(n^2)?


Are physics engine able to decrease that complexity, for example by grouping objects who are near each other and check for collisions inside this group instead of against all objects ? (for example, far objects can be removed from a group by looking at its velocity and distance from other objects).


If not, does that make collision trivial for spheres (in 3d) or disk (in 2d) ? Should I make a double loop, or create an array of pairs instead ?


EDIT: For physics engine like bullet and box2d, is collision detection still O(N^2) ?





Sunday, January 29, 2017

javascript - HTML5 platformer collision detection problem


I'm working on a 2D platformer game, and I'm having a lot of trouble with collision detection. I've looked trough some tutorials, questions asked here and Stackoverflow, but I guess I'm just too dumb to understand what's wrong with my code.


I've wanted to make simple bounding box style collisions and ability to determine on which side of the box the collision happens, but no matter what I do, I always get some weird glitches, like the player gets stuck on the wall or the jumping is jittery. You can test the game here: Platform engine test. Arrow keys move and z = run, x = jump, c = shoot. Try to jump into the first pit and slide on the wall.


Here's the collision detection code:


function checkCollisions(a, b)
{
if ((a.x > b.x + b.width) ||
(a.x + a.width < b.x) ||
(a.y > b.y + b.height) ||

(a.y + a.height < b.y))
{
return false;
}
else
{
handleCollisions(a, b);
return true;
}
}


function handleCollisions(a, b)
{
var a_top = a.y,
a_bottom = a.y + a.height,
a_left = a.x,
a_right = a.x + a.width,
b_top = b.y,
b_bottom = b.y + b.height,
b_left = b.x,

b_right = b.x + b.width;

if (a_bottom + a.vy > b_top && distanceBetween(a_bottom, b_top) + a.vy < distanceBetween(a_bottom, b_bottom))
{
a.topCollision = true;
a.y = b.y - a.height + 2;
a.vy = 0;
a.canJump = true;
}
else if (a_top + a.vy < b_bottom && distanceBetween(a_top, b_bottom) + a.vy < distanceBetween(a_top, b_top))

{
a.bottomCollision = true;
a.y = b.y + b.height;
a.vy = 0;
}

else if (a_right + a.vx > b_left && distanceBetween(a_right, b_left) < distanceBetween(a_right, b_right))
{
a.rightCollision = true;
a.x = b.x - a.width - 3;

//a.vx = 0;
}
else if (a_left + a.vx < b_right && distanceBetween(a_left, b_right) < distanceBetween(a_left, b_left))
{
a.leftCollision = true;
a.x = b.x + b.width + 3;
//a.vx = 0;
}

}

function distanceBetween(a, b)
{
return Math.abs(b-a);
}

Answer



You shouldn't be checking every block stored in collisionMap.


it is many times more faster only detecting blocks around the player by indexing the original tile map.


To check if you are standing on a tile:



  1. You get the player X,Y co-ordinate


  2. Add the player height to Y.

  3. Divide this X, Y by tile width, height

  4. Index the original map data and get the tile

  5. check if tile == "n" to determine if are standing on anything or not.


You do this twice, once for the bottom left hand side of the player and once on the bottom right hand side of the player.


Code is rough and some variables are just made up but names give clue to what is what:


 // returns true if there is a tile other than "n"
function collided(x, y) {
return game.currentLevel.map[y >> 5][x >> 5] != "n";

}

// Collision for standing...
var bottomY = playerY + playerHeight;
var isStanding = collided(playerX, bottomY) || collided(playerX + playerWidth, bottomY);

// if isStanding is true then you've got to stop falling
// The % 32 part ensures the player feet lands perfectly on the tile Y boundary
if (isStanding) {
playerY = (bottomY % 32) - playerHeight;

// set other stuff here such as canJump and velocityY = 0, e.t.c.
}

You repeat this for left / right and top of the player.


Note: Your character height is higher than 32 pixels so you probably need to do 3 calls to collided, one for top, one for midway down, and one for bottom


Added more info:


 function collided(x, y) {
return game.currentLevel.map[y >> 5][x >> 5] != "n";
}


is the same as


 function collided(x, y) {
return game.currentLevel.map[Math.floor(x / 32)][Math.floor(y / 32)] != "n";
}

This >> means rotate the bits X number of times.


32 is a power of 2 number, i.e. it is a bit in binary, for this reason, rather than doing divide by 32, you can do >> 5 instead.


The advantage of doing this is the rotating bits is far faster at machine level than doing a divide and you also do not have to worry about rounding.


32 in binary is 00010000


So, if you 000010000 >> 5 Becomes 00000001



which is the same as 32 / 32 = 1


If you want to learn more, search for bitwise rotation


word request - Someone who gets an advantage by sucking up someone else


What do you call a student who always sucks up to the teachers / professors in order to gain better marks or an employee who get a promotion by complementing a higher manager or boss etc. in the polite and impolite way?



Answer



You could call the person a suck-up, or a brownnoser. These two are insults.




  • suck-up
    a person who tries to get the approval of someone in authority by saying and doing helpful and friendly things that are not sincere

  • brownnose

    : to try to get the approval of (an important or powerful person) by praise, flattery, etc.



Unreal Engine 3 vs id Tech 3 vs Unity



I'm trying to decide which engine I should start using to try to start building a game in.


I had chosen Unity, but upon hearing that Unreal Engine 3 had just become kinda free to use, I found myself questioning my decision.


Technically Unreal is still the most expensive commercially, then Unity, then id Tech 3 (free).


But, it also could be the fastest to work in? Or is just the most powerful, but Unity actually does so much for you, that it makes the most sense to work with this, and take a hit on performance/tuning (like Java/C#).


Thoughts please, can anyone speak from experience of all three?



I have experience with modding since the doom days, then in Quake 1 and Half Life. I also have experience in 3DS Max. I don't have a desire at this point my life to really get into the nitty gritty of C++ animation and rendering issues, I'd rather get something up and running quickly, to see if it's possible. But Unreal experience tempts me greatly.



Answer



UDK, id Tech 3, and Unity are all vastly different tools.


With UDK, you have script-level access, not native. As such, you are somewhat limited in the modifications you can perform. Additionally, UnrealScript is extremely slow; as such, it's difficult to optimize any product you do end up creating.


Overall, it's not very well crafted for anything that drastically doesn't match Epic's product line.


id Tech 3 will give you C++ access. That being said, it's much older technology, the tools aren't as robust, etc. Personally, I've never used it; but, it's not something you're going to build a commercial product with (unless you're looking for something scaled back. Check out this list: http://en.wikipedia.org/wiki/Id%5FTech%5F3#Projects%5Fbased%5Fon%5Fthe%5FGPL%5Fsource%5Frelease).


As for Unity? It's a great place for a beginner/someone that doesn't want to have to delve into the complex details of an engine. Additionally, it's more flexible.


Can you release a triple-A title on it? No. That being said, you're not going to be using it for that.


With the ultimate goal of educating yourself without having to dive into C++, I'd highly recommend Unity.


difference - "Consider" vs. "Regard"



1) We don't consider this film suitable for young children (LongMan)


Could it be -- We don't regard this film as a suitable film for young children


2) She is considered to be one of the finest pianist of her generation


Could it be -- She is widely regarded as the finest pianist of her generation


3) I am seriously considered resigning (it seems can't be written with regard)


4) She stood back and regarded him coldly




According to LongMan:


Regard is thinking about someone in a particular way.


Consider is to think about something carefully before making decision.


I wrote this paragraph:



While such features can be used to classify the page elements into "content" and "noise", they may not be applicable to all elements of the page. To illustrate this, suppose we want to eliminate the navigation bar from the page sidebar. We may create a rule in which the link density is employed to distinguish such a part, but when this rule is applied to the page, all such elements are removed regardless of their locations in the page, even if they are within the main content (e.g. Table of Contents). However, if the user was able to specify the context in which a rule must be applied (e.g. the page sidebar), then before removing such an element, context would be regarded.



Could it be considered in replace of regarded? Are they the same?





However, sometimes in the articles I confuse them and need a rule of thumb for that. (Now, it seems making decision is a key)




british english - -ise or -ize in IELTS writing


There are many places suggest not to mix British and American spelling in IELTS test, such as the articles on IELTS-Blog and nativespeakeronline (No link here. I don't have enough reputation to post more than 2 links).
When I search on forums, the most common idea is people in North America prefer -ize and people in other places prefer -ise. However, an article on learnenglish.de says:



the Oxford University Press insists that words such as computerize, capitalize, capsize, organize, organization, privatize, publicize, realize should take the -ize ending




And for some words in this list like "organization", people on forums say most British still prefer "organisation".
In this case, if I stick to using British spelling on IELTS test, should I use -ise or -ize for the words in this list?



Answer



I'm an American and use American spellings for everything. This answer is based on comments, including a British English speaker, and internet research.


Most British speakers and publications use -ise endings. However, as you have pointed out, Oxford Spelling uses -ize.


This has led to some British English publications and speakers using -ize, while most ignore the guideline and continue to use -ise. Tellingly, the London paper The Times switched from using -ize to -ise in 1992.


Therefore, if you're using British spellings for everything else, you should probably use -ise, but shouldn't be penalized for using -ize.


Saturday, January 28, 2017

rendering - How can I create my own sky maps?



What are the methods/tools for generating realistic skies with clouds and atmospheric shading?


FOSS alternatives and spherical projections get extra points.





verbs - First come, first served



What is the structure of this sentence?



First come, first served



"come" and "served" seem to be v3 but "first" means someone. Therefore I couldn't understand why "first come" instead of "first came"



Answer



That sentence employs two literary or rhetorical techniques with the aim of creating a stronger, more memorable statement.


The first technique is called anaphora, which is the repetition of a word or phrase at the beginning of successive clauses.


Another example of anaphora (from Abraham Lincoln's 2nd Inaugural Address):




With malice toward none; with charity for all; with firmness in the right,...



The "First ... first" anaphora makes the statement stronger by repetition and therefore easier to remember.


The second technique is called ellipsis, which is the omission of words from a sentence's syntax which would otherwise be readily understood. It is used here to shorten the sentence and thereby make it a stronger statement, packing the meaning into fewer words.


Example:



[Full] The flood destroyed my house. Why did it destroy mine?
[Elliptical] The flood destroyed my house. Why mine?



The "First come, first served" sentence without ellipsis would probably be something like the following, though there are other possibilities (elided words shown in brackets):




[Those who are] first [to] come [shall be the] first [who are/will be] served.



Notice how much pithier, how much more memorable, how much stronger is First come, first served than the complete sentence would be. Total words: four. Total impact: much, much greater.


Paint vs Draw Difference in meaning


What are the differences between 'to paint' and 'to draw' when we are talking about arts? As I guess draw refers to pictures in pencil or pen and paint to watercolor pictures or something. I need to clarify these things. :)



Answer



You're right: drawing is dry (e.g. using a pencil or pen), painting needs paint and a brush.


From here, compare a drawing:
enter image description here


with a painting:


enter image description here


grammaticality - To see vs Seeing


It felt really nice seeing all the things fall together into place.


Vs


It felt really nice to see all the things fall together into place.


Is this just an infinite- gerund thing ? Or are the meanings of the two sentences different ?



Answer




In your example



It felt really nice seeing all the things fall together into place.
It felt really nice to see all the things fall together into place.



There is no real difference in meaning or nuance.


However, the usual expression is



It felt really nice seeing things fall into place.
It felt really nice to see things fall into place.




since "all" and "together" is automatically implied and is redundant.


figurative language - Meaning of 'solitudes'



[4th and 5th last paras] Professor Hugo Cyr, of the University of Quebec in Montreal, a law clerk at the time when LeBel was appointed, ...


... says LeBel was good “at bringing people together. That allowed him to co-write very important decisions” like Dunsmuir in 2008 (that revamped the criteria for judicial review of the decisions of administrative bodies and lower courts) and the 2007 Canadian Western Banks decision on the division of powers. It signalled Ottawa doesn’t always trump the provinces, that courts would respect the legislative choices of both and advanced the idea of co-operative federalism, which LeBel developed further in other rulings and tried to “ensure that basically our federal system is not a system of two solitudes.”


1. [mass noun] The state or situation of being alone


2. A lonely or uninhabited place




The ODO definitions don't seem to fit. How does it make sense for a federal system to be [1.] left alone? It's an independent entity already? [2.] It must be inhabited, because Members of Parliament work there?



Answer



"Two solitudes" alludes to the 1945 novel Two Solitudes, by Hugh MacLennan, about the conflicts between English- and French-speaking Canadians. Today, the phrase usually refers to the way English- and French-speaking Canadians tend to live very separately from each other, with little culture or social life in common.


Here's why "two solitudes" makes sense in the context where you found it. Federalism is a "two-tier" form of government in which provinces each have their own government and there is also a national, or "federal", government. One approach to federalism would be to have a strict separation of jurisdiction and authority between the provinces and the federal government ("two solitudes"), where neither can impinge on the other's decisions—the federal government, say, attending to foreign policy, national defense, monetary policy, and inter-province commerce, and each provincial government attending to commerce within its own province, education within its own province, roads and infrastructure within its own province, etc. It appears that LeBel played an important role in decisions that established overlapping authority for the provinces and the federal government.


"Two solitudes" is an interesting, even poetic choice of words for a situation of strictly delimited authority between the federal and provincial governments. Because of the sad connotation of the word "solitude", it casts the federal and provincial governments as lonely people each tending silently to their own walled gardens on some cold, cloudy day. It suggests that they'd cheer up if they took down the walls and talked and worked together on the gardens, even though they won't agree about everything.


Because of MacLennan's novel and the term's use for Canada's cultural divide, the analogy with strict division of legislative powers might come across more clearly and with less of the poetic connotation to (English-speaking) Canadians than to other English speakers.


I just googled and found that the phrase first occurs in these two sentences of the novel: "He wondered if Heather had ever felt as he did now. Two solitudes in the infinite waste of loneliness under the sun." [link]


grammaticality - Are double negatives like 'he's never not been in the family' grammatically correct?



I'm asking this question because I was taught not to use double negatives, because they are ungrammatical and that people who use them sound uneducated. However, today here on this site I found an answer with a double negative and asked my self is it correct to use double negatives? Well my doubts arose since this answer has eight positive votes. Even though I understand the meaning of it, I still wonder if it is correct or not. Below is the answer I'm talking about as well is the link to it.



Answer:



"It might add the subtle extra nuance of meaning that since you were born he's never not been in the family."



Link: https://english.stackexchange.com/a/158385


P.S. Not trying to put this site and the people from it in doubt, just clarifying and making sure to learn well this beautiful language.




grammaticality - "What color is your car?" vs "what is the color of your car?"


The pattern what x be y? is frequent in English and can be seen in sentences like these:



What color is your car?


What time is it now?



What day does school begin?


What size is this shirt?



Are the following alternatives as good English?



What is the color of your car (or, what is your car's color)?


What is the time now?


What is the day that school begins on?


What is the size of this shirt?





Answer



All of them are grammatically fine. In the US at least, your second set is perhaps somewhat less common, particularly in speech. And the example of "What is the day that school begins on" is somewhat awkward: more natural would be "What is the day when school begins" or, among purists, "what is the day on which school begins."


Friday, January 27, 2017

textures - Preferred way to render text in OpenGL



I'm about to pick up computer graphics once again for an university project. For a previous project I used a library called FTGL that didn't leave me quite satisfied as it felt kind of heavy (I tried lots of rendering techniques, text rendering didn't scale very well).



My question is, is there a good and efficient library for this? If not, what would be the way to implement fast but nice looking text? Some intended uses are:



  • Floating object/character labels

  • Dialogues

  • Menus

  • HUD


EDIT: Preferably it could also load fonts



Answer



A popular framework is Crazy Eddie's GUI.



But whilst that is appealing, its not unusual to roll your own (and perhaps regret it as the scope increases later ;))


Its normal to have your glyphs on bitmaps and then draw the bitmaps using OpenGL.


Sometimes you show transient text that might only appear for a handful of frames. Just using GL_QUADS+glVertex will be sufficient. But for any large quantity of text or any long duration of visibility its well worth putting the GL_QUADS in a VBO - I've noticed big performance improvements from this.


There is of course the question of generating the actual glyphs that you need. There are programs like bmfont that you can use for that. Or you might need rather more complicated rendering, e.g. freetype on demand. I've been using bmfont with my own renderer quite happily, its very straightforward to deduce.


adverbs - 'not everyone is prepared' : Is 'not' a determiner?



Despite the overnight detention of Thailand's ousted prime minister Yingluck Shinawatra and a number of family members and politicians, there are indications today that not everyone is prepared to obey the commands of the leaders of the military coup. (Aussie ABC)



When I read the bold part: not everyone is prepared, I wonder if I have to take not as a determiner for the next noun, everyone, just as in half of half the season. Or if not is preposed/shifted from everyone is not prepared. Which is it?



Answer



For readers who are not familiar with the technical language, or do not have access to the Cambridge Grammar of the English Language:


OP knows that when a noun phrase (NP) starts with a chain of modifiers, the first or only word in the chain is ordinarily a determiner: an article (such as a, an, the) or a demonstrative (such as this, that, those or a quantifier (such as a number or some, all, every, few) or a possessive (such as his, her, John's).


Seeing that the subject of the clause not everybody is prepared to obey the commands &c is the NP not everybody, she wonders whether not is to be understood as a determiner, or is the ordinary negator which has been moved to the front from its ordinary position in Everyone is not prepared.


Snailplane answers that this not is a special kind of modifier ("pre-head dependent") which precedes everyone in order to negate only that constituent, not the entire sentence. Not everyone is prepared means [not every] one is prepared—some people may be prepared, but at least one person is not.



This is the ordinary way in which we partially deny an assertion about everyone, everybody, all (of), everything, one, or about NPs in which these are used in the possessive



Not everything you read on the internet is true.
Not all of us agree with you. Not one of us agrees with you.
Not everybody's mother is so forgiving as his.



Not can also be used this way with some other quantifiers/quantified pronouns, such not many, not a few, not much, not a little.



Not many were impressed with his lecture.
Not a few of us think otherwise.




But these expressions are only used at the beginning of a subject NP. For instance, we do not say



He greeted not everyone.
He gave not everyone a smile.



Not is not used this way with other quantifiers/quantified pronouns except in not..but constructions; these constructions can play any syntactic role:



Not some but all of us are angry.
They gave not three but eight scholarships.




unity - How can I fix zig-zagging UV mapping artifacts on a generated mesh that tapers?



I am creating a procedural mesh based on a curve and the size of the mesh gets smaller throughout the curve as you see below.


enter image description here


And the problem is UV gets zig-zagged as the size changes (it works perfectly when the size of the mesh is same throughout the curve).


enter image description here


 Vertices.Add(R);
Vertices.Add(L);
UVs.Add(new Vector2(0f, (float)id / count));
UVs.Add(new Vector2(1f, (float)id / count));
start = Vertices.Count - 4;
Triangles.Add(start + 0);

Triangles.Add(start + 2);
Triangles.Add(start + 1);
Triangles.Add(start + 1);
Triangles.Add(start + 2);
Triangles.Add(start + 3);

mesh.vertices = Vertices.ToArray();
//mesh.normals = normales;
mesh.uv = UVs.ToArray();
mesh.triangles = Triangles.ToArray();


How can I fix this?




What's the difference between "noun to verb" and "noun that verb" in meaning?


Is there a subtle difference between those sentences in meaning?





  1. A hero is a brave person who does things to help others.

  2. A hero is a brave person who does things that help others.




Answer



Yes, there is a very subtle difference in meaning. In the first sentence, the emphasis is on helping others:



A hero is a brave person who does things to help others.




In the second sentence, the emphasis is on the actions (things) that are done by the hero:



A hero is a brave person who does things that help others.



You'd more likely use the first example for a hero who seeks out people who are in trouble and then does things to help them - imagine a hero who rescues people from captivity. The emphasis is on the people.


The second example would be for a hero who does things that are good, with the goal that some possibly unknown people might benefit from those actions - imagine a hero who kills an evil witch. The emphasis is on the heroic action.


verbs - to get VS. getting


When I have to catch a train, I'm always worried that I'll miss it. So, I like getting/ to get to the station in plenty of time.


In grammar in use book, the bold part has been considered as correct answer. I am wondering why.


What is more, would you show me a more detailed explanation or another synonym for the following?-- I have some problem with especially using the preposition in along with plenty of time.


in plenty of time


My specific question is here:


Although there has been mentioned something an habit or something like that-- considering the adverb"always"--,so why don't we say getting?



Thanks in advance



Answer



Regarding the use of in with time:


There's a couple of common expressions that use in with time (there's probably more than below):


In time - means before an understood deadline of some sort. It differs from on time - on time means you arrived at the correct time - in time may mean you got there early.


("In time" can mean "when circumstances allow" or "eventually" - it will usually but not always start the sentence, or precede the subject-verb part of the sentence, i.e. In time, we will conquer the enemy or *If you keep working at it, in time you will succeed.)


In plenty of time - means with an ample amount of time left over.


For in time and in plenty of time, the point of time that you arrive is "within" or "inside of" the range of time you have to be at the destination, so "in" makes sense.


Let's say we are talking about a train - the train leaves at 5:00PM, and you learned of the train leaving then at 3:00PM. You arrived at 4:45PM. 4:45PM is in the range of 3:00PM to 5:00PM.


Some others:



In good time - equivalent to in plenty of time (people racing one another comes to mind with this)


In enough time - when something is ready - The cookies are baking. In enough time we can eat them.


In no time - means something has taken no time to happen, or a very short duration of time passed. - I was driving recklessly and got to the station in no time.


So...



I like getting to the station in plenty of time.


I like to get to the station in plenty of time.



These sound fine to me, but are something you'd hear in speech more than see in writing in my opinion.





Regarding the difference between getting and to get:


In my initial opinion as a native speaker, there is not a difference between them. However, this says the following:



Using a gerund (-ing form) suggests that you are referring to real activities or experiences. Using an infinitive (to X) suggests that you are talking about potential or possible activities or experiences.



So, since you are talking about a potential activity, to get is the right thing to use.


opengl - Can I make color data not render as gradient?


I would like for the color between my vertices to not be rendered as a gradient, but as a hard break. Is there any way to accomplish this in OpenGL/GLSL?



Answer



You can try doing this with flat attribute qualifier in shaders, like so:


flat vec3 surfColor;

It tells GLSL to pass values from vertex to fragment without interpolation.


From GLSL Interpolation qualifiers:



Interpolation qualifiers control how interpolation of values happens across a triangle or other primitive. There are three basic interpolation qualifiers.



flat​ The value will not be interpolated. The value given to the fragment shader is the value from the Provoking Vertex for that primitive.
...



Additional read on SO: https://stackoverflow.com/questions/27581271/flat-qualifier-in-glsl


meaning - Should vs. Shouldn't



They believe this.



  1. Should they?


  2. Shouldn't they?



Do the both replies mean the same?



Answer



Both questions are asking for a normative statement in response to somebody's belief. However, there is a difference in emphasis.


As I said in an answer to the question "'should They?' or 'should they be?'?":



These are actually both fine, but they have a different emphasis.




They believe this. Should they?



This is stating they believe something but then questioning if it's appropriate. In other words, there is doubt being expressed.


It could be rephrased as:



They believe this. But why do they believe it? Isn't is strange that they do?






They believe this. Shouldn't they?




This is stating that they believe it but then questioning why it should be questioned. Here, there isn't doubt in the appropriateness of the belief itself but puzzlement as to why somebody might think it should be otherwise.


It could be rephrased as this:



They believe this. Is there some reason to think their belief is wrong?




You can ask either Should they? or Shouldn't they? and get the same general answer in response. But which wording you use, as well as the tone of voice associated with it if it's asked in conversation rather than writing, will determine if you, as the questioner, are more critical or supportive of the belief.


ai - What should be created first in a video game?



When starting developing a video game, should one focus on creating the environment (buildings, trees, mountains etc) first or the A.I. (Playable character, NPCs etc)?



Answer



The first step is to create a minimum viable product.



A MVP is the absolute minimum which can be considered a playable game. It doesn't need any graphics yet except for some placeholders. It should just accept basic input and implement the most core game mechanics.


Then iterate from there.


The reason is that you need a test-bed for testing out if your game idea actually works. You could waste months developing assets and AI for a game idea which turns out to not be fun at all when actually played and you would be forced to trash it all.


Also, it's next to impossible to design assets and AI "blind" without being able to put them in the game and experience for yourself how they look and feel when actually playing with them. When you have no working prototype game to put these into you might end up wasting countless hours. You will design and polish assets which you will then redesign from scratch when you have finally the chance to see them in the game. And after that you might end up throwing them away anyway because you decide to remove the game mechanic which uses them for not being fun.


Then when you have your prototype, the question "AI first or graphics first" is quite nonsensical because you usually have programmers and artists working on each in parallel. However it is important for them to communicate, because look and behavior of actors in a game need to match. The player will expect that a "bulky brute" enemy behaves differently than a "nimble speedster" enemy. The process can be driven by the programmers ("We are programming an object which behaves such-and-such, come up with how it could look"), by the artists ("We are designing an object which looks such-and-such, come up with a way how it could behave") or it could be a synergetic process where both sit together and brainstorm ideas for new game entities. Whatever process works for your particular team.


c# - Unity: detect animation's end


I need a way to detect if animation's clip finished playing and then execute a certain code. Here's some script, that I wrote (called in Update):


    if (Input.GetButtonDown ("Fire1") && pc_atttacking == false && PlayerStats.staminaCurrent != 0) {
pc_atttacking = true;
pc_anim.SetBool("attack", true);
}


if (pc_anim.GetCurrentAnimatorStateInfo (0).IsName ("attack")) {
pc_atttacking = false;
pc_anim.SetBool("attack", false);
}

But it doesn't work as I want; it executes second code too early - when "attack" animation is at slightly more than half of playing position. I want to execute it when "attack" animation is at last frame.




Thursday, January 26, 2017

singular vs plural - "0.4 point" or "0.4 points"? "1.0 point" or "1.0 points"?



I still can't wrap my head around this one and have to consult references every time I want to be safe:



  • Is it "0.4 point" or "0.4 points"?

  • Is it "1.0 point" or "1.0 points"?


I know that I can work around that by using four tenths of a point or one point instead, but sometimes writing 0.4 point/points or 1.0 point/points is called for, especially in technical documents.


I gathered that this mostly goes by the style guide I choose to (or have to) use, and it's quite possible that there is no universally accepted convention for this. Then again, in light of potential benefits for learners here, I think it's worth asking, and I hope that we can lay out some rules of thumb, something that can be used as a general guideline, especially on writing tests and exams.


Addendum: another case that's worth mentioning in answers, for completeness, is "0.0 point" or "0.0 points"? In my humble opinion, it's safe to assume that most learners on our site know what to use when the quantity falls out of the range between -1.0 and 1.0.



Answer



I started analyzing this question by trying to figure out a context where I might use this. I thought of a gymnastics meet, where someone might say:




Alex lost by X points.



If X = 1, the answer is obvious. If X = 1.0, though, the answer isn't so clear, particularly if the it's presumed the speaker would include the "point oh" part of the numerical value in the quote.


I think I'd be inclined to use the plural:



Alex lost by one point zero points.



because I'd certainly use the plural if the eventually winner had scored a tenth of a point more or less:




Alex lost by one point one points. (for 1.1)
Alex lost by zero point nine points. (for 0.9)



That's how this quiz seems to handle the quandary, and, while it's not unanimous, that's the conclusion that seems to have been drawn on this forum, too.


Interestingly enough, when I tried to find instances of “1.0 point” online, many of the hits were preceded by an article, where the singular would make more sense:



This is a 1.0 point [pen], and what I wanted was the 1.6 point.


Typically, these loans come with a 3.0 or 3.5 point fee attached, but right now you can receive a 48-60 month Buy & Hold loan with just a 1.0 point fee.



grammaticality - Is there a grammatical rule impeding the presence of 'for' in "I have lived here 'for' all my life"?




  1. I have lived here all my life.

  2. I have lived here for all my life.




Yes, 1 is perfectly 'standard' English, but I wonder why one cannot add for to 1 before 'all my life'?


Is there a grammatical rule governing this matter? If so, can anybody explain such rule?


I'm asking because in my language, as far as I know, both 1 and 2 are acceptable, with and without for (per).




fixed timestep - What is the point of update independent rendering in a game loop?


There are dozens of articles, books and discussions out there on game loops. However, I pretty often come across something like this:


while(running)
{
processInput();
while(isTimeForUpdate)
{
update();

}
render();
}

What basically is bothering me about this approach is the "update-independent" rendering e.g. render a frame when there is no change at all. So my question is why this approach is often taught?



Answer



There's a long history of how we arrived at this common convention, with lots of fascinating challenges along the way, so I'll try to motivate it in stages:


1. Problem: Devices run at different speeds


Ever try to play an old DOS game on a modern PC, and it runs unplayably fast - just a blur?


A lot of old games had a very naive update loop - they'd collect input, update game state, and render as fast as the hardware would allow, without accounting for how much time had elapsed. Which means as soon as the hardware changes, the gameplay changes.



We generally want our players to have a consistent experience and game feel on a range of devices, (as long as they meet some minimum spec) whether they're using last year's phone or the newest model, a top-end gaming desktop or a mid-tier laptop.


In particular, for games that are competitive (either multiplayer or via leaderboards) we don't want players running on a particular device to have an advantage over others because they can run faster or have more time to react.


The surefire solution here is to lock the rate at which we do gameplay state updates. That way we can guarantee the results will always be the same.


2. So, why not just lock the framerate (eg. using VSync) and still run the gameplay state updates & rendering in lockstep?


This can work, but is not always palatable to the audience. There was a long time when running at a solid 30 fps was considered the gold standard for games. Now, players routinely expect 60 fps as the minimum bar, especially in multiplayer action games, and some older titles now look noticeably choppy as our expectations have changed. There's also a vocal group of PC players in particular who object to framerate locks at all. They paid a lot for their bleeding-edge hardware, and want to be able to use that computing muscle for the smoothest, highest-fidelity rendering it's capable of.


In VR in particular, framerate is king, and the standard keeps creeping up. Early in the recent resurgence of VR, games often ran around 60 fps. Now 90 is more standard, and harware like the PSVR is beginning to support 120. This may continue to rise yet. So, if a VR game limits its framerate to what's doable & accepted today, it's liable to be left behind as hardware and expectations develop further.


(As a rule, be wary when told "players can't perceive anything faster than XXX" as it's usually based on a particular type of "perception," like recognizing a frame in sequence. Perception of continuity of motion is generally far far more sensitive. )


The last issue here is that a game using a locked framerate also needs to be conservative - if you ever hit a moment in the game where you're updating & displaying an unusually high number of objects, you don't want to miss your frame deadline and cause a noticeable stutter or hitch. So you either need to set your content budgets low enough to leave headroom, or invest in more complicated dynamic quality adjustment features to avoid pegging the whole play experience to the worst-case performance on min-spec hardware.


This can be especially problematic if the performance problems show up late in development, when all your existing systems are built & tuned assuming a lockstep rendering framerate that now you can't always hit. Decoupling update & rendering rates gives more flexibility for dealing with performance variability.


3. Doesn't updating at a fixed timestep have the same problems as (2)?



I think this is the meat of the original question: if we decouple our updates and sometimes render two frames with no game state updates in between, then isn't it the same as lockstep rendering at a lower framerate, since there's no visible change on the screen?


There's actually several different ways games use the decoupling of these updates to good effect:


a) The update rate can be faster than the rendered framerate


As tyjkenn notes in another answer, physics in particular is often stepped at a higher frequency than the rendering, which helps minimize integration errors and give more accurate collisions. So, rather than having 0 or 1 updates between rendered frames you might have 5 or 10 or 50.


Now the player rendering at 120 fps can get 2 updates per frame, while the player on lower spec hardware rendering at 30 fps gets 8 updates per frame, and both their games run at the same gameplay-ticks-per-realtime-second speed. The better hardware makes it look smoother, but doesn't radically alter how the gameplay works.


There's a risk here that, if the update rate is mismatched to the framerate, you can get a "beat frequency" between the two. Eg. most frames we have enough time for 4 game state updates and a little leftover, then every so often we have enough saved up to do 5 updates in a frame, making a little jump or stutter in the movement. This can be addressed by...


b) Interpolating (or extrapolating) the game state between updates


Here we'll often let the game state live one fixed timestep in the future, and store enough information from the 2 most recent states that we can render an arbitrary point between them. Then when we're ready to show a new frame on-screen, we blend to the appropriate moment for display purposes only (ie. we don't modify the underlying gameplay state here)


When done right this makes the movement feel buttery smooth, and even helps to mask some fluctuation in framerate, as long as we don't drop too low.


c) Adding smoothness to non-gameplay-state changes



Even without interpolating gameplay state, we can still get some smoothness wins.


Purely visual changes like character animation, particle systems or VFX, and user interface elements like HUD, often update separately from the gameplay state's fixed timestep. This means if we're ticking our gameplay state multiple times per frame, we're not paying their cost with every tick - only on the final render pass. Instead, we scale the playback speed of these effects to match the length of the frame, so they play as smoothly as the rendering framerate allows, without impacting game speed or fairness as discussed in (1).


Camera movement can do this too - especially in VR, we'll sometimes show the same frame more than once but reproject it to take into account the player's head movement in between, so we can improve the perceived latency and comfort, even if we can't natively render everything that fast. Some game streaming systems (where the game is running on a server and the player runs only a thin client) use a version of this too.


4. Why not just use that (c) style for everything? If it works for animation and UI, can't we simply scale our gameplay state updates to match the current framerate?


Yes* this is possible, but no it's not simple.


This answer is already a bit long so I won't go into all the gory details, just a quick summary:




  • Multiplying by deltaTime works to adjust to variable-length updates for linear change (eg. movement with constant velocity, countdown of a timer, or progress along an animation timeline)





  • Unfortunately, many aspects of games are non-linear. Even something as simple as gravity demands more sophisticated integration techniques or higher-resolution substeps to avoid diverging results under varying framerates. Player input and control is itself a huge source of non-linearity.




  • In particular, the results of discrete collision detection and resolution depend on update rate, leading to tunneling and jittering errors if frames get too long. So a variable framerate forces us to use more complex/expensive continuous collision detection methods on more of our content, or tolerate variability in our physics. Even continuous collision detection runs into challenges when objects move in arcs, requiring shorter timesteps...




So, in the general case for a game of medium complexity, maintaining consistent behaviour & fairness entirely through deltaTime scaling is somewhere between very difficult & maintenance intensive to outright infeasible.


Standardizing an update rate lets us guarantee more consistent behaviour across a range of conditions, often with simpler code.


Keeping that update rate decoupled from rendering gives us flexibility to control the smoothness and performance of the experience without altering the gameplay logic.



Even then we never get truly "perfect" framerate independence but like so many approaches in games it gives us a controllable method to dial in toward "good enough" for the needs of a given game. That's why it's commonly taught as a useful starting point.


Wednesday, January 25, 2017

grammar - "The irrealis mood form is unique to be, and limited to the 1st and 3rd person singular"



"The irrealis mood form is unique to be, and limited to the 1st and 3rd person singular”



Rodney Huddleston and Geoffrey K. Pullum, A Student's Introduction to English Grammar. Cambridge University Press, 2005



What did he mean by this?



"if you were" - About 222,000,000 results


"if you was" About 17,200,000 results


"if you were my girlfriend" About 2,380,000 results


"if you was my girlfriend" About 34 results





Tuesday, January 24, 2017

sentence meaning - Using of past perfect


In the following sentence we use the past perfect tense:



He had probably crashed because he had gone to sleep while he was driving.



I thought the past perfect is used when we're talking about "before-past-events". What in the sentence we're talking about? He have already crashed or it is less direct predicting to the future?



Answer




Context, context, context.


Yes, past perfect may be used to introduce "before-past" events; but the past Reference Time (RT) which such events precede does not have to be explicitly mentioned in the same sentence. Consider, just for instance, two distinct contexts in which this conclusion might be uttered:



The driver left Boston at about 10 am on the 22nd. The crash occurred at 1:40 pm on the 23rd, sixteen hundred miles away; he must have driven through the night, without stopping to sleep. He probably crashed because he went to sleep while he was driving.



This paragraph puts the sentence in the context of a present judgment. It is uttered (Speech Time) in the present, and it narrates prior events in the simple past, locating those events at a past RT.



Sgt. Turnbull gave evidence for the Highway Patrol. He showed that the driver had been on the road for more than twenty-seven hours without sleeping. He had probably crashed because he had gone to sleep while he was driving.



This paragraph puts the sentence in the context of a past judgment, uttered at the time of the hearing, a past RT. The events it narrates occurred prior to that RT and are consequently expressed with the past perfect.





Note that this is a modal past, not a perfect.


algorithm - How to correct shooting in touch-screen shooting games?


Assume a shooting game for iPhone that the character shoot toward where player has touched.


But as we know, There may be fault in touching screen by player and it conclude to bad game play and low fun.


So, How can I correct shooting method ?



Answer




I think when player touch a point, he target some thing that will place in a cone as below picture show.


enter image description here


So, we just need to check collision of objects in this cone, and if any exist, the player most probably decided to shoot at it.


unity - Algorithm for creating spheres?


Does anyone have an algorithm for creating a sphere proceduraly with la amount of latitude lines, lo amount of longitude lines, and a radius of r? I need it to work with Unity, so the vertex positions need to be defined and then, the triangles defined via indexes (more info).





EDIT


enter image description here


I managed to get the code working in unity. But I think I might have done something wrong. When I turn up the detailLevel, All it does is add more vertices and polygons without moving them around. Did I forget something?




EDIT 2


enter image description here


I tried scaling the mesh along its normals. This is what I got. I think I'm missing something. Am I supposed to only scale certain normals?



Answer



To get something like this:


enter image description here



Create an icosahedron (20-sided regular solid) and subdivide the faces to get a sphere (see code below).


The idea is basically:



  • Create a regular n-hedron (a solid where every face is the same size and every edge is the same length). I use an icosahedron because it's the regular solid with the greatest number of faces. (There's a proof for that somewhere out there. Feel free to Google if you're really curious.) This will give you a sphere where nearly every face is the same size, making texturing a little easier.


enter image description here




  • Subdivide each face into four equally-sized faces. Each time you do this, it'll quadruple the number of faces in the model.


    ///      i0

    /// / \
    /// m02-m01
    /// / \ / \
    /// i2---m12---i1


i0, i1, and i2 are the vertices of the original triangle. (Actually, indices into the vertex buffer, but that's another topic). m01 is the midpoint of the edge (i0,i1), m12 is the midpoint of the edge (i1,12), and m02 is, obviously, the midpoint of the edge (i0,i2).


Whenever you subdivide a face, make sure that you don't create duplicate vertices. Each midpoint will be shared by one other source face (since the edges are shared between faces). The code below accounts for that by maintaining a dictionary of named midpoints that have been created, and returning the index of a previously created midpoint when it's available rather than creating a new one.





  • Repeat until you've reached the desired number of faces for your cube.




  • When you're done, normalize all of the vertices to smooth out the surface. If you don't do this, you'll just get a higher-res icosahedron instead of a sphere.




  • Voila! You're done. Convert the resulting vector and index buffers into a VertexBuffer and IndexBuffer, and draw with Device.DrawIndexedPrimitives().




Here's what you'd use in your "Sphere" class to create the model (XNA datatypes and C#, but it should be pretty clear):



        var vectors = new List();
var indices = new List();

GeometryProvider.Icosahedron(vectors, indices);

for (var i = 0; i < _detailLevel; i++)
GeometryProvider.Subdivide(vectors, indices, true);

/// normalize vectors to "inflate" the icosahedron into a sphere.
for (var i = 0; i < vectors.Count; i++)

vectors[i]=Vector3.Normalize(vectors[i]);

And the GeometryProvider class


public static class GeometryProvider
{

private static int GetMidpointIndex(Dictionary midpointIndices, List vertices, int i0, int i1)
{

var edgeKey = string.Format("{0}_{1}", Math.Min(i0, i1), Math.Max(i0, i1));


var midpointIndex = -1;

if (!midpointIndices.TryGetValue(edgeKey, out midpointIndex))
{
var v0 = vertices[i0];
var v1 = vertices[i1];

var midpoint = (v0 + v1) / 2f;


if (vertices.Contains(midpoint))
midpointIndex = vertices.IndexOf(midpoint);
else
{
midpointIndex = vertices.Count;
vertices.Add(midpoint);
midpointIndices.Add(edgeKey, midpointIndex);
}
}



return midpointIndex;

}

///
/// i0
/// / \
/// m02-m01
/// / \ / \

/// i2---m12---i1
///

///
///
public static void Subdivide(List vectors, List indices, bool removeSourceTriangles)
{
var midpointIndices = new Dictionary();

var newIndices = new List(indices.Count * 4);


if (!removeSourceTriangles)
newIndices.AddRange(indices);

for (var i = 0; i < indices.Count - 2; i += 3)
{
var i0 = indices[i];
var i1 = indices[i + 1];
var i2 = indices[i + 2];

var m01 = GetMidpointIndex(midpointIndices, vectors, i0, i1);

var m12 = GetMidpointIndex(midpointIndices, vectors, i1, i2);
var m02 = GetMidpointIndex(midpointIndices, vectors, i2, i0);

newIndices.AddRange(
new[] {
i0,m01,m02
,
i1,m12,m01
,
i2,m02,m12

,
m02,m01,m12
}
);

}

indices.Clear();
indices.AddRange(newIndices);
}


///
/// create a regular icosahedron (20-sided polyhedron)
///

///
///
///
///
///
/// You can create this programmatically instead of using the given vertex

/// and index list, but it's kind of a pain and rather pointless beyond a
/// learning exercise.
///


/// note: icosahedron definition may have come from the OpenGL red book. I don't recall where I found it.
public static void Icosahedron(List vertices, List indices)
{

indices.AddRange(
new int[]

{
0,4,1,
0,9,4,
9,5,4,
4,5,8,
4,8,1,
8,10,1,
8,3,10,
5,3,8,
5,2,3,

2,7,3,
7,10,3,
7,6,10,
7,11,6,
11,0,6,
0,1,6,
6,1,10,
9,0,11,
9,11,2,
9,2,5,

7,2,11
}
.Select(i => i + vertices.Count)
);

var X = 0.525731112119133606f;
var Z = 0.850650808352039932f;

vertices.AddRange(
new[]

{
new Vector3(-X, 0f, Z),
new Vector3(X, 0f, Z),
new Vector3(-X, 0f, -Z),
new Vector3(X, 0f, -Z),
new Vector3(0f, Z, X),
new Vector3(0f, Z, -X),
new Vector3(0f, -Z, X),
new Vector3(0f, -Z, -X),
new Vector3(Z, X, 0f),

new Vector3(-Z, X, 0f),
new Vector3(Z, -X, 0f),
new Vector3(-Z, -X, 0f)
}
);


}




}

rotation - Arcball Problems with UDK



I'm trying to re-create an arcball example from a Nehe, where an object can be rotated in a more realistic way while floating in the air (in my game the object is attached to the player at a distance like for example the Physics Gun) however I'm having trouble getting this to work with UDK.


I have created an LGArcBall which follows the example from Nehe and I've compared outputs from this with the example code.


I think where my problem lies is what I do to the Quaternion that is returned from the LGArcBall.


Currently I am taking the returned Quaternion converting it to a rotation matrix. Getting the product of the last rotation (set when the object is first clicked) and then returning that into a Rotator and setting that to the objects rotation.


If you could point me in the right direction that would be great, my code can be found below.


class LGArcBall extends Object;

var Quat StartRotation;
var Vector StartVector;
var float AdjustWidth, AdjustHeight, Epsilon;


function SetBounds(float NewWidth, float NewHeight)
{
AdjustWidth = 1.0f / ((NewWidth - 1.0f) * 0.5f);
AdjustHeight = 1.0f / ((NewHeight - 1.0f) * 0.5f);
}

function StartDrag(Vector2D startPoint, Quat rotation)
{
StartVector = MapToSphere(startPoint);

}

function Quat Update(Vector2D currentPoint)
{
local Vector currentVector, perp;
local Quat newRot;

//Map the new point to the sphere
currentVector = MapToSphere(currentPoint);


//Compute the vector perpendicular to the start and current
perp = startVector cross currentVector;

//Make sure our length is larger than Epsilon
if (VSize(perp) > Epsilon)
{
//Return the perpendicular vector as the transform
newRot.X = perp.X;
newRot.Y = perp.Y;
newRot.Z = perp.Z;


//In the quaternion values, w is cosine (theta / 2), where
//theta is the rotation angle
newRot.W = startVector dot currentVector;
}
else
{
//The two vectors coincide, so return an identity transform
newRot.X = 0.0f;
newRot.Y = 0.0f;

newRot.Z = 0.0f;
newRot.W = 0.0f;
}

return newRot;
}

function Vector MapToSphere(Vector2D point)
{
local float x, y, length, norm;

local Vector result;

//Transform the mouse coords to [-1..1]
//and inverse the Y coord
x = (point.X * AdjustWidth) - 1.0f;
y = 1.0f - (point.Y * AdjustHeight);

length = (x * x) + (y * y);

//If the point is mapped outside of the sphere

//( length > radius squared)
if (length > 1.0f)
{
norm = 1.0f / Sqrt(length);

//Return the "normalized" vector, a point on the sphere
result.X = x * norm;
result.Y = y * norm;
result.Z = 0.0f;
}

else //It's inside of the sphere
{
//Return a vector to the point mapped inside the sphere
//sqrt(radius squared - length)
result.X = x;
result.Y = y;
result.Z = Sqrt(1.0f - length);
}

return result;

}

DefaultProperties
{
Epsilon = 0.000001f
}

I'm then attempting to rotate that object when the mouse is dragged, with the following update code in my PlayerController.


    //Get Mouse Position
MousePosition.X = LGMouseInterfacePlayerInput(PlayerInput).MousePosition.X;

MousePosition.Y = LGMouseInterfacePlayerInput(PlayerInput).MousePosition.Y;

newQuat = ArcBall.Update(MousePosition);

rotMatrix = MakeRotationMatrix(QuatToRotator(newQuat));
rotMatrix = rotMatrix * LastRot;

LGMoveableActor(movingPawn.CurrentUseableObject).SetPhysics(EPhysics.PHYS_Rotating);
LGMoveableActor(movingPawn.CurrentUseableObject).SetRotation(MatrixGetRotator(rotMatrix));


"Whether" Vs "If"


In Grammar Quizzes If/Whether, it says to use if to indicate one condition and whether for two conditions. I am satisfied with everything about the grammars of if/whether, except with this one.



Let me know if you get a cell phone reception. (one condition)


Let me know whether (or not) you can get a cell phone reception. (two conditions)



In the first sentence, just because there is not "can", that indicates it is only one condition. How is this true? There are two conditions, either you get a cell phone reception or you don't. Hence, why cannot I use "Whether"?


Why is it that the use or omission of "can" in that sentence will indicate either one condition or two?


I have stared at this for a long time and I still don't get the reason why in the first sentence we can't use "Whether".



Please tell me other one-condition sentences where you can only use "If" not "Whether".




Sunday, January 22, 2017

difference - Informatics vs. Computer Science


In French, we use the term informatique for computer science, as the latter can be seen as the science that studies the treatment of information. Is informatics a synonym for computer science? If not, what is the difference?



Answer




It depends — different people use the words in different ways. Don't assume any particular nuance from the use of computer science vs. informatics without clarifying context.


Computer science is more commonly described among its practitioners as the science of computation than the science of information. While laypeople cannot be expected to understand what “science of computation” is, the term computer science is not nearly as prone to the interpretation “knowing how to fix your computer” like the word informatique is in French, due to containing the word science.


Informatics, on the contrary, is usually the science of information, often (but not always) with a focus on its social implications. The term information science also gets some use; it has a more consensual meaning covering how societies process information.


Just to add to the confusion, information theory has a precise meaning; it is the branch of theoretical computer science that studies mathematical models of information with a quantitative perspective.


Informatics is not a very common word and does not have a single widely-agreed meaning. Nuances and trends are still evolving. Wikipedia currently gives a particular meaning in its introduction section:



Informatics is - in a general sense - the science of information. As an academic field it involves the practice of information processing, and the engineering of information systems. (…) The field considers the interaction between humans and information systems alongside the construction of computer interfaces. It also develops its own conceptual and theoretical foundations and utilizes foundations developed in other fields. As such, the field of informatics has great breadth and encompasses many individual specialisations including the more particular discipline of computing science.



Certainly, by some definitions, everything that is listed here could be considered aspects of applied computer science. For example, human-computer interaction is often classified as bridging computer science with sociology and other fields. For example (more or less random), the CMU HCI Institute defines itself as “headquartered within the School of Computer Science, [but representing] a broad spectrum of the CMU campus including the College of Humanities and Social Sciences, Tepper School of Business, College of Fine Arts, Carnegie Institute of Technology, Software Engineering Institute, as well as the School of Computer Science.”


The history section and talk page provide differing perspectives on the word. It started out as a translation of the German Informatik and French informatique (which cover a wide range of meanings including computer science and information technology).



Wars (at least flame wars) have been fought over which term should apply to which concept, and whether X is a subdiscipline of Y or an overlapping discipline, etc. Tread with care, and define your terms.


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...