Wednesday, September 30, 2015

software engineering - Display a Message Box over a Full Screen DirectX application


In our custom assertion handler, I'd like to display a message box asking to see whether or not this failure can be ignored. However, when our DirectX game is full screen, I can't get the MessageBox function to display above the full screen.


Note: The first parameter to MessageBox is the the HWND used to create the device, and it still does not work.


Is this even possible?



Answer



Yeah, you very well may be out of luck - (although there's a MessageBoxOptions that allows you to specify ServiceNotification, which might do the right thing http://msdn.microsoft.com/en-us/library/system.windows.forms.messageboxoptions.aspx)



Typically I write my own message rendering at that point (to make sure you can use the assert anywhere, on xbox, whatever).


grammar - Given the answer "It's my first time here", what questions could I ask to receive that answer?



Confused by this question, I find it difficult to ask a question about a number of occasions (about a single occasion, in particular) when there is a specific answer expected.



It's my first time in Ukraine.



I don't want to ask



Is this your first time in Ukraine?


Is this your first visit to Ukraine?


Have you ever been to Ukraine [before]?




because it can be answered shortly with a yes-no answer. I am looking for an idiomatic question structure starting with "what/which time/occasion", if there is any.


My abortive attempts like



What/Which time is it for you in Ukraine?


What/Which occasion is it for you in Ukraine?



sound awful and look completely incorrect.



The last time we went to Paris, it rained every day.




Suppose I know that they've been to Paris several times and that one of their trips was spoiled by [the ?] rain. I want to know exactly on which occasion it happened. How would I ask it?


My suggestion



On which occasion did it rain every day?



is just hilarious.


I am completely lost.



Answer



Answering this question, and this one, it did occur to me that there is a gap in English id you want to express a particular occasion when something happened in the form of a question. However, in real life, you would be able to work around it based on what you already knew.


For your Ukraine question, I would say:




How many times have you been in Ukraine? [If this is their 5th trip, they will answer with '5'.]



If you want to deal with events which happened on an unspecified occasion during one of the trips, things get a bit trickier. But actually, your 'hilarious' suggestion is perfectly good. It sounds a bit formal, but grammatically it is fine. Here are some alternatives.



On which occasion was it that it rained every day?


Which time did it rain the most?


Which visit was the rainiest?



grammar - Is "envisaging" a gerund in this context or something else?


Context:



The government is working to build 175 GW (giga watt) of renewable energy capacity by 2022, envisaging an estimated investment of $175-180 billion.



Is "envisaging" word used here is gerund or present participle form?




articles - Is there always a "the" before a superlative adjective?


For example:




I could not face being alone again and losing the person dearest to me.



I wonder why there is no "the" in front of "dearest".



Answer



The noun superlative


The the is there, two words ahead of the superlative adjective. Usually in English the adjective comes ahead of the noun, but in this sentence it comes after the noun. The is not so flexible,* so it still precedes the noun. You could also write it like this:



(1) I could not face being alone again and losing the dearest person to me.




The noun superlative is actually a very standard construction. Here are some typical examples:



The person most capable should be chosen for the job.


The person last to use the bathroom is responsible for cleaning it up.


The motion-picture camera is the tool closest to the human sense of observation. [Source]



As your example and the last two examples illustrate, the reason for putting the superlative after the noun is often to avoid separating the superlative from a prepositional phrase that modifies it: “dearest to me”, “closest to [something]”. My sentence (1) sounds a little awkward because it separates the superlative from its prepositional phrase, though it’s still grammatical and comprehensible. If you really wanted to put dearest first, you’d probably rewrite it with a phrase or clause that modifies the noun phrase as a whole, although this invokes a different sense of dearest (no longer the superlative of dear to me but dear to general):



(2) I could not face being alone again and losing the dearest person I know.




When the modifies the adjective but the noun won’t take an article, then you have to put the after the noun:



Ladies and gentlemen, meet Henry the Eighth, also known as Henry the Fattest, Henry the Meanest, and Henry the Worst (well, the worst after King John).



You actually don’t need the


There actually isn’t any special rule that a superlative requires the. It’s just that a doesn’t make sense there, since a means to pick one of many, and by definition a superlative has only one instance. But you can use other determiners that can refer to a unique instance, including no article at all:



that most cunning of animals, the fox. [Source]


I sent my fastest galloper to Daleer Khan. [Source]


This fastest car will not be in garages any time soon. [Source. This one is unusual, but it shows that it can be done. Context must provide something for this to point to.]



Alan seemed most likely to succeed. [Source]


“Rapunzel is fairest of all.” [Source]



You can even put a in front of a superlative when you intend the superlative to designate only a very high degree of something rather than the one item with the highest degree:



The hermitage is a most curious piece of architecture. [Source]





* But maybe CarSmack can figure out a phrase of the form adj noun the (not like “Henry the Eighth”, etc.).


phrase usage - Do you have a / the time?


I am trying to cope with the ever increasing trend of new phrases in English language and found something.


I have heard many a times people use "Do you have a/the time?" In reply, either we say "Yes/No" depending upon our schedule or we tell the current time.


In which cases do we use a or the? Is it tense specific?



Answer



"Do you have the time?" would be used to ask what time it is currently.
"Do you have time?" would be used to ask if the person has time in their schedule.


To the best of my knowledge "Do you have a time?" is not used at all, at least in standard American English. It can however be used as a phrase in a larger question (as graciously pointed out by J.R.). An example of this could be "Do you have a time of the year you prefer?"


Tuesday, September 29, 2015

directx - Why are there different ways of building projection matrices?


Matrix.PerspectiveFovLH documentation page says that this method uses the following formula to build a perspective projection matrix.


[w, 0, 0, 0]
[0, h, 0, 0]

[0, 0, zFar/(zFar - zNear), 1]
[0, 0, -zNear * zFar / (zFar - zNear), 0]

where


h = cot(fovY / 2)
w = h * aspectRatio

DirectXMath's DirectX::XMMatrixPerspectiveFovLH uses the same formula but with a difference. It calculates w as w = h / aspectRatio therefore creates a different matrix.


There is a difference between orthogonal projection matrix building too.


Why are there such differences or am i missing something?




Answer



Simply because there are many ways to compute the projection of objects in a 3D scene onto a 2D plane. That's why you have perspective versus orthographic projections (and various flavors thereof, such as off-center projections), and that's why you can use slightly different formulae to compute the projection transformation.


Sometimes the differences are semantic in nature (such as in the case of perspective versus orthographic). Sometimes they are purely conventional in nature. Sometimes they are due to known quantities or characteristics of the inputs the system.


It's sort of similar to how you can represent your vectors as 4x1 or 1x4 matrices, and that consequently has a impact on whether you multiply your vectors on the right or the left of your transformation matrices.


Easy to use cross-platform 3D engines for C++ game development?



I want to try my hand at writing a 3D game. However I don't want to start at such a low level of drawing individual triangles and writing my own 3D object loader and so on. I've heard of things like Irrlicht, Crystal Space 3D, and Cafu, but I don't have any experience with any of them. I'm looking for suggestions from people who have experience with these or other engines on which ones are well written, and are easy to get started using, without having to learn a ton of 3D math theory and how GPUs work internally.




unity - Can Cloud Functions be used for a multiplayer game server?


I'm building a turn-based online multiplayer game with Unity for both desktop and mobile.


Traditionally, I would build a Java socket server, host it in Google Compute Engine or similar, and have players connect to it. Since this works with sockets I can easily notify players of relevant events, such as matchmaking, chat, enemy turn, etc.


I've been curious about Serverless Functions for a while, such as Google Cloud or Amazon Lambda.


However, at first glance it doesn't seem to me like that would work for my game: because there ins't a constant connection (with sockets), I can't notify players of relevant events in realtime - or can I?


For mobile I realize I could probably use something akin to push notifications (so the serverless code may push messages to the relevant player's phone). But that doesn't seem as simple for desktop games.


Well, what if the players poll for messages? Like every second, call a Cloud function and ask them if there's anything for them.


I'd image that would work, but that seems rather overkill - with as little as a couple thousand players, calling the same function every second for prolonged times (the game's matches are long) sounds like it would easily increase expenses.


Is there something I am missing? A coding practice that would make serverless code feasible for a cross-platform online multiplayer game? I want to make it work, but it would seem like a socket server is still my only option.





pronouns - What exactly is the word "there" in an existential construction? And related questions


Consider the example below:




"There was a cat under the table."



There have been numerous questions asked that have involved the topic of existential constructions and the word "there" that is used in them. I would like to see some grammatical rationales that will explain what that word "there" actually is -- or is not -- in an existential construction in today's standard English.


These are some of the things that I've heard, with respect to that "there" and/or the existential construction:




  1. "There" is the grammatical subject of the clause.





  2. "There" is a dummy pronoun.




  3. The subject is an external complement. (optional)




  4. An existential construction has no clausal object. (optional)




  5. There is no such thing as a passive existential construction. (optional)





What syntactical arguments can be made for or against those above statements? And how well accepted are those above statements?


Please provide some vetted grammatical sources in your answers.



Answer



Part 1 Subjects: Words, Phrases and Functions


To make this section of the answer easier to think about, let's look at an even simpler example:



There's a new president.




The number one question here is: What is the subject of this sentence? This isn't as easy as it looks. If we want to answer this question we need to really understand what a subject is. And if we want to understand what a subject is, we need to understand the difference between a function in a sentence, and a part of speech, for example a Noun. Being a Noun and being a Subject are completely different. A Noun can be a Subject but it can do many other jobs as well. For example, a Noun can also be an Object, a Modifier in a Noun Phrase, or the Complement of a Preposition:



  • I like monkeys. (Direct Object)

  • I'm a monkey fanatic. (Modifier in Noun Phrase)

  • I received a message from the monkeys. (Complement of Preposition)


So Nouns seem to be a type of word. The different jobs that a word can do are called functions. The words Subject, Object, Modifier, Complement are all different jobs or functions. There are many other types of function.


Very often we see a group of words, not just one word, doing some particular function in a sentence:



The mice like cheese




Here, the Subject is two words: The mice. The most important word in that group is the Noun mice. We call the chunk of words the mice a Noun Phrase. We can have very long Noun Phrases:



I am a very keen monkey fanatic.



Here a very keen monkey fanatic has the job of Complement of the Verb BE.


This big Noun Phrase has some words in it that seem to work together. For example the word very seems to go together with the word keen. The answer to How keen is he? is Very keen!. In the chunk very keen, the Adjective keen seems to be the main word. This chunk is an Adjective Phrase. So, we have a big Noun Phrase functioning as Complement of BE, and inside the Complement we have an Adjective Phrase functioning as Modifier. So large phrases have smaller phrases inside them. Every phrase always has its own function.


Sometimes we might want to do a test, to see which chunks of words go together in one phrase. One well-known test, is to use a substitute word to replace part of a sentence. Usually, if the substitute word replaces a group of words, then that whole group is one phrase and will have its own function. We can do this test with The mice like cheese. Let's use the word They:



They like cheese.




So the word they replaced the words The mice. This shows that the mice is one phrase - a Noun Phrase. It also indicates that The mice has one function - it's the Subject.


There is one very special function we haven't talked about. Us teachers and linguists are a bit naughty; we say things like Subject Verb Object, things like that. Of course Verb is a type of word, not a function! Verbs can have many functions, they can be Subjects, for instance:



To love is the most important thing.



But there is one function that can only be carried by Verb Phrases (in English). No other words or types of phrase can do this job:



I smoke.




Here the job being done by the Verb smoke is the job of Predicate. In the same way that every sentence in English has a Verb, every English sentence has a Predicate. This is the job that the Verb Phrase does. What I want to show you now, is that the functions of Subject and Object are not equal. The Subject is a far more important and fundamental part of any sentence than the Object. Let's do a substitution test with the sentence:



The mice like cheese.



We know that we can substitute they for The mice. Let's use an auxiliary verb as another substitute word. We know that auxiliaries can 'stand in' for other words in sentences. The sentence is present simple so we need the auxiliary DO. Look what happens to the sentence:



They do.



We can see that both of the words like and cheese have been replaced. This shows that like cheese is one phrase. The head word is the Verb like, so like cheese is a Verb Phrase. The function or job of the Verb Phrase in the sentence is Predicate.


Inside the Verb Phrase (the Predicate) , there is a small Noun Phrase, cheese. The function of cheese inside this Verb Phrase is Complement of the verb. It is a special kind of complement: an Object. This test shows something very important about Subjects that makes them completely different from Objects and other complements. Subjects are outside the Predicate. We can say that they are external to the Verb Phrase. Other complements of the verb are Internal complements. They live inside the Verb Phrase and inside the Predicate. If we replace the Verb Phrase, all the complements of the verb are replaced too. In fact, everything outside of the Subject is part of the Predicate and will be replaced in a substitution test like this.



Hold on a minute! This sounds like the job of Subject is about how sentences are made, how we build them. What about meaning? Subjects must have a special meaning, mustn't they? Some people say that verbs tell us about actions. They say that the person or people that do the actions are the Subjects. So in Bob punched Nelson, the Subject is Bob. In this sentence this is true, but in many sentences it isn't. In the sentence Bob is a monkey fanatic, Bob isn't doing anything. The sentence is just telling us about a quality or chracteristic of Bob. There's no action here. Let's do a substitution test for this sentence with the pronoun he and the auxiliary verb BE:



He is.



Here we can see that we have a subject and a predicate, even though there's no action and no person doing the action. Ok, so maybe that's not a good test because BE here is used with a stative meaning. How about a sentence like Bob was punched by Nelson. We can ask the question Who was punched by Nelson? The answer will be:



Bob was.



Here we see was being used for was punched by Nelson. Again the sentence has two parts, a Subject Bob and the Predicate was punched by Nelson. Now here Bob wasn't doing the punching, he received the punches. In a passive sentence like this the person doing the action appears in the Verb Phrase. So the role of the Subject in the sentence, what that person does or doesn't do, is not significant in terms of what is the Subject. Notice again that the Subject is external - it's outside the Predicate. We do have names for the person who does something and the person it is done to. They are called thematic roles. In both sentences Bob was punched by Nelson and Nelson punched Bob, Nelson has the thematic role of agent. Bob has the thematic role of patient.


Subjects, it seems, are indeed about the structure of the sentence. They are about how we build sentences. They are not about meaning, in the sense that they are not about what the Subject is or isn't doing. We have other words to talk about such meaning. Subjects are about grammar, syntax, not meaning.



Let's review what we've looked at. We have talked about how parts of speech and functions are different. We showed that the basic parts of any English sentence are the Subject and the Predicate. Objects and any other complements of the verb are found inside the Predicate. Because the Predicate always has a Verb as its head, we say that subjects are external to the Verb Phrase. Objects and any other parts are internal.


Now let's look again at the first example sentence in this post:



There is a new president.



We could ask the question Is there a new president? The answer would be:



There is.



Here the auxiliary verb is is standing in for the whole Verb Phrase. The Predicate therefore is is a new president. These are the words that have been 'replaced' by is. This shows that a new president is internal to the Verb Phrase. It cannot be the Subject here. It must be a Complement of the verb BE. However, we do still see the word There. This shows that There is not part of the Predicate. It must, therefore, be the Subject! In fact in all sentences like this with expletive there, there is the subject.



There are many other reasons and ways to show that there is the subject in sentences like this. There is also one reason why some people are surprised, or don't believe, that There is the subject. You can find a discussion about these things in Part 2. ( - after I write it)


For an introduction to functions, phrases, constituency tests and all that jazz, I recommend English Syntax and Argumentation by Bas Aarts 2013.


Hope this is helpful!


word choice - “I have little money” vs. “I have a little money”


What is the difference between “I have little money” and “I have a little money”?


Are they the same?




modal verbs - "I might as well sell it" Or "I should sell it"


I read the following in a book.



I use my car very little. There is no point in keeping it. I might as well sell it.



Is it Okay to replace "might as well" with "should"?




I should sell it.



What is the difference in meaning between them?



Answer



Both sentences are fine, but they have slightly different meanings.


The first sentence shows less certainty or more reluctance than the second sentence. "Might as well" means that this action (selling it) is no worse than some other alternative (not selling it). The "as well" piece literally means "equally good".


"I should sell it" implies that selling it is the best option. You may still choose not to sell it (we often fail to do things that we really should do), but you are stating that this is the correct choice.


Depending on context, however, the meaning of these sentences can be very close. "Should" can also be used to signal reluctance, as in



I really should give up cigarettes.




but it doesn't have to.


phrases - Exact meaning of "to kindly invite"



It is common to thank somebody for "a kind invitation". However, when somebody writes



I kindly invite you to event xyz,



does that not suggest that the person who invites the other is doing the invited person a favour? If yes, the meaning would be quite different from phrases such as



I cordially invite you ...



or




It is a pleasure to invite you ...



My google search produced many hits for the phrase "kindly invite", but all of them point to websites of non-native speakers/institutions.



Answer



The meaning of "to kindly invite" is straightforward. It means what you think it means. You are also right in thinking that it is different from the other alternatives. It appears rude, as the inviter is suggesting that he is doing them a favour. For this reason, it is uncommon to write that you are "kindly inviting" someone, the other two examples are far more common, with "cordially" being preferred.


phrase meaning - What does it mean? "being into someone"


I was reading a book and there was a sentence in it :



Are you into me?




It was like a romantic dialog but i don't know the exact meaning. So i have 2 questions:
1. What does it mean?
2. I think it means "Do you love me?" . If this meaning is right, which one is more polite? "I love u" or "I'm into you" ? What's the difference?



Answer



to be into something means that you are very interested in it. For example (and the following examples are very typical uses of this expression, by the way):



I'm into computers.



This means that you're very interested in the field of computer technology. You have lots of computers at home, you read books about operating systems, programming languages and things like that. In other words, you're a computer buff.



Another example:



Sorry, I'm not gay. I'm only into girls.



This means that you're only interested in dating girls and not men because you are heterosexual.





Are you into me?



Here, the person probably wants to know whether the other person he or she is talking with has feelings of romantic love for them. Basically, she or he wants to know if the other person likes her or him (in other words, wants to know if the other person is interested in them romantically).





Simply put, I'm into you is a slang way to say I love you.


tense - "Is" vs "has been" in English


What is the difference in meaning in these two sentences?




He is appointed as Manager.



and



He has been appointed as Manager.





Similarly, what is the difference between these two sentences?



Amount has been paid to you as basic salary.




and



Amount is paid to you as basic salary.





Monday, September 28, 2015

subject auxiliary inversion - The order of words in a clause: "tell me who is the real man" vs. "tell me who the real man is"




"Tell me who she is."



"Tell me who your boyfriend is."



We usually reverse the order, so it becomes like that.


But I wonder whether "tell me who is the real man" also works because "tell me who the real man is" sounds like we have already known the real man and I am just asking about his name.


If my friend and I are going to arm-wrestle, and I say:



"Let's see who is the real man."



Is that correct?




plural forms - Should you say hour or hours in this type of sentence?


Being a non native speaker of English, this type of sentence always bites me:



It was a pleasant four hours journey from Nashik to Pune.



Should it be hour or hours?




Answer



As kiamlaluno comments, the standard form is a two-hour wait, three-man band, four-course meal...


Although not everyone always bothers with the hyphen, you should include it if you want your written form to be above criticism. But never pluralise the "unit" (two-hour, three-day, four-month, six-foot, etc.).


Is there a 2d physics engine that can model fluids and gases?



At this point the platform and programming language don't matter I would just like to know if something out there exists for this. Any help is appreciated.




Sunday, September 27, 2015

xna - Where is the XACT documentation?


All the links here are broken:



http://msdn.microsoft.com/en-us/library/bb172314.aspx



Answer



XACT can be found here


Hope it helps


capitalization - Shall we capitalize the word after colon?


Shall we capitalize the word after colon?


For example:



The question is: S/shall we capitalize "s" in "shall"?



Another example, https://stats.stackexchange.com/q/91024/1005



For example:




  • E/every marginal distribution of a multivariate normal distribution must be a univariate normal distribution.

  • S/so it is for the multinomial distribution (which is the multivariate generalization of binomial distribution).

  • S/so it is for Dirichlet distribution (which is the multivariate generalization of beta distribution)

  • N/not sure for multivariate t distribution.



(In other words, should each of those individual bullets be capitalized, or not?)




opengl - What is the purpose of the canonical view volume?


I'm currently learning OpenGL and haven't been able to find an answer to this question.


After the projection matrix is applied to the view space, the view space is "normalized" so that all the points lie within the range [-1, 1]. This is generally referred to as the "canonical view volume" or "normalized device coordinates".


While I've found plenty of resources telling me about how this happens, I haven't seen anything about why it happens.


What is the purpose of this step?



Answer



The most important is that it converts yours points(vertices) from 3D world space to 2D screen space.


That means that after vertex is multiplied with this matrix X and Y coords are position on the screen (between [-1, 1]) and Z is the depth. Z is used for depth-buffer and identifies how far is vertex (or fragment) from your cameras near plane.


Projection means that vertices which are more near from near plane are more far from middle of the screen -> triangle more near to camera appears to be bigger that one that is far. And this is based on yours field of view - you are entering it in some createProjectionMatrix function or createFrustum. It works that it shears and scales yours camera frustum and vertices in it into unit cube. Values that are greater than 1 and smaller than -1 are not displayed.


Also keeps pixel aspect ratio, so pixel can be sqaure. That is simple. It just shears camera frustum like this: more wider screen -> more vertical shear and vice versa.



Simple answer:
It defines yours camera frustum and is good to:



  • make objects which are near to you look bigger than objects that are far from you.

  • keep pixel aspect ratio - Everybody likes square pixel right? :)


3d - Is C++ "still" preferred in game development?



I am a 2D Game Programmer.Some programming languages which I am good at are C,Java ,C#. I also know Actionscript 2.0,3.0 and some javascript. I'm interested in learning 3D Game programming. So far from the research I have accumulated by googling and reading different game development forums and articles. I've noticed that most programmers tend to prefer C++.Also in an online game programming teaching course I noticed they prefer to teach C++ and Visual C++ as the starting course. The reason I am asking this question since I would like to know the "strength" difference of C++, C# and Java for 3d game programming.


Also include links to good 3d game programming articles for the already 2d game programmer.


P.S : IMHO , I also find C++ to be cryptic.



Answer



Yes, C++ is the language used most often (though some people do still use C).


There are numerous reasons for this. Sheer momentum is one - it's simply the language that has been used for years, a lot of tech already exists and people are comfortable with it, so changing is not going to happen overnight.


Then there is the issue of control. Game developers are control freaks, and we like to know everything that is going on in our code. C++ gives us that control, C# and Java (to pick on the two alternatives you mention) take control away. In many ways that might be a good thing, but game coders don't like it :)



Finally there's the simple practical issue that the SDKs for various platforms are very C++ centric. Using another language inevitably involves writing wrappers, cross-compiling down to VMs, and possibly (in the case of some console development) it's not allowed by the platform holder (they really don't like people doing JIT compiling, for a start).


State / Screen management in Entity Component Systems


My entity/component system is happily humming along and, despite some performance concerns I initially had, everything is working fine.



However, I've realized that I missed a crucial point when starting this thing: how do you handle different screens?


At the moment, I have a GameManager class which owns a component manager and entity manager. When I create an entity, the entity manager assigns it an ID and makes sure it's tracked.


When I modify the components that are assigned to an entity. an UpdateEntity method is called, which alerts each of the systems that they may need to add or remove the entity from their respective entity lists.


A problem with this is that the collection of entities operated on by each system is determined solely by the individual Systems, typically based on a "required component" filter. (An entity has to have a Renderable component to be rendered, for instance.)


In this situation, I can't just keep collections of entities per screen and only Update/Draw those collections. They'd have to either be added and removed depending on their applicability to the current screen, which would cause their associated components to be removed, or enable/disable entities in a group per screen to hide what's not supposed to be visible.


These approaches seem like really, really crappy kludges.


What's a good way to handle this? A pretty straightforward way that comes to mind is to create a separate GameManager (which in my implementation owns all of the systems, entities, etc.) per screen, which means that everything outside of the device context would be duplicated. That's bothersome because some things are always visible, or I might want to continue to display the game under a translucent menu window.


Another option would be to add a "layer" key to the GameManager class, which could be checked against a displayable layer stack held by the game manager. *System.Draw() would be called for each active layer, in the required order as determined by the stack. When the systems request an iterator for their respective entity collections, it would be pre-filtered to a (cached) set of those entities that participate in the active layer. Those collections could be updated from the same UpdateEntity event that's already used to maintain each system's entity collections.


Still, kinda feels like a hack. If I've coded myself into a corner, feel free to throw tomatoes as long as they're labeled with a helpful suggestion.


Hooray for learning curves.




Answer



After trying a few different approaches, I implemented the following, and it's working quite well.


Briefly:


I have a GameManager class which is responsible for maintaining systems, components and resources.


public class GameManager : Disposable
{
public EntityManager EntityManager { get; private set; }
}

GameManager is the game's primary interface to the engine. It provides methods for creating entities, etc. The relevant part here is EntityManager (abbreviated, relevant methods shown):



public class EntityManager
{
public List Entities { get; private set; }
internal Dictionary Caches { get; private set; }

private Channel _nextChannel = null;

internal EntityCache CreateCache(string name, params Type[] filter)
{
name = name.Trim().ToLower();


if (Caches.ContainsKey(name))
throw new Exception("A cache of the same name already exists");

var cache = new EntityCache();
cache.Filter = filter;

Caches.Add(name, cache);

return cache;

}

private bool MatchesFilter(IEntity entity, IEnumerable filter)
{
return filter.All(t => entity.Is(t));
}

internal void PreUpdate(float dt)
{
if (_nextChannel != null)

{
foreach (var kv in Caches)
{

var cache = kv.Value;

cache.ActiveItems.Clear();
cache.ActiveItems.AddRange(
cache.Items.Where(
(entity) =>

{
var enable = !entity.Is() || entity.As() == _nextChannel;
entity.Enabled = enable;
return enable;
}
)
);
}
_nextChannel = null;
}


}
///
/// update the caches by adding or removing the specified entity, based on its assigned components
///

///
internal void Update(IEntity entity)
{
if (!Entities.Contains(entity))
Entities.Add(entity);


if (Manager.Components.ContainsKey(entity))
{
var components = Manager.Components[entity];

foreach (var cache in Caches.Values)
{
var matches = MatchesFilter(entity, cache.Filter);
var contains = cache.Items.Contains(entity);


var active = entity.Is() ? (entity.As() == _nextChannel) : true;

if (matches && !contains)
{
cache.Items.Add(entity);
if (active)
cache.ActiveItems.Add(entity);

}
else if (!matches && contains)

{
cache.Items.Remove(entity);
}

}
}
}

public void SetChannel(Channel channel)
{

_nextChannel = channel;
}

}

EntityManager maintains filtered caches of entities:


internal class EntityCache
{
///
/// list of component types that this filter requires

///

public Type[] Filter { get; internal set; }

///
/// all items in the system that match this filter (set by EntityManager)
///

public List Items { get; private set; }

///
/// Items that are active (should be updated, drawn, etc.)

///

public List ActiveItems { get; private set; }

internal EntityCache()
{
Items = new List();
ActiveItems = new List();
}
}


Also, a Channel component is used to group entities into groups/channels/screens. (Channel exposes a ChannelId property used to separate groups.)


When EntityManager starts its Update cycle, it checks if a channel change request has been received. If so, it rebuilds the ActiveItems lists. Entities that have a Channel component attached are added to the ActiveItems collection if their channel is the same as the next selected channel. Entities that do not have a Channel component are always active (good for global input processors, debug displays, loggers, etc.)


Systems only operate on the ActiveItems collections during the Draw and Update cycles.


So, when initializing a game, I might do this:


var playChannel = new Channel("play");
var menuChannel = new Channel("menu");

var ship = GameManager.Create("ship");
...add ship rendering components...
ship.Add(playChannel);


var splashLogo = GameContent.Create("splash-screen-logo");
...add logo rendering components...
splashLogo.Add(menuChannel);

Manager.EntityManager.SetChannel("menu");

The last line updates the ActiveItems collections, so on the next cycle, any entities with an attached Channel with ID "menu" will be drawn and updated, but everything else will be ignored. An input processor switches channels when required.


I also added a small serialization-friendly state machine which handles navigation between screens, but that's another topic.


I initially had each System maintain its own entity caches, but I found myself creating systems which required the same component filters, so those caches would be duplicated. Moving them into an EntityManager provided a centralized interface to all of the entities in the game, made implementation of the screen/channel system fairly trivial, and made it much easier to remove entities and components from the game when necessary.



Hope this helps someone!


Saturday, September 26, 2015

modal verbs - Why the past tense? And how can I understand these 'would's and 'could's?



How could a humble tortoise beat the legendary Greek hero Achilles in a race? The Greek philosopher Zeno liked a challenge and came up with this paradox. First, the tortoise is given a slight head start. Anyone fancying a flutter would still rush to put their money on Achilles. But Zeno pointed out that, to overtake him, Achilles would first have to cover the distance to the point where the tortoise began. In that time the tortoise would have moved – so Achilles would have to cover that distance, giving the tortoise time to amble forwards a bit more. Logically this would carry on forever. However small the gap between them, the tortoise would still be able to move forwards while Achilles was catching up. Meaning that Achilles could never overtake.
Source: 60-Second Adventures in Thought (Open University). (YouTube video)



My question: I don't understand the tense of the bold verbs. When telling a story, we normally use present tense, but why the author use almost all the past forms?




c# - In Monogame, why does Rectangle.Offset not work?


I have the following code in a default Monogame Game project:


protected override void Update(GameTime gameTime)
{
if (Keyboard.GetState().IsKeyDown(Keys.Left))
{
paddle.Box.Offset(-10, 0);

Debug.WriteLine(paddle.Box);
}
if (Keyboard.GetState().IsKeyDown(Keys.Right))
{
paddle.Box.Offset(10, 0);
Debug.WriteLine(paddle.Box);
}
base.Update(gameTime);
}


paddle.Box is a normal XNA Rectangle.


The problem is that the location of paddle.Box does not change after calling any of the Offset() overloads, as debugging confirms. If I just assign a new Rectangle, it works, but Offset (and Inflate(), FWIW) seems to be broken.


What am I doing wrong?



Answer



This is because Rectangle is a struct, which causes this to be a bit of tricky case. Since structs are passed and returned by value in C#, calling Paddle.Box will return a copy of Paddle.Box. After that, you call Offset on this fresh copy of Paddle.Box, but it's the copy, not the rectangle you were trying to change! The copy did change however, but it is discarded straight after that line. This is why calling '= new Rectangle...' does work.


You will encounter similar things with built-in Vectorn types.Assigning a new object ('... = new ...') is generally what you should do in these scenarios. (On a side-note, I believe that C# even prevents you from doing this on properties and member variables).


Edit: A more of an actual answer: if you want to use offset, you can do something like this instead:


protected override void Update(GameTime gameTime)
{
if (Keyboard.GetState().IsKeyDown(Keys.Left))

{
Rectangle box = paddle.Box;
box.Offset(-10, 0);
paddle.Box = box;
Debug.WriteLine(paddle.Box);
}
if (Keyboard.GetState().IsKeyDown(Keys.Right))
{
Rectangle box = paddle.Box;
box.Offset(10, 0);

paddle.Box = box;
Debug.WriteLine(paddle.Box);
}
base.Update(gameTime);
}

grammar - Concrete vs Abstract nouns


What is the difference between a material and a concrete noun?? Are 'Promise, truth, lie and comment' countable Abstract nouns?? What others examples can be given for the same.




Unity doesn't change particle color when render is set to mesh? (Probably a bug)


I've got a particle system with Render Mode set to Mesh. Then I applied a material to it, which is just white with the default shader. Now I can't change the start color nor the color over lifetime etc. As far as I know that shouldn't happen, right? I'm using Unity 5.5.0f3


This is what my PS looks like with the material :



This is what I achieved with 3 particle systems with 3 different materials, but actually, I don't want these materials. Instead, I want to set the start color property of the particle system to apply some color. The material solution restricts me in terms of random start color and stuff like this.




Answer




I'm not sure why you say "The material solution restricts me in terms of random start color and stuff like this."


You can get random start colours into a material just fine. As I said in my first comment, all you need to do is use (or create) a material that uses the mesh's vertex colours.


For example, you can Create->Shader->Standard Surface Shader (since it appears you want lighting to apply to your meshes), and then make two small modifications:


    CGPROGRAM
#pragma surface surf Standard fullforwardshadows
#pragma target 3.0

sampler2D _MainTex;

struct Input {

float2 uv_MainTex;

// Modification 1: add a vertex colour parameter to the Input struct.
float4 vertexColor : COLOR;
};

half _Glossiness;
half _Metallic;
fixed4 _Color;


void surf (Input IN, inout SurfaceOutputStandard o) {
fixed4 c = tex2D (_MainTex, IN.uv_MainTex) * _Color;

// Modification 2: multiply the albedo by this vertex colour.
c *= IN.vertexColor;

o.Albedo = c.rgb;
o.Metallic = _Metallic;
o.Smoothness = _Glossiness;
o.Alpha = c.a;

}
ENDCG

Create a material using this shader and assign it to your particle system. Now you can play with colours in the particle system as much as you want!


Animation of a particle system generating many different coloured cubes


Friday, September 25, 2015

articles - “the top levels of government” -- why not "of THE government"?


Example taken from: Russia questions five suspects over Nemtsov killing:



However no information has emerged as to the possible motive the men could have had in killing the charismatic opposition leader. His allies believe his assassination was a hit ordered by the top levels of government determined to silence dissenters. The allegation has been strenuously denied.



Why not say by the top levels of the government? What do you think the difference would be?



Answer




... ordered by the top levels of government ...




The "missing" article is called zero article:



Definition:


An occasion in speech or writing where a noun or noun phrase is not preceded by an article (a, an, or the).


In general, the zero article is used with proper nouns, mass nouns where the reference is indefinite, and plural count nouns where the reference is indefinite. Also, the zero article is generally used with means of transport ("by plane") and common expressions of time and place ("at midnight," "in jail")





  1. The indefinite article a (or its phonetic variant an) is used to indicate:





    • one of many -- I hope to meet a girl.

    • an unidentified thing (or person) -- I met a girl.





  2. The definite article the is used to indicate:





    • an identified thing -- I met a girl at the dance.





  3. The zero article is used to indicate:




    • generic plural nouns -- I have met girls in the past.

    • uncountable nouns -- I want to find companionship.


    • things in general -- The dance is at school.





It is quite normal for common nouns to use the zero article even in reference to a definite thing, especially as the object of prepositions. Everyone going to the dance knows exactly which school they will go to, but they have two options in talking about where the dance will be:



The dance is at school.
The dance is at the school.




Government is one of these common nouns that leaves the writer this option:



... ordered by the top levels of government
... ordered by the top levels of the government



One rationale for this flexibility is that the context already makes the identity of this common noun so definite that the definite article is implied even when it is not expressed.




A partial list of common nouns that can sometimes be definite without the definite article:



Institutions: church, college, prison, school, university & hospital (except not hospital in US English) ... :

I met a girl at school, but not: I met a girl at dance.


Places: work, home, bed ... :
I met a girl at home.
but not:
I met a girl at dance.


Meals: breakfast, lunch, dinner ... :
I met a girl after dinner.
but not:
I met a girl after dance.


Holidays: Christmas, Easter, Hanukah, New Year ... : I met a girl after dinner.

but not:
I met a girl after dance.


Transportation: bike, car, foot, plane, train ... :
I met a girl on foot.
but not:
I met a girl on dance floor.



For more detailed information consult:


http://en.wikipedia.org/wiki/Zero-marking_in_English#Zero_article


http://grammar.ccc.commnet.edu/grammar/determiners/determiners.htm



prepositions - "You must wear a suit TO an interview" vs "You must wear a suit FOR an interview"


In the sentence-



You must wear a suit to an interview



shouldn't the to be replaced by for? Or what's the difference between these two here?



Answer



The difference is fairly slight. Some cases you could use either and others one or the other would only work.



To would be used for a location or an event (could imply motion)


For would be for a purpose, benefit, etc


The trick is that a location/event is often a purpose; your purpose is to go to that location/event. With verbs ("to wear to run"), the trick is that some words can be both verbs or nouns (e.g. run as a noun is an event of running). In these cases, both may be grammatical, but slightly change the meaning.


Examples:



You must wear a suit to the wedding


You must wear a suit for the wedding



Either of these works because a wedding is either the event or the purpose for wearing the suit.




You must wear shoes to the bank



Bank is a location so this works.



You must wear shoes for the bank



This still could make sense, but it would be somewhat less commonly used than to the bank.



You must wear boots for safety




Purpose, so it works



You must wear boots to safety



This doesn't make sense.



You must wear a hat to garden



versus




You must wear a hat for gardening



You cannot wear a hat "for garden"; for in this case would expect a noun, which then needs an article ("a garden" or "the garden") and would now be a location.


If you say



You must wear a hat to gardening



You've changed the meaning slightly; gardening is now an "event" as opposed to an intended action (purpose).


unity - How to run a timer parallel to a series of coroutines and WaitForSeconds


In the code below, I have a cycle for enemies appearing and disappearing.



IEnumerator EnemyCycle()    {
while (isRepeating)
{

for (int j = 0; j < enemies.Length; j++) {

canStartUpdatingReset = true;
Enemy currentEnemy = enemies [j];
var _myMaterial = currentEnemy.GetComponent().material;
var _currentFade = StartCoroutine(FadeToForEnemy(_myMaterial, 0f, fTime, currentEnemy.gameObject, false));


coroutinesToStop.Add(_currentFade);

if (currentEnemy.hasWeapon) {
weaponCycleCoroutines.Add(StartCoroutine(FadeToForWeapon(currentEnemy.weapon.GetComponent().material, 0f, fadeTime, currentEnemy.weapon, false)));

}
}

yield return new WaitForSeconds (hideTime);


for (int j = 0; j < enemies.Length; j++) {

Enemy currentEnemy = enemies [j];
var _myMaterial = currentEnemy.GetComponent().material;
var _currentFade = StartCoroutine(FadeToForEnemy(_myMaterial, 1f, fTime, currentEnemy.gameObject, true));

coroutinesToStop.Add(_currentFade);
if (currentEnemy.hasWeapon) {
weaponCycleCoroutines.Add(StartCoroutine(FadeToForWeapon(currentEnemy.weapon.GetComponent().material, 1f, fadeTime, currentEnemy.weapon, true)));

}
yield return new WaitForSeconds (showTime);

}
}
}

I have an enemyCycleDuration float which is


enemyCycleDuration = 60*(hideTime + fadeTime + showTime + fadeTime)


Note that fadeTime comes from FadeToForWeapon and FadeToForEnemy. The idea here is I want the enemyCycleDuration to be run in parallel to EnemyCycle() so it is reset (please see code below) at the same time that


yield return new WaitForSeconds (showTime);

is reached in the EnemyCycle().


I am resetting enemyCycleDuration in the following way in the update method but EnemyCycle() seems to be ahead of enemyCycleDuration, always completing before enemyCycleDuration is reset. How can I get both to run parallel to each other in timing and complete at the same time?


if (canStartUpdatingReset)  {
timeElapsed +=1;
if(timeElapsed >= enemyCycleDuration) {

timeElapsed = 0;


Debug.Log ("Reset CycleDuration");
}
}


infinitives - "He intends leaving tomorrow"



He intends to leave tomorrow. (1)



He intends leaving tomorrow. (2)


(The Cambridge Grammar of the English Language)



CGEL says there’s no discernible difference between the two, yet I imagine some difference from the ‘be+~ing’ meaning. This presents a plan / intention and implies near future. Although the adjunct, tomorrow, weakens the meaning of the plan or near future, (2) still has the meaning of your intentionality or volition, I guess. Can it be the proper difference?



Answer



One of the hot topics among English-language linguists is the ‘Great Complement Shift’—the apparently well-established fact that for about four hundred years speakers have been drifting away from infinitive non-finite complements and toward gerund non-finite complements. You'll find a comfortably brief discussion in 3.4 of this draft of a forthcoming book chapter.


It’s important to note, however, that this trend has no predictive value at all. There are many verbs which exhibit the opposite tendency, away from gerunds and towards infinitives. This paper, for instance, aptly titled ‘Swimming against the tide of the Great Complement Shift’, identifies prefer and continue as two such verbs.


Intend is another such. The Comments to your question show how distasteful WendiKidd, Mari-LouA and I find the use with gerund complements, and our instinct is corroborated by the corpus data cited by Alex B. The Google NGram which Peter Shor links suggests, and the one below appears to confirm, that use with the gerund has never been as common as that with the infinitive, and has steadily become less common over the past century.


enter image description here


Use with the gerund is basically a 19th-century alternative: perfectly correct, but unusual today.



As for a distinction in meaning, I think it very unlikely, unless you suppose that 19th-century writers were two or three times more likely to have firm short-term intentions than their modern counterparts.


When you're dealing with an individual verb, the distinct between infinitive or gerund or FOR .. TO .. or that complementation is certainly meaningful. But I'm very dubious about claims that such distinctions have any global significance; and even if such significance could be shown, it would still be irrelevant to individual cases, which should always be suspected of Swimming Against the Tide.


libgdx - How can I convert a tilemap to a Box2D world?


I want to use Box2D physics and lighting with a .tmx map. How can I "convert" a tilemap to Box2D world? My basic idea is to go through the tiles on the map and create an object for them in Box2D.


I'm using the Tiled map editor for the tilemap, and the target platform is PC.


Firstly, is this a good solution for my idea? Or is this even possible?
Secondly, if yes, then I dont know how to get the tile's position.



My code so far:


public class WorldLoader {
public static TiledMap map;

public static void loadMap(String mapName) {
map = new TmxMapLoader().load(mapName);
TiledMapTileLayer collisionLayer = (TiledMapTileLayer) map.getLayers().get("collision");

for (int x = 0; x < collisionLayer.getWidth(); x++) {
for (int y = 0; y < collisionLayer.getHeight(); y++) {

Cell cell = collisionLayer.getCell(x, y);

if (cell != null && cell.getTile() != null) {
// float tileX = collisionLayer.getProperties().containsKey("x");
// float tileY = cell.getTile().getProperties().get("y", Integer.class);

BodyDef bodyDef = new BodyDef();
bodyDef.position.set(tileX, tileY);

PolygonShape shape = new PolygonShape();

shape.setAsBox(16, 16);

Body body = GameWorld.world.createBody(bodyDef);
body.createFixture(shape, 0f);

shape.dispose();
}
}
}


}

}




3d - Plotting entities on a radar


I'm trying to build a radar system like the one in the original X-Wing games. The way it works is that there are two circular radar systems, one for behind the ship, and one for infront.


So, I've written a class to represent the radar, it has a vector representing the direction the radar is facing, and a 3D position of where the radar is. Both of these things will change in realtime as the ship moves and so the radar will need updating each frame.



Now I'm trying to figure out how to transform the position of another ship onto the radar. What I need is a final 2D X/Y coordinate between -1,-1 and 1, 1 for plotting on the 2D radar screen.


Given two vectors (the direction of the ship - which the radar is facing - and the direction to the ship we are plotting), how can I calculate a 2D X-Y position on the radar? Obviously I also have access to the up and right vectors of the ship too.


My instinct says that this should be relatively straightforward, but my math skills suck.



Answer



As is typical, about 10 minutes after posting this question I realized that "planes" are actually a thing and this is pretty easy...


To find the position on the X axis, I can do this:



  1. Project the ship position onto the XZ plane

  2. Get the direction to the ship (e.g. (ship_pos - radar_pos).normalize())

  3. Calculate the angle between the radar's forward direction and this direction


  4. X = (angle_in_degrees / 90.0) * plane_classification (where plane_classification is -1 if the point is to the left of the YZ plane, 0 if it's on the plane, and 1 if it's to the right of it)


You can then work out the Y-axis position by reversing the planes in steps 1 and 4.


Thursday, September 24, 2015

ogre - How to set object's / node's absolute rotation correctly?


Usually when I want to rotate an object/node in my Ogre scene I call the node's rotate() method. That rotates the node locally relative to it's current rotation. So for example, when I start with 0 rotation, then rotate twice for 5 degrees about one axis, then after the second call the object is rotated by 10 degrees in total.


Now I need to set the absolute rotation of the node/object directly, regardless of its current rotation. Thus, say I don't know the objects current rotation, I need to set it say to 45 degrees on the X axis. Something like setRotation().


I know there is a setOrientation() method in the SceneNode class, which expects a quaternion object. I also know that I can get the current orientation quaternion. What I don't know: how can I use/change this current orientation quaternion to set the new absolute rotation of the node?



PS: Crosspost at http://www.ogre3d.org/forums/viewtopic.php?f=2&t=77710



Answer



I'm just replicating the answer from that crosspost :D


setOrientation(Quaternion(Degree(45),Vector3(1,0,0)));


How were art assets created in the late 16-bit/early 32-bit era?


How were 2d and 3d art assets typically created in the early-to-mid 1990's (16-bit and 32-bit eras?)



Answer



For 2D, Deluxe Paint was pretty popular in those days.


For 3D, 3D Studio was around on the PC (eventually becomming Autodesk 3D Studio Max later in it's life). On the Amiga you had Lightwave (which was also used for TV and film).


modifiers - When adjectives become predicatives, do they also become adverbs?




Optional depictive predicatives as adjuncts


Obligatory predicatives are clearly complements, dependent on the occurrence of an appropriate verb. With optional ones, however, there are grounds for saying that while the resultatives are complements, the depictives are adjuncts. Resultatives are either obligatory (as in the He talked himself hoarse construction) or else need to be licensed by the verb. Optional depictives, however, are less restricted in their occurrence. One manifestation of this has just been noted: they can occur in transitive clauses with either S or O as predicand. Another is that they can occur in combination with an obligatory predicative or in the ditransitive construction:


29  i) They look even more fantastic naked.
ii) They served us our coffee black.

We will therefore regard such predicatives as adjuncts, so that the predicative/non-predicative contrast cuts across that between complements and adjuncts.


Like numerous other kinds of adjunct, predicatives may be integrated into the structure as modifiers, or detached, as supplements:


30  i) They left empty-handed.                                 [modifier]
ii) Angry at this deception, Kim stormed out of the room. [supplement]

The supplements are positionally mobile and are set apart prosodically. The modifiers are of course more like the complements, especially in cases where they occur very frequently with a particular verb, as with leave in [i], die in He died young, bear in the passive He was born rich, and so on.


(CGEL, p.262)




I don’t find this modifier explanation except on this part. So it’s not clear to me whether the book says empty-handed is the predicative for they, and this enters not into CGEL’s but into the traditional category of adverbs as a modifier. When I say ‘it sounds clear’, this adjective clear is both a predicatve (for it) and an adverb (for sounds) is what the book says?




This is the answer that I've got from Linguistics Beta which is written by Tim Osborne:



The adjectives in question do indeed behave in a unique way. They are dependents of the verb, but they are predications over the subject (or object), e.g


 He died young.

The adjective young is a direct dependent of the verb died, but it is a predication over the subject he, i.e. it assigns the property of youngness to he. In other words, young is behaving like an adverb/adjunct syntactically because it is a direct dependent of the lexical verb died, but it is definitely an adjective insofar as it looks like an adjective and is assigning a property to a (pro)noun.


As Jlawler points out, the terminology used to denote these words varies. Some call them depictive adjuncts or participant-oriented adjuncts. Depictive adjuncts are stage-level predicates; the property that they assign is not an intrinsic characteristic of the noun, but rather its applicability is transient. Adjectives that assign intrinsic properties cannot occur in this use, e.g.



 *Bill died interesting.

Unlike young, which is a transient state because we all get older, interesting is intrinsic and inalienable. The distinction between stage-level and individual-level predicates is discussed at the bottom of the article here: https://en.wikipedia.org/wiki/Predicate_%28grammar%29.


The direct answer to the question is therefore as follows: predicative adjuncts modify the verb if one interprets modify to mean 'be syntactically dependent on', or they modify the subject or object if one interprets modify to mean 'assign a property to'. Note that typical attributive adjectives unify both of these meanings of modify, e.g.


 the young man

In this case, young is both syntactically dependent on man and it is assigning a property to man.




Answer



The definitive answer is given here: https://linguistics.stackexchange.com/questions/8438/do-predicative-adjuncts-modify-nouns-or-verbs. Be sure to read all the comments as well, especially John Lawler's.



Why many abstract nouns get an indefinite article while it's taught that abstract nouns shouldn't get it?


I was told that abstract nouns don't get articles. (You can see here for example). But I found many abstract nouns that get indefinite articles, such as: "of a truth", "of a size", "of a lifetime", "of a certain age", "a love", "a wish", "a difference", "a power" and more. What is the explanation for that?




word choice - Fish vs Fishes for plural use


Now, I encountered a sentence in a text book, saying



Many fish are specially adapted to live only in certain places.




I know that plural of the word fish can be fish as Merriam says


screenshot of the dictionary entry for


But wouldn't it someway or somewhat sound unusual or "too unique"?


Is it only to me?



Answer



Fish is certainly the most common and arguably correct plural of the word "fish". However, "fishes" is an archaic plural form, and is apparently also used in some situations which I will go on to explain.


An example of the archaic use of "fishes" as plural is the biblical account of a miracle involving "five loaves and two fishes". Actually modern English translations of this use "fish" as the plural, but people of a certain age were taught this in school from the King James version (1611) and as a result many people still refer to this as the miracle involving "five loaves and two fishes"! This idiom may even have been passed on to younger generations.


The collective term for fish is a school, or shoal. You would correctly refer to a school of fish - not "fishes".


However, I found this use of "fishes" as a plural in a scientific textbook from 1968. The book is even titled "Deep Water Fishes of California"!



Unless a marine biologist here can advise otherwise, it would seem that it is also acceptable to use fishes when referring to more than one type of fish, although it should equally be correct to say "different types of fish".


Wednesday, September 23, 2015

grammatical number - Singular or plural for seconds


For numbers of seconds, is it smaller or equal to 1 we use second, larger than 1 we use seconds?


For example:




0 second
0.5 second
1 second
1.5 seconds




Answer



SOME of the rules around 1 are:





  • "X somethings" when X is not 1




  • For 1 and 0 amounts with decimals pronounced "0 point Y" and "1 point Y", it is somethings:
    0.5 somethings, 0.1 somethings, 1.5 somethings, 1.1 somethings




  • For quantifications ending on a something, we have half a something, a quarter of a something because it is still relative to 1 (or a)





The same is the case for time, weight, money and other quantifications.



  • 1 second/kilo/dollar

  • half a second/kilo/dollar

  • a third of a second/kilo/dollar


  • a quarter of a second/kilo/dollar - note a quarter (dollar) is one coin in the US.




  • 0 seconds/kilos/dollars




  • 0.5 (zero point five) seconds/kilos/dollars

  • 0.1 (zero point one) seconds/kilos/dollars


For the rest of the rules and exceptions and possibly perceived rules, have a read of the answers to Is -1 singular or plural?


java - Multi threaded game - updating, rendering, and how to split them


From the StackOverflow post (it was recommended I move this):


So, I'm working on a game engine, and I've made pretty good progress. However, my engine is single-threaded, and the advantages of splitting updating and rendering into separate threads sounds like a very good idea.


How should I do this? Single threaded game engines are (conceptually) very easy to make, you have a loop where you update -> render -> sleep -> repeat. However, I can't think of a good way to break updating and rendering apart, especially if I change their update rates (say I go through the update loop 25x a second, and have 60fps for rendering) - what if I begin updating halfway through a render loop, or vice versa?



Answer



You're going to want to double/triple buffer any data necessary for rendering that gets altered in the update pass. That way you won't be rendering with something that's been partially changed. The reason you'll probably need to triple buffer is needing 1) the copy you're updating, 2) the last copy you updated fully, and 3) the copy that is currently being used for rendering that you don't want to change.



The hardest part is probably working out the best way to organise your data for this.


possessives - Can I say "house's roof", or only "roof of the house"?


For example:

1) House's roof collapsed yesterday.
or
2) The roof of the house collapsed yesterday.


Which of these two is better and why?



Answer



Both are understandable, but you have to be careful how you construct your sentence.



House's roof collapsed yesterday.



Doesn't work, because I don't know what house you're talking about. There are millions of houses. You need to say




My house's roof collapsed yesterday.



Which is a perfectly acceptable setntence.



The roof of the house collapsed yesterday



Is perfectly clear, but a little more formal. I would still say



The roof of my house collapsed yesterday




Unless you were in a conversation where the phrase "the house" is unambiguous, such as if you were discussing it with the contractor who built your house in the first place.


word choice - anyone vs someone. Which one?





  • Has someone seen my bag?





  • Has anyone seen my bag?





Which one is grammatically correct? Why? Please explain.


Which one should I use at this place?


Can you give some more examples?



Answer




Agree with pmusser - they're both correct.


However any is a Negative Polarity Item, whereas some is not. Also, when you say "Has someone seen my bag" you actually mean at least one from the group has seen your bag. On the other hand, "Has anyone seen my bag" is a general addressing.


To make 'someone/anyone' clearer, think about these sentences -



Someone can do it - at least one person can do it.
Anyone can do it - any person (or better everyone) can do it.



More examples as you asked are here. See Travis' answer in the same, which says:



In my opinion, the big difference between "someone" and "anyone" is that "someone" refers to some person, and that person is specific, even though it may not be known, while "anyone" refers to some person, and all people are equally interchangeable as said individual.




past vs past perfect - "He had a gun." or "He has had a gun."


What is the difference between the sentences





  1. He had a gun.



and




  1. He has had a gun.



I think when you are saying about the past why don't you just say it as "He had a gun" instead of "He has had a gun"?, this goes same with these below sentences as well.





  1. He has killed.

  2. He has had killed.





  1. She had sex before she died.

  2. She had had sex before she died.






Tuesday, September 22, 2015

mathematics - Is it possible to procedurally place objects in a non-gridded game?


I'd like to implement procedural world generation, but I don't want it to look gridded or blocky, where everything is obviously placed on an integer grid.


I know that you can do this in gridded worlds by inputting a square's x and y into a noise function, or similar, but is it possible to generate a more natural looking object placement using procedural methods?


This is in the context of an adventure game, if it matters.


Edit: I guess I should have been a bit more clear in my original question, but I'm mostly wondering about the actual placement of objects in game, e.g. trees, buildings.


Edit 2: I feel silly now. I typed up this question too quickly, and I didn't realize I was asking a yes or no question. I've reposted my actual question which asks, more specifically, how this can be done. Sorry!




Answer



EDIT


To address you change from generation of worlds to generation of objects in game.


Yes, the same still applies. For example, included in my original post, SpeedTree is used for placing vegetation in game:


enter image description here


So yes, it's entirely possible. Most any large world (Skyrim for example) will use some form of procedural generation for placing items like this. They're not all placed by hand and they're clearly not aligned to a grid.




Procedural generation absolutely has use outside of a grid world. You need look no further than Terragen for excellent examples of such:


enter image description here


SpeedTree is another popular choice for many games for producing vegetation.



Noise generation commonly fractal in nature, that means you can continue "down" to smaller and smaller details.


And a popular method from Red Blob Games uses polygons, blending and noise:


enter image description here


word usage - What is the meaning of "if anything"?


I do understand the meaning of "if anything" in the context. I can understand each word individually.



Here is the text:



In the past it was a common belief that snakes couldn't hear much, if anything, since they have no external ears and don't seem to respond much to noises. However, some scientific research refutes this common misconception.



I feel like the text is understandable without saying "if anything" so why does the writer put it in the text?



Answer



If anything is a an idiom used to describe a very small amount of something.



if anything (at all)
if (there is) anything



The price of the book, if anything, is a dollar.
That city, if anything, is a nice place to visit.



A similar phrase



if nothing else



has the same meaning as if (there is) anything



That city, if nothing else, is a nice place to visit.




modal verbs - Could vs. was able to


A grammar book says that in the following sentences we must not use "could" instead of "was/were able to".




  • The fire spread through the building very quickly, but everyone was able to escape.





  • They didn't want to come with us at first, but finally we were able to persuade them




However, when I searched the English language corpus COCA by "finally could", I found some counter-examples. Here are two examples from COCA.




  • I told her to get in line. Did it make you feel better? It did. I finally could say something.




  • Then, when it ended and I finally could get my family back, it came at a price, like suddenly being blind.





Are these examples grammatically incorrect?


Edit(Jun. 5, 2014) I posted the same question here.




c++ - How to detect collision between two directed object?


I'm currently writing a game which is like Battle City game. But right now I'm facing a trouble involved to checking collision between two objects. This is the code that I wrote:



//-------------------------------------------------------------------------------------------
// check collision between a tank and another object
//
bool GameController::checkTankMeetsObject(Tank tank, GameObject ob)
{
int obX = ob.getCoord().getX();
int obY = ob.getCoord().getY();

// calculate area of obstacle: bottom left (X1, Y1), top right (X2, Y2)
int obX1 = obX - SQUARESIZE / 2;

int obX2 = obX + SQUARESIZE / 2;
int obY1 = obY - SQUARESIZE / 2;
int obY2 = obY + SQUARESIZE / 2;

int tankX = tank.getCoord().getX();
int tankY = tank.getCoord().getY();

switch (tank.getDir())
{
case UP:

if ((tankX < obX2 + SQUARESIZE / 2 && tankX > obX1 - SQUARESIZE / 2) &&
(tankY + SQUARESIZE / 2 > obY1 && tankY + SQUARESIZE / 2 < obY2))
return true;
break;

case DOWN:
if ((tankX < obX2 + SQUARESIZE / 2 && tankX > obX1 - SQUARESIZE / 2) &&
(tankY - SQUARESIZE / 2 > obY1 && tankY - SQUARESIZE / 2 < obY2))
return true;
break;


case LEFT:
if ((tankX - SQUARESIZE / 2 < obX2 && tankX - SQUARESIZE / 2 > obX1) &&
(tankY > obY1 - SQUARESIZE / 2 && tankY < obY2 + SQUARESIZE / 2))
return true;
break;

case RIGHT:
if ((tankX + SQUARESIZE / 2 < obX2 && tankX + SQUARESIZE / 2 > obX1) &&
(tankY > obY1 - SQUARESIZE / 2 && tankY < obY2 + SQUARESIZE / 2))

return true;
break;
}

return false;
}

This code does well with normal circumstance, but in special ones like which I describe below, it doesn't work.


enter image description here


The white squares are obstacles and the grey square is the tank. Current direction of the tank is RIGHT. In this situation, I can not move the tank RIGHT or LEFT, only direction I can go is DOWN. Is there any solution to optimize my code?





grammar - I am working in company name or at company name?



Please help me figure out this one.



"I am working in [company name]"



"I am working at [company name]"



Which one is correct? In or at?




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