Monday, September 30, 2019

punctuation - Can "A game a few would play" be a valid structure?


This is a line in a "poem", but I have changed two words to "game" and "play" with preserving the sentence exact structure.




Indeed, a game a few would play.



I have searched for this structure which would be (if it is written in general): [noun] + [quantifier] + [verb]. But found nothing similar.


Also, I want to know if it should take a certain punctuation mark between the noun and the quantifier. I think it may be a period as it appeared that there's no structure like that. However, it is only a small pause between the two.



Answer



"Indeed, a game a few would play" sounds fine.


Remember that "a few" means a small, but noteworthy number, sometimes representing an undetermined number from a larger group.


"Few", without the indefinite article, is used to mean scarcely any.





  • "A game a few would play" then means that a small number of people would play it.




  • "A game few would play" would mean a game that not many people engaged in.




As written, I would not insert any pauses other than the comma after "indeed".


determiners - No Articles for countable and definable words



Source


Have a contractor apply ( ) water proofing material from ( ) grade level down.


Why do you think "material" and "level" are without an article?




c++ - Does Windows 8 still support DirectX 9?



Is Windows 8 supporting DirectX 9? Because I was looking through some samples written in C++ and DirectX 9 made for Windows 8. It wasn't that, like I know it ( look here http://directxtutorial.com/Lesson.aspx?lessonid=111-4-2 ). E.g. Inizialising DirectX with COM:


ComPtr dev;
ComPtr devcon;

It's just weird because I know it with the old way:


ID3D11Device *dev;                  
ID3D11DeviceContext *devcon;

( I hope you understand what I want to tell )


I hope it hasn't change completely due the released their new OS.




Answer



Yes, Windows 8 does support DirectX 9.


For development, the old DirectX SDK is now deprecated, but you'll have all the libraries and headers you need within the new Windows 8 SDK, which comes included with Visual Studio 2012. You can go for the "old way" with no problem. If you need PIX for some debugging, or the high level D3DX library, you'll have to install the old DXSDK again, as this is not in the Windows 8 SDK.


However this is only valid for plain old desktop apps. For Metro-style apps, I'll let Chuck Walbourn from Microsoft speak:



Direct3D9 and Direct3D9Ex are not supported for Metro style applications. Use of the DirectX SDK with Metro style applications is not recommended or supported. See http://msdn.microsoft.com/en-us/library/ee663275.aspx.


There are a number of resources available to help you in porting a Direct3D 9 codebase to Direct3D 11. The majority of the material for porting from Direct3D 9 to Direct3D 10.x applies fully here since Direct3D 11's API is very similiar to Direct3D 10.


See http://blogs.msdn.com/b/chuckw/archive/2011/07/11/getting-started-with-direct3d-11.aspx. Be sure to review the Windows to Reality: Getting the Most out of Direct3D 10 Graphics in Your Games presentation as it covers numerous pitfalls and performance issues developers have hit in the past, and DirectX 11 Technology Update for a summary of the differences between Direct3D 10.x and Direct3D 11.


MSDN has a porting guide as well http://msdn.microsoft.com/en-us/library/ff476190.aspx which points you to http://msdn.microsoft.com/en-us/library/bb205073.aspx for going directly from Direct3D 9 to Direct3D 11.




Sorry, you can't use D3D9 directly for Metro-style apps. But you can use D3D11 and limit yourself to some feature level (e.g. D3D_FEATURE_LEVEL_9_3) if you want to support legacy hardware.


word usage - "Help you" vs "help you out"


Example:




Actually, there's someone who can help you."


Actually, there's someone who can help you out."



What's the difference between the two? Or they mean the same thing?




articles - Generic noun plural case



1) Studying at a good institute can really make a difference.


2) Studying at good institutes can really make a difference.


Do both the sentences carry the same meaning ?




Sunday, September 29, 2019

c# - Changing one prefab changes all other instances of that prefab too


I have made two prefabs of my enemies for my 2D game: normal and damaged. The I put several of these prefabs on scene. When enemies health <=0 I need to destroy its GameObject and then instantiate a damaged prefab on its position. But when I am doing this, all other prefabs are destroying too and damaged prefabs are instantiated on their positions. After searching this site I found out that any changes with one prefab are applying to all other prefabs on scene? Is this right?


P.S. I have edited the script where I am destroying prefab and added to it a simple check, if the prefabs renderer is visible on scene, then I need to destroy it, because all other prefabs are not visible at this moment. Do I need to check to make sure that this is the instance of the prefab is that I need every time when I want to apply to it some change?



Answer



Once a prefab has been instantiated, anything you do to that prefab should be independent of other instances of that prefab. It's more likely you have a code error that is accidentally changing all your instances. For example: How can I edit the components of an instantiated prefab? addresses editing the components of one prefab without changing any others.


You need to ensure you're referencing the specific object you're trying to change. Don't reference the prefab source, just the gameObject you want to change. If you change something that's common to all the instances, like a mesh or texture, it will affect all the instances, similar to this problem: How to make prefabs independent?


modal verbs - How to backshift "would" (used for saying what someone used to do in the past)?



How to backshift the following sentence:



As a child he would get up early and go fishing.



I think it should be:



He said when he had been a child he would/would have get up early and go fishing.



But I am not sure if it should be would or would have, since would on its own can serve as a past marker.



Answer




It doesn't really make sense to shift this particular sentence into the past in this way. If you're going to use the past perfect here, you need to mention a period of time, such as "when he had been a child for ten years". Suppose we change the sentence a bit:



He said that after he had been out of school for five years he would get up early and go fishing every morning.



That makes more sense. Now, you can see that the tense of the "fishing" clause doesn't change, just because the context in which the fishing is done does. This sentence is also correct:



He said that after he had been out of school for five years he used to [not "had used to"] get up early and go fishing every morning.



However:




He said that after he had been out of school for five years he had gotten up early and gone fishing every morning.



Exactly why this is so, perhaps someone else can explain.


Saturday, September 28, 2019

xna - How do I create a player movement system in Farseer?


My group of students is helping produce a a 2D platformer. We tried making a pixel-based collision system which fell through. Now I am trying this physics engine on for size and see new ways to create and control my player. Like the obvious circle body player:


Image


I was using a different type of player movement system like this XNA video example.


What system would work for a player that needs to be able to jump and move in mid-air (as in the above link), and can run up slopes like the circular body example?


I guess that the circular body can be made to do anything, but would like community input.




Answer



Please take my answer as "the right way to do this", not necessarily the "good for a student project" way.


Rigid body physics are entirely inappropriate for modeling "walking" behaviour.


Rigid body physics are good for handling things like bouncing and friction. Which are things you want to avoid in a typical platformer. There is no "right shape" that will make a satisfying platformer character on its own.




Basically you need to not be afraid to take matters into your own hands and "override" the physics engine. Rather than working with impulses and forces, like you might for typical physics bodies, you should manually control your player's position and velocity. (Sounds scary, but it's perfectly ok to do.)


I recommend: Before the physics step, set the velocity to an appropriate value using typical platformer movement mechanics. After the physics step, modify the position to correct any unplatformerly behaviours (I find it best to "snap" the player object onto the ground, rather than relying on physics - which can cause the player to "skip" off the ground).


The actual shapes you use are then fairly irrelevant.


Obviously this is a fair bit more work, and you have to be able to deal with the 2D geometry calculations. But the results are markedly better.





Here's how I do it:


My initial attempts used a diamond shape, which is advantageous because it only has one point of contact with the ground to worry about (similar benefits to using a circle, only better). I ignore/cancel collisions with this point in the physics engine (if they're with a ground surface) - because I handle them myself by snapping it to the ground in my "fix-up" step.


(The "weight" effect of the player in that video is done manually too. Without it, this works better with static level geometry.)


More recently I have taken to using a "hovering rectangle". Rather than snapping to the ground, I snap some distance above it. The rectangle body provides collision detection with the walls and ceiling, while the hover behaviour handles the floor.


I'm actually exploring doing away with the rigid body entirely, because I'm working on movements like wall jumping, etc. And, again, rigid bodies aren't well suited for simulating these kind of human movements.


java - Appropriate level representation / data stucture for a 2D platfrom game?


I'm about to program a copy of Mario in Java. I'm thinking on 2 representations/data structures for the levels but I'm not sure which one should I choose:



  • A 2D integer array.


  • A quadtree to divide the level in pieces.


What are its advantages and disadvantages?



Answer



The point of a quadtree is to efficiently cull large chunks of the data so that you only spend time on the data in the immediate vicinity. However a 2D array already gives you location-specific random access, so for a 2D game that may make a quadtree redundant. In a 3D game you can't use an array to locate everything and that's where quadtrees (or better yet octrees) are handy.


Now, I'm talking here about the underlying data representation for the level. Depending on how your graphic architecture is setup (eg. doing 2D graphics with planes in a 3D engine) you may want to use quadtrees in the scene graph in order to efficiently cull graphical content.


And then don't forget various enemies and other interactive objects in your level. Perhaps you use a 2D array to manage the tiles of the level, but use quadtrees to organize all the interactive elements (eg. for a physics engine).




Think of it this way: pick a point at random in your level, and then think about how much work it'll take to figure out everything within a 1000 pixel radius of that point. If you can do that quickly because everything is organized by location in a 2D array, then you don't need a quadtree. If however you would have to loop through everything and check each object's distance individually, then you could make the search much more efficient by using a quadtree.


LibGDX: Easy way to draw partial sprites


I am surely overlooking something, but is there an easy to draw for example only half a sprite in LibGDX? I originally thought I could do this with setBounds() but this distorts the sprite.




In OpenGL, is it a bad idea to "combine" immediate mode and retained mode for the sake of GUIs?


Suppose I have a 3D scene being drawn with glDrawArrays(...) and I want to render something simple, like a 2D overlay. Would it be a bad idea to use immediate mode for such a thing, instead of setting up a 2D renderer with retained mode?


Example:


void Draw()
{
// Draw the 3D scene:
// *does stuff*

glDrawArrays(...);
// *some other stuff*

// Setup a quad with immediate mode (for something like a vignette overlay)
glBegin(GL_QUADS);
glTexCoord2f(...); glVertex2f(...);
glEnd();
}

Answer



It is a bad idea insofar as it is nonsensical. There is nothing to "set up" that you have not already done, except for an ortho projection matrix (which you will have to do in any case).



Portability is probably not a problem, although it should be. IHVs seem to be very reluctant to drop support for immediate mode for the foreseeable future (it seems to "work fine" even in core profiles), so although immediate mode should have died out long ago, it will probably stay forever. Performance is another story. Do you really want something that accounts for 0.1% of the scene complexity to consume 15-20% of the CPU time -- GL calls are relatively lightweight, compared to e.g. DX, but they are not free -- and 15-20% of real frame time due to stalling the pipeline? Can you even afford that with your time budget? Most games can't.


And then of course, the quirks. Oh the quirks. The apparent beauty of immediate mode is that it is (seemingly) easy and straightforward to do something like drawing a couple of quads quick. In reality, immediate mode can be such a pain in the rear, it's so full of non-obvious pitfalls.
On the other hand side, it is just as easy (and more straightforward if you ask me!) to just write a small 5-LOC function DrawQuad which when called adds vertex coordinates and indices to a memory buffer and increments a counter. Which, surprise, you can then draw with glDrawArrays/Elements and which you can reuse (the GPU copy, not just the userland copy!) the next frame as-is as long as nothing is changed.
Immediate mode must, there is no other way, allocate a buffer and do a PCIe transfer every time. Or, something equivalent in latency (GPU reading main memory over the bus, whatever). The driver cannot possibly know (or assume) that the data remained exactly the same as the frame before.


Getting data to the GPU is a high-speed, but also a high-latency operation. Not only is the bus transfer per se a complicated, high latency protocol (several protocol layers, packetizing, acknowledgements, etc.), but also not all GPUs are even able to transfer and draw at the same time, or if they can do it, they may not be able at all times to switch between or initiate new operations freely while doing something different. Read as: Thou shalt not transfer vainly.


rotation - I'm rotating an object on two axes, so why does it keep twisting around the third axis?


I see questions come up quite often that have this underlying issue, but they're all caught up in the particulars of a given feature or tool. Here's an attempt to create a canonical answer we can refer users to when this comes up - with lots of animated examples! :)




Let's say we're making a first-person camera. The basic idea is it should yaw to look left & right, and pitch to look up & down. So we write a bit of code like this (using Unity as an example):


void Update() {
float speed = lookSpeed * Time.deltaTime;


// Yaw around the y axis using the player's horizontal input.
transform.Rotate(0f, Input.GetAxis("Horizontal") * speed, 0f);

// Pitch around the x axis using the player's vertical input.
transform.Rotate(-Input.GetAxis("Vertical") * speed, 0f, 0f);
}

or maybe


// Construct a quaternion or a matrix representing incremental camera rotation.

Quaternion rotation = Quaternion.Euler(
-Input.GetAxis("Vertical") * speed,
Input.GetAxis("Horizontal") * speed,
0);

// Fold this change into the camera's current rotation.
transform.rotation *= rotation;

And it mostly works, but over time the view starts to get crooked. The camera seems to be turning on its roll axis (z) even though we only told it to rotate on the x and y!


Animated example of a first-person camera tilting sideways



This can also happen if we're trying to manipulate an object in front of the camera - say it's a globe we want to turn to look around:


Animated example of a globe tilting sideways


The same problem - after a while the North pole starts to wander away to the left or right. We're giving input on two axes but we're getting this confusing rotation on a third. And it happens whether we apply all our rotations around the object's local axes or the world's global axes.


In many engines you'll also see this in the inspector - rotate the object in the world, and suddenly numbers change on an axis we didn't even touch!


Animated example showing manipulating an object next to a readout of its rotation angles. The z angle changes even though the user didn't manipulate that axis.


So, is this an engine bug? How do we tell the program we don't want it adding extra rotation?


Does it have something to do with Euler angles? Should I use Quaternions or Rotation Matrices or Basis Vectors instead?



Answer



No this isn't an engine bug or an artifact of a particular rotation representation (those can happen too, but this effect applies to every system that represents rotations, quaternions included).


You've discovered a real fact about how rotation works in three-dimensional space, and it departs from our intuition about other transformations like translation:



Animated example showing that applying rotations in a different order gives different results


When we compose rotations on more than one axis, the result we get isn't just the total/net value we applied to each axis (as we might expect for translation). The order in which we apply the rotations changes the result, as each rotation moves the axes on which the next rotations get applied (if rotating about the object's local axes), or the relationship between the object and the axis (if rotating about the world's axes).


The changing of axis relationships over time can confuse our intuition about what each axis is "supposed" to do. In particular, certain combinations of yaw and pitch rotations give the same result as a roll rotation!


Animated example showing a sequence of local pitch-yaw-pitch gives the same output as a single local roll


You can verify that each step is rotating correctly about the axis we requested - there's no engine glitch or artifact in our notation interfering with or second-guessing our input - the spherical (or hyperspherical / quaternion) nature of rotation just means our transformations "wrap around" onto each other. They may be orthogonal locally, for small rotations, but as they pile up we find they're not globally orthogonal.


This is most dramatic and clear for 90-degree turns like those above, but the wandering axes creep in over many small rotations too, as demonstrated in the question.


So, what do we do about it?


If you already have a pitch-yaw rotation system, one of the quickest ways to eliminate unwanted roll is to change one of the rotations to operate on the global or parent transformation axes instead of the object's local axes. That way you can't get cross-contamination between the two - one axis remains absolutely controlled.


Here's the same sequence of pitch-yaw-pitch that became a roll in the example above, but now we apply our yaw around the global Y axis instead of the object's


Animated example of a mug rotating with local pitch and global yaw, with no roll problemAnimated example of first-person camera using global yaw



So we can fix the first-person camera with the mantra "Pitch Locally, Yaw Globally":


void Update() {
float speed = lookSpeed * Time.deltaTime;

transform.Rotate(0f, Input.GetAxis("Horizontal") * speed, 0f, Space.World);
transform.Rotate(-Input.GetAxis("Vertical") * speed, 0f, 0f, Space.Self);
}

If you're compounding your rotations using multiplication, you'd flip the left/right order of one of the multiplications to get the same effect:


// Yaw happens "over" the current rotation, in global coordinates.

Quaternion yaw = Quaternion.Euler(0f, Input.GetAxis("Horizontal") * speed, 0f);
transform.rotation = yaw * transform.rotation; // yaw on the left.

// Pitch happens "under" the current rotation, in local coordinates.
Quaternion pitch = Quaternion.Euler(-Input.GetAxis("Vertical") * speed, 0f, 0f);
transform.rotation = transform.rotation * pitch; // pitch on the right.

(The specific order will depend on the multiplication conventions in your environment, but left = more global / right = more local is a common choice)


This is equivalent to storing up the net total yaw and total pitch you want as float variables, then always applying the net result all at once, constructing a single new orientation quaternion or matrix from these angles alone (provided you keep totalPitch clamped):


// Construct a new orientation quaternion or matrix from Euler/Tait-Bryan angles.

var newRotation = Quaternion.Euler(totalPitch, totalYaw, 0f);
// Apply it to our object.
transform.rotation = newRotation;

or equivalently...


// Form a view vector using total pitch & yaw as spherical coordinates.
Vector3 forward = new Vector3(
Mathf.cos(totalPitch) * Mathf.sin(totalYaw),
Mathf.sin(totalPitch),
Mathf.cos(totalPitch) * Mathf.cos(totalYaw));


// Construct an orientation or view matrix pointing in that direction.
var newRotation = Quaternion.LookRotation(forward, new Vector3(0, 1, 0));
// Apply it to our object.
transform.rotation = newRotation;

Using this global/local split, the rotations don't have a chance to compound and influence each other, because they're applied to independent sets of axes.


The same idea can help if it's an object in the world that we want to rotate. For an example like the globe, we'd often want to invert it and apply our yaw locally (so it always spins around its poles) and pitch globally (so it tips toward/away from our view, rather than toward/away from Australia, wherever it's pointing...)


Animated example of a globe showing better-behaved rotation


Limitations



This global/local hybrid strategy isn't always the right fix. For example, in a game with 3D flight/swimming, you might want to be able to point straight up / straight down and still have full control. But with this setup you'll hit gimbal lock - your yaw axis (global up) becomes parallel to your roll axis (local forward), and you have no way to look left or right without twisting.


What you can do instead in cases like this is to use pure local rotations like we started with in the question above (so your controls feel the same no matter where you're looking), which will initially let some roll creep in - but then we correct for it.


For example, we can use local rotations to update our "forward" vector, then use that forward vector together with a reference "up" vector to construct our final orientation. (Using, for example, Unity's Quaternion.LookRotation method, or manually constructing an orthonormal matrix from these vectors) By controlling the up vector, we control the roll or twist.


For the flight/swimming example, you'll want to apply these corrections gradually over time. If it's too abrupt, the view can lurch in a distracting way. Instead, you can use the player's current up vector and hint it toward the vertical, frame-by-frame, until their view levels out. Applying this during a turn can sometimes be less nauseating than twisting the camera while the player's controls are idle.


Friday, September 27, 2019

questions - Identify people in a photo


Look at this quiz. Is it correct to say:




Whose photo is this?




As far as I know there's a difference between



This is a photo of David. (=You can see David in the photo.)



and



This is David's photo. (=The photo belongs to David, but you can see Mike in it.)





So the right question is



Who is this a photo of?




Please correct me if I'm mistaken.




plural forms - Why are there so many specific words for groups of animals?


I found this link to names of the groups of animals. I am confused because there are so many various congregations. Is there any guidance rather than learning by rote if I want to remember them?




security - How to verify if the client files are the same as the server files?



In a client-server game architecture, what are the possible ways to verify that the client has not modified things like gfx assets or client side scripts?


Obviously no solution is perfect, but I would love to hear some ideas.


I am thinking something like an hash on all the files in the resources directory. Does that sound feasible?



Answer



If this is for hack prevention, it's a losing battle.


Things like hashes and sending random bits of data back to the server for validation come to mind, but nothing stops the hacker from using a separate, non-compromised copy of the original data as source for answering such checks.


Same goes for sending checksums of in-memory resources.


One way might be to send screenshots or checksums thereof, but then you hit the problem of different video cards/drivers rendering subtly different frames...


All that said, I'd consider outsourcing the problem to someone who has been doing it for a while, like http://www.evenbalance.com/ (punkbuster).


objective c - How to approach 360 degree snake without having it "slide"


There's a great question here that helps me a little bit in what I want to do, and it explains it quite well:


How To Approach 360 Degree Snake


Basically, I want to have a smooth 360-degrees Snake game, where the snake follows along. I can easily do the same thing as described in the question above (video example), but as you can see that kind of "drags" or "slides" the snake along, which is not what I'm looking for.


I want the entire snake to follow the entire path that the head of the snake follows.


The only solution I can think of is to make some kind of "buffer" to store the rotations of the head, and then "lag" that behind on the other bodies.


Since I think that will end up way too complex, what's the correct way of implementing it?



Here's a screenshot of how my snake looks like right now, to get an idea of what exactly I want to move:




Answer



One method is to have the head define a trail as it moves and position all other nodes at positions along this trail.


In this method you need to define the position of the body parts as a constant distance along the snake from the head.


So on each frame you want to;



  1. update the position of the head.

  2. add the current position of the head to a list of previous positions it occupied

  3. for each node of the body


    1. get/calculate the distance the body should be away from the head

    2. traverse the trail by that distance

    3. set the body position to this position on the trail




The following is a C++03 program which shows how this can be achieved. It isn't perfect, but it demonstrates the idea;


#include 
#include

#include
#include
#include

struct Vector3
{
Vector3(double x = 0, double y = 0, double z = 0) :
x(x),
y(y),
z(z)

{
}

double x;
double y;
double z;

Vector3 operator +(const Vector3 v) const
{
return Vector3

(
x + v.x,
y + v.y,
z + v.z
);
}

Vector3 operator -(const Vector3 v) const
{
return Vector3

(
x - v.x,
y - v.y,
z - v.z
);
}

Vector3 operator *(double scalar)
{
return Vector3

(
x * scalar,
y * scalar,
z * scalar
);
}

double magnitude()
{
return sqrt(x*x + y*y + z*z);

}

void normalise()
{
double mag = magnitude();
if (mag != 0.0)
{
x /= mag;
y /= mag;
z /= mag;

}
}

std::string toString()
{
std::stringstream ss;
ss << "(" << x << ", " << y << ", " << z << ")";
return ss.str();
}
};


class Trail
{
public:
struct Point
{
Vector3 position;
double distanceToNext;
};


Trail() :
m_maxPoints(0),
m_points()
{}

size_t maxPoints() const
{
return m_maxPoints;
}
void maxPoints(size_t size)

{
m_maxPoints = size;

if (m_points.size() >= m_maxPoints && m_maxPoints != 0)
{
m_points.resize(m_maxPoints, Point());
}
}

void addPoint(Vector3 vec)

{
Point p;
p.position = vec;
if (!m_points.empty())
{
p.distanceToNext = (vec - m_points.front().position).magnitude();
}
else
{
p.distanceToNext = 0.0;

}
addPoint(p);
}

void addPoint(Point point)
{
if (m_points.size() >= m_maxPoints && m_maxPoints != 0)
{
m_points.resize(m_maxPoints - 1, Point());
}

m_points.push_front(point);
}

Vector3 positionFromHead(double distance) const
{
for (size_t i = 0; i < m_points.size() - 1; ++i)
{
const Point& p = m_points[i];
if (distance > p.distanceToNext)
{

distance -= p.distanceToNext;
}
else
{
// Lerp between last and current points.
Vector3 offset = m_points[i + 1].position - p.position;
offset.normalise();
offset = offset * distance;
return p.position + offset;
}

}

if (!m_points.empty()) // is last point?
{
return m_points.back().position;
}

return Vector3(); // list is empty
}


private:
size_t m_maxPoints;
std::deque m_points;
};

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

trail.addPoint(Vector3(50, 0, 0));

trail.addPoint(Vector3(10, 0, 0));
trail.addPoint(Vector3(0, 0, 0));

Vector3 posA = trail.positionFromHead(5);
std::cout << " 5 units from head - Expecting (5, 0, 0) and got " << posA.toString() << "\n";
Vector3 posB = trail.positionFromHead(10);
std::cout << "10 units from head - Expecting (10, 0, 0) and got " << posB.toString() << "\n";
Vector3 posC = trail.positionFromHead(25);
std::cout << "25 units from head - Expecting (25, 0, 0) and got " << posC.toString() << "\n";


return 0;
}

Of particular importance is this method which actually works out the position based on the distance;


  Vector3 positionFromHead(double distance) const
{
for (size_t i = 0; i < m_points.size() - 1; ++i)
{
const Point& p = m_points[i];
if (distance > p.distanceToNext)

{
distance -= p.distanceToNext;
}
else
{
// Lerp between last and current points.
Vector3 offset = m_points[i + 1].position - p.position;
offset.normalise();
offset = offset * distance;
return p.position + offset;

}
}

if (!m_points.empty()) // is last point?
{
return m_points.back().position;
}

return Vector3(); // list is empty
}


In this instance each position on the trail is stored with a distance to the next one but this could be calculated on the fly. It's calculated in the addPoint() methods.


Note: don't use that Vector3 class. It was created only for this example to keep the dependencies down.


If the distance requested is longer than the list you'll just be given the position of the end of the trail.


If this were to be used you would need to make sure that you set maxPoints to an appropriate number or use 0 if you want it to be unbounded. To be clear, the maxPoints doesn't need to correspond to the number of bodies in your snake, you just want it to store enough to make a trail equal to the length of the snake.


You may want to consider limiting the max length with a max total distance instead of a max number of points. Also, if you set it to unbounded (0) it will consume more memory every frame so only use that when experimenting.


In practice you might do something similar but not exactly the same thing.


Thursday, September 26, 2019

xna - Biased, conservative random walk


I have a sprite which has Velocity and Position, either stored as Vector2. At each Update cycle, velocity is added to the position.



I would like to give the sprite a third vector, Target. New targets may be given at any iteration. I would like the sprite to essentially move in a random walk pattern, however two parameters must be exposed:



  1. A typical random walk is equally likely to increase or decrease the distance to any given Target (plus the small chance of tangential movement). I must be able to bias my random walk such that, while still random, the direction on which the sprite "decides" should be more likely to bring it closer to Target.

  2. The random walk should be "smooth"- the sprite should not rapidly change direction, as this will look like it's "flickering" or "trembling" to the player. It should gradually veer this way or that, moving randomly, while slowly getting closer when averaged.


What is a good, simple way to do this? If possible, give the answer as a Vector2 RandomWalk(Vector2 target) method.


I already have a NextGaussian(mean, stdev) method available, if that is helpful.



Answer



I would take the "wander" steering-behavior (source code can be found here) and tweak it in a way so that the random numbers are biased towards your target.


tense - "If something was" vs "If something were"


Which of these sentences is correct, and why?





  1. "What if the Moon was a Disco ball?" or




  2. "What if the Moon were a Disco ball?"





Answer



We use the preterite (past tense form) when expressing a counterfactuality.




  • If she loved me, I would change my job (but she doesn't love me).


But when it's a form of the verb to be, we can use "were" in place of it.



  • What if the Moon was/were a Disco ball (but it's not).


This form is known as irrealis were. It isn't used for marking tense; it's a mood form indicating that it conveys a degree of remoteness from factuality.


The choice between were and was is a matter of style: were is somewhat more formal than was.





Huddleston and Pullum, A Student's Introduction to English Grammar


opengl - GL_DEPTH_COMPONENT vs GL_DEPTH_COMPONENT32


I googled like crazy and checked the OpenGL documentations but I couldn't find out how the precision of a depth buffer created using GL_DEPTH_COMPONENT is chosen.



As far as I know the precision is implementation dependent. But how will the precision be chosen? Will it always use the highest precision possible or rather the fastest one? Or is no general answer possible?


Shoud I always go with GL_DEPTH_COMPONENT32 instead?



Answer



For a basic, unsized internal format like GL_DEPTH_COMPONENT, the implementation chooses a resolution. The implementation may only used the format and type parameters to choose an internal format, but otherwise the format is up for the implementation to choose.


GL_DEPTH_COMPONENT32 is probably overkill, and as of 4.5, isn't a required format for OpenGL implementations to support (though 16 and 24 bit ones are). Consider that higher resolution depth buffers may not be as performant.


The exact requirements are documented in the OpenGL specification. On the 4.5 Compatibility spec, it is documented on section 8.5, page 230.


nouns - Friend or Friends in this sentence


I came across this English sentence when I was reading an article:




Have you ever met anyone on holiday who you were friends with at school or university?



Wasn't it supposed to be "friend" in place of "friends" there?




Wednesday, September 25, 2019

Which game engine is ideal for a 3D RPG?



I am thinking about making a small RPG. I know some basics of openGL, but I do not want create my own engine.


My criteria are:



  1. Ease of use

  2. Can do rpg game

  3. 3D



Which game engine is ideal for a 3D RPG?



Answer



it is absolutely Unity3D, and the basic version is for free.


http://unity3d.com/


Good luck


Tuesday, September 24, 2019

idioms - Etymology of "dog slow"


When I think of dogs I have an image of them being fast animals, running and jumping, chasing a ball or another dog.


So, I am surprised that dog slow means very slow.


What is the etymology of this expression?


Usage in the wild (1 2):



Keep in mind that StackTrace is dog slow - so use it sparingly.


Why is android's String.format dog slow?





word usage - I have "a doubt" about whether this phrase is acceptable English


To my (British) ear, it never sounds correct to say you have a doubt about something.


I expect that doubt to be pluralised, even if there's only one specific thing that I'm doubtful of, in one specific way, so I would always say "I have doubts about something".


Answers to this ELU question say that using doubt as a synonym for question is "Indian English". That seems to be the case in this ELL question which starts with "I have a doubt on my construction", because the OP really is saying "I have a question" (which he goes on to actually ask). Okay, it should have been a question/doubt about something, not on, but I'm not concerned with that detail here.



But in another ELL question the OP says "...there is a doubt that can I use [some construction]". In that case it's not easy to see how the word doubt can be replaced with question.


I don't have a problem with, for example, "The reason for my doubt is [some reason]", because there I interpret it as doubt=uncertainty (a state of mind, syntactically equivalent to words like happiness, agitation, sorrow, etc.). But you certainly can't "have a happiness about something". So my question is...



Is it acceptable today to use singular noun doubt in any contexts where it means something other than state of mental uncertainty? If so, what are those contexts?




Answer



Because doubt is an old word (the OED attests it from 1225) there are a number of nuances of meaning. In summary, with my numbers not OED's:




  1. A subjective state of uncertainty about the truth or reality of something;


  2. (plural) A feeling of uncertainty as to something;

  3. The condition of being objectively uncertain;

  4. A state of affairs which gives rise to uncertainty;

  5. A matter or point involved in uncertainty; a difficulty (Obsolete);

  6. Apprehension, dread, fear (Obsolete);

  7. A thing to be dreaded; danger, risk (Obsolete).



As a singular noun, it is decidedly abstract and refers to a state of being. Thus one can be in doubt about something. As a mass noun referring to a state of being, doubt would not normally be pluralised.


When it refers to a particular feeling of uncertainty it is pluralised. Thus if one has that feeling, one has doubts. One does not "have a doubt" because the singular doubt refers to a state of being; senses 5, 6 and 7 which refer to particular things are obsolete in Standard English.



The uses which are obsolete in Standard English may have survived or been resurrected in other dialects. The ELU references say that it does occur in Indian English.


physics - Pros and cons of different integrators



When creating things like physics in games you need an integrator. I've seen Verlet integration mentioned several places as a great alternative to Euler integration. For instance in the famous document by Thomas Jakobsen. However in this article Glenn Fiedler writes:




Rather than introduce you to the vast array of different integrators that exist, I’m going to cut to the chase and go straight to the best. This integrator is called the Runge Kutta order 4 integrator aka RK4.



So apparently there's no silver bullet. What is the pros and cons of different integrators? Regarding simplicity, speed, accuracy, stability, etc. Which integrators is most suitable for which types of games? When would you use Verlet, RK4 or others? Should you ever use Euler?



Answer



Pros and cons of both methods:


RK4 Pros:



  1. accuracy (thanks to its better approximation series it yields a 4th order precission)

  2. artificial/inherently induced damping (a bit like implicit methods do it) adds stability (whereas a simple Euler step doesn't - it does the opposite actually, introducing ghost energy that builds up and could plunge the system into chaos)



RK4 Cons:



  1. computation expense: while not that demanding in comparison to implicit methods or hybrid IMEX methods, RK4 is 4 times more expensive than the explicit Euler since it requires that many more function evaluations. This shows when aiming for the bleeding edge of optimization.

  2. still unstable: depending on the types of forces involved, RK4 can be just as unstable as Euler. On average, RK4 is a bit more stable and tends to draw this benefit from its endowed damping "skills".

  3. Non-symplectic: numerical damping comes with a cost - you cannot simulate systems where energy/volume/etc. loss shouldn't apply a visible effect over time (e.g. Molecular Dynamics, Potential Field derived forces, variational problems)


Verlet Pros:



  1. once or two times the complexity of an Euler step (depending on your Verlet flavour: position or velocity).

  2. symplectic: conserves internal energy


  3. second order accuracy: many games do not require high precision floating point results, and second order is more than pleasing for the eye in a game scenario (plus: it was used in a non-gaming scenario simulation when it was "discovered", so it's not that bad)


Verlet Cons:



  1. stable, but still: probably the best explicit method in terms of stability. It tends to win the edge when hard constraints are added to the system, thus allowing for less head-aches when implementing projected constraints in position based dynamics engines. It sets off to infinity if the system is perturbed with large external forces and no damping/friction is added. Even so, there are certain numerically imposed limits to how large the internal (spring) forces can be, but they're higher on average than what RK4 can do

  2. lower accuracy: not useful if you want high precission estimations

  3. requires, on average, smaller time-steps than RK4 for some simulations (RK4 benefits from both its accuracy and internal damping)


Using one over the other depends on the scenario. If stiffness and large external forces and virtual energies are a problem, then consider other methods having the "implicit" word in their description/title.





Note some authors/books use the term semi-implicit Euler for an actual explicit Euler integrator called the symplectic Euler method (or Euler Cromer) from which Verlet is actually derived. Verlet is also called by some people the "leapfrog method". Velocity Verlet and the midpoint method are fairly similar since an estimation at a time step of t + 0.5*dt is required for a predictor-corrector-like step. IMEX methods (implicit-explicit) are also used to name two similar but not identical approaches: separate the computations into stiff and non-stiff parts and use different integrators on them (the explicit for non-stiff, implicit for stiff) OR solve for the velocity with an implicit update step and update the position in an explicit manner (this is a hybrid semi-implicit method falling on the IMEX class of methods because the stiff parts affect the acceleration computation the most). Implicit methods are more cumbersome and require solving a system of simultaneous non-linear equations for the entire configuration. Implicit methods are used for deformable bodies and usually aren't used for decoupled rigid bodies.


As stated in one of the comments, if you can, do not use Euler. Use either the midpoint method, the semi-implicit Euler or, at the same expense, the position-Verlet. All of them have slightly higher accuracy and sensibly more stability than the explicit Euler integrator.


Recommended mini-comparison reading:


http://wiki.vdrift.net/Numerical_Integration


c# - How do I achieve supersampling / anti-aliasing in pixel shaders?


I am trying to write a couple pixel shaders to apply to images similar to Photoshop effects. For example this effect:



enter image description here


But I noticed there is aliasing in my resulting image (the above image is a sample from the linked website).


What can I do to prevent this? I couldn't find any article that explains how to solve this. I read some techniques like rendering in a higher resolution and then downsizing the image, but I need to solve this in a pixel shader capacity.




Monday, September 23, 2019

Gathering Stats from a StarCraft 2 game


One of the maps I've played, nicknamed SotiS (DoTA in SC2) has the ability to maintain stats, which are sent back to their own server.


Does anybody know how this is done?




Capitalizing family members' names (i.e. nouns, NOT proper nouns)


My daughter's English text book has a note which reads if you are directly talking to a person about the only person in your house, it can be capitalized.


For example:



"Mommy, have you seen my tab?"
"What would I do with it? Ask your Sister. She's fond of playing on it"



I want to confirm the capitalization of 'sister' here. This is new to me, actually!


And yes, it has nothing to do with emphasizing 'sister' that many may think the reason of capitalizing. Say--




"Yes, last night I asked Mommy about it, but then she gave a reluctant smile!"




Answer



From the book 'Painless Grammar' by Rebecca, PhD


Capitalize 'mom' and 'dad' when you are calling your parent's name but not when you refer to 'my mom' and 'my dad'.


CAPS



Hi Mom! Welcome home, Dad



NO CAPS




My father and my mother are busy. Could your mom or dad drive us to the movie?



pronouns - "It is" or "it are"


Does it always agree with a singular verb?



For example, does one say (i) or rather (ii)?



  • (i) It is the birds he is chasing away.

  • (ii) It are the birds he is chasing away.



Answer



A verb and its subject generally agree in number:



It is the birds he is chasing away.
The Great Lakes are the largest surface freshwater system on the Earth. (example from epa.gov)




In some dialects and in limited situations, agreement can be notional instead. In that case, the way you're thinking about it (as either singular or plural) is more important than its grammatical form:



%The Clash are a well-known band. (example from Wikipedia)



But agreement with it is never notional. It is always singular, so the following sentence is unacceptable:



*It are a well-known band.



Some subjects are conjoined (consisting of at least two conjuncts, A and B), in which case the verb typically takes plural agreement, even if the individual conjuncts are singular:




He and I are a couple.
Both he and it are far too valuable to be anywhere but a secure installation. (example from COCA)



As you can see, it is sometimes followed by are in these cases because agreement is with the entire subject he and it, not just with it, and this subject is plural.


Other subjects are disjoined (consisting of at least two disjuncts, A or B), and in this case the verb generally agrees with each disjunct individually:


  ‹êœ±ÉªÉ´É¢á´œÊŸá´€Ê€› or ‹êœ±ÉªÉ´É¢á´œÊŸá´€Ê€› is


    or


  ‹á´˜ÊŸá´œÊ€á´€ÊŸ› or ‹á´˜ÊŸá´œÊ€á´€ÊŸ› are


But sometimes singular and plural noun phrases are coordinated, and we end up with a number conflict. This conflict has to be resolved somehow, and different speakers have different preferences for doing so. For example, some prefer agreement with the plural disjunct, while others prefer agreement with the closer disjunct:



  ‹á´˜ÊŸá´œÊ€á´€ÊŸ› or ‹êœ±ÉªÉ´É¢á´œÊŸá´€Ê€› is    ← agreement with the closer disjunct
  ‹á´˜ÊŸá´œÊ€á´€ÊŸ› or ‹êœ±ÉªÉ´É¢á´œÊŸá´€Ê€› are  ← agreement with the plural disjunct  


But if we put the plural disjunct second, then the plural disjunct is the closer disjunct:


  ‹êœ±ÉªÉ´É¢á´œÊŸá´€Ê€› or ‹á´˜ÊŸá´œÊ€á´€ÊŸ› are  ← agreement with the closer disjunct
  ‹êœ±ÉªÉ´É¢á´œÊŸá´€Ê€› or ‹á´˜ÊŸá´œÊ€á´€ÊŸ› are  ← agreement with the plural disjunct


So in these cases we can make both groups happy by putting the plural disjunct second. Many style guides recommend doing exactly this. However, some speakers would prefer to avoid this conflict altogether; these speakers would prefer rewriting the sentence so that they don't have to pick one or the other.




In this answer, I've used the following symbols:
  % marks a sentence that is considered standard English by some speakers but not others
  * marks a sentence that is considered nonstandard by all speakers



The matter of agreement with conjoined subjects is actually more complicated than this. See e.g. Heidi Lorimor's thesis, Conjunctions and Grammatical Agreement.


grammar - "Black and white dogs": ambiguity with coordinate adjectives


A black and a white dog means "two dogs".
A black and white dog means "one dog".


Then what about black and white dogs?


Does this mean two things? "Dogs, each of black and white color" and "dogs of black and dogs of white"?




Sunday, September 22, 2019

iphone - 2D non-tile based map editor



I am currently developing a relatively simple 2D, topdown oriented adventure game for the iPhone and was wondering what would be the easiest way to create the maps for my game. I figured I would need some kind of visual editor that would give me immediate feedback and would allow me to place all objects in the world exactly where I want them. I could then load the saved representation of the world I create in the editor in my game.


So, I am looking for a simple map editor that allows me to do this. All the objects in my game are simply textured rectangles build up from two triangles. All I need to be able to do is position different rectangles/objects in the map, and give them a texture. I am using texture atlases, so it would be useful to be able to assign portions of textures to the objects. I then need to be able to extract all the objects from the saved representation of my maps, together with the name/identifier of the texture(atlas) they use, and the area of the texture atlas.


I have looked at some tile-based map editors like Tiled and Ogmo, but they don't seem to be able to do what I want. Any suggestions?


EDIT: a more concrete example: something like the GameMaker level editor, but then with added export functionality in a handy format.





Nested possessives


Let's imagine the following situation:


My mom has a boyfriend and her boyfriend has a car.


I borrowed this car and I want to tell another person who is the owner of this car, I believe I have to use 's twice in this sentence:




This is my mom's boyfriend's car.



Honestly I think that this is correct, but I am unsure if I can use the 's twice or more in this sentence, is this correct? Could I go even further than that?



This is my mom's boyfriend's brother's car.



Thanks a lot!



Answer



Yep, it works fine.






  1. my mom



    This is a noun phrase (NP). The head is mom, and its determiner is my.



    [my mom]'s



    We've added the genitive 's, so now it's a genitive noun phrase. Genitive NPs can be determiners in larger noun phrases:






  2. [my mom]'s boyfriend



    Now we've made a larger NP. Its determiner is the genitive NP [my mom]'s, which we made in step one.



    [[my mom]'s boyfriend]'s



    Now we've added the genitive 's again, so we've got a genitive NP again.






  3. [[my mom]'s boyfriend]'s brother



    This whole thing is an NP. Its determiner is the genitive NP [[my mom]'s boyfriend]'s.



    [[[my mom]'s boyfriend]'s brother]'s



    Now we've made it into a genitive NP. Again.






  4. [[[my mom]'s boyfriend]'s brother]'s car



    This is another NP. Its determiner is the genitive NP [[[my mom]'s boyfriend]'s brother]'s.




As you can see, we're repeating the same operations over and over. You can do it as much as you like. Eventually you'll probably amuse or confuse your conversation partner, though.


xna - How can I acheive a smooth 2D lighting effect?


I'm making a 2D tile based game in XNA.


Currently my lightning looks like this.


How can I get it to look like this?


Instead of each block having its own tint, it has a smooth overlay.


I'm assuming some sort of shader, and to pass the lighting values for the surrounding tiles to the shader, but I'm a beginner with shaders so I'm not sure.


My current lighting calculates the light, and then passes it to a SpriteBatch and draws with the tint parameter. Each tile has a Color that is calculated before draw in my lighting algorithm, which is used for the tint.


Here is an example on how I currently calculate lighting (I do this from left, right, and bottom too, but I got really tired of doing this frame by frame...)


enter image description here



So actually getting and drawing the light so far is no problem!


I have seen countless tutorials on fog of war and using gradient circular overlays to create smooth lightning, but I already have a nice method to assign each tile a lightning value, it just needs to be smoothed between them.


So to review



  • Calculate Lighting (Done)

  • Draw Tiles (Done, I know I will need to modify it for the shader)

  • Shade tiles (How to pass values and apply "gradient)



Answer



How about something like this?



Don't draw your lighting by tinting your tile sprites. Draw your unlit tiles to a render target, then draw the tile lights to a second render target, representing each one as a grayscale rectangle covering the area of the tile. To render the final scene, use a shader to combine the two render targets, darkening each pixel of the first according to the value of the second.


This will produce exactly what you have now. That doesn't help you, so let's change it a bit.


Change the dimensions of your lightmap render target so that each tile is represented by a single pixel, rather than a rectangular area. When compositing the final scene, use a sampler state with linear filtering. Otherwise leave everything else the same.


Assuming you've written your shader correctly the lightmap should be effectively "scaled up" during compositing. This will get you a nice gradient effect for free via the graphics device's texture sampler.


You may also be able to cut out the shader and do this more simply with a 'darkening' BlendState, but I'd have to experiment with it before I could give you the specifics.


UPDATE


I had some time today to actually mock this up. The answer above reflects my habit of using shaders as my first answer to everything, but in this case they're not actually necessary and their use needlessly complicates things.


As I suggested, you can accomplish exactly the same effect using a custom BlendState. Specifically, this custom BlendState:


BlendState Multiply = new BlendState()
{

AlphaSourceBlend = Blend.DestinationAlpha,
AlphaDestinationBlend = Blend.Zero,
AlphaBlendFunction = BlendFunction.Add,
ColorSourceBlend = Blend.DestinationColor,
ColorDestinationBlend = Blend.Zero,
ColorBlendFunction = BlendFunction.Add
};

The blending equation is


result = (source * sourceBlendFactor) blendFunction (dest * destBlendFactor)


So with our custom BlendState, that becomes


result = (lightmapColor * destinationColor) + (0)

Which means that a source color of pure white (1, 1, 1, 1) will preserve the destination color, a source color of pure black (0, 0, 0, 1) will darken the destination color to pure black, and any shade of gray in between will darken the destination color by a middling amount.


To put this into practice, first do whatever you need to do to create your lightmap:


var lightmap = GetLightmapRenderTarget();

Then just draw your unlit scene directly to the backbuffer as you normally would:


spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend);

/* draw the world here */
spriteBatch.End();

Then draw the lightmap using the custom BlendState:


var offsetX = 0; // you'll need to set these values to whatever offset is necessary
var offsetY = 0; // to align the lightmap with the map tiles currently being drawn
var width = lightmapWidthInTiles * tileWidth;
var height = lightmapHeightInTiles * tileHeight;

spriteBatch.Begin(SpriteSortMode.Immediate, Multiply);

spriteBatch.Draw(lightmap, new Rectangle(offsetX, offsetY, width, height), Color.White);
spriteBatch.End();

This will multiply the destination color (unlit tiles) by the source color (lightmap), appropriately darkening unlit tiles, and creating a gradient effect as a result of the lightmap texture being scaled up to the necessary size.


level design - How can I create borders in an open-world game that don't feel artificial?


When creating open-world maps, a big issue to take into consideration is how "borders" of sorts are implemented. Obviously, in an open-world game, there shouldn't be invisible-wall borders, as it ruins immersion, and makes the game feel more "artificial".


I've done a little bit of research online and I've found the following methods:



  • Have the map be an island, surrounded by water that will kill you if you venture out too far.

  • Have the map be surrounded by mountains that are much too steep to climb over.

  • A combination of the above; mountains plus a body of water. The Elder Scrolls V: Skyrim does something like this but does have places where paths lead out of the world. (Thanks @Pharap)


These seem like the best methods but I'm wondering if there are any other methods that can be used to create borders in an open world without ruining immersion.




Answer



Just some quick additional suggestions, that sometimes complement what others have already said.


1) water solution: I never understood why killing the player with a shark or something. Just let him/her swim infinitely (like with a proceduraly generated infinite ocean). That alone would closer resemble the idea of how distant it would be in real life to cross an ocean by swimming. The player would just get tired at some point of going forward and then would decide to reload (because going back all over again would be just as tedious).


Of course, if you have modern boats, ships, jet-skis, etc, and the concept of gas as resource, that works well too and then it becomes part of the item number 4 below, since the player can just sail until running out of gas. Then, if he/she can swim, it becomes again a problem of just letting him/her swim forever.


2) scene barrier: it does not have to be mountains. A dense forest, as someone else told here. A canyon with a beautiful view. A part of a city with too many buildings in the way and the only possible streets blocked. A huge fire destroying parts of a city, or a gas leak, or a radiation accident in part of a city that blocks the way. If the city was invaded by aliens, maybe the gigantic spaceship is itself blocking the path to other parts of the city as it crushed when arriving. Or, why not, you can have flying islands like in Zelda Skyward Sword, where the boundary is given by not-falling-to-death.


3) challenging who tries: you can always increase the challenge exponentially as far as the player goes. Imagine an open-world in the country fields. The player crosses farms in the direction of the inner-lands of your world. More and more enemies show up with no power-up, health kits or something in the way. If you make these field camps procedural and increase the challenge, the player will eventually get killed without having the feeling that he/she was cheated by an artificial border. I like this approach because it even creates in the mind of the players the impression that there might be something hidden ahead (of course, you have to take care and don't abuse on this illusion, to avoid the players becoming mad at you!).


4) lack of resources: if a player has to eat/take medicine/whatever, and/or if vehicles have gas, you don't need boundaries. Let the player and/or its vehicles die. That is particularly useful in a space game, where creating a non-artificial barrier is quite difficult. In other words, if that suits your gameplay framework, make the open world finite by not being accessible due to being impossible to accumulate resources to go beyond a give distance.




I won't keep going with a ton of suggestions based on storyline and gameplay. My reasons: first I don't know which type of game we are talking about. Second: frankly, as nice as it can be to have a story-line or gameplay related solution such as failing missions because some hostage has died when you tried to get out of the borders, I don't think that is exactly what you meant and, on the contrary, I found those to be usually harmful for immersion. But if you happen to be interested in these types too, let me know and I can drop some ideas that I have either seen or thought.


Also, as a general point, notice that more than once I touched procedural generation. Really, I think procedural generation is your friend here. You don't need to use it only for having infinite worlds. I always say we should start using it much more often to make the finite open-games more realistic and diverse. Using it for a fake endless border would be a neat use.



relative clauses - a way that most people think {is / it is} wrong


I was reading definition/meaning of the word "perverse" in Oxford Dictionary, came across :



showing deliberate determination to behave in a way that most people think is wrong, unacceptable or unreasonable



Shouldn't it be :




showing deliberate determination to behave in a way that most people think it is wrong, unacceptable or unreasonable




Answer



Your it is unncessary.


You understand correctly that there is an empty 'slot' in the sentence—the subject of the clause is wrong &c.


There are two ways of looking at what's going on:




  • In traditional grammar the that is understood to be a "relative pronoun" which 'stands for' a "referent" or "antecedent", way, and acts as the displaced subject of is wrong &c





  • Many contemporary grammars call the that a "relativizer", a sort of variable which points backward toward the referent, the variable's 'value', and forward toward an empty slot ("gap" or "trace"); it instructs the hearer or reader to find the gap and fill it with the value.




The two analyses amount to pretty much the same thing: that empty slot is a feature, not a bug; StackExchange would tag it .


It is not ungrammatical to fill the gap with it as you do; this happens frequently in speech. (Grammarians call it a resumptive pronoun, one which 'resumes' mention of the referent.) However, it is redundant, and is deprecated in writing.


word usage - Is "snows" ever used as noun?



In Italian, nevi (the plural of neve, "snow") is used in some expressions, such as l'uomo delle nevi (a.k.a. Yeti), and le nevi dei Pirenei. (The last expression is referring to the Pyrenees, but I could use it when referring to any mountain belt.)


Is snows ever used as noun (even if in set phrases), or is it never used as noun?



Answer



'Snow' is what is called a 'mass noun'. Like 'water' or 'traffic', it already describes a collection of things (a mass) and so there isn't likely a number of such items, just some of it.



'The snow that fell overnight was deep' is correct.


'The snows that fell overnight were deep' is incorrect (or poetic)



You can however talk about multiple instances of water, 'the glasses of water' which can be said grammatically as 'the waters in those glasses' but that is a strange transformation, almost poetic, and surely to be avoided in speech and most writing.


The same goes for 'snow'.




'The snows that fell in each of the towns were deep.'



works and occurs, but is a somewhat strange way to say it. One would more likely reword it to avoid the strange plural.



'The snow that fell in each of the towns was deep.'



or to emphasize that a snowfall occurred in a number of towns, and though the depth was different in each one, the amounts were all deep.



'The different amounts of snow in the towns were all deep.'




sounds much better. So the answer is yes, 'snows' can be used as a plural noun but it is not common and is not natural sounding. So if you are translating from a language with plural snow, you should reword to avoid the plural.


For a comparison here is the google nGram comparing 'the snow' and 'the snows':


enter image description here


Saturday, September 21, 2019

xna - Terrain Generation for Tile-Based 2D Platformer


I'm currently working on a tile-based 2D platformer similar to Terraria in some ways, although I'm having difficulty with the terrain generation. I have some basics done, although they do not come out as anything useful.


I have tried a few different techniques like Perlin Noise and read about some others such as Midpoint Displacement, although I'm not sure what one would be best, or a combination of different techniques to generate different areas. (Such as Midpoint Displacement for the general shape of the terrain and Perlin Noise for the caves.)



I have found an excellent explanation of how I could layer it up with the Accidental Noise Library, although it is in C++, and I do not know enough C++ to compile it into a DLL that I can use from C#. I have tried to copy this in C#, although, I do not know how I can merge two effects together (the gradient for the general base, and then the fractal for detail).


Currently I am using a Plasma Fractal and the results are extremely varied. For example it can generate terrain where there is hardly any surface, or it can generate terrain where there is no surface at all.


An example of an okay map, would be better with some more improvements, though. (Black is solid, white is air):


Good map


And an example of a terrible map. (Black is solid, white is air):


Terrible map


Basically, what I'm asking is, what would be a better way of generating the terrain, or forcing it to make sure that there is a reasonable amount of surface area, with the generation time as quick as possible. Or, alternatively, how I would be able to achieve the same result as the Accidental Noise Library, but in C#.


Any examples would be very much appreciated.



Answer



I would try sticking with Perlin noise, but adding a weight to it based on height, to ensure a certain average density at certain altitudes. To quote part of Notch's post on Minecraft terrain generation:




So I switched the system over into a similar system based off 3D Perlin noise. Instead of sampling the “ground height”, I treated the noise value as the “density”, where anything lower than 0 would be air, and anything higher than or equal to 0 would be ground. To make sure the bottom layer is solid and the top isn’t, I just add the height (offset by the water level) to the sampled result.



Essentially, you're taking a little slice of a Minecraft terrain. So generate 2D Perlin noise, but weight it so that anything above a certain point is likely to be air, and anything below a certain point is likely to be earth.


This will give you a good ground terrain, with some overhangs and interesting features, as well as some caves and floating islands. (If you don't want floating islands, you can test for them and remove them manually.) This method won't give you things like tunnels, so you'll want a method for adding those in after terrain generation, such as a random-walk.


reported speech - Is it gramatically correct to say 'She said that she hadn't got any money?


In MyGrammarLab Elementary A1/A2 by Mark Foley and Diane Hall Pearson 2012 I came across the following example sentence in the unit covering Reported Speech statements: 'I haven't got any money.' - She said she hadn't got any money.



In all the texbooks I have ever read they say that we form the negative past simple of any verb with the auxiliary did for all persons and the particle 'not'. Somehow it is not the case here. And they also teach us that the form of 'to have got' in the past simple tense is 'had' NOT 'had got'. So, my question is: is it grammatically correct (because I am interested whether such a sentence would be penalised at any EFL exam a student might take) to make the above changes or not?


The task of the exersice I am citing here is the following: Complete the reported statements with verbs, pronouns or possessives.


In my opinion it is rather unreasonable to give such a controversial example sentence at such a level bearing in mind that students have been exposed to Reported Speech for the first time.




prepositions - "Stay home" or "stay at home" – which is correct and why?





Stay home.


Stay at home.



When "home" functions as an adverb, it can modify the verb "stay". There are other examples, such as "go home",but there is no expression:



Go to home.



So I wonder which one is correct.





game industry - How can I handle copyrighted music?


I have a curious question regarding on musics used in music rhythm game. In Guitar Hero for example, they used all different music albums in one program. Then, each album requires to ask permission to the owner, composer of the music, or the copyright owner of the music. Let's say, if you used 15 albums for the music rhythm game, then you have to contact 15 copyright owners and it might be that, for the game developer, that the profit earned goes to the copyright owner or owner of this music. For the independent game developers, was it okay if either used the copyright music by just mentioning the name of the singer included in the credits and in the music select screen or use the non-popular/old music that about 50 years ago? And, does still earn money for the indie game developers by making free downloadable game?



Answer



Neither being an indie developer, nor releasing game for free, doesn't grant you some additional rights implicitly. You can either need to have agreement with rights owner, or use music that is in public domain or other license (like CC license) that allows some sort of free usage.


Also as Markus correctly mentioned in comment, Public Domain is a tricky thing. So I guess you are more limited in classics than it may seems.


Friday, September 20, 2019

phrase choice - "grip the bar closely" or "grip the bar with your hand close to each other"?


Tell me please what is the most natuaral way to say that I want someone to grab a barbell with hands close to each. Here are exaples:



Grip the bar closely to activate your triceps before doing a close-grip barbell barbell bench press!


Grip the bar with your hand close to each other to activate your triceps before doing a close-grip barbell press.



The second varian is wordy, so I would like to know a shorter natural version of saying that in a less short fasion.




Answer



I agree with Jason's point that specificity is more important than brevity if you can injure yourself by doing that lift incorrectly. That said, let's look at another linguistic option open to you.



Grip the bar with hands close together for the barbell bench press.


For the barbell bench press, grip the bar with hands close together.



Not the absence of determiner before hands and the use of the with "barbell bench press", and the phrase close together.


grammaticality - Happiness 'from' vs 'of' vs 'to'?



utilitarianism = the belief that the right course of action is the one that will produce the greatest happiness of the greatest number of people




I would've first chosen happiness + from or to, so would someone please explain the preposition of here? Could others be used? If so, which? What are the similarities and differences?


2. What's this phenomenon called? Does it occur to other words?



Answer




To produce the greatest happiness of the greatest number of people.



The sentence implies the happiness will belong to the people, thus, they will be happy.



To produce the greatest happiness from the greatest number of people.




The sentence implies the happines will be produced using people. Such process could make them rather unhappy if overdone. Who is to become happy is not mentioned here, it could be a single person or multiple persons. Maybe the happiness is to be accumulated and returned to the people from whom it was produced, at a later date.



To produce the greatest happiness to the greatest number of people.



This looks ungrammatical to me. We can "produce something to someone", but this is usually said in formal contexts, such as "to produce papers, documents, drafts, estimates..", and the recipient is usually a government, a regulatory body, the police etc.


Of is a possessive preposition. I quote from Wikipedia:



the child's bag might also be expressed as the bag of the child


our cats' mother might be expressed as the mother of our cats




Hence,



The people's happiness -> The happiness of the people.



When you choose the prepositions from or to, they start to work with the verb produce, resulting in the combinations produce something from and produce something to.



I produced my documents to the court.


We produce cottage cheese from milk.



The proposition of, on the other hand, does not combine with the verb produce. It combines with the noun word happiness.



This is not always so: of could combine with, or depend upon, other verbs. Different prepositions have different dependency patterns:



I cured him of his tooth-ache.



A poetic example of of being dependent upon a verb:



Wisdom enough to leech us of our ill
Is daily spun; but there exists no loom
To weave it into fabric; undefiled
Proceeds pure Science, and has her say; but still

Upon this world from the collective womb
Is spewed all day the red triumphant child.



translation - Which one do you call "pepper", pimienta o pimiento?


So I always thought pepper was the english equivalent of the spanish word pimienta


a bowl of peppercorns



But now I look the translation for pimiento and it also returns pepper (Google Translator)


yellow, orange, red, and green bell peppers


Do you call both pimienta and pimiento "pepper" or the translator isnt working properly?



Answer



Yes, most English speakers do call both foods "pepper". There are few ways to distinguish them if you need to.


This is also known as black pepper (or red pepper, depending on the color): Black pepper kernels


On the left, you can see some ground pepper, while on the right there are some pepper kernels. You can refer to the small individual balls as pepper kernels or peppercorns.




The second kind you posted are also known as bell peppers, because they are shaped like bells. yellow, red, and green bell peppers
You can distinguish these by color. (E.g. red bell pepper, green bell pepper)





Note that these are also peppers.


a variety of peppers with labels


of phrases - The definite article before the word "consistency" and "of"


Do I need to use "the" in the following sentence?


Here goes:



"we need the consistency of performance."



What I saw is that usually "the" is dropped before the word, but I cannot get a handle why. The word "performance" modifies the word "consistency" so I think the article is necessary.


Tell me please if I am wrong.




Answer



Abstract nouns such as "consistency", "beauty", "quality" normally don't take an article, unless we are talking about a specific instance.


So if we were reviewing a particular show or concert we might talk about "the consistency of this performance" or "the consistency of the performance"; if we are talking about an actor's prowess we might say "the consistency of his performance" (even if we are not meaning a single performance, we have still specified it to that actor).


But if we are talking in general, we would say "consistency of performance".


There is not always a clear distinction, and in some cases it is possible with or without an article.


[I've just realised, rereading your post, that it probably relates to performance at work rather than artistic performance, but my reply still works.]


Is there a known most efficient version of A* search algorithm?



Is there a known 'most efficient' version of the A* search algorithm? I know some people write papers on the most efficient way to compute common operations, has this been done for A*?



Answer



If you don't mind bibliography, take this list as a starting point. It's a series of articles from the Game Programming Gems and the AI Game Programming Wisdom series, with the most relevant ones being:



  • Beyond A* - Game Programming Gems 5

  • Advanced Pathfinding with Minimal Replanning Cost: Dynamic A Star (D*) - Game Programming Gems 5

  • How to Achieve Lightning Fast A* - AI Game Programming Wisdom

  • Practical Optimizations for A* Path Generation - AI Game Programming Wisdom

  • A* Aesthetic Optimizations - Game Programming Gems

  • A* Speed Optimizations - Game Programming Gems



If I remember correctly from what I've read, there's no ultimate version of A* being presented, but rather a series of optimization and improvements you can make to increase its performance or memory usage in specific scenarios.




I wanted to add a bit more detail since I own these books, but I won't have access to them until the end of the month. Here's what I can somewhat recall from memory though. First, there are several optimization you can apply while using a regular A* implementation.


The most significant change you can make is simplifying the search space. There are many different ways to represent your search space, each with pros and cons, and choosing the correct one for the job is pretty much the most deciding factor in A* performance. The most common space representations are using a grid, a navigation mesh or a visibility graph.


Tweaking the heuristic can also affect the speed of your pathfinding. For instance, they say that the heuristic has to be admissible (i.e. it never overestimates the actual cost) for A* to find you the best path. But sometimes if you overestimate the heuristic a little it will speed up the search and the paths returned will be similar enough (maybe not perfect every time, but significantly close).


Finally, there are many variations on the algorithm itself to make it work under different circunstances, for instance, just to name a few:



  • D* (Dynamic) - Dynamic in the sense that it works under the assumption that the terrain can change even while you're still looking for the path.

  • HPA* (Hierarchical) - Uses several layers at different abstraction levels to speed up the search. For instance, an higher level layer may simply connect rooms, while a lower level layer takes care of avoiding obstacles.


  • IDA* (Iterative Deepening) - Reduces memory usage in comparison with regular A* by using iterative deepening.


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