dinsdag 8 oktober 2019

C game: fastest way to sort 2d objects by distance

Sorting the 2d objects in my SunRacer game took 6300 counts with QuickSort. It was strange to me that a nearly sorted array was not sorted any faster. So I went to look for a better sort algorithm.
At this moment, I'm using the bucket sort algorithm, and sort each bucket with the insertion sort algorithm. Sorting the objects now take 185 counts according the SDL2 performance counter.

More details:
In my game, objects can have a distance from 0 to 1000.
I created 40 buckets and move all objects in one of these 40 buckets. This way, I have 40 small buckets with objects which are near to eachother. Sorting these buckets is faster because there are not many objects in each bucket. Insertion sort becomes slow on big arrays (50+ elements). My buckets are max. 50 elements.

The fastest way to place objects in a bucket is to compare each time with the half of the remaining buckets.
if (element->distance < 500) {
  if (element->distance < 250) { ... }
  else { .... }
} else {
  if (element->distance < 750) { ... }
  else { ...  }
}


Snellere atan2

float Globals::ApproxAtan2(float y, float x)
{
    const float n1 = 0.97239411f;
    const float n2 = -0.19194795f;
    float result = 0.0f;
    if (x != 0.0f)
    {
        const union { float flVal; Uint32 nVal; } tYSign = { y };
        const union { float flVal; Uint32 nVal; } tXSign = { x };
        if (fabsf(x) >= fabsf(y))
        {
            union { float flVal; Uint32 nVal; } tOffset = { PI_FLOAT };
            // Add or subtract PI based on y's sign.
            tOffset.nVal |= tYSign.nVal & 0x80000000u;
            // No offset if x is positive, so multiby 0 or based on x's sign.
            tOffset.nVal *= tXSign.nVal >> 31;
            result = tOffset.flVal;
            const float z = y / x;
            result += (n1 + n2 * z * z) * z;
        }
        else // Use atan(y/x) = pi/2 - atan(x/y) if |y/x| > 1.
        {
            union { float flVal; Uint32 nVal; } tOffset = { PI_2_FLOAT };
            // Add or subtract PI/2 based on y's sign.
            tOffset.nVal |= tYSign.nVal & 0x80000000u;
            result = tOffset.flVal;
            const float z = x / y;
            result -= (n1 + n2 * z * z) * z;
        }
    }
    else if (y > 0.0f)
    {
        result = PI_2_FLOAT;
    }
    else if (y < 0.0f)
    {
        result = -PI_2_FLOAT;
    }
    return result;
}

donderdag 3 oktober 2019

Turn off green lines Visual Studio

When you open a C/C++ project in Visual Studio 2019, a lot of green lines (squiggles) appear.
This can be turned off:
Options->Text Editor->C/C++-> Advanced-> Code Analysis-> Disable C++ Code Analysis Experience.