Saturday, December 31, 2016

java - Mods for Minecraft Server - how does it work?


Minecraft server comes as a single jar. How are mods developed? How do they interact with the original jar? What is there under the hood?


What technologies are involved there? I'm mostly a C++/Python guy, but I'd like to learn something about mods development.



Answer




A JAR is simply a ZIP file, containing the various class files and other metadata used - it's a completely standardized format.


ZIP files can be extracted, and the class files can be edited as necessary for the modification. The modified files are then added back into the archive, which makes the server use the modified files instead of the original ones.


Technically, Minecraft mods are really "hacked" versions of the original code: the actual binary class files have to be modified to let the game know about the new stuff; there's no official mod support yet (although Notch has stated that they'll work on it during Beta).


Of course, that isn't a very nice way of doing things if you actively design for mods. Instead, you would design some sort of plugin architecture which allows custom code to be run where appropriate. Exactly how you would go about this depends on what you want your mods to be able to do - e.g., if security is a concern, you probably want to design the mod interface to use some sort of scripting, so you can restrict mods from doing all sorts of things to the user's computer.


word request - What do you call the crack between the seating mattresses in a couch?


enter image description here


As you see in the picture, we have 3 mattresses and 2 cracks in the middle that extends from the upper area to the bottom area. What are these cracks called? Is there a specific word for it?




Answer



There is no specific name for this, but things that fall into these cracks are said to be behind, beneath, under, between, in, or underneath the cushions.



If you're ever short of money remember there's always loose change beneath the sofa cushions. Always.



(Edit) If you do search for examples to see which of these might be more prevalent, try not to make your search too specific. For example, I found this headline (among many others) from a search for "beneath the cushions":



Members Find Billions Beneath Pentagon Couch Cushions



this from "under the cushions":




Aretha Franklin's will discovered under couch cushions



and this from "between the cushions":



A Sofa That Encourages You To Lose Things Between the Cushions



Since all these seem to mean more or less the same thing, which you should use depends on which sounds best under the circumstances.


What is the difference between Past simple and Past perfect



I cleaned my room after I got up.



I had cleaned my room after I got up.



In the above two sentences, though there is a difference in the tenses used- the former being in simple past and the latter in past perfect- I am not able to deduce any significant diff. in their meanings. Are both of the sentences correct, and can these be used interchangeably. Please explain.


Another example:



British invaded India in 1947


British had invaded India in 1947



Thanks :)



Answer




Essentially, the simple past tense and past perfect refer to different time frames when things happen. These time frames are relative to each other, not set times that stand on their own.


Which tense you choose would depend on the context and the time frame the main events are set in. There is no distinction when the sentences are taken out of context in the way you have done.


For example, if you tell a story or relate an event to someone using the simple past, then if you want to mention something that happened earlier, you can use the past perfect to express that.


Let's make up a little story for fun:



The phone rang, and my mother shouted "Billy, it's your friend Mary on the phone, and before you get into a long conversation, I want you to clean your room this afternoon. I will not put up with the mess any longer."


"Yes mum", I replied, although I had cleaned my room after I got up.



So, in the above story, the use of the past perfect tells us that the cleaning took place before the main events in the past tense time frame.


Note: I corrected the word "before" in your example, because it doesn't make sense to say you cleaned your room before you got up - because that would suggest you did it in your sleep!



Friday, December 30, 2016

Can't scale properly to android device in Game Maker Studio 1.4


My phone is using a resolution of 360 x 640 with a 9:16 aspect ratio. I set my room in game maker to 360 x 640 and game maker thinks it's in landscape mode. I disabled landscape mode in the android settings and set to portrait only, like it should be. How do I get it to scale properly?


This is the code I have in my Scale Manager Object.


Create Event:


///Display Properties
ideal_width = 0;
ideal_height = 640;


aspect_ratio = display_get_width()/display_get_height();
ideal_width = round(ideal_height/aspect_ratio);

//check for odd numbers
if(ideal_width & 1) {
ideal_width++;
}

for (var i = 1; i <= room_last; i++) {

if(room_exists(i)) {
room_set_view(i,0,true,0,0,ideal_width,ideal_height,0,0,ideal_width,ideal_height,0,0,0,0,-1);
room_set_view_enabled(i,true);
}
}

surface_resize(application_surface,ideal_width , ideal_height);
window_set_size(ideal_width,ideal_height);
room_goto(room_next(room));


enter image description here



Answer



I switched the variables locations in this line


ideal_width = round(ideal_height/aspect_ratio);

Now it's


ideal_height = round(ideal_width/aspect_ratio);

pronunciation - When do we pronounce Z as "zed" and not "zi:"


When we learned the ABC song and English alphabet, we pronounced Z as [zed]. But in the practical usage, I never heard people say [zed], but they always say [zi:]


So when shall we say [zed]?


Or such pronunciation is totally archaic and not used in the modern English.



Answer



Very simple.


Br Eng is 'zed'.


Am Eng is 'zee'.


Martha added the very salient point that this is only when spelling words or reciting the alphabet, never in the pronunciation of a word itself….

though there is a hint of it in a word like zebra, where Am E will say zeebra, rather than the Br E zebra.
Ref: OALD


What 2D engine can I use to port my flash game to iOS and Android?



I would like to port my 2D flash game to Android and iOS. Is there any cross platform engine you could recommend? Corona is the only promising one I have found so far.



Answer



I would try http://gamesalad.com/. While Android publishing is not yet supported (planned for fall according to http://gamesalad.com/corporate/roadmap/) it can publish in HTML5, which should work well in many places, possibly android browsers too. YMMV.


Why isn’t there an article?



He turned to the right towards Capel Street. Ignatius Gallaher on the London Press! Who would have thought it possible eight years before? Still, now that he reviewed the past, Little Chandler could remember many signs of future greatness in his friend. People used to say that Ignatius Gallaher was wild Of course, he did mix with a rakish set of fellows at that time. drank freely and borrowed money on all sides. In the end he had got mixed up in some shady affair, some money transaction: at least, that was one version of his flight. But nobody denied him talent. There was always a certain... something in Ignatius Gallaher that impressed you in spite of yourself. Even when he was out at elbows and at his wits' end for money he kept up a bold face. Little Chandler remembered (and the remembrance brought a slight flush of pride to his cheek) one of Ignatius Gallaher's sayings when he was in a tight corner:


"Half time now, boys," he used to say light-heartedly. "Where's my considering cap?"



-- James Joyce, Dubliners



Does talent mean “people or a person with a natural ability to do something well (OALD)” in this context? If so, why isn’t there an article before it?



Answer



It's a literary way of saying:



But nobody denied that he had talent.



Yes, talent here means the natural ability to do things well.


This is a construct you are unlikely to hear in everyday speech, but you come across it every now and then in literature, particularly in the era when Joyce wrote, or earlier. I found a few instances with a Google book search. For example, from a biography published in 1884:




There are many — not men of small calibre either — who believed these acts were impolitic, absolute mistakes; but nobody denied him the rewards of unmixed moral courage.



Again, this is a literary way of saying:



Nobody denied that he earned the rewards of unmixed moral courage, even if he did make mistakes.



In other words, everyone agreed that he was steadfast to his principles, and earned the rewards of that fine reputation.


Also, from an 1801 work:




Nobody denied him several brilliant qualities, considerable capacity, an agreeable turn of mind, manners at once noble and prepossessing, an easy and florid style of elocution...



which is a way of saying, no one denied that he possessed several brilliant qualities...


Lastly, from an 1898 publication:



Generosity no one denied him...



which could be paraphrased, everyone agreed he was generous.


Similar phrasing can be found in more modern works, though. Published just this year:




No one denied her talent and intelligence, but the other side of this coin was apparently an outrageous capacity for self-styling and display...



In other words, everyone would admit she was talented and intelligent...


However, it's hard to find a feminine counterpart to this construct in English, because the pronoun her maps to both him and his, so perhaps that one doesn't sound as awkward to the modern ear.


Thursday, December 29, 2016

modal verbs - Difference between "should" and "must"


What is the difference between "should" and "must"?


e.g. "They should have called the police." Can I use "must" in that sentence or not?


e.g. "You should read his new book." How about this sentence?



Answer



To answer your first question 'must' is possible in the above example but the meaning will be different than i suppose you have in your mind


When we use 'should' we think what is right/moral/decent thing to do at the time.


When you say 'They should have called the police.' - (Here you know it for sure that police have not been called)



But when you say 'They must have called the police.' (Here you are almost instinctively sure that the police had been called after you have anaylzed the situation well, but officially you don't know whether they called the police or not)


See below how 'should' and 'must' function in your examples


They should have called the police. (It is your opinion)


They must have called the police. (It is your speculation)


For Example



  1. There has been a burglary in one of the houses in your neighborhood. Now, any random family would call the police in this situation. So it is extremely easy for you to speculate that 'They must have called the police' - because that was the sensible and normal thing to do after the burglary.


But when you know that they didn't call the police in this situation then you might express your surprise in the following sentence




  1. I am surprised that they didn't call the police after the burglary. They should have called the police and informed them about it. (Must is not possible in this example)


Another example


Suppse you are telling your friend the following



  1. If you were having such a hard time at school, then you should have told me. (meaning that you might have been able to help your friend out)


Here 'must' is not possible - because you can't compel your friend to share things with you. Sharing is not compulsion. So you can't say --


You must share your problems / feelings with others.


But you say --



You should share your problems / feelings with others.


'Must' in one of its meanings implies compulsion, obligation etc.


To answer your second question -


You should read his new book. (Sounds less convicing than 'must' but it is still a suggestion)


Here 'should' works as a suggestion But You must read his new book. (sounds more convicing)


If there is any book or movie that you have liked very very much then you use 'must' not should. 'Must' will work as 'strongly recommended'


So it should be


You must read his new book. It's amazing.


Is it possible to use the Unreal Engine as a big C++ library, without using the editor?


I want to write a game entirely in C++, but I would like to profit from the possibilities offered by the Unreal Engine, especially in terms of graphics and physics. Nevertheless, I strongly dislike its visual editor: I find it heavy, slow and unintuitive. Finally, it forces me to use Visual Studio instead of my favourite C++ IDE.


Is there a way to use the Unreal Engine as a big library that I could simply include in my C++ project, or am I forced to used the Unreal Editor?


Related question for Unity: How can I build a game in Unity with minimum/no use of the visual editor?




sentence meaning - "for that matter"


I've got a dumb question, Let's take a look at this sentence "He doesn't like young women or any women for that matter" so what's the main matter, his not liking all kind of women or merely young women ?




xna - Random enemy placement on a 2d grid


I want to place my items and enemies randomly (or as randomly as possible). At the moment I use XNA's Random class to generate a number between 800 for X and 600 for Y. It feels like enemies spawn more towards the top of the map than in the middle or bottom. I do not seed the generator, maybe that is something to consider.


Are there other techniques described that can improve random enemy placement on a 2d grid?



Answer



Random placement doesn't look random enough to the eye. You'll probably want the enemies spaced out a bit more evenly. Take a look at this article about Poisson disk sampling, or read about blue noise.



html5 - Best technique for drawing isometric tiles


I'm thinking about making a simple isometric game with HTML5 Canvas, and wondering what's the fastest way to render the tiles.


Since the tiles are diamond shaped, but drawImage draws rectangles, I have to leave out the corners (the black parts in the following):


sample diamond tile


I think that leaves me with three options:




  1. Use Image objects with alpha channels (.png). I'm afraid this might kill performance.

  2. Use a clipping path. If the renderer is optimized this could be pretty fast.

  3. Prerender square tiles, like this:


prerendered square tiles


I'd have the black square as one actual tile in memory, and I'd draw such a tile for the green field, and all fields next to it, or above and below. The diagonal (blue) fields would be make up of the corners of the rectangular tiles. This would avoid clipping or alpha channels, but I would have to prerender all possible combinations of tiles, and it seems like overkill.


What's the best or fastest way to do isometric tiles? What do other games, like FarmVille, use?




How to add a scrolling camera to a 2D Java game?


I am attempting to create a game where the camera follows the player, always making sure the player is in the center of the screen. How would I go about this? This game is a 2D Java game, made with no engine.


I found an opensource game demonstrating what I want but I cannot work out how to add that to my game. The game is here, if you need it.



Thanks



Answer



First, you need to define the size of the viewport (the camera resolution), for simplicity, let's assume the camera viewport is the size of the screen, we have a 800*600 screen.


Next, you need to define the maximum and minimum offsets of your camera. Assuming you have a world with a size of 1600*1200, the maximum offset would be 800 on X and 600 on Y and 0 on both axis for the minimum offsets. The general formulas to determine the offsets is:


offsetMaxX = WORLD_SIZE_X - VIEWPORT_SIZE_X
offsetMaxY = WORLD_SIZE_Y - VIEWPORT_SIZE_Y
offsetMinX = 0
offsetMinY = 0

Now, over frames, you need to calculate the actual position of the camera. A position that would make the player being centered on the screen. The position need to be calculated relatively to the player position.



camX = playerX - VIEWPORT_SIZE_X / 2
camY = playerY - VIEWPORT_SIZE_Y / 2

Don't forget to check if the camera position do not exceed the maximum and minimum offsets.


if camX > offsetMaxX:
camX = offsetMaxX
else if camX < offsetMinX:
camX = offsetMinX
if camY > offsetMaxY:
camY = offsetMaxY

else if camY < offsetMinY:
camY = offsetMinY

Now that you know the position of the camera, you will to translate the world to this position. When you open a plain window and start drawing stuffs, the area you see start at 0,0. To create the illusion of a camera following the player, you will need to set your drawing area position (the screen in your example) to the camera position.


I don't know what framework/engine you are using but the easiest way to do it is to translate the whole graphic context by the opposite of the current offsets. You will need to know how to access your graphic context and apply a translation to it.


In slick2d, it could look like this:


public void render(..., Graphics g) {
g.translate(-cam.x, -cam.y)
//render the rest of your game
}

oop - Architecture to draw many different objects in OpenGL


I have some objects that I want to draw. I am not sure how I can create my architecture in a way where I can draw everything as fast as possible.


As example:


class MyObject
{

float[] vertices;
float[] colors;
float[] textures;

public MyObject()
{
//fill every buffer with data
}

public void Draw()

{
//set shader
//set shader uniforms etc.

//foreach buffer
BindBuffer();
VertexAttribPointer();

DrawArrays();
}

}

In this way, I can draw every object like myObject.Draw after it is constructed. The problem would be, that if I have 5000 objects, I have 5000 draw calls. I need to set the shader every time even if I loop over the 5000 objects because I don't know if they use the same shaders.


Another way:


class MyObject
{
bool needsToBeChanged;

public MyObject()
{

//set my edge points
needsToBeChanged = true;
}

void ChangeMyObject() //e.g. I changed the height of my object
{
needsToBeChanged = true;
}
}


class GLWindow
{
float[] vertices;
float[] colors;
float[] textures;

GameLoop()
{
foreach(MyObject myObj in allMyObjects)
{

if(myObj.needsToBeChanged)
{
//get objects points for drawing it and set the global buffers up

myObj.needsToBeChanged = false;
}
}

DrawArrays(); //draw only once (because every data is in the buffer)
}

}

Only 1 draw call for everything. I guess this will be faster than first method. The problem on this code is the big buffer that contains everything. Let's imagine we have inherited from MyObject and want to draw objects in different shapes. Now the Loop gets more complicated. You may have to split it because you need another shader for example for text. Now you have 2 arrays... And with other changes the Loop becomes more and more complicated and harder to maintain.


What solutions (beside the both) are available for this kind of problem? Can I use the first way or is there a better way where I can reduce the draw calls? How is it solved in other applications?



Answer



Generally speaking, you will need a separate draw call for each set of objects that have a different material (by material I mean a different shader, texture or other shading parameters).


So the obvious approach is to group objects that have the same material, so that they can be rendered together, avoiding the expensive state changes. This is normally done by batching objects that share the same material. A data structure that helps achieving this is the scene graph.


Once you have batched objects with the same material you eliminate redundant state changes. The shader program and textures are now set outside and a batch is rendered. Conceptually, this would look like this:



for each batch in batches

set common material properties
for each object in batch
draw object
end for
end for

But you still have multiple draw calls within each batch. This could be resolved if all objects resided inside the same Vertex Buffer. Packing everything in the same VB is feasible and might be the best option in some cases. Modern OpenGL, however, provides instanced rendering (see a tutorial here), which is a very good solution to reducing the number of draw calls.


Overall, some parts of your rendering will probably be better optimized with simple batching or a scene graph, while other will be more efficient if implemented using instancing. You should profile and test to discover the ideal approach. But bare in mind that this is an optimization step, therefore, you should first worry about making the game/software work, then you optimize it.


tense - The difference between present simple and future simple usage in expressing a future event?


What is the difference between when I said:



They come, when they are ready.



and



They will come, when they are ready.




?



Answer




They come when they are ready. (No comma)



This does not actually express the future: the present simple expresses things general truths about the present. For example, if I say "I eat cereal for breakfast", it is not limited to just today or the future. It means I eat cereal everyday. I may not have eaten much cereal, and in the future I may instead eat toast, but for the present it is true. Thus, your example means that whenever they are ready, whether it's today, tomorrow, or yesterday, they come.



They will come when they are ready.




This indicates the future. It is not necessarily as general as the present simple. This just indicates a single instance. When I say, "I will eat cereal when it's time for breakfast", I mean that the next time it is time for breakfast, I'm going to eat cereal - just that once.


Wednesday, December 28, 2016

word request - What do you call an action that is less serious than a "crime" (that is not illegal, just against rules)?


Example sentence:



Dying your hair pink is a __ in secondary school.



I thought of words like "offense" and "misdeed," but they don't ring quite right.



Answer



It depends on the context. If you are talking about any kind of official disciplinary system with rules and punishments, then any of these may work: infraction, violation, transgression, breach, contravention and various others. In this case, for example:




Dying your hair pink is a serious transgression of school policy.



You can also say the action itself is banned, restricted, prohibited, forbidden, barred, or simply not allowed.



Dying your hair pink is against school policy.



If instead you are talking about something that goes against social or moral norms, you could use (with varying degrees of severity): taboo, anathema, frowned on, proscribed, off limits, no-no, unmentionable, abomination, faux pas and others:



Smoking in restaurants, which once was common practice, is now practically a hanging offense in many parts of the United States.




(edit) These terms cover a wide range of severity. As mentioned in the comments, "transgression" is pretty serious, while "against the rules" is fairly mild. Please provide more details about how "bad" you want it to sound, and I can be more specific.


word usage - “that” and “which” as relative pronoun


Since both “that” and “which” can be used to modify things in a sentence with an adjective clauses, which one is preferred in which situations? I found the following rules on the Internet. I am wondering if there are other rules. Thank you very much.


Rules cited from http://www.worldwidewords.org/articles/which.htm


• In clauses that follow impersonal constructions, such as it is, that is preferred: “It was the dog that died”.


• Clauses that refer back to the words anything, nothing, something, oreverything have a slight preference for that over which: “Can you think of anything that still has to be done?”


• Clauses that follow a superlative also tend to prefer that: “Thank you for the most superb dinner that I’ve ever eaten”.


Thank you very much!




euphemism - Is it an idiom or slang: holy mac and cheese?



I came across this phrase: Holy mac and cheese


What does it mean actually? Is it a slang term or an idiom?




What concepts are there for interactive water?



I want water to be a gameplay object in my game. The player should be able to take in in a bucket and tip it out somewhere in the world. Water should flow in some way so that it can be used to build rivers and transport game objects or to create particular apparatuses. It's comparable to the game Minecraft where you can build cool things involving water or just create just some small waterfalls. However, there my game isn't made out of blocks so there is smooth terrain.



In most games water is simply placed at a given height. That works well for lakes and Oceans, but for flowing rivers and usage in apparatuses this concept is to limited. In Minecraft water is implemented as a block which spreads inside the blocky grid, too. That approach is a bit more what I need to realize my idea but I don't use these blocks and therefore such water simulation would look very misplaced.


What concepts of representing water which the player can interact with in the mentioned manners are there? How can I realize oceans, rivers, buckets and so on with one general approach? There shouldn't be an infinite amount of water. If you fill your bucket, the volume of the lake the water was taken from should decrease unnoticeable. Moreover if the player would place water somewhere that volume of water should never go missing.



Answer



If you're looking to have not a lot of water move over a terrain, then your best bet will likely be some form of Smoothed Particle Hydrodynamics (or SPH). In this formulation, you simulate a set of particles as they adhere to the laws of hydrodynamics (namely, the Navier-Stokes equations). There is a great series of articles written about this from Intel:


http://software.intel.com/en-us/articles/fluid-simulation-for-video-games-part-1


Rendering your particles as fluid will likely be done using some sort of metaball formulation. You can get a good intuition from this article. The basic technique is described here, and what you can expect it to look like is something like this although it will depend how you write your shaders.


For larger bodies of water, I suggest looking at this tutorial which outlines some of the techniques used to generate a large body of water. You can combine this with the previous method to have fluid that flows into large bodies of water too.


Tuesday, December 27, 2016

word meaning - "have you ever gone to" to ask past experience


is it correct to ask: Have you ever gone to Spain? if i want to know whether or not he had visited Spain in his life (experience)?




"Ain't no ",Is this not a double negation



I have heard this song ,"Ain't no party like a chipmunk party" ,there is a negation in the word Ain't itself, why we need to use no after that .Aren't those two negations cancelling out ?




libgdx - How do I destroy a Box2D body on contact without getting an IsLocked assertion error?


I get this error when attempting to remove a body from the world:



java: /var/lib/hudson/jobs/libgdx/workspace/trunk/gdx/jni/Box2D/Dynamics/b2World.cpp:134: void b2World::DestroyBody(b2Body*): Assertion 'IsLocked() == false' failed.



What am I doing wrong?



Answer



From my little experience with box2d in libgdx, it can sometimes be difficult to isolate and resolve issues with exceptions which was only worsened by the latest port. Pre 2.2.1, I could easily remove bodies from the world without synchronization issues like you are experiencing but after migrating to the libgdx build that supported 2.2.1, I started seeing the same issues. The workaround for me, which was suggested by several people was that you cannot remove bodies from the world while the world is possibly being simulated.


Is there a possibility that you are attempting to remove a body from the world when the world is being stepped? Basically, if you try to do this, box2d doesn't like it so what you have to do is remove bodies outside of the world.step. What I did was added a utility class for the body's .userData with a bool isFlaggedForDelete which would get checked outside the world.step method.



public void sweepDeadBodies() {
for (Iterator iter = CURRENT_WORLD.getBodies(); iter.hasNext();) {
Body body = iter.next();
if(body!=null) {
YourCustomUserData data = (YourCustomUserData) body.getUserData();
if(data.isFlaggedForDelete) {
CURRENT_WORLD.destroyBody(body);
body.setUserData(null);
body = null;
}

}
}

If you run something like this right after your world.step, it should work. In your code where you are trying to destroy the body, just set it's .isFlaggedForDelete to true and it will get removed before the next world.step.


xna - 2D Platform Game Jumping


I'm currently writing a game in XNA for fun which uses C#. I have got my sprites loaded and when the character moves right he looks like he is running right and when he moves left he looks like he is running left.


I been looking everywhere for a good coding example for how to create a jumping ability. I have read all the physics stuff that I can stand and it doesn't help when I can't figure out how to use say space bar to jump yet can't keep them from using space just jump again until they land.




movement - RTS Game Protocol


I've been thinking about a multi player RTS game. The part that I can't seem to get around is keeping unit movement synced. If I move unit A to spot XY, I have to communicate that back to server that relays to the other client.


I'm curious what the communications would look like. Would you just communicate to the server that I'm moving unit A to XY from JZ? Maybe you need to communicate movement coord by coord instead? What's the most efficient methodology to communicate movement of units from one client to the other?


EDIT


This is a reposted question from stackoverflow. I found that this site was probably a better place for the question.


One of the better answers from that post:


I assume you're intending to use the Client-Server networking paradigm? In which case you cannot trust the clients to handle the actual positioning of units, you must delegate that task to the server. You then take the command list from each client per-tick, and compute the movement of each unit, once this has been completed, next tick you relay the position of each unit relevant to each client (either on a whole-map basis, or per-view basis), and start the process again.




Monday, December 26, 2016

opengl - Rotate billboard towards camera


I'm trying to create a particle system in OpenGL, and as such I need to use billboards.



I need these billboards to face the camera at all times.


The tutorials I've been following only rotated the billboard on 1 axis, such as billboards being used as grass or plants, but I need a method of rotating the quad to always face the camera, even when looking down on it.




The Original Scene: Prior to rotation


Desired Scene: Desired Scene


While searching for an answer, I only really found the technique of turning the mat3 component of the camera's view/model matrix back to an identity matrix. This isn't quite what I need, as the point's location in space never change then.


Incorrect Scene: Incorrect Rotation




How can I calculate a new rotation matrix that will successfully rotate a quad always towards the camera, or modify an existing matrix?


In the geometry shader I have access to the camera's position, the perspective matrix, and the view/model matrix.



I didn't include any shader code because it is really trivial; I create vertices that are an offset of the desired point's position based on the desired size. So if the quad should be 50 x 50, the vertex is the position offset by 25 on X and Y, multiplied by the Camera's Perspective x View matrix.




Solution:


mat4 VP = pMatrix * vMatrix;       
vec3 CameraRight = vec3(vMatrix[0][0], vMatrix[1][0], vMatrix[2][0]);
vec3 CameraUp = vec3(vMatrix[0][1], vMatrix[1][1], vMatrix[2][1]);

vec3 Pos = gl_in[0].gl_Position.xyz; // The desired point for the billboard

vec4 v1 = VP * vec4(Pos + CameraRight * 0.5 * Size + CameraUp * -0.5 * Size, 1.0);

vec4 v2 = VP * vec4(Pos + CameraRight * 0.5 * Size + CameraUp * 0.5 * Size, 1.0);
vec4 v3 = VP * vec4(Pos + CameraRight * -0.5 * Size + CameraUp * -0.5 * Size, 1.0);
vec4 v4 = VP * vec4(Pos + CameraRight * -0.5 * Size + CameraUp * 0.5 * Size, 1.0);

Finished



Answer



I think this article is what you are looking for.


Article from opengl tutorials


Basically, you'll have to find the matrix camera rotation and apply a derived form to your mesh.


Hope it helps!



word choice - Is it acceptable to use "whose" when referring to an object?


Whose is used for people (e.g. "Whose that girl?"), but is it acceptable to use whose for objects too?
Is there another word I should use for objects?


To make the question clearer, when I ask "Whose that car?" I am expecting an answer similar to "It's X's car." where X refers to a person. I could say "a man whose opinion I respect." and whose opinion would refer to the opinion of a person.
Could I say "the desk whose drawer was broken by my brother"? Should I replace whose with another word?



Answer



There are two uses of whose:




  1. Relative whose, used in forming relative clauses.

  2. Interrogative whose, used in asking a question.


The former can refer to inanimate objects, but the latter cannot.




Take a look at this sentence, in which relative whose refers to an inanimate object:



Two of these were large marble jars whose manufacture must have represented an enormous amount of work since metal tools were unknown at that time. (source)




Here, relative whose refers back to the noun phrase large marble jars, an inanimate object. This usage is fairly common and unremarkable.


However, interrogative whose does not have this ability. If you wanted to ask which cars had engines that needed replacing, this sentence would be unacceptable:



*Whose engines need replacing?



This is because interrogative whose cannot refer back to cars, an inanimate object.




Huddleston and Pullum use the labels personal and non-personal for this distinction. In these terms, interrogative whose is personal, and relative whose can be either personal or non-personal.




In this answer, * marks a sentence as unacceptable.



2d - How do I make a rope from point A to B in Box2D?


I need to make a rope (preferably not elastic) from one point to the next in Box2D. If it helps, I'm trying to develop one of those 2D Spiderman games, like this: http://www.gamesbutler.com/game/4327/Hanger/





game design - How to develop RPG Damage Formulas?


I'm developing a classical 2d RPG (in a similar vein to final fantasy) and I was wondering if anyone had some advice on how to do damage formulas/links to resources/examples? I'll explain my current setup. Hopefully I'm not overdoing it with this question, and I apologize if my questions is too large/broad


My Characters stats are composed of the following:


enum Stat
{
HP = 0,
MP = 1,

SP = 2,
Strength = 3,
Vitality = 4,
Magic = 5,
Spirit = 6,
Skill = 7,
Speed = 8, //Speed/Agility are the same thing
Agility = 8,
Evasion = 9,
MgEvasion = 10,

Accuracy = 11,
Luck = 12,
};

Vitality is basically defense to physical attacks and spirit is defense to magic attacks.


All stats have fixed maximums (9999 for HP, 999 for MP/SP and 255 for the rest). With abilities, the maximums can be increased (99999 for HP, 9999 for HP/SP, 999 for the rest) with typical values (at level 100) before/after abilities+equipment+etc will be 8000/20,000 for HP, 800/2000 for SP/MP, 180/350 for other stats


Late game Enemy HP will typically be in the lower millions (with a super boss having the maximum of ~12 million).


I was wondering how do people actually develop proper damage formulas that scale correctly? For instance, based on this data, using the damage formulas for Final Fantasy X as a base looked very promising. A full reference here http://www.gamefaqs.com/ps2/197344-final-fantasy-x/faqs/31381 but as a quick example: Str = 127, 'Attack' command used, enemy Def = 34.


1. Physical Damage Calculation:
Step 1 ------------------------------------- [{(Stat^3 ÷ 32) + 32} x DmCon ÷16]

Step 2 ---------------------------------------- [{(127^3 ÷ 32) + 32} x 16 ÷ 16]
Step 3 -------------------------------------- [{(2048383 ÷ 32) + 32} x 16 ÷ 16]
Step 4 --------------------------------------------------- [{(64011) + 32} x 1]
Step 5 -------------------------------------------------------- [{(64043 x 1)}]
Step 6 ---------------------------------------------------- Base Damage = 64043
Step 7 ----------------------------------------- [{(Def - 280.4)^2} ÷ 110] + 16
Step 8 ------------------------------------------ [{(34 - 280.4)^2} ÷ 110] + 16
Step 9 ------------------------------------------------- [(-246)^2) ÷ 110] + 16
Step 10 ---------------------------------------------------- [60516 ÷ 110] + 16
Step 11 ------------------------------------------------------------ [550] + 16

Step 12 ---------------------------------------------------------- DefNum = 566
Step 13 ---------------------------------------------- [BaseDmg * DefNum ÷ 730]
Step 14 --------------------------------------------------- [64043 * 566 ÷ 730]
Step 15 ------------------------------------------------------ [36248338 ÷ 730]
Step 16 ------------------------------------------------- Base Damage 2 = 49655
Step 17 ------------ Base Damage 2 * {730 - (Def * 51 - Def^2 ÷ 11) ÷ 10} ÷ 730
Step 18 ---------------------- 49655 * {730 - (34 * 51 - 34^2 ÷ 11) ÷ 10} ÷ 730
Step 19 ------------------------- 49655 * {730 - (1734 - 1156 ÷ 11) ÷ 10} ÷ 730
Step 20 ------------------------------- 49655 * {730 - (1734 - 105) ÷ 10} ÷ 730
Step 21 ------------------------------------- 49655 * {730 - (1629) ÷ 10} ÷ 730

Step 22 --------------------------------------------- 49655 * {730 - 162} ÷ 730
Step 23 ----------------------------------------------------- 49655 * 568 ÷ 730
Step 24 -------------------------------------------------- Final Damage = 38635

I simply modified the dividers to include the attack rating of weapons and the armor rating of armor.


Magic Damage is calculated as follows: Mag = 255, Ultima is used, enemy MDef = 1


Step 1 ----------------------------------- [DmCon * ([Stat^2 ÷ 6] + DmCon) ÷ 4]
Step 2 ------------------------------------------ [70 * ([255^2 ÷ 6] + 70) ÷ 4]
Step 3 ------------------------------------------ [70 * ([65025 ÷ 6] + 70) ÷ 4]
Step 4 ------------------------------------------------ [70 * (10837 + 70) ÷ 4]

Step 5 ----------------------------------------------------- [70 * (10907) ÷ 4]
Step 6 ------------------------------------ Base Damage = 190872 [cut to 99999]
Step 7 ---------------------------------------- [{(MDef - 280.4)^2} ÷ 110] + 16
Step 8 ------------------------------------------- [{(1 - 280.4)^2} ÷ 110] + 16
Step 9 ---------------------------------------------- [{(-279.4)^2} ÷ 110] + 16
Step 10 -------------------------------------------------- [(78064) ÷ 110] + 16
Step 11 ------------------------------------------------------------ [709] + 16
Step 12 --------------------------------------------------------- MDefNum = 725
Step 13 --------------------------------------------- [BaseDmg * MDefNum ÷ 730]
Step 14 --------------------------------------------------- [99999 * 725 ÷ 730]

Step 15 ------------------------------------------------- Base Damage 2 = 99314
Step 16 ---------- Base Damage 2 * {730 - (MDef * 51 - MDef^2 ÷ 11) ÷ 10} ÷ 730
Step 17 ------------------------ 99314 * {730 - (1 * 51 - 1^2 ÷ 11) ÷ 10} ÷ 730
Step 18 ------------------------------ 99314 * {730 - (51 - 1 ÷ 11) ÷ 10} ÷ 730
Step 19 --------------------------------------- 99314 * {730 - (49) ÷ 10} ÷ 730
Step 20 ----------------------------------------------------- 99314 * 725 ÷ 730
Step 21 -------------------------------------------------- Final Damage = 98633

The problem is that the formulas completely fall apart once stats start going above 255. In particular Defense values over 300 or so start generating really strange behavior. High Strength + Defense stats lead to massive negative values for instance. While I might be able to modify the formulas to work correctly for my use case, it'd probably be easier just to use a completely new formula. How do people actually develop damage formulas? I was considering opening excel and trying to build the formula that way (mapping Attack Stats vs. Defense Stats for instance) but I was wondering if there's an easier way? While I can't convey the full game mechanics of my game here, might someone be able to suggest a good starting place for building a damage formula?


Thanks





Sunday, December 25, 2016

animation - How to transition between states and mix states in a finite state machine?


I don't understand how to use a finite state machine with the entity controlled by the player.


For example I have a Mario style game (2d platform). I can jump, run, walk, take damage, swim, etc. So my first thought was to use this actions as states. But what happens, if you are running when you take damage? Or jumping, taking damage and shooting at the same time?


I just want to add functionalities (actions) to the player in a clean way (not using it for all the actions in the entity update) .



Answer



I guess the normal way is to have multiple state machines. This way you can stick to atomic states which often makes your live a lot easier than having to deal with complex states.



For example:



  • Damage Mode: Normal, Invulnerable (as in just hit), invincible (as in got a star)

  • Pace: Walking Mode, Running Mode

  • Abilities: Normal, Super, Fire, Fly

  • Movement Type: Walking, Swimming, Flying


In object oriented designed there is the sate pattern for this. It boils down to having one interface per state machine. And a class per possible state which implements this interface.


To give an example: There would be an interface DamageMode and subclasses NormalDamageMode, InvulnerableDamageMode and InvincibleDamageMode. Whenever the player collidates with an enemy the method DamageMode.collision(enemy) is called. It is handled by the class responsible for the current state.


So if damageMode == NormalDamageMode the player will be damaged and the state variable will be set to InvulnerableDamageMode. In InvulnerableDamageMode nothing happens and in InvincibleDamageMode the enemy will be damaged. Of course there needs to be timers to go back from InvulnerableDamageMode and InvincibleDamageMode to NormalDamageMode.



The main advantage of the state pattern compared to if-elseif-elseif-elseif-blocks is that it allows to structure your code better.


LibGdx Android Phone Resolution problem


I am using the LibGdx framework and have an issue.


Currently, I am creating a game in a resolution of 480 x 320 and using 'GL20' to remove the restriction of that dreaded 'power of two' error.


It works really well, but only in desktop and phones whose screen sizes are the same. But when I try it to a phone with a resolution of 320 x 240, I can only see a small part of the screen and the screen calculations that I made for touch events are now incorrect.



Is there any way to make it work the same as in the desktop version? Like for example, even on the 320x240 phone, the resolution of the game is still at 480x320.



Answer



This is a problem pretty much everyone faces when getting into LibGDX. What you need to remember as you code is this: pixels are bad. Down with pixels.


Because you're using a camera object to determine how/where to draw your sprites on screen, you can set your game's world to use any units you want, and scale to each screen just by constructing the camera appropriately.


If you were to use a tile map to build your levels, I'd say use those tiles as your unit. Doesn't matter how you draw your levels, though -- make up a unit of measurement and stick to it. My screen (in landscape view) is 20 units (tiles, metres, character-heights, whatever) high, with the width scaled so that the tiles are square (ppu is pixels per unit):


// Always a screen height of 20 units;
// width depends on screen aspect ratio.
float height = 20;
float ppu = Gdx.graphics.getHeight() / height;
float width = Gdx.graphics.getWidth() / ppu;


So say you run it on a Full HD screen (1920x1080). If height = 20, then ppu = (1080 / 20) = 54. So width = (1920 / 54) = 35.55555... Your sprites will be automatically scaled (up) to fit that screen size.


On the smaller of the resolutions you mentioned? ppu = (240 / 20) = 12, so width = (320 / 12) = 26.66666... Your sprites will be automatically scaled (down, this time) to fit that screen too.


Then construct your camera using those values:


OrthographicCamera cam = new OrthographicCamera(width, height);
cam.position.set(width / 2, height / 2, 0);
cam.update();

width / 2 and height / 2 being the centre of the screen. If you're using your camera's combined matrix as the SpriteBatch's projection matrix -- batch.setProjectionMatrix(cam.combined) -- then it'll take care of screen resolution for you. And that's it.


Well, almost. You now need to define your Sprites and any other objects in your shiny new world coordinates. If your Sprite was 32 pixels high on your test 480x320 phone, its new height is 2. Don't change the TextureRegions -- they're still in pixels, since they're to do with your image file, not your world. Not at all confusing, right?



Now, if you want to translate from touch coordinates to in-game coordinates, you need to do a two-step conversion as explained here. First from screen coords to camera coords, then from camera coords to world coords:


// Vector2 touchV comes from your InputAdapter.touchDown()
cam.unproject(touchV);
float x = cam.position.x - cam.viewportWidth + touchV.x;
float y = cam.position.y - cam.viewportHeight + touchV.y;

meaning in context - "What is the age of marriage in your culture?"


Some time ago, I had an IELTS exam and my examiner asked me:



What is the age of marriage in your culture?



I thought he simply is mentioning the culture that I grow up with so I said:




It varies from person to person in my family, since my cousin has got married when she was 23 but my that got married when he was 26, but overall I can say it is between 20 to 30.



The examiner stopped me and asked again:



That was not my question. I've asked, what is the age of marriage IN YOUR CULTURE (while pointing his finger at me)



I repeat the scenario over and over but it doesn't make any sense to me. Of course I gave him my opinion about the age of marriage, but it is very strange to me.


Is it correct in English to ask that question?



Answer





What is the age of marriage in your culture?



Be careful, the original question does not ask for an opinion — “Of course I gave him my opinion about the age of marriage, but it is very strange to me.”
The IELTS question does not ask how old were your friends or family when they got married. That would be considered a personal question, inappropriate in an exam situation. Remember, the exam is an artificial environment; in real life, people will repeat themselves, explain, or paraphrase until the listener has understood.


As an IELTS candidate, you should ask the examiner to repeat their question if you think you misheard — “I'm sorry, could you repeat that, please?” If you want to be doubly sure, you can also ask:



  • Do you mean how old people are when they marry in my country?

  • Do you mean the average age people marry in my country?

  • Do you mean the minimum legal age for marriage in [Italy, Turkey, etc.]?



Now, whether an IELTS examiner is allowed to reply with a simple "No", or, "Yes, that's what I meant." I don't know, but I do know that these exams are audio recorded, so examiners who do not follow protocol might be reprimanded. You might have to rely on their facial expressions, then again experienced examiners will probably have learnt to keep a deadpan face. If you're not certain, cover all your bases.



Well in my experience, people tend to marry between the ages of 20 and 30, but the youngest age you can marry in my country is sixteen.



Note that the speaker did not parrot the words in the examiner's question, candidates should paraphrase and try to speak as naturally as possible.


In real life, any of the below would have been a simpler and less ambiguous question to answer.



How old can you be to marry in your country?
What is the legal age for marriage in your country?
What is the minimum age for someone to marry in your culture?




The level of difficulty increases as the exam progresses, they are meant to test candidates' coping and comprehension skills as well as their speaking abilities.


Saturday, December 24, 2016

level design - Procedural terrains in 3D: what has been done ? Are there common algo and/or theories about it?




Besides programming, modeling an environment takes a great deal of time.


I don't know about the work time involved, for example, in a WoW dungeon level, or other beautiful city-like, future environment, jungles, fantasy, etc, but this kind of work is made from scratch by artists.


What are the techniques involved in the TorchLight level randomizer, and does other titles have similarities with this ? Is there a family name for such techniques ?



Answer



Roguelikes have been doing this kind of thing since they were invented, and they are the "seed" Torchlight (and Diablo) got their ideas from.


I don't know about Torchlight's specifically, but in general, what you are looking for is called "Procedural Level Generation".


Fuel procedurally generates a zone so bast that it would not fit on the DVD the game comes in. I particularly enjoyed reading Shamus Young's series on it.


Another interesting example of procedurally generated content is Introversion's not-yet-release game, called Subversion. Have a look at Part 12 on that page; it's specially juicy.


Speaking about procedurally generated cities, there's also some middleware around - check out http://www.procedural.com/.


For more games/middleware, check out the Procedural Generation Wikipedia page and the Procedural Generation Wiki.



xna - Implementing a wait function in a game script


I have been implementing behavior for enemies in my game and so far I have been doing it sort of like below:



public void update()
{
if (frame > 60 && frame % 30 == 0)
{
shootAtPlayer();
}
frame++;
}

Which is meaning after frame 60 shoot the player every 30 frames. The frame-count is important as the game is fixed frame-rate and everything is relying on this at the moment. There are many small scripts for enemy behavior like above and I currently iterate through each one calling update(). I have realized it will quickly get unweildy dealing in absolute frames and I want to move towards a pattern where I can specify to do X for 60 frames then do Y e.t.c, something that is easily understandable and easy to write. I want to go for something like below:



wait(60)
while(true)
{
shootAtPlayer();
wait(30);
}

I was wondering if there is a design pattern that would easily support such a syntax. My initial thoughts were to create a thread for each script object and have the wait implemented similar to below:


wait(int frames)
{

while(frames > 0)
{
frames--;
suspend();
}
}

with the method running the scripts calling resume in turn on each script. I could potentially have up to 300 scripts running at once which would mean 300 threads to handle. Am I taking the correct approach to solving this problem?


I am programming this in C# XNA.



Answer




It would be simpler to create to use events and fibers


Using a fiber means you can yield and return how many frames to wait until it should be called it again.


Then with a priority queue you can iterate over all events scheduled for the current frame.


IEnumerator ai_script() 
yield return 60;
while(true)
{
shootAtPlayer();
yield return 30;
}

}

and then in the gameloop


while(running){

frame++;
updateFysics();

IEnumerator ie;
while((ie = delayQueue.Pop(frame))!=null){

if(ie.MoveNext()){//move next then does the call true means there is another wait, false means the task is done
delayQueue.add(ie,ie.Current+frame);//Current holds the delay requested
}
}

}

This solution is heavy misuse of C# syntax, but you can use explicit Fibers instead.


phrases - Is "in one go" British English or just English?


I'm playing a game on a forum that involves guessing who posted. An American English speaker said that because the poster wrote "in one go" (meaning "in one sitting"), they were probably British or European as that's not an American expression.


But the Oxford Learners Dictionaries' definition does not mention "in one go" being British English despite saying that several of the other expressions on that page are British.


Here's the context:



If there is a book I'm desperate to read then when I eventually do I have to read it in one go. Sometimes this means staying up all night.



And here is the argument the poster made:




However, you Europeans don't seem to realize it, but "in one go" is not an American expression, unless anyone has picked that up from being online, but it's not native to here. I only heard the term "on the go" (as in, "how many games you have on the go") within about the last year, and it was Brits using the term. I use the term "on the go" meaning on the run, like busy, busy.



Is this true? Is it an unusual expression in American English? If so, what phrase would you use instead?



Answer




Is “in one go” British English or just English?



I've wrestled with this one, mostly because of the way you've titled your question.


Take, for example, nappies (which we call diapers in the U.S.). I would consider nappies to be UK English; I rarely hear the word, and, more importantly, when I do, I almost have to translate it in my mind.



As for in one go, I looked at a lot of blogs and message boards, and, indeed, when I managed to find this expression on the internet, it was almost invariably traced to a U.K. speaker1. But, for some reason, it doesn't sound chiefly British to me. It's immediately understandable. I got this done in one go doesn't sound like something I would never say, (unlike, I need to go change a nappy).


So, getting back to your title, I find myself wondering: What makes something "British English" vs. "just English"?


If I had to make a ruling, I'd say, no, "in one go" is not "British English", and I'll count on Macmillan to back me up.


Here is the definition of nappy in the American version of Macmillan:


enter image description here


Now here is the definition of the noun go in the same edition:


enter image description here


So, the Macmillan editors, at least, don't seem to think the phrase is British enough to be tagged BRITISH.


That absence of a BRITISH tag doesn't appear to be an oversight, either; that same entry also reveals:


enter image description here



In short, Macmillan would categorize



I'll have a go at answering this question



as British English, but



I typed this whole answer in just one go



would be what you called "just English."


Based on my usage searches, though, I think it's a borderline call, so I wouldn't vehemently argue against Codeswitcher's stance.





1Like this one, from an electrician:



In the latter case, then you'd be doing yourself a favour to have the whole lot done in one go.



The speaker is a self-identified electrician from Thornbury, which I assume is a U.K. Thornbury, judging by the way favour is spelled.


image - Free to use resources for 2d platformer Sprites



I've looked at a couple other questions about Sprites but most seem to apply to Isometric or RPG related sprites. So I'm wondering if there is a decent place for 2D side scrolling plat-former type sprites?



Answer



You can try the free sprites from hasgraphics. They can be used in commercial and non-commercial projects.


Friday, December 23, 2016

My C++/OpenGL "Hello Triangle" Code Does Not Draw A Triangle When Using SDL As A Window Library


I have been using the website Learn OpenGL but I am using SDL as a window Library.


My code seems to builds the window correctly but no triangle appears. I am compiling my code using Visual Studio 2013. I have spent many hours looking over the code but cannot see an error. Can anyone tell me where I have gone wrong?


#include 
#include

#include
#include
#include

#include

//***************************************************************************
// The Width of the screen
//***************************************************************************
const GLuint SCREEN_WIDTH = 800;

//***************************************************************************
// The height of the screen
//***************************************************************************

const GLuint SCREEN_HEIGHT = 600;

bool success = GL_TRUE;

const GLchar* vertexShaderSource = "#version 330 core\n"
"layout (location = 0) in vec3 position;\n"
"void main()\n"
"{\n"
"gl_Position = vec4(position.x, position.y, position.z, 1.0);\n"
"}\0";


const GLchar* fragmentShaderSource = "#version 330 core\n"
"out vec4 color;\n"
"void main()\n"
"{\n"
"color = vec4(1.0f, 0.5f, 0.2f, 1.0f);\n"
"}\n\0";

int main(int argc, char *argv[])
{

//***********************************************************************
// Initialize SDL
//***********************************************************************
if (SDL_Init(SDL_INIT_EVERYTHING) < 0)
{
std::cout << "SDL could not initialize!SDL Error :" <<
std::string(SDL_GetError());

return EXIT_FAILURE;
}

else
{
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK,
SDL_GL_CONTEXT_PROFILE_CORE);

SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);


//*******************************************************************
//The window we'll be rendering to
//*******************************************************************
SDL_Window *window = SDL_CreateWindow("Breakout",
SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, SCREEN_WIDTH,
SCREEN_HEIGHT, SDL_WINDOW_SHOWN |
SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE);

if (window == NULL)
{

std::cout << "Window could not be created!SDL_Error: " <<
std::string(SDL_GetError()) << std::endl;

return EXIT_FAILURE;
}

//*******************************************************************
//OpenGL context
//*******************************************************************
SDL_GLContext context = SDL_GL_CreateContext(window);


//*******************************************************************
// Set the required callback functions
//*******************************************************************
SDL_Event windowEvent;

//*******************************************************************
//Use OpenGL 3.3
//*******************************************************************


//*******************************************************************
// Set this to true so GLEW knows to use a modern approach to
// retrieving function pointers and extensions
//*******************************************************************
glewExperimental = GL_TRUE;

//*******************************************************************
// Initialize GLEW to setup the OpenGL Function pointers
//*******************************************************************
GLenum glewError = glewInit();

if (GLEW_OK != glewError)
{
std::cout << "Failed to initialize GLEW: " <<
glewGetErrorString(glewError) << std::endl;

return EXIT_FAILURE;
}

glEnable(GL_CULL_FACE);
glEnable(GL_BLEND);

glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

//*******************************************************************
// Define the viewport dimensions
//*******************************************************************
glViewport(SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
SCREEN_WIDTH, SCREEN_HEIGHT);

//*******************************************************************
// Build and compile our shader program

// Vertex shader
//*******************************************************************
GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertexShader, 1, &vertexShaderSource, NULL);
glCompileShader(vertexShader);

//*******************************************************************
// Check for compile time errors
//*******************************************************************
GLint success;

GLchar infoLog[512];
glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success);
if (!success)
{
glGetShaderInfoLog(vertexShader, 512, NULL, infoLog);
std::cout << "ERROR::SHADER::VERTEX::COMPILATION_FAILED: " <<
infoLog << std::endl;
}

//*******************************************************************

// Fragment shader
//*******************************************************************
GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragmentShader, 1, &fragmentShaderSource, NULL);
glCompileShader(fragmentShader);

//*******************************************************************
// Check for compile time errors
//*******************************************************************
glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &success);

if (!success)
{
glGetShaderInfoLog(fragmentShader, 512, NULL, infoLog);
std::cout << "ERROR::SHADER::FRAGMENT::COMPILATION_FAILED: " <<
infoLog << std::endl;
}

//*******************************************************************
// Link shaders
//*******************************************************************

GLuint shaderProgram = glCreateProgram();
glAttachShader(shaderProgram, vertexShader);
glAttachShader(shaderProgram, fragmentShader);
glLinkProgram(shaderProgram);

//*******************************************************************
// Check for linking errors
//*******************************************************************
glGetProgramiv(shaderProgram, GL_LINK_STATUS, &success);
if (!success) {

glGetProgramInfoLog(shaderProgram, 512, NULL, infoLog);
std::cout << "ERROR::SHADER::PROGRAM::LINKING_FAILED: " << infoLog << std::endl;
}
glDeleteShader(vertexShader);
glDeleteShader(fragmentShader);

//*******************************************************************
// Set up vertex data (and buffer(s)) and attribute pointers
//*******************************************************************
GLfloat vertices[] = {

-0.5f, -0.5f, 0.0f, // Left
0.5f, -0.5f, 0.0f, // Right
0.0f, 0.5f, 0.0f // Top
};
GLuint VBO, VAO;
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);

//*******************************************************************
// Bind the Vertex Array Object first, then bind and set vertex

// buffer(s) and attribute pointer(s).
//*******************************************************************
glBindVertexArray(VAO);

glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices,
GL_STATIC_DRAW);

glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat),
(GLvoid*)0);


glEnableVertexAttribArray(0);

//*******************************************************************
// Note that this is allowed, the call to glVertexAttribPointer
// registered VBO as the currently bound vertex buffer object so
// afterwards we can safely unbind
//*******************************************************************
glBindBuffer(GL_ARRAY_BUFFER, 0);


//*******************************************************************
// Unbind VAO (it's always a good thing to unbind any buffer/array to
// prevent strange bugs)
//*******************************************************************
glBindVertexArray(0);

//*******************************************************************
// DeltaTime variables
//*******************************************************************
GLdouble deltaTime = 0.0f;

Uint64 lastFrame = 0L;
Uint64 currentFrame = SDL_GetPerformanceCounter();

while (true)
{
//***************************************************************
// Calculate delta time
//***************************************************************
lastFrame = currentFrame;
currentFrame = SDL_GetPerformanceCounter();


deltaTime = ((currentFrame - lastFrame) * 1000 /
(GLdouble)SDL_GetPerformanceFrequency());

double tmpDeltaTime = deltaTime;

//std::cout << "Hello 1 - deltaTime: " << std::to_string(deltaTime) <<
// std::endl;

if (SDL_PollEvent(&windowEvent))

{
if (windowEvent.type == SDL_QUIT)
{
break;
}
}

//***************************************************************
// Clear the colorbuffer and render
//***************************************************************

glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);

//***************************************************************
// Draw our first triangle
//***************************************************************
glUseProgram(shaderProgram);
glBindVertexArray(VAO);
glDrawArrays(GL_TRIANGLES, 0, 3);
glBindVertexArray(0);


//***************************************************************
// draw OpenGL: Swap the screen buffers
//***************************************************************
SDL_GL_SwapWindow(window);
}

//***************************************************************
// Properly de-allocate all resources once they've outlived their
// purpose

//***************************************************************
glDeleteVertexArrays(1, &VAO);
glDeleteBuffers(1, &VBO);

SDL_GL_DeleteContext(context);
SDL_DestroyWindow(window);
SDL_Quit();
}

return EXIT_SUCCESS;

}

Answer



This line:


glViewport(SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, SCREEN_WIDTH, SCREEN_HEIGHT);

... does not really make sense. You're passing in special constants only known by SDL to an OpenGL function that expects actual coordinates. If anything, I'd expect that to be glViewport(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT).


But then, I have never actually seen or used glViewport, and it looks like it's part of the deprecated fixed-function pipeline matrix stack, which you probably don't want to use since you're using shaders and VAOs. Simply remove the line, and voilà ! Triangle.


procedural generation - Algorithm for procedureral 2D map with connected paths


Problem to solve: Generate a random 2D dungeon map for a tile-based game where all rooms are connected.


I am looking for better solutions than what I currently have.


My current solution is that I run two algorithms. The first generates the dungeon with its rooms. The second make sure that all rooms are connected. I am curious what other soltions may exist. Faster and / or easier etc. Speed is not really a concern, but if speed can be gained at no real cost, well, that is a good thing. More important is that I, and others that read, may learn different ways to approach and solve the problem.


Below are my current implementation. Rooms currently have no exits or exits in any 2, 3 or 4 directions.


Generating the dungeon rooms


Setup: Set the current room to the top left room.




  1. Get a valid room type for the room (where valid room type is a type with no exits out of the dungeon and that have exits that matches the exits of the room above and the room to the left. Only need to check above and to the left due to step 2 below).

  2. Put down the room and advance the x-coordinate one step. If the x-coordinate exceeds the dungeon width, set the x-coordinate to 0 and advance the y-coordinate one step. If the y-coordinate exceeds the dungeon height, we are done.

  3. Repeat from #1.


I then check to see if all rooms are connected If they are not all connected I run a second algorithm that, in a non-sexy but definately good enough way in terms of dungeon layout, goes through the rooms and change them so that all end up being connected.


Checking to see if all rooms are connected


Setup: Create a 2D map of integers representing paths and initialize the entries to a "unprocessed" (not yet traversed) value, -1. Set a start path index integer that keeps track of the current path to 1. Set the current room to the top left room by adding it to a stack of rooms to check.



  1. If the stack contains rooms to check, pop it set the path index of the room to the current path index. If the stack does not contain any rooms, increase the path index and try to get a room by advancing column by column, row by row, until we get a room that has not been processed yet. If no room can be found, we are done.


  2. Check to see if the room has an exit to the left. If it has add the left room to the stack if it is not already on there.

  3. Repeat step 2 for down, right and top directions (since we are using a stack that means the rooms are traversed in clockwise order, starting with the top direction).

  4. Repeat from step 1.

  5. If the path indices count is greater than one, there are disconnected rooms.


If there are disconnected rooms I then group the rooms by their path index, get the index of the biggest path and connect all other rooms to those rooms. This is a work in progress, but my (current, "brutish") plan is to go through each room in a room group (except the first) check to see if there is a horizontal or vertical path to the biggeset room group, and if so, create a horizontal / vertical path there by injecting / updating the rooms inbetween. Rinse and repeat. Ugly, yes, but it is something that will not be noticable in terms of visual pattern so it works in that sense.



Answer



One of the best, and most used, algorithms I've seen out there is generating dungeons using Binary Space Partitioning.


The best general explanation I've read is the one found in The Chronicles of Doryen (attached at the end for backup purposes) because explains the procedure without getting into the code, thus leaving the implementation to the reader.


Two other tutorials on the same subject, with code, can be found at







Building the BSP tree


We start with a rectangular dungeon filled with wall cells. We are going to split this dungeon recursively until each sub-dungeon has approximately the size of a room. The dungeon splitting uses this operation :



  • Choose a random direction : horizontal or vertical splitting

  • Choose a random position (x for vertical, y for horizontal)

  • Split the dungeon into two sub-dungeons



enter image description here


Now we have two sub-dungeons A and B. We can apply the same operation to both of them.


enter image description here


When choosing the splitting position, we have to take care not to be too close to the dungeon border. We must be able to place a room inside each generated sub-dungeon. We repeat until the lowest sub-dungeons have approximately the size of the rooms we want to generate.


enter image description here


Building the dungeon


Now we create a room with random size in each leaf of the tree. Of course, the room must be contained inside the corresponding sub-dungeon. Thanks to the BSP tree, we can’t have two overlapping rooms.


enter image description here


To build corridors, we loop through all the leafs of the tree, connecting each leaf to its sister. If the two rooms have face-to-face walls, we can use a straight corridor. Else we have to use a Z shaped corridor.


enter image description here



Now we get up one level in the tree and repeat the process for the father sub-regions. Now, we can connect two sub-regions with a link either between two rooms, or a corridor and a room or two corridors.


enter image description here


We repeat the process until we have connected the first two sub-dungeons A and B


enter image description here



java - How to implement a 2d collision detection for Android


I am making a 2d space shooter using opengl ES. Can someone please show me how to implement a collision detection between the enemy ship and player ship. The code for the two classes are below:


Player Ship Class:



package com.proandroidgames;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import javax.microedition.khronos.opengles.GL10;

public class SSGoodGuy {
public boolean isDestroyed = false;
private int damage = 0;




private FloatBuffer vertexBuffer;
private FloatBuffer textureBuffer;
private ByteBuffer indexBuffer;
private float vertices[] = { 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f,
1.0f, 0.0f, 0.0f, 1.0f, 0.0f, };
private float texture[] = { 0.0f, 0.0f, 0.25f, 0.0f, 0.25f, 0.25f, 0.0f,
0.25f, };

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

public void applyDamage(){
damage++;
if (damage == SSEngine.PLAYER_SHIELDS){
isDestroyed = true;
}

}



public SSGoodGuy() {
ByteBuffer byteBuf = ByteBuffer.allocateDirect(vertices.length * 4);
byteBuf.order(ByteOrder.nativeOrder());
vertexBuffer = byteBuf.asFloatBuffer();
vertexBuffer.put(vertices);
vertexBuffer.position(0);
byteBuf = ByteBuffer.allocateDirect(texture.length * 4);
byteBuf.order(ByteOrder.nativeOrder());
textureBuffer = byteBuf.asFloatBuffer();

textureBuffer.put(texture);
textureBuffer.position(0);
indexBuffer = ByteBuffer.allocateDirect(indices.length);
indexBuffer.put(indices);
indexBuffer.position(0);
}

public void draw(GL10 gl, int[] spriteSheet) {
gl.glBindTexture(GL10.GL_TEXTURE_2D, spriteSheet[0]);
gl.glFrontFace(GL10.GL_CCW);

gl.glEnable(GL10.GL_CULL_FACE);
gl.glCullFace(GL10.GL_BACK);
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertexBuffer);
gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, textureBuffer);
gl.glDrawElements(GL10.GL_TRIANGLES, indices.length,
GL10.GL_UNSIGNED_BYTE, indexBuffer);
gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY);

gl.glDisable(GL10.GL_CULL_FACE);
}
}

Enemy Ship Class:


package com.proandroidgames;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;

import java.util.Random;

import javax.microedition.khronos.opengles.GL10;

public class SSEnemy {

public float posY = 0f;
public float posX = 0f;
public float posT = 0f;
public float incrementXToTarget = 0f;

public float incrementYToTarget = 0f;
public int attackDirection = 0;
public boolean isDestroyed = false;
private int damage = 0;

public int enemyType = 0;

public boolean isLockedOn = false;
public float lockOnPosX = 0f;
public float lockOnPosY = 0f;


private Random randomPos = new Random();

private FloatBuffer vertexBuffer;
private FloatBuffer textureBuffer;
private ByteBuffer indexBuffer;

private float vertices[] = { 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f,
1.0f, 0.0f, 0.0f, 1.0f, 0.0f, };


private float texture[] = { 0.0f, 0.0f, 0.25f, 0.0f, 0.25f, 0.25f, 0.0f,
0.25f, };

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

public void applyDamage() {
damage++;
switch (enemyType) {
case SSEngine.TYPE_INTERCEPTOR:
if (damage == SSEngine.INTERCEPTOR_SHIELDS) {

isDestroyed = true;
}
break;
case SSEngine.TYPE_SCOUT:
if (damage == SSEngine.SCOUT_SHIELDS) {
isDestroyed = true;
}
break;
case SSEngine.TYPE_WARSHIP:
if (damage == SSEngine.WARSHIP_SHIELDS) {

isDestroyed = true;
}
break;

}
}

public SSEnemy(int type, int direction) {
enemyType = type;
attackDirection = direction;

posY = (randomPos.nextFloat() * 4) + 4;
switch (attackDirection) {
case SSEngine.ATTACK_LEFT:
posX = 0;
break;
case SSEngine.ATTACK_RANDOM:
posX = randomPos.nextFloat() * 3;
break;
case SSEngine.ATTACK_RIGHT:
posX = 3;

break;
}
posT = SSEngine.SCOUT_SPEED;

ByteBuffer byteBuf = ByteBuffer.allocateDirect(vertices.length * 4);
byteBuf.order(ByteOrder.nativeOrder());
vertexBuffer = byteBuf.asFloatBuffer();
vertexBuffer.put(vertices);
vertexBuffer.position(0);


byteBuf = ByteBuffer.allocateDirect(texture.length * 4);
byteBuf.order(ByteOrder.nativeOrder());
textureBuffer = byteBuf.asFloatBuffer();
textureBuffer.put(texture);
textureBuffer.position(0);

indexBuffer = ByteBuffer.allocateDirect(indices.length);
indexBuffer.put(indices);
indexBuffer.position(0);
}


public float getNextScoutX() {
if (attackDirection == SSEngine.ATTACK_LEFT) {
return (float) ((SSEngine.BEZIER_X_4 * (posT * posT * posT))
+ (SSEngine.BEZIER_X_3 * 3 * (posT * posT) * (1 - posT))
+ (SSEngine.BEZIER_X_2 * 3 * posT * ((1 - posT) * (1 - posT))) + (SSEngine.BEZIER_X_1 * ((1 - posT)
* (1 - posT) * (1 - posT))));
} else {
return (float) ((SSEngine.BEZIER_X_1 * (posT * posT * posT))
+ (SSEngine.BEZIER_X_2 * 3 * (posT * posT) * (1 - posT))

+ (SSEngine.BEZIER_X_3 * 3 * posT * ((1 - posT) * (1 - posT))) + (SSEngine.BEZIER_X_4 * ((1 - posT)
* (1 - posT) * (1 - posT))));
}

}

public float getNextScoutY() {
return (float) ((SSEngine.BEZIER_Y_1 * (posT * posT * posT))
+ (SSEngine.BEZIER_Y_2 * 3 * (posT * posT) * (1 - posT))
+ (SSEngine.BEZIER_Y_3 * 3 * posT * ((1 - posT) * (1 - posT))) + (SSEngine.BEZIER_Y_4 * ((1 - posT)

* (1 - posT) * (1 - posT))));
}

public void draw(GL10 gl, int[] spriteSheet) {
gl.glBindTexture(GL10.GL_TEXTURE_2D, spriteSheet[0]);

gl.glFrontFace(GL10.GL_CCW);
gl.glEnable(GL10.GL_CULL_FACE);
gl.glCullFace(GL10.GL_BACK);


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

gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertexBuffer);
gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, textureBuffer);

gl.glDrawElements(GL10.GL_TRIANGLES, indices.length,
GL10.GL_UNSIGNED_BYTE, indexBuffer);

gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);

gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
gl.glDisable(GL10.GL_CULL_FACE);
}



}


word usage - Difference between "Trip", "Travel", and "Journey"


Are there any significant differences between words trip, travel, and journey (nouns)?


Are those interchangeable words or are there any specific expressions which uses one of them but not another?



Answer



These three words can be synonyms, but have slightly different connotations.


First, travel is usually a verb...



I will travel to Washington DC.



...but not always. In common speech (at least as far as I am familiar), when used as a noun, it is used in its plural form:




How were your travels?



Compared to the substantially equivalent sentences:



How was your trip?
How was your journey?



One could also ask How was your travel?, but it this would have a more specific meaning, for instance, "How was your flight from New York to L.A.?" as opposed to "How was your entire journey, and the time you spent in L.A.?"


Trip and journey are more closely interchangeable, and vary mostly in duration, distance, and formality.



A trip can be a short journey. One can take a trip to the store, but it would be unusual (except in poetic exaggeration) to take a journey to the store


A journey would often imply a longer (in terms of time and/or distance) trip, perhaps to multiple destinations, or with a greater sense of unknown. A journey may not be fully planned out ahead of time.


A business conference to Seattle would probably be described as a trip, whereas a family vacation road-trip from Nebraska, through the Colorado Rockies, camping in Nevada, then stopping in Las Vegas and returning through Oklahoma and Kansas, might be described as a journey.


Often, in colloquial English (at least in the U.S.), trip is far more commonly used than journey, even when describing long/epic travels.


Both trip and journey can also be verbs, but when used as verbs they are not interchangeable. To journey is to engage in the act of journeying:



We journeyed to the Grand Canyon.



However to trip is to cause someone to stumble or lose their balance.




She tripped the thief with her cane.
I tripped over the dog.



To trip up has the additional connotation of causing someone to blunder:



The reporter tripped up the senator.



There are also some additional cases where trip and journey cannot be interchanged in some common expressions:



  • A guilt trip


  • A high brought on by recreational drugs can be called a "trip."

  • Trippy -- slang; reminiscent of the "trip" (high) brought on by recreational drugs; especially LSD


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