Sunday, May 31, 2015

xna - How to calculate origin and position of a weapon which should be "in hands"?


I'm currently stuck with my game, which is from the top perspective. I'm currently using these sprites for player: (using the second at the top):


enter image description here


And here's what I use for my gun


enter image description here


My problem is that I am not sure how to calculate origin & position to make sure that gun is always in player's hands. This is my code for drawing player and gun


spriteBatch.Draw(Textures.Load("player"), new Vector2(playerPosition.X, playerPosition.Y), new Rectangle(35, 2, 27,27), Color.White, player.rotation, new Vector2(playerWidth / 2, playerHeight / 2), 1f, SpriteEffects.None, 1f);
spriteBatch.Draw(Textures.Load("Guns/deagle"), new Vector2(playerPosition.X, playerPosition.Y), null, Color.White, player.rotation, new Vector2(playerWidth / 2, playerHeight / 2), 1f, SpriteEffects.None, 1f);

With rotation of 0, I'd need to move my gun to playerPosition.Y + 15 to make sure gun is in guy's hands, but when I do it, it looks fine but as soon as I rotate him, it's even more weird than now.



Here's how it currently looks like, with my specified code above.


https://dl-web.dropbox.com/get/capture-14.mp4?w=40052a2d


All I need is to make sure that gun will be always in guy's hands



Answer



You need to offset the gun's position based on the rotation of the player. Here's the first formula that comes to mind:


x = x + offset*cos(rotation)

y = y + offset*sin(rotation)

So in your specific case use this as the gun's position:



new Vector2( playerPosition.X + 15 * (float) Math.Cos(player.rotation), playerPosition.Y + 15 * (float) Math.Sin(player.rotation) )

optimization - Multithreading/Optimisation for Random Generation in Gamemaker


I have a FurGeneration() script in my game; when run, it randomly generates individual oFur objects in specified areas in the game's single Room. Each has a random depth and one of three sprites, and the script produces the impression of dense, layered fur. I've attached a screenshot.


enter image description here



At the moment, the script is working well, as I am using it on relatively small areas. However, my next challenge is to apply this across the single, 20,000 x 20,000 room of my game to produce a consistent field of fur.


My first attempt at this was to create a background sprite, a simple 1000x1000 grey square with its image_alpha set to 0. These would be generated in rows across the entire space of the room, and then each one would have the FurGeneration() script run on it to generate individual squares of fur flush with each other. I've applied this to one 'row' of my games' Room, and the game really slows down; it doesn't crash, but evidently there are just t0o many calculations going on at once.


My question is: is there a way to multi-thread in Gamemaker? Or does it already multi-thread, meaning that this plan is a foolish one? It would be interesting to hear your thoughts.



Answer



Yes, GM:S already does multi-threading programming on its own. Being a development framework, it would be a pain in the neck if it didn't so.


Instead of creating several objects with different sprite_indexes to create a seamless field of fur, you may want to draw them on a Surface first, and then draw it into your room.


What are Surfaces?
Surfaces are a special type of canvas on which you can draw whatever you want, at any moment, with any object, and in any way, and when you're done you can draw such surface in your room (or GUI as well) and see the results.


There are many possible applications of Surfaces, such as fake lighting effects, particles, several blending modes at once, and so on.


So, instead of generating oFur objects randomly, since they are to be drawn on the screen, you can create a Surface and draw random fur sprites on it at random position (using the same position algorithm to create your oFurs); when you're done, simply draw the Surface.



There ARE performance advantages. Assuming your early oFurs weren't supposed to be moving, you can draw on your Surface once only in a particular Event, and then draw your Surface into the room in the Draw Event. This is better than having n oFur instances, which must draw their sprite_index at their x and y position, each step. You draw the single sprites on the Surface once only, and finally draw the Surface at position (0, 0) so that it is able to fit your room.


meaning in context - J.R.R. Tolkien's Letter 171



p 240 of 493 of this PDF at http://85.17.122.176/bookreader.php/139008/The_Letters_of_J.R.R.Tolkien.pdf:


'Helms too they chose' is archaic. Some (wrongly) class it as an 'inversion', since normal order is 'They also chose helmets' or 'they chose helm ets too'. (Real mod. E. 'They also picked out some helmets and round shields'.) [1.] But this is not normal order, and if mod. E. has lost the trick of putting a word desired to emphasize (for pictorial, emotiona l or logical reasons) into prominent first place, without addition of a lot of [2.] little 'empty' words (as the Chinese say), so much the worse for it. And so much the better for [3.] it the sooner it learns the trick again. And some one must begin the teaching, by example.




1. Please elucidate Tolkien's intent? I thought that he'd prefer 'Helms too they chose'? But then he claims it is 'archaic' and the bolded? These would contradict his position, no?


2. What are little 'empty' words


3. What's the antecedent of it?



Answer



In the letter the excerpt is from, Tolkien is defending the use of (deliberate) archaism as a valid/useful stylistic choice.


With this in mind, the passage becomes clearer. 'Helms too they chose' is an example of how he would like to see archaic phrasing used. It is non-standard (I.E. archaic), but it is concise, clear, and puts the word he wants to emphasise ('helms') into 'prominent first place'.


Standard English, on the other hand, can no longer do this without adding a lot of extra words that don't actually add anything new to the sentence - something like 'Helmets were another thing that they also chose'. Twice as many words used, yet the same amount of information conveyed - therefore the extra words are 'empty'.


In the final sentence 'it' means 'modern English'. (The sooner modern English relearns how to say 'helms also they chose', the better.)


Saturday, May 30, 2015

Meaning and usage of "as such"



This is a passage from an article on the origin of the idiom basket case.



The origins of this idiom are somewhat grisly. In World War I, there were cases reported which involved soldiers who lost both their arms and legs in battle. Any soldier in such a condition would be especially helpless, and other soldiers dubbed them "basket cases" in reference to the fact that they would have to be carried around by others. As such, the original origins of the phrase caused it to invoke physical helplessness.



As such is defined on Dictionary.com as:



a. as being what is indicated; in that capacity: An officer of the law, as such, is entitled to respect.
b. in itself or in themselves: The position, as such, does not appeal to him, but the salary is a lure.



I have a feeling that as such in this context means definition a from above? and I'm guessing indicate in definition a means to state or express, especially briefly or in a general way? But what about in that capacity? If capacity means position; function; role, then I'm guessing this part of definition a does not apply?




Answer



Technically, the first definition, as being what is indicated; in that capacity: An officer of the law, as such, is entitled to respect, is correct. It's what has just been indicated by the preceding passage/text.


It simply means 'as a result,' 'because of this,' 'thus,' 'therefore,' etc.


If you want to define it in terms of to indicate, then it literally means as indicated by what was just said, or as a result of this.



But what about in that capacity? If capacity means position; function; role, then I'm guessing this part of definition a does not apply?



It does apply generally speaking. In that capacity, the original origins of the phrase caused it to invoke physical helplessness.


Capacity references the state of being limb-less and being carried around in a basket, which is mentioned in the sentence before it. That capacity invokes feelings of helplessness when the narrator thinks of the idiom basket case. In other words, that idiom invokes feelings of helplessness when thought of in the capacity of being limb-less and unable to move.


You're taking the definition of this transition phrase way too literally.



Modern opengl for direct3d programmers



I don't think this is quite the same questions as this one but if you disagree feel free to close this :)


With SteamOS being announced yesterday I can see that it's entirely possible that opengl will get a big boost in usage in the near future. Now I already know direct3d11 quite well but I think maybe it's time to learn opengl too.



Are there any good resource for learning modern opengl that are aimed at programmers who already know direct3d11 pretty well. So don't need any education on the concepts and math, just on how to use the API and any important differences?




grammaticality - Adverb between conjugated verb and infinitive?



The judicial function in considering and applying statutes is one of interpretation and interpretation alone. The duty of the court in every case is loyally to endeavour to ascer­tain the intention of the legislature; and to ascertain that intention by reading and interpreting the language which the legislature itself has selected for the purpose of expres­sing it. (Source)




1. What's this phenomenon called? Is this placement unusual or due to my English's primitiveness?


2. Why not situate the adverb after 'endeavour', or even split the infinitive 'to endeavour' and wedge it in between? What are the similarities and differences due to a different position?



Answer



It is (merely) an attempt to avoid the bugbear of a "split infinitive", i.e. "to loyally endeavor".


https://www.englishforums.com/English/BernardShawSplitInfinitive/wjlmg/post.htm


xna - Does passing uniform constants from technique into shader cause branches?


I am trying to find a way to organize my evergrowing number of shader techniques/functions (I am coding in sm_3.0). One way is to do this:


float4 PS_Crossroads(PS_INPUT input, uniform bool left_right) : COLOR0
{
if (left_right)
GoLeft();
else
GoRight();
...

}

technique LEFT
{
pass Pass1
{
VertexShader = compile vs_3_0 VertSh();
PixelShader = compile ps_3_0 PS_Crossroads(true);
}
}


technique RIGHT
{
pass Pass1
{
VertexShader = compile vs_3_0 VertSh();
PixelShader = compile ps_3_0 PS_Crossroads(false);
}
}


My question is will this cause a branch at runtime or will the compiler be smart enough to split it into two separate techniques?


Thanks.


P.S. Ok I won't post this as answer, because we already have an answer by someone much more experienced than me, but from my humble tests (on different PCs) and my humble Google research, this approach (using uniform constants) is efficient and indeed forces the compiler to create different shader versions for each branch, removing flow controll completely from the finall compiled shader. I tested the compiled shader codes with Nvidia NSight.



Answer



In HLSL, creating separate techniques that pass different compile-time values into a shader function will definitely generate efficient code. Optimizing away control flow due to compile-time constants is implemented in Microsoft's HLSL bytecode compiler, which means it doesn't matter which GPU or drivers you have; the optimization is already done by the time the shader gets to the driver's shader compiler. (Unless you disable optimization in the HLSL compiler - in which case, the optimization may very well still be done at the driver level.)


In GLSL, where there is no IHV-independent compiler and bytecode language, things are less certain. Shader compilers are generally pretty aggressive about optimizing away compile-time constants in any form, and a good mature GLSL compiler will have no trouble with this. But there are some platforms/drivers where the GLSL compiler doesn't do a good job, which led Unity developer Aras Pranckevičius to develop a standalone GLSL optimizer.


tense - "have read" vs "read" - Is this simple present vs present perfect?



I have read an interesting book yesterday and underlined the new words which are simple but effective.



Present perfect tense specifies an action that has recently finished. The above sentence is present perfect if I am using have (I believe).


But in my book have is given as error and the sentence is corrected by removing have. I believe by removing have we are changing the tense to simple present. But simple present does not indicates an activity that is finished.


I am not sure why have is error in the above sentence. Please suggest.




What are the challenges and benefits of writing games with a functional language?




While I know that functional languages aren't the most commonly used for game writing, there are a lot of benefits associate with them that seem like they would be interesting in any programming context. Especially the ease of parallelization I would think could be very useful as focus is moving toward more and more processors.


Also, with F# as a new member of the .NET family, it can be used directly with XNA, for example, which lowers the threshold quite a bit, as opposed to going with LISP, Haskell, Erlang, etc.


If anyone has experience writing games with functional code, what has turned out to be the positives and negatives? What was it suited for, what not?



Edit: Finding it hard to decide that there's a single good answer for this, so it's probably better suited as a community wiki post.




Friday, May 29, 2015

grammaticality - Why is 'neither' (without 'nor') singular?


I ask about 'neither' as a determiner. I want to dredge below the last 5 paras under 'Tip 2' , which don't explain. Neither does p 90, A Student's Introduction to English Grammar (2005).



Consider: 2. Neither of the parties ?IS? concerned.
= 3. Both two or more parties are NOT concerned
Does the plurality of the verb in 3, prove that 'neither' should be plural? Why or why not?


I edited the nouns in the original below to simplify.



You need to be careful, because there are two separate situations.
[I omit the second situation here, which I ask NOT about.]


(1) "Neither" withOUT "nor", as in "Neither of the ... parties is concerned with Egypt."


If it is "neither" only, then it is singular and takes a singular verb even though the plural verb might sound better to us.






Thursday, May 28, 2015

Has anyone ever made a shader that produces something similar to pixel art?


I find that pixel art is really pleasing to look at; it has this kind of crisp, satisfying perfection to it.


I've been following some beginner pixel art tutorials, when I got an idea: what if someone made a shader (in GLSL for example) that took 3D scenes and did the best possible job at making it look like it was drawn by a pixel artist? The concepts of anti-aliasing and shading should be relatively easy to perform. Constraining your colour palette would be very simple as well.


Of course, no computer program could outdo the manual work of a great pixel artist, but has anyone ever tried this before?



  • Is this idea at all possible?

  • Are there any games that use it?

  • Have there been (documented) failed attempts?





unity - Make camera follow and rotate with player without childing it


I want to have a camera, that follow the player, without childing it to the player object. So far I have this one line, that follows the player, but does not rotate with it (meaning the camera should look where the player's front is looking, how can I do it?


transform.position = player.transform.position + offset;

Answer



Something like this:


transform.position = player.transform.position - player.transform.forward * distance;
transform.LookAt(player.transform);

where float distance is the distance of camera form player



Consider also the solution 2 : Make camera child of player and in your player die script , you can "deatach" camera from player object


transform.parent = null;

dative alternation - "My friend gave me this book", what is the passive voice?


What is the passive voice of the following sentence?



My friend gave me this book.



Is it:



I was given this book by my friend.




or



This book was given to me by my friend.




Answer



Both of your sentences are acceptable, but they're passive versions of two different sentences.




Your original sentence can be rephrased:




1a. My friend gave me this book.
1b. My friend gave this book to me.



These two sentences have the same meaning, but they differ grammatically. In the latter sentence me is part of the preposition phrase to me.


The relationship between these two sentences is sometimes referred to by linguists as the dative alternation. In English Verb Classes and Alternations: A Preliminary Investigation, Beth Levin lists several types of verbs which participate in this alternation, for example:



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

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

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



Give, of course, fits in the first category, but we can do the same thing with any of the verbs listed above:



2a. She handed me the letter.
2b. She handed the letter to me.



Because your sentence can be rephrased this way, we can come up with a passive version of either one, and they end up having the same meaning:



3a. My friend gave me this book.         ← active
3b. I was given this book by my friend.      ← passive


4a. My friend gave this book to me.       ← active

4b. This book was given to me by my friend.  ← passive



Example 4b has to because its active equivalent also had to. This means that example 4b is not a direct passive equivalent of your sentence, but it can be used and has the same meaning.


Because example 3a is ditransitive, in principle it is also possible to make another passive by promoting its direct object (this book) to subject position:



5a. My friend gave me this book.        ← active
5b. This book was given me by my friend.   ← passive



However, speakers are much more likely to say sentences 3b or 4b. Not all speakers will find example 5b acceptable, and it is particularly likely to sound odd to American English speakers. You should be able to understand this sort of passive if you come across it, but to be safe I suggest you avoid using it yourself.





So as you can see, both of your sentences are acceptable, but only I was given this book by my friend is a direct passive equivalent of your active example.


usage - What is difference between "accomplishment" and "achievement"


It seems that in my native language is used only one word for translating both words "accomplishment" and "achievement". Are they synonyms? Are there some difference in usage of these words?



Answer



The content of this answer was taken from Translation Directory.



An achievement is a goal that has been reached.


An accomplishment is a job or project that has been completed.



Accomplishments



Accomplishment also involve change, but they present the events they refer to as bounded in time. They can be decomposed into two endpoints (the beginning and the culmination of the event) and a process part. Examples of accomplishment are "build a house", "run to the store".


Accomplishments can occur in the progressive. They do not occur with time-span adverbials, but do occur with time-frame adverbials.





  • John is running to the store.





  • John ran to the store in an hour/*for an hour.




Achievements


Achievement are like accomplishments lacking a process part. They denote punctual change. Examples of achievement predicates are "reach the top", "win the race", "find his glasses".



modal verbs - Request a context for a hypothetical use of "could"


As Leech, Geoffrey N. suggests in Meaning and the English Verb §186, could can have the following usage:



#1. Hypothetical equivalent of can (= ‘possibility’)


The house is one of the most beautiful that could be imagined.


#2. Hypothetical equivalent of can (= ‘ability’)


Do you know anyone who could repair this clock for me?




I didn't understand how the hypothetical use was involved in these two examples until I found an explanation from here:



Part 1 If someone is messing around with your clock - but they haven't broken it yet - you can say:



  • "Do you know anyone who could repair this clock for me?"


It means: "If you break my clock, who do you think is going to mend it?"


That's a hypothetical question and you have stated it correctly.


Part 2 Some sentences are definitely hypothetical - because that is their grammatical structure; others can be hypothetical because of the way they are used..





  • If you wanted to, you could go to a baseball game with me




  • You think I could mend your clock




The first is definitely hypothetical because it has "if" and "could"


The second does not seem to have a hypothetical structure but very often it will mean..




  • If for one moment you were to think I could mend your clock then you'd be very much mistaken!


..in which case there is a hypothetical use


I think your textbook (Meaning and the English Verb) is saying that, on the one hand you need to see how the words: if, were, could, would and so on are used to form hypotheses; but on the other hand, you need to know that, in English, hypothesis is sometimes implied with only a hint of those words.



So what kind of context would be apt for #1 so that could could be regarded as a hypothetical equivalent of can (= ‘possibility’) rather than a mere representation of 'real' possibility?


Can you please contrive a hypothetical scenario for Leech's explanation of #1?



Answer



These are both hypothetical because they express uncertainty. The difference between "could fix my clock" and "can fix my clock" is that "could fix my clock" is less definite--it refers to someone who MIGHT be able to, vs "can fix my clock"--this person is definitely expected to be able to fix it. The only real difference is one of tone: "could" is more polite because it makes the speaker's request less demanding (I don't need you to guarantee the repair, just suggest someone I could ask).


In #1, I would say the difference is in what can be done, in some limited sense, vs. what hypothetically could be done, ever. Let me give you a different example that will be more clear:




(1) "This TV has the best display that can be produced."



vs.



(2) "This TV has the best display that could be produced."



In the first example, there is a definite implication of "at this time" or "with current technology," etc. Phrasing it that way suggests that under different circumstances, in the future, it will be possible to produce a better display. But in my second example, the speaker is saying people will never be capable of producing a better display. It's not just the best that can be done right now; it's the best that's theoretically possible, ever.*


Anyway, in your example, this house isn't one of the most beautiful that I personally can imagine, or that any of my friends can imagine, etc. It's one of the most beautiful that any human being at any point in history could possibly imagine. The sentence is referring to a broad hypothetical possibility rather than a more restricted or bounded possibility.


But please keep in mind I'm somewhat overstating the difference to clarify how the "hypotheticality" framework might apply. Practically speaking, the difference between "can" and "could" is mainly one of tone, which won't necessarily be obvious or easy to extrapolate from this framework.



[*] That difference goes away if I add some kind of limit to the second sentence: if I say "the best display that could be produced [under the circumstances / with available resources / with current technology / etc...]", that's a lot more like the "can" example. It's still talking about what's hypothetically possible, but it's stating boundaries for the hypothetical situations being discussed. But note! That changes the tone dramatically. If I say "The best TV that could be produced." I sound like a salesman talking about how awesome my product is. If I say "The best TV that can be produced." the tone sounds like I expect improvements to happen in the future. But if I say "The best TV that could be produced with available methods" I sound like I'm apologizing or making excuses for not doing better; if I say "The best TV that can be produced with available methods" it starts to sound like I'm bragging again, because I'm emphasizing that my company has made the best possible use of the methods available... When I add the qualifier, the tone flips, and "could" goes from making me sound more confident to making me sound less confident. So I would say that the theoretical difference is one thing, but to use it successfully, you'll need to look at a lot of examples.


Unity - blur on one camera effects the other as well



I'm trying to fake a DOF effect for Sprites by using 2 cameras, one for the sharp objects, one for the blurred ones. I have set up the layers like Blur and Sharp accordingly.


So I have these 2 cameras, and I use Unity's Blur (optimized) script to blur things, and I have this script on only one camera, the one that is responsible for the blurred render.


I have the cameras like:


Cam 1:



  • Clear flags: Don't clear (this is the main, sharp cam)

  • Culling mask: sharp layer

  • has no blur effect (or any other post proc effect).


Cam 2:




  • Clear flags: don't clear (this is the blur cam)

  • culling mask: blur

  • Has Blur (optimized).


Now, if this blur cam is on the back, meaning its depth is LESS than the main cam's depth, I have a sharp player ground and a blurry background. However, I need a blurry foreground too that should be on top of the player ground.


The issue starts when I set the blur camera's depth higher than the main cam's. In this case, everything gets blurred, no matter that the main cam has no blur effect on it.


Question is, how to set this up so only the desired layers get the blur?



Answer



With the help of DMGregory there is some neat workaround to basically fake depth of field for sprites. The reason we can't just blur the foreground cam is that these post-processing effects take the final image and work the magic on them.



There are of course more than one ways to do so. One is to sort of pre-blur your sprites in an external 2D app (GIMP or PS for example) and export it to Unity, that way you have a "static" sprite that doesn't need much calculation other than a simple sprite as it is.


This however forbids you from a lot of options like animating the blur, making it more dynamic, reduce the blur if you are unsatisfied and so on.


The other is to use RenderTextures. To do so, you max want to create one in the inspector Right click > Create > RenderTexture and set it up so it suits your needs. I kept it low res as blurred images don't really need to be crisp.


Once you have it, create another camera and set up its layers so it renders only the foreground. In the meantime your main cam should exclude the foreground. Make this BlurCam a child of your MainCam so it follows it. Its depth shall be higher than your MainCam's.


Unity has some scripts, like Blur (optimized) to get you a nice result fast enough. Put that on your BlurCam. After that, assign your RenderTexture as Target Texture for the BlurCam. Set BlurCam's clear flags Solid Color and make its alpha 0.


Drop a mesh plane on the canvas and make it a child of the BlurCam (so it follows it).


Assign a transparent unlit shader (or whatever you wish, it worked nice with my sprites) to that plane and make texture your RenderTexture.


After that, if you placed the plane right, you basically see all your "Foreground" layer sprites blurred. You just have to toss around those sprites to the scene, the blur happens rendertime.


Bear in mind though, that this RenderTexture method, if abused, can propose a meaningful performance hit, especially for mobile as it is a weaker hardware. Always keep an eye on your profiler before setting up these.


prepositions - Their products are of very high quality


Why should we have of in this sentence?



Their products are of very high quality.




Can we simply drop the word of?




Wednesday, May 27, 2015

verbs - Using an adjective after "turn"


Are we allowed to use any adjective after the word "turn"?


For example:



  • turn hot

  • turn cold

  • turn red

  • turn white


  • turn salty




unity - How is this rotation done?


There is a video here that shows how the camera rotates around Leon. The camera rotates around Leon in a circle, this is not difficult, but I don't understand the timing logic.


Once given a short push, the camera keeps rotating for a few more milliseconds.


If the camera would only be rotated during the real mouse movement, the camera would not keep rotating a bit after there is no more mouse movement.


However, in this video, the camera rotates a few more milliseconds even after the last mouse movement.


How could this be accomplished?



Specifically, I would like to ask if somebody can tell me if the developers add some extra movement in the direction of the mouse movement which they then "smooth out", or if they "smooth out" the end of the user's mouse movement.


Thank you!



Answer



Implementing this sort of momentum in camera motion (or really just about anything) can be done with easing functions.


When the actual input to the camera movement system stops, you have (or can compute, depending on your implementation) the speed at which the camera was rotating during the input period. Rather than simply set that speed to zero, jerking the camera to a halt, you apply some sort of easing function to slowly reduce that speed to zero, resulting in the gradual settling you see in the video.


This can be done fairly straightforwardly by adding a new state to your camera. Previously you had two states, explicitly or implicitly: moving and stopped. Add a third state, "settling." You can do this as simply as adding a "settling time left" field to your camera that is zero normally, but which you set to a non-zero value representing the number of seconds the camera takes to smoothly come to stop. Implicitly when this value is non-zero the camera is in the "settling" state.


Then, every update, if the camera is settling, keep it moving based on whatever easing function you've chosen and the time remaining, deduct from the remaining time, and there you are.


meaning in context - as good ~ as I ever knew



“Now, yer mum an' dad were as good a witch an' wizard as I ever knew.”
(Harry Potter and the Sorcerer's Stone)




What’s the meaning of the highlighted part?



Answer



Harry's mum was a good witch and his dad was a good wizard.



Yer mum and dad were a good witch an’ wizard.



How good were they? They were as good as any witch or wizard I ever knew.



Yer mum and dad were as good a witch an’ wizard as I ever knew.




These constructions are maybe, possibly, just a little bit too colloquial for, say, an exceptionally dry academic journal; but anywhere else they’re fine.


Tuesday, May 26, 2015

word meaning - "As far as I can say", "as far as I know", "as far as I can tell"



As far as I am concerned.
As far as the economic problems here are concerned.
And As far as I know.


My perception: All these are incorrect. Because we just use " As far as I am concerned" to mean " In my opinion" . Therefore it does not actually make sense saying: " in the economic problems's opinion." " I can say my opinion" " I know my opinion" and so forth.



Answer



I think you are mistakenly generalizing on a single instance.


As far as I am concerned may be used in contexts where it has approximately the same effect as saying in my opinion; but it does not mean in my opinion.


Examine the actual construction of the expression as far as X is concerned:



as far as means to the extent or degree that

X is concerned means X is involved or relevant



Consequently, as far as I am concerned only has the effect of saying in my opinion when it is used to introduce an opinion.



As far as I am concerned, Bob’s a jerk.This means “My concern in this matter does not go beyond recognizing that Bob’s a jerk; I am not interested in any subtler analysis of his behavior.”



But in other contexts as far as X is concerned takes on quite different meanings:



As far as the economic problems here are concerned ...This means “To the extent that our discourse involves the economic problems here [I have this to say] ...”




Similarly, as far as I know means to the extent that my knowledge reaches—that is, “I do not claim to know everything about this topic, but what I do know is this ...”


xna - How can I use a Texture2D larger than 2048 x 2048?



I'm having issues working with a large image. I've read other threads on using images larger than a Texture2D supports, but found nothing that addresses my problem specifically with implementation hints.


My screen resolution is 1920 x 1080. I'm working in C# XNA. The game in question is pretty much a board game.


I have an 3840 x 3840 image I planned to use for the terrain map. The idea was to make each new game look a little different from the last by having the program randomly select a 1920 x 1080 segment of that large image to display. My code to randomly select and display a part of the image is working.


Unfortunately, I can't even get the initial 3840 x 3840 image to load. Just picking "Add Existing Item" and adding the image to the content window on the right causes my program to error that a Texture2D can only be 2048 x 2048 maximum.


How do I best handle this? I may later need to scale or rotate the map.




Suggestions I've seen around:



  • Cut it up into sections.

  • Use a smaller image that is made "seamless" or "tile-able", then choose a random starting X,Y point in it and fill the screen with that.



Are these good ways to go about it? How would I actually do this? Would I still be able to scale and rotate the map?




java - Adding a short delay between bullets


I'm having some trouble simulating bullets in my 2D shooter. I want similar mechanics to Megaman, where the user can hold down the shoot button and a continues stream of bullets are fired but with a slight delay. Currently, when the user fires a bullet in my game a get an almost laser like effect. Below is a screen shot of some bullets being fired while running and jumping.



Bullets being fired


In my update method I have the following:


if(gc.getInput().isKeyDown(Input.KEY_SPACE) ){
bullets.add(new Bullet(player.getPos().getX() + 30,player.getPos().getY() + 17));
}

Then I simply iterate through the array list increasing its x value on each update.


Moreover, pressing the shoot button (Space bar) creates multiple bullets instead of just creating one even though I am adding only one new bullet to my array list. What would be the best way to solve this problem?



Answer



You can add a little timer:



if(gc.getInput().isKeyDown(Input.KEY_SPACE) && 
gameTime.getTimeMS() - shootTime > shootDelayInMilliseconds) {
shootTime = gameTime.getTimeMS();
bullets.add(new Bullet(player.getPos().getX() + 30,player.getPos().getY() + 17));
}

Basically you are noting the last time your character shot, then ensuring that enough time has passed before shooting again.


As for adding multiple bullets to the array list, it's doing this because you likely can't press the space bar fast enough to only have the space bar pressed for one frame. Each update you're adding one bullet. Add the delay like above will likely solve that problem. If you want to have a longer delay before you start repeating shots, you can doing something like:


if(gc.getInput().isKeyDown(Input.KEY_SPACE) && !previousInput.isKeyDown(Input.KEY_SPACE)) {
startShootTime = gameTime.getTimeMS();

}
if(gc.getInput().isKeyDown(Input.KEY_SPACE) &&
gameTime.getTimeMS() - shootTime > shootDelayInMilliseconds &&
gameTime.getTimeMS() - startShootTime > initalShootDelayInMilliseconds ) {
shootTime = gameTime.getTimeMS();
bullets.add(new Bullet(player.getPos().getX() + 30,player.getPos().getY() + 17));
}

Where initalShootDelayInMilliseconds is the time before holding the space bar causes repeated shots and shootDelayInMilliseconds is the time between each repeated shot thereafter. This is similar to the keyboard input for many text editors, holding a key for a certain amount of time will cause that key to repeat at a (often shorter) delay rate.


movement - Making Minecraft in 2D. Blocks move when player moves


I want to make a 2D Minecraft game and I have drawn the grass blocks and you can dig but when the palyer moves the dirt moves too. It draws on every block wich the player touches a dirt block because I said that it has to draw it on r.getX() and r.getY() and it changes every time the player moves. Could someone please help me?



This is my code.


import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;

import java.awt.event.MouseListener;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.ArrayList;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JPanel;

public class Gameplay extends JPanel implements ActionListener, KeyListener, MouseListener{

public BufferedImage player;
public BufferedImage grass;
public BufferedImage dirt;
private BufferedImage dbImage;
private Graphics dbg;
private int x = 0;
private int y = 0;
private double velX = 8.0f;
private double velY = 8.0f;
public Rectangle rectangle;

public Rectangle rectangle2;
public Rectangle MouseRect;
public boolean BlockD = false;
public ArrayList blockList = new ArrayList();
private int[] xb = {0, 50, 100, 150, 200, 250, 300, 350, 400, 450, 500, 550, 600, 650};
private int[] yb = {0, 50, 100, 150, 200, 250, 300, 350, 400, 450, 500, 550, 600, 650};
//
public Gameplay(){
addMouseListener(this);
addKeyListener(this);

setFocusable(true);
try {
player = ImageIO.read(getClass().getResource("Player.png"));
grass = ImageIO.read(getClass().getResource("Grass.png"));
dirt = ImageIO.read(getClass().getResource("Dirt.png"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}


public void paint(Graphics g){
dbImage = (BufferedImage) createImage(getWidth(), getHeight());
dbg = dbImage.getGraphics();
paintComponent(dbg);
g.drawImage(dbImage, 0, 0, this);
repaint();
}

public void paintComponent(Graphics g){

drawBlock(g);
rectangle2 = new Rectangle(x, y, 35, 35);
g.drawString("Jake", x, y);
for(Rectangle r : blockList) {
g.drawImage(dirt, (int) r.getX(), (int) r.getY(), this);
}
// Draw player after dirt blocks
g.drawImage(player, x, y, this);
}


public void drawBlock(Graphics g){
for(int first = 0; first < 10; first++){
for(int second = 0; second < 10; second++){
g.drawImage(grass, xb[first], yb[second], this);
}
}
}

@Override
public void actionPerformed(ActionEvent e) {

// TODO Auto-generated method stub

}

@Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_UP){
y += -velY;
}
else if(e.getKeyCode() == KeyEvent.VK_DOWN){

y += velY;
}
else if(e.getKeyCode() == KeyEvent.VK_LEFT){
x += -velX;
}
else if(e.getKeyCode() == KeyEvent.VK_RIGHT){
x += velX;
}
else if(e.getKeyCode() == KeyEvent.VK_SPACE){
int blockX = Math.round(x / 50) * 50;

int blockY = Math.round(y / 50) * 50;
blockList.add(new Rectangle(x, y));
}
}

@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub

}


@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub

}

@Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub


}

@Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub

}

@Override

public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub

}

@Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
if(e.getButton() == MouseEvent.BUTTON1){


}
}

@Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub

}
}


Thanks.



Answer



This is exactly what you'd expect to happen. This is the code that draws your dirt blocks:


for(Rectangle r : blockList) {
if(rectangle2.intersects(r)) {
if(BlockD){
g.drawImage(dirt, (int) r.getX(), (int) r.getY(), this);
}
}
}


This code says, for every rectangle (grass block) on the map, draw a dirt block if the player is standing on that rectangle. So of course your dirt blocks move when the player moves - that's what you're telling it to do.


I'm guessing what you want to do is create a dirt block on the current block when you press space. This should be a quite simple fix:


public Gameplay() {
addMouseListener(this);
addKeyListener(this);
setFocusable(true);
try {
player = ImageIO.read(getClass().getResource("Player.png"));
grass = ImageIO.read(getClass().getResource("Grass.png"));

dirt = ImageIO.read(getClass().getResource("Dirt.png"));
} catch (IOException e) {
e.printStackTrace();
}

// Remove this code!
/* for(int first = 0; first < 10; first++){
for(int second = 0; second < 10; second++){
rectangle = new Rectangle(xb[first], yb[second], 50, 50);
blockList.add(rectangle);

}
} */
}

public void keyPressed(KeyEvent e) {
if (...) {
// Movement code for player
}
else if(e.getKeyCode() == KeyEvent.VK_SPACE){
// Place dirt block at current coordinates

// Round the coordinates to closest block
int blockX = Math.round(x / 50) * 50;
int blockY = Math.round(y / 50) * 50;
blockList.add(new Ractangle(blockX, blockY, 50, 50));
}
}

public void paintComponent(Graphics g){
drawBlock(g);
g.drawString("Jake", x, y);


// Draw all dirt blocks
for(Rectangle r : blockList) {
g.drawImage(dirt, (int) r.getX(), (int) r.getY(), this);
}
// Draw player after dirt blocks
g.drawImage(player, x, y, this);
}

Note that I have changed what blockList is used for. Before it was the rectangles for all grass blocks but now it is the rectangles for the dirt blocks.



meaning - nothing a good beating wouldn't have cured




"I accept there's something strange about you, probably nothing a good beating wouldn't have cured - and as for all this about your parents, well, they were weirdos, no denying it, and the world's better off without them in my opinion - asked for all they got, getting mixed up with these wizarding types - just what I expected, always knew they'd come to a sticky end -" (Harry Potter and the Sorcerer's Stone)




What’s the meaning of the highlighted part?



Answer



This is probably Harry's uncle Vernon telling Harry that had he been spanked (beaten) very hard instead of treated like a special child, there would be nothing strange about him. Vernon believes that violence solves problems and that beating Harry every time he used magic would have killed the magic, or at least Harry's desire to use magic, and that he would have grown up to be a normal boy, like Vernon and Petunia's son Dudley.


There's a saying in English: Spare the rod and spoil the child. It means that children flourish and grow up well only if they are strongly disciplined mentally, emotionally, and physically. It's from the King James Version of the Christian Bible, Proverbs 13:24:


He that spareth his rod hateth his son: but he that loveth him chasteneth him betimes.


It's justification for corporal punishment.


Monday, May 25, 2015

mmo - synchronizing client-server actions


What's the usual way to handle events that are checked both on server and the client, like attacking? There's a cooldown timer to an attack of which the client is aware (so to prevent spamming server requests and attack button is held).


Next there's a cooldown timer on the authoritative server. My problem is that sometimes attacks that end up firing on the client aren't executed on the server, because the server timer (serverFrameTime - lastAttackFrameTime > attackCooldown) didnt count up to the desired time, and so those are 'blank' attacks on the client.



Is there a standard way to handle that without emiting too many messages? This is a problem for me because i might be firing more of those events and more timers, so autoattacking without clicking is not a long term solution for me.




word choice - "Neither", "none", "no one" + [of them] + verb-s


In a comment on English Language & Usage I read the following answer responding to a(n) asker's question: "Neither sound natural."


I have always had more than one doubt on the "neither" usage and I would like understand(ing) the "secrets" to use this word better or, at the best, correctly.


So, let us consider the following examples:



1 Neither sound natural.



2 None sound natural.


3 No one sound natural.


4 Neither of them sound natural.


5 None of them sound natural.


6 No one of them sound natural.


7 Neither sounds natural.


8 None sounds natural.


9 No one sounds natural.


10 Neither of them sounds natural.


11 None of them sounds natural.



12 No one of them sounds natural.



Comparing the above sentences (one) with each other, can anybody explain which is grammatical and why?




tense - Difference between "is added" and "was added"


I need to know the meaning and tense of these sentences:



(A) "This feature is added to the last version."



(B) "This feature was added to the last version."



I can't understand the difference between "is added" and "was added". Is there any difference between these two sentences, or do they mean the same thing?



Answer




This feature is added to the last version.



is not grammatical. It is not now being added, since the last version is already out there.



This feature is added to the current version.

This feature is added to this release.



These sentences still do sound a bit off though, you would normally find them as:



This feature has been added to the current version.
This feature has been / is being added to this release.



("is being" if the current release is still in development.)


For others than the current version:


This feature was added in the last version.

This feature will be added in the next version.


"Is added" is used to describe a change in functionality based on some action or event:



This feature is added when you upgrade to the newest version.
This feature is added by selecting the option in the "options" screen.



graphics - Any interesting thesis topic?



I study Computer Science at Technical University of Lodz (in Poland) with Computer Game and Simulation Technology specialization. I'm going to defend BSc thesis next year and I was wondering what topic I could choose but nothing really interesting is coming to my mind.


Maybe You could help me and suggest some subjects related to programming graphics, games or simulations? (or maybe something else that is interesting enough :) ). I would be very grateful for any suggestion!



Answer



Few topics come to my mind



  • Fluids simulation: Navier-strokes equations. And gpgpu acceleration (video)


  • Fluids rendering - volumetric raycasting (video)

  • Volumetric rendering - marching cubes (video)

  • Realtime bokeh rendering (paper)

  • Point based rendering (video)

  • Realtime rain rendering (paper)

  • Simple raytracer with global ilumination - propably without accelaration structs.


And the best is contact some computer games/graphics/movie company and offer them to create something they need for free. That have only pluses. You will have hard and interesting thesis ( and prototype ) and some experienced advisor from company who will help you. Don't be afraid to do it. Enthusiasm helps very much in this case. (I know it)


modal verbs - I have two questions about how to use 'will'


There are two sentences that I'd like to fully understand.



Only 30 years ago, it was almost impossible to come across a family that had a car, but Korea has changed beyond all recognition and cars have become very common. More often than not, one family 'will' have 2 or 3 cars.




I can't understand why 'will' is used. What if I use just 'has' instead of 'will have'? All I know about how to use 'will' is 'voluntarily action' or 'prediction'. Could you help me understand the difference 'will' and 'will have' above sentence?



Once I'm done with my banking, everyone wishes me a good day and someone 'will' always be on hand to hold the door open when I leave.



Similarly, I'd also like to know the difference 'someone is always on hand' and 'someone will always be on hand'. For me, it is much easier way that I use the former than the latter.


Thanks in advance.



Answer



"Will/would" is originally a verb that expresses volition, but this use today is limited. It is mostly found in negative sentences such as "I won't have it" meaning I don't want to tolerate it.


Today "will/would" is mostly used as auxiliary verb for future tense and conditional.



But there is a third use of "will" for describing behaviour or qualities that are normal and always found to be true as in


1 Paper will burn (if you set it on fire).


2 Wood will float on water.


3 If the temperature is below zero rain will fall as snow.


Here "will" has nothing to do with volition or future tense. Grammars speak of "habitual actions" or paraphrase by saying "used for things that always happen". This is a special use of "will" that is not so easy to explain.


By the way, "will" can be a full verb (will/willed/willed), expressing volition, but it is relatively rare. Etymonline translates Arabic inshallah as "If Allah wills (it)."


Added: The Longman English Grammar by L.G. Alexander has will/would for habits in paragraph 11.63 "will/would" to describe characteristic habit/behaviour


1 In fine weather, he will often sit in the sun for hours.


2 As he grew older, he would often talk about his war experiences.


3 Boys will be boys. (Common fixed phrase)



4 Accidents will happen. (Common fixed phrase)


(Added: Thinking about this use of will/would for characteristic habit/behaviour I would say this is an extension of the future tense: It will be so always or mostly.)


And in paragraph 11.64 "Will" and "would" to describe natural tendancy


5 Water will boil at 100°C.


(Added: characteristic behaviour of things: I think this is the same extension: It will be so whenever you check.)


modal verbs - "Will" or "Would"?



In my understanding, while talking about future whether to use "would" or "will" depends on our perception and subjective.


If you are confident about something you can use 'will' instead of 'would' and, use 'would' if you are less confident about something( while talking about future).


For instance,




  1. Egypt has decided to build a new city near Cairo, that city will create more jobs



( It means we are sure that city is going to be constructed and at the same moment ,it is going to create more jobs-100% confident that it will happen).





  1. Egypt has decided to build a new city near Cairo, that city would create more jobs



( Not sure about the job creation because of unreliable government , and happens only if everything goes well- it means, only if government makes city and creates more job).


It would be great if someone could help me on above regards, I am totally going insane on this 'would' and 'will' confusion.




Sunday, May 24, 2015

Unity procedural TileMap generation without creating gameobject per tile


I've been searching internet to find an efficient way to create a procedural tilemap without creating a GameObject per tile. All the TileMap tutorials I've found are creating tiles by creating hundreds of GameObjects. Thus the hierarchy in Unity is expanding unexpectedly.


I'm pretty sure this is not the "right" way to do it. Especially after seeing the new Unity 2D tools that supports tilemaps. Unity made it so, you can create tiles in "one" gameobject, not for each tile.


So, how do I do it in the right and effiecent way?



Answer



Here's what I'm aware of:


Option 1. GameObject per tile. It's not completely horrible in certain cases. Depending on your needs, it could work.. well enough.


Option 2. A single quad or plane referencing a texture you create at run-time. You would essentially use your tile atlas texture to "paint" your map as one new texture. Depending on the size of your map of course, you might want to have multiple quads/planes each representing portions of your map.



Option 3. Create your own mesh. This would more than likely be the method you'll like most once implemented. It'll give you tons of flexibility and probably the highest performance. You would essentially create a quad per tile and set each vertex UV to map to the tiles in your tile atlas.


For Option 2, I'd suggest watching this video series by quill18creates: 3D TileMap tutorial series by quill18creates


For Option 3, this is my code, with tweaks, so it may not be perfect:


//For this, your GameObject this script is attached to would have a
//Transform Component, a Mesh Filter Component, and a Mesh Renderer
//component. You will also need to assign your texture atlas / material
//to it.

void Start() {
meshFilter = GetComponent();


BuildMesh();
}

public void BuildMesh() {
int numTiles = mapSizeX * mapSizeY;
int numTriangles = numTiles * 6;
int numVerts = numTiles * 4;

Vector3[] vertices = new Vector3[numVerts];

UVArray = new Vector2[numVerts];

int x, y, iVertCount = 0;
for (x = 0; x < mapSizeX; x++) {
for (y = 0; y < mapSizeY; y++) {
vertices[iVertCount + 0] = new Vector3(x, y, 0);
vertices[iVertCount + 1] = new Vector3(x + 1, y, 0);
vertices[iVertCount + 2] = new Vector3(x + 1, y + 1, 0);
vertices[iVertCount + 3] = new Vector3(x, y + 1, 0);
iVertCount += 4;

}
}

int[] triangles = new int[numTriangles];

int iIndexCount = 0; iVertCount = 0;
for (int i = 0; i < numTiles; i++) {
triangles[iIndexCount + 0] += (iVertCount + 0);
triangles[iIndexCount + 1] += (iVertCount + 1);
triangles[iIndexCount + 2] += (iVertCount + 2);

triangles[iIndexCount + 3] += (iVertCount + 0);
triangles[iIndexCount + 4] += (iVertCount + 2);
triangles[iIndexCount + 5] += (iVertCount + 3);

iVertCount += 4; iIndexCount += 6;
}

mesh = new Mesh();
//mesh.MarkDynamic(); if you intend to change the vertices a lot, this will help.
mesh.vertices = vertices;

mesh.triangles = triangles;
meshFilter.mesh = mesh;

UpdateMesh(); //I put this in a separate method for my own purposes.
}


//Note, the example UV entries I have are assuming a tile atlas
//with 16 total tiles in a 4x4 grid.


public void UpdateMesh() {
int iVertCount = 0;

for (int x = 0; x < mapSizeX; x++) {
for (int y = 0; y < mapSizeY; y++) {
UVArray[iVertCount + 0] = new Vector2(0, 0); //Top left of tile in atlas
UVArray[iVertCount + 1] = new Vector2(.25f, 0); //Top right of tile in atlas
UVArray[iVertCount + 2] = new Vector2(.25f, .25f); //Bottom right of tile in atlas
UVArray[iVertCount + 3] = new Vector2(0, .25f); //Bottom left of tile in atlas
iVertCount += 4;

}
}

meshFilter.mesh.uv = UVArray;
}

Efficient billboarding sprites in Unity 5


What's the most efficient way to do billboarding sprites in Unity 5?



I want to make a forest of sprite trees in 3d space. Those sprites need to face the camera at all times. I am working on VERY performance restricted hardware - I need the game to run on mobile at 60+ FPS - the scripts have their overhead and moving/turnign trees cannot be static, so I cant use static batching for them.


The naive method of adding a script to each tree that makes it LookAt the camera each update is not good enough in terms of FPS.


I know the grass/details for terrain uses billboards, but it uses the sprite only as a silhouette for the grass and paints it with a flat colour.



Answer



Instead of using LookAt, you can have the shader force the object to be rendered facing the camera. Thus, no script needs to be added to the tree, and the extra work the shader does is very little. Here's an example: Billboard Shader


Also, since they don't actually move or rotate (as far as the CPU is concerned) and share the same material, you can turn on static batching.


I hope this helps!


3d - Implementing Geometry Instancing in DirectX


I have a project that I'm doing in Managed DirectX (DX9) where I want to render lots of grass. My current method (many draw calls) is slow, but I've heard Geometry Instancing can fix that.


I know that I have to have one vertex buffer to store the vertices that will drawn multiple times. I know that I need another vertex buffer to store the transformations (from what I've seen you can only have one additional vertex buffer). So should the second vertex buffer store transformation matrices? I tried coding this, but when I want to create a new vertex buffer one of the required parameters is vertexFormat, but I can't supply a vertex format since this is a matrix.



I also wanted to try to have the second vertex buffer store the translation values as Vector3, but how do I tell DirectX that the values in the second vertex buffer are to be used as translation values? Secondly, I also need rotation values. Do I store these in a third vertex buffer?


Basically, I want to use geometry instancing to draw multiple instances of a quad that are rotated and translated.



Answer



What you'll wind up doing David is creating a vertex buffer to hold the different transformation matrices for each instance of grass. You will need a vertex declaration that has your standard 'grass' vertex components( pos, norm, uv...etc ), and in that same declaration 4 additional 4-component floats to hold the 4x4 transformation matrix...the declaration will look like this:


IDirect3DVertexDeclaration9 *pVDInstances = NULL;

// create instance vertex declaration
D3DVERTEXELEMENT9 pElements[] = {
{ 0, 0, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0 }, // position
{ 0, 12, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_NORMAL, 0 }, // normal

{ 0, 24, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0 }, // uv
{ 1, 0, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 1 }, // 1st row transformation matrix
{ 1, 16, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 2 }, // 2nd row transformation matrix
{ 1, 32, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 3 }, // 3rd row transformation matrix
{ 1, 48, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 4 }, // 4th row transformation matrix
D3DDECL_END()// add additional data declarations before this line if you require( be sure to change the 'stride' when setting the 2nd stream source below... )
};

hr = pd3dDevice->CreateVertexDeclaration( ( D3DVERTEXELEMENT9* )&pElements, &pVDInstances );
if( FAILED( hr ) )

{
// handle failure
}

Take note of the first parameter of the D3DVERTEXELEMENT9 constructor...it is '0' for the mesh object and '1' for the transformation matrix. This is because you are going to instruct the graphics device to use 2 different vertex buffers. Also take note of the 'offset' parameters...they begin again at 0 for the 2nd vertex buffer.


Before you can render though, you must also set the frequency of transformation matrices per instance...such that for every instance of grass the graphics device will use 1 transformation matrix.


Before the draw call you will instruct the graphics device like this:


if( FAILED( hr = pd3dDevice->SetStreamSourceFreq( 1, ( D3DSTREAMSOURCE_INSTANCEDATA | 1ul ) ) ) )
{
// handle error

}


// the instance buffer holds the transformation matrices for each instance of grass
IDirect3DVertexBuffer9 *pVBInstances = pXGrassModel->GetInstanceBuffer();

// Set up the instance data stream
if( FAILED( hr = pd3dDevice->SetStreamSource( 1, pVBInstances, 0, sizeof( D3DXMATRIX ) ) ) ) // you can change this if your instance buffer holds more than a single transformation matrix
{
// handle error

}
if( FAILED( hr = pd3dDevice->SetVertexDeclaration( pVDInstances ) ) )
{
// handle error
}

// then set materials and textures as usual and draw


Here is a vertex shader for instances:


struct VS_OUTPUT_Inst
{

float4 Position : POSITION0;
float3 Normal : TEXCOORD0;
float2 UV : TEXCOORD1;
};

VS_OUTPUT_Inst InstancesPass_Vertex_Shader( float4 vPos : POSITION,
float3 vNormal : NORMAL,
float2 vUV : TEXCOORD0,
float4 vRowX : TEXCOORD1,
float4 vRowY : TEXCOORD2,

float4 vRowZ : TEXCOORD3,
float4 vRowW : TEXCOORD4 )
{
VS_OUTPUT_Inst Output = ( VS_OUTPUT_Inst )0;

float4x4 mWorld;
mWorld._m00_m01_m02_m03 = vRowX.xyzw;
mWorld._m10_m11_m12_m13 = vRowY.xyzw;
mWorld._m20_m21_m22_m23 = vRowZ.xyzw;
mWorld._m30_m31_m32_m33 = vRowW.xyzw;


float4x4 mWorldView = mul( mView, mWorld );

float4 Pos = mul( vPos, mWorld );
Pos = mul( Pos, mView );
Pos = mul( Pos, mProjection );

Output.Position = Pos;

Output.Normal = normalize( mul( vNormal, ( float3x3 )mWorldView ) );


Output.UV = vUV;

return( Output );
}

Note the Semantics used here can be traced to the semantics used in the vertex declaration above...


Saturday, May 23, 2015

unityscript - Unity Input.GetMouseButtonDown(0) is not working


My code to detect left mouse click is not working Input.GetMouseButtonDown(0) and Input.GetMouseButtonUp(0). But same code for Input.GetMouseButton(0) is working.



Code:


void FixedUpdate()
{
#if UNITY_ANDROID
mouseWorldPos = Camera.main.ScreenToWorldPoint(Input.mousePosition + new Vector3(0, 0, 4f));
mouseCameraOffset = bowlingBall.position - mouseWorldPos;

if (Input.GetMouseButtonDown(0))
{
Debug.Log("last");

lastMousePos = Input.mousePosition;
}


meaning in context - Distorted Cabin & Oily Sheen: What is going on in this paragraph?


I have been reading a book, and I have a question about the following excerpt:



"We're here," The Tortoise in the Lake said, cutting across Dong Huong's gloomy thoughts.


"I can see nothing."


There came a low rumble, which distorted the cabin around her, and cast an oily sheen on the walls. "Watch."


Outside, everything was dark. There was only the shadow of The Two Sisters in Exile, the dead ship that they'd been pulling since Longevity Station.


The Two Sisters in Exile, a fantasy novel by Aliette de Bodard




Are these changes happening in the “real” life of the novel?, or are they an illusion that exists merely in the mind of the narrator? If they are only an illusion, why does the author not say so? Has the author omitted something, or are these changes are really happening as the author says?




Is "Maybe he …, maybe he …" considered a comma splice?



Maybe he told her everything, maybe he'd been watching me all this time.



Is this considered a comma splice? Why or why not?



Answer



"Comma splice" isn't a term with a strict definition. Generally, people use the term when they think a pair of independent clauses that are joined without a coordinator would be better written as separate sentences. In other words, they call this sort of thing a "comma splice" if they consider it an error.


Sentences can sometimes be joined without an explicit coordinator like and or or. Writers tend to do this when they're closely related in meaning or structure. For example:




I came, I saw, I conquered.



Although this has no explicit coordinator, this famous example has nonetheless been written as a single sentence. All three clauses are similar in structure and are related in meaning. It works.


When it works, people tend to call it asyndeton.
When it doesn't work, they tend to call it a comma splice.


But that's more of a judgment call than anything, because there's no strict technical definition that separates one from the other.



Maybe he told her everything, maybe he'd been watching me all this time.




I'd call it the asyndetic coordination of two clauses that are similar in structure and related in meaning. It seems fine to me the way it is. (I can't guarantee that an English teacher wouldn't mark it with a red pen, though.)


software engineering - Finding other programmers to help on a project



As a semi FAQ question attempt :


Where can you find people to work with you on a project? Particularly programmers. One thing that is obvious is that all programmers have a project (or twenty), and the chances of a programmer just hanging around looking for something to do is a lot less likely than if it were an artist needed on the team.



So, where do you post? Where do you search and follow people around until it looks like they are a viable team member? Is it really difficult to assemble a team that are not close friends or chat buddies? Are there sites with this sort of posting?


To clarify : I am referring to a team.


Example 1 : I am making gameEngineOfAwesomeness. I need help.


Example 2 : I am 70% complete on this game, and i need help.


Example 3 : I have an open source project idea, with a prototype. I need help.


It doesn't necessarily mean open source, just programmers who can work with me on something (and where to find them :))



Answer



1) Press the flesh at places like Penguicon or local users group meetings and have your elevator pitch down and some color fliers with calls to action. If you want to enlist the help of others, you will need to market yourself and your idea. Explain 'why you' and 'why this' to a group of people who don't know you and surely have 15 of their own ideas that they haven't followed through on themselves. If you have a prototype, set up several machines in a con-suite or talk to the users group about being a speaker and present what you have to as large an audience as you can.


2) Make it easy to help you by setting up all of the infrastructure yourself before you talk to anyone. Get a well populated WIKI in place, source control system, storyboards (even if the art stinks), etc. and ideas on how 'this game' is going to change the world.


3) Be prepared to do more work than any two or three other team members, because you will need to be cheerleader, project manager, and contributor all.



Friday, May 22, 2015

cocos2d x - Spriting Animation Method


http://www.kickstarter.com/projects/539087245/spriter


At 3:00 they discuss that there is a method used to separate the parts of character into individual sprites and move them saving production time and video memory. What is this method called I am thinking that I want to implement it for my game but need to do more research. Thanks alot =)




Answer



It's called 2D skeletal animation. Essentially you're animating a skeleton that has sprites for the body parts placed on top of it. This allows you to reuse animations for different characters and characters can have multiple sets of armor, weapons, etc.


There are a number of questions on the site already about it:


Tools for 2D skeletal animation


How Plants vs Zombies animation is done?


Tips on combining the right Art Assets with a 2D Skeleton and making it flexible


And some other good resources:


http://www.catalinzima.com/2011/06/2d-skeletal-animations/


http://www.thecareergamer.com/braaaains-zombieville-usa-tech-review/


Enjoy your research.



singular vs plural - "I'm wearing a red PANT." or "I'm wearing a red PANTS."


Is correct to use "Pant" or is "Pants" better?


Here the phrase below:



I'm wearing a red pants.




Answer



Individual items of clothing which consist of two components (one for each side of the body), often have no singular form, and are always treated as plural even though they are a single unit. Thus, you would wear red pants or wear a pair of red pants.





There are numerous English words which are always treated as plural: scissors, congratulations, outskirts, jitters, forceps, savings, suds, etc.— too many to cover in one answer. But if we limit it to clothes (itself always plural), I can suggest these guidelines:




  • most garments for the lower body which cover the legs individually are always plural: trousers, shorts, overalls, breeches, chaps, bloomers, etc. Even a one-legged person would not wear "a" jodphur or sweatpant or boardshort; he or she wears jodphurs, sweatpants, or boardshorts. The explanation behind it is that tailors made them in two pieces, one for each leg, and so they always came to be referred to in the plural; a shirt or coat, in contrast, was made from a single piece of cloth.


    Terms referring to specific types or expressions of those garments also take the plural: dungarees, chinos, bell bottoms, and so forth. Indeed, even derivates and brand name uses follow this pattern, whether in the name itself (e.g. Dockers®) or by synecdoche: what comes between me and my Calvins? (i.e. my Calvin Klein jeans).


    In contrast, items which come as a pair of separate pieces follow regular pluralization: one mitten, one pair of mittens, two mittens.




  • suspenders / braces. In AmE, braces when referring to the orthodontic devices are also always plural; I'm not sure about BrE.





  • pajamas (AmE) / pyjamas (BrE) and derived nicknames like jammies, PJs, or jim-jams.




  • some lower body undergarments with legs or where a separate gap is provided for each leg: pants (BrE) / panties (AmE), boxers, drawers, long johns, jockies, knickers, briefs (inc. "tighty-whities"), tights, thermals— but not, for example, pantyhose, a jockstrap, or a thong.




  • eye and ear accessories consisting of single piece but with a separate component for each eye— [eye]glasses, binoculars, bifocals, contacts, shades, etc.— or each ear— earmuffs, headphones, cans. In contrast, you can have a singular monocle, eyepatch, or scope; one earring or one earbud. Headset is an exception.





Note finally that in some cases, a singular form of the word does exist, but it refers to something different: glasses and glass, slacks and slack, trunks and trunk, "Daisy Dukes" and Daisy Duke.


rendering - What is a texture atlas?


I've heard about this concept, but what is it?



Answer



A texture atlas is simply a way to stuff multiple sprites into a single texture. You also will need an index into the texture so that you can find where each of the sprites are located.


The reason these are used is because it's more efficient to bind a texture once and change the UV values being used than to bind multiple textures for each sprite you draw.


Here is an article from Gamasutra on texture atlases that helped me a lot when I was first getting started



c++ - D3D/DXGI handle fullscreen transition


I have a D3D11 application, and I want to add proper fullscreen suport. Now I can let DXGI switch my window to fullscreen for me, and I'm under the impression that DXGI will take care of everything needed to make the swap chain flip front and backbuffer instead of blitting them.


However, letting DXGI perform the swich seems unreliable with a multi monitor setup - secondary screens stay entirely black after the switch a great deal of the time, with no apparent reason or pattern to it.


It can take a few times switching back and forth before I get the fullscreen window and the rest of the desktop being shown on the other screens.


Apparently I'm not alone with this, Battlefield 3 and WoW seem to have similar issues for a lot of people.


Now, the actual question: I guess since even those AAA game dev companies can't get this to work, my biggest hope would be to somehow perform the switch to fullscreen myself.


Is there anything I can do to elevate my window/swapchain into proper, buffer-flipping fullscreen mode?



Answer



To my knowledge, the onlything that works is:


 DwmEnableComposition(DWM_EC_DISABLECOMPOSITION);


at the start of your application and:


DwmEnableComposition(DWM_EC_ENABLECOMPOSITION);

before quitting. For the transitions, proceed as usual. I have tried InvalidateRect(NULL, NULL, true) just after switching to fullscreen to no avail. Hope this helps.


grammar - Short on/of - really interchangeable?


I wonder whether these are really interchangeable as some dictionaries suggest. Being a not native speaker, I cannot tell when it is right.


They are short on confidence.
They are short of money.


But this sounds odd to me: //I would use “of”.



He is short on 5 USD. We are short on one person (in the group).


To me the distinction would be that general lacking would be both on/of but lack of a certain number (to reach a limit or so) would be rather “of”. Is that correct?


Also, can the “of” be dropped? Like We are one person short. I am 5 USD short.



Answer



Short of means ‘a lack of/lacking something’ or ‘not enough of something’, while short on means ‘significantly less/fewer than desired or expected’. The latter, then, always implies a comparison while the former merely declares an absence.


In many cases this nuance is irrelevant. A person short of cash or short of time, i.e., doesn't have enough money or time, can just as easily be short on money or time, i.e., have less than desired.


But this is not always the case. A person can be short on/of money, but lacking a specific amount, someone can only be €10 short or short €10. This construction never uses a preposition.


A sports team could be one man/woman short or short one player because it lacks one player, but a fan could lament that the team is short on good players this year (compared to previous years), i.e., making an implicit (or explicit) comparison to some desired or expected number.


Speaking of comparisons…


After vigorous exercise:




With her muscles aching and still short on breath, she ran toward it.



A person can also be short of breath after exercise, and most are, but since shortness of breath describes a symptom of a disease or medical condition, short of breath is far more common in that context:



My sinus became very stuffy and I hated that feeling, because it made me short of breath.



The variance in usage here depends less on the lexical meaning of the two expressions than it does on the medical connotation.


The lexical difference, however, is far more apparent in short of/on words. Someone short of words lacks the language to express something, while someone short on words simply doesn't say as much as others normally would:




I am short of words, there is no word to describe what I feel right now, it is almost as if it is a dream but I know that nothing can be more real than what I am feeling right now.


I am short of words to thank you for your selfless service…



In the first sentence, a young woman has just won a private airplane in a contest and struggles for words, while in the second, the speaker claims a lack of words to express deep gratitude (which the speaker then goes on to express in many words).


A person short on words doesn't lack the means of expression; they simply by nature or circumstance choose to use fewer than others might:



Short on words, he was nearly always to be found with his head burrowed in a book. Though he was brief when he spoke, he liked to use long and difficult words, which often made Lucy laugh.


Headline: Gotta Hear It: Lowry short on words with media. A visibly frustrated Kyle Lowry addresses the media following a fourth straight loss by the Raptors.



News media are never short on athletes and coaches who are short on words after embarrassing defeats.



Short on this, long on that


A respected US senator had this to say about Heavyweight Champion Sonny Liston:



Liston's testimony apparently impressed Republican senator Everett Dirksen, who said Liston was “short on words but long on clout.”



Dirksen meant that while Liston didn't say much, what he did say had a real punch. To do so, Dirksen employed the common expression short on x but long on y. Remember that short on always implies a comparison: in this expression, that comparison is made explicit using its opposite. Short of cannot be used in this construction because it only designates absence without comparing one thing to another.


Short of a goal, specific place or time


We can use short of to indicate a position in time, space, or a process lacking a particular distance to another, somehow significant point:



If you wish to access the creek lower down, make a right turn just short of the two-mile marker.



These ruins at present occupy an area somewhat short of a thousand English acres…


Kenya celebrates its 48th birthday, two years short of the golden jubilee, but facing serious challenges.


We left to the United States from Genoa on the Italian liner, “Rex,” arriving November 9, 1939, three days short of my third birthday.


Once more he had shown the high promise that somehow always fell just short of fulfillment. — F. Scott Fitzgerald



In this sense, action short of a strike is a fixed concept in British labo[u]r law:



Other, more imaginative forms of industrial action short of a strike include 'working to rule', 'working without enthusiasm', the 'go-slow' or withdrawing 'goodwill'.



Short of + noun/gerund participle



This construction means "in the absence of":



Short of doing it yourself, the best way of escaping into nature is to read a book like A Walk in the Woods.


Cantinetta Wine & Pasta: Short of going to Italy this is as good as it gets.


Short of a miracle, no military genius, not even his, could avert the inevitable.



The long and the short of it…


Beyond the constructions particular to short of or short on, if an implicit or explicit comparison is important, then use short on. If the mere absence of something is what you wish to convey, then use short of. If you can't for the life of you tell any difference, then use whichever you like.


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