Author Archives: kingcrimsontenseconds

Unreal Engine 4 memo: How to create god ray / light shaft effect for trees using the volumetric fog?

To create the god ray / light shaft effect through trees, we should use the volumetric fog feature recently added to Unreal Engine. Google search will give us the following 3 references:

The thing is even after perusing the first 2 references you may still have a hard time implementing the desired effect. Here is a summary of the right steps that you need to follow to avoid hours of trial-and-errors:

  • Add the tree, directional light, exponential height fog to the map.
  • For the exponential height fog, check the option volumetric fog; to make the god rays more obvious, increase fog density; optionally, increase fog height falloff so that the fog is concentrated at lower altitude.
  • For the directional light, to make the god rays more obvious, increase the intensity, for example to 20 lux; to create light shafts between leaves, check light shaft bloom.
  • Critical: Ensure that the mobility property of both the tree and directional light is set to movable. Without this step, the tree would have wrong, static shadow, and the directional light would not be able to create the god rays in the fog.

The above steps end up applying volumetric fog effect on a global scale. Optionally we may follow the great presentation (starting at 14:24) to implement the local volumetric fog effect via the particle system.

Unreal Engine 4 memo: How to perform rotator interpolation correctly?

In order to let an actor transition from one rotator to another smoothly, function FMath::RInterpConstantTo() should be used. The official documentation on this function is too brief to be helpful. This article aims to clear up the confusion.

Add member function and variable declaration

First off, in the actor class declaration, add the following functions and variables. PerformRotationInterpWithDelay(Delay) is the public interface to be called outside the class. Its purpose is to halt for a duration of Delay, then let the actor rotate smoothly until the target rotator is reached, which in our example is simply FRotator::ZeroRotator.

UCLASS()
class QL_API AMyActor : public AActor
{
    GENERATED_BODY()

public:

    ...

    //------------------------------------------------------------
    // After Delay seconds, perform PerformRotationInterpCallback()
    // which sets bStartRotationInterp to true, and performs rotation interpolation
    // in Tick() until the rotation becomes FRotator::ZeroRotator
    //------------------------------------------------------------
    UFUNCTION(BlueprintCallable, Category = "C++Function")
    void PerformRotationInterpWithDelay(const float Delay);

protected:

    ...

    //------------------------------------------------------------
    //------------------------------------------------------------
    UFUNCTION()
    void PerformRotationInterpCallback();

    //------------------------------------------------------------
    //------------------------------------------------------------
    bool bStartRotationInterp;
}

Define the functions

Implementation detail of PerformRotationInterpWithDelay(Delay) is shown below. After Delay, function PerformRotationInterpCallback() is called, which simply sets the flag bStartRotationInterp, making the actor rotate in the next Tick() call.

For the static function FMath::RInterpConstantTo(), the first argument is the current actor rotator GetActorRotation(), not the initial actor rotator. The second argument is the target actor rotator, which is set to FRotator::ZeroRotator in this example. The third argument is the duration in second between two frames DeltaTime. The last argument is the interpolation speed not adequately explained in the documentation. Here is what it actually represents: For each call of FMath::RInterpConstantTo(), the pitch, yaw, roll of the actor are uniformly incremented by a value of k. k is first set to the difference between target rotator and current rotator, but then clamped by [-m, m], where m is equal to DeltaTime times the interpolation speed. An interpolation speed of S indicates a change in pitch, yaw, roll by S degree per second. FMath::RInterpConstantTo() returns the new rotator to be applied to the actor per Tick(). To take into account the finite precision of floating point arithmetic, currentRotation.Equals(targetRotation) is subsequently performed. If it evaluates to true, the flag bStartRotationInterp is unset, and the rotation stops.

//------------------------------------------------------------
//------------------------------------------------------------
void AMyActor::PerformRotationInterpWithDelay(const float Delay)
{
    GetWorldTimerManager().SetTimer(StartRotationDelayTimerHandle,
    this,
    &AMyActor::PerformRotationInterpCallback,
    1.0f, // time interval in second
    false, // loop
    Delay); // delay in second
}

//------------------------------------------------------------
//------------------------------------------------------------
void AMyActor::PerformRotationInterpCallback()
{
    bStartRotationInterp = true;
}

//------------------------------------------------------------
//------------------------------------------------------------
void AMyActor::Tick(float DeltaTime)
{
    Super::Tick(DeltaTime);

    ...

    // interp rotation
    if (bStartRotationInterp)
    {
        FRotator NewRotation = FMath::RInterpConstantTo(GetActorRotation(), FRotator::ZeroRotator, DeltaTime, 100.0f);
        SetActorRotation(NewRotation);

        if (GetActorRotation().Equals(FRotator::ZeroRotator))
        {
            bStartRotationInterp = false;
        }
    }
}

Porting code from Nvidia GPU to AMD : lesson learned

In the past several weeks I have been porting a codebase from Nvidia CUDA platform to AMD HIP. Several critical issues were encountered, some solved, some attributed to compiler bugs, some remaining unfathomable to me.

There are 3 important things I have learned so far from the painstaking debugging process.

  • An unsigned integer with n bits only allows 0~(n-1) times bitwise left shift (<<). Excess shifts lead to undefined behavior. For Nvidia platform, 0 bit will be added, whereas for AMD, 1 bit will be added!!!
  • Currently there is a serious compiler bug: the wavefront vote function __any(pred) , which is supposed to work like __any_sync(__activemask(), pred) in CUDA, yields incorrect result in divergent threads!!!
  • This is very easy to miss: the parameter of wavefront vote functions __any(pred), __all(pred), etc is a 32-bit integer for both Nvidia and AMD platforms. If, however, a 64-bit integer is passed to the function, higher bits will be truncated!!! The solution is to explicitly cast the 64-bit integer to bool, which is then implicitly cast to int.

FindNVML.cmake done correctly — how to have CMake find Nvidia Management Library (NVML) on Windows and Linux

Nvidia Management Library (NVML) is a powerful API to get and set GPU states. Currently there is a lack of official CMake support. The first couple of google search results point to a script on github, which unfortunately is only partially correct and does not work on Windows. Here we provide a working solution, tested on Scientific Linux 6 and Windows 10, with CUDA 9.1 and CMake 3.11.

The NVML API is spread across several locations:

  • Linux
    • Header: ${CUDA_INCLUDE_DIRS}/nvml.h
    • Shared library: ${CUDA_TOOLKIT_ROOT_DIR}/lib64/stubs/libnvidia-ml.so
  • Windows
    • Header: ${CUDA_INCLUDE_DIRS}/nvml.h
    • Shared library: C:/Program Files/NVIDIA Corporation/NVSMI/nvml.dll
    • Import library: ${CUDA_TOOLKIT_ROOT_DIR}/lib/x64/nvml.lib

It is critical to note that, on Windows a dynamic library (.dll) is accompanied by an import library (.lib), which is different from a static library (also .lib). In CMake the target binary should link to the import library (.lib) directly instead of the .dll file. With that, the correct FindNVML.cmake script is shown in listing 1.

Listing 1

# FindNVML.cmake

if(${CUDA_VERSION_STRING} VERSION_LESS "9.1")
    string(CONCAT ERROR_MSG "--> ARCHER: Current CUDA version "
                         ${CUDA_VERSION_STRING}
                         " is too old. Must upgrade it to 9.1 or newer.")
    message(FATAL_ERROR ${ERROR_MSG})
endif()

# windows, including both 32-bit and 64-bit
if(WIN32)
    set(NVML_NAMES nvml)
    set(NVML_LIB_DIR "${CUDA_TOOLKIT_ROOT_DIR}/lib/x64")
    set(NVML_INCLUDE_DIR ${CUDA_INCLUDE_DIRS})

    # .lib import library full path
    find_file(NVML_LIB_PATH
              NO_DEFAULT_PATH
              NAMES nvml.lib
              PATHS ${NVML_LIB_DIR})

    # .dll full path
    find_file(NVML_DLL_PATH
              NO_DEFAULT_PATH
              NAMES nvml.dll
              PATHS "C:/Program Files/NVIDIA Corporation/NVSMI")
# linux
elseif(UNIX AND NOT APPLE)
    set(NVML_NAMES nvidia-ml)
    set(NVML_LIB_DIR "${CUDA_TOOLKIT_ROOT_DIR}/lib64/stubs")
    set(NVML_INCLUDE_DIR ${CUDA_INCLUDE_DIRS})

    find_library(NVML_LIB_PATH
                 NO_DEFAULT_PATH
                 NAMES ${NVML_NAMES}
                 PATHS ${NVML_LIB_DIR})
else()
    message(FATAL_ERROR "Unsupported platform.")
endif()

find_path(NVML_INCLUDE_PATH
          NO_DEFAULT_PATH
          NAMES nvml.h
          PATHS ${NVML_INCLUDE_DIR})

include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(NVML DEFAULT_MSG NVML_LIB_PATH NVML_INCLUDE_PATH)

Once find_package(NVML) is called in user CMake code, two cache variables are generated: NVML_LIB_PATH and NVML_INCLUDE_PATH. For Windows, there is an additional NVML_DLL_PATH.

Far cry 5 is bad

This is what a triple A game looks like in 2018? What the fudge?

Story: The writer creates an intriguing start but fails to keep the story convincing and coherent. Many things are illogical or left unexplained. How did Faith and Jacob obtain their mind control ability? How did Joseph foresee the future? If everyone and everything you fight for is shortly to be shattered in pieces, what is the point of fighting and playing this game at all? The game has overdosed on mysticism and nihilism.

Game mechanics: The main quest is concocted from rudely intervening cutscenes and mediocre boss fights. The skirmish against Peggies in side quests is fun to play but feels very repetitive later on due to lack of variation. One of the few memorable fights is where you are tasked with preventing a group of Peggies from defusing the bombs you have planted at their factory; one of the few memorable stash quests is where you have to do a sequence of well timed grapples and jumps in order to loot a stash placed underneath a bridge. Perhaps the best thing is that you can partner with a dog (Boomer), a lion (Peaches) and a bear (Cheeseburger). But that’s all the pros of this game.

Character: Sadly, there’s no memorable character, except for the Marshal who is a joke.

Graphics: Beautifully crafted and highly performance-optimized environment.

Overall, I would rate this game 5/10, and I will not buy a game at full price from Ubisoft next time. Not GG.

 

 

Epitaph

By King Crimson (1969)

The wall on which the prophets wrote
Is cracking at the seams
Upon the instruments of death
The sunlight brightly gleams
When every man is torn apart
With nightmares and with dreams,
Will no one lay the laurel wreath
When silence drowns the screams

Confusion will be my epitaph
As I crawl a cracked and broken path
If we make it we can all sit back
And laugh
But I fear tomorrow I’ll be crying,
Yes I fear tomorrow I’ll be crying

Between the iron gates of fate,
The seeds of time were sown,
And watered by the deeds of those
Who know and who are known;
Knowledge is a deadly friend
If no one sets the rules
The fate of all mankind I see
Is in the hands of fools

Lo Wang’s fortune cookie quotes

    • You are not illiterate.
    • Confucius say it is easy to hate and difficult to love. Frankie say relax.
    • Thank you Lo Wang! But your fortune is in another cookie!
    • What’s a seven-letter word for ‘cryptic’?
    • Live each day like it’s your last. Or at least today, because… Oh I don’t want to spoil it.
    • Light travels faster than sound. That’s why some people look brilliant, until you hear them speak.
    • Whoever coined the phrase ‘quiet as a mouse’ never stepped on one.
    • Help! I am being held prisoner in a video game factory.
    • Don’t sweat the petty things and don’t pet the sweaty things. – George Carlin
    • You’re never too old to learn something stupid.
    • All men eat, but Fu Man Chu.
    • Some mistakes are too fun to make only once.
    • With sufficient thrust, pigs fly just fine.
    • He who takes advice from a cookie is sure to crumble.
    • You will stop procrastinating. Later.
    • Cardboard belt is a waist of paper.
    • The difference between an oral thermometer and a rectal thermometer is all a matter of taste.
    • You don’t need a parachute to skydive. You need a parachute to skydive twice.
    • Laugh and the world laughs with you. Cry and the world laughs at you.
    • That’s what ki said.
    • The good news: you’re not paranoid. The bad news: everyone is actually trying to kill you.
    • The early bird gets the worm. The second mouse gets cheese.
    • Small cookies bring great joy.
    • Time is an illusion. Lunchtime doubly so.
    • To be is to do. – Socrates
      To do is to be. – Sarte
      Do be do be do. – Sinatra
    • It is better to have loved and lost than to have had loved and gotten syphilis.
    • Cookie monster wasn’t here.
    • Chew, or chew not. There is no pie.
    • To maintain perfect accuracy, shoot first and call whatever you hit the target.
    • Information is not knowledge. Knowledge is not wisdom. Wisdom is not truth. Truth is not beauty. Beauty is not love. Love is not music. Music is the best. – FZ
    • Man who stand on toilet, high on pot.
    • It is better to have loved and lost than to have loved and got syphilis.

 

Reference: Shadow Warrior (2013)

Nvidia and Intel both make me furious

Nvidia: Hey, we have now started supporting icc 17.0 since cuda 9.0, but we won’t tell you that this is what you would end up having for your c++11 code:

nvcc warning : The -std=c++11 flag is not supported with the configured host compiler. Flag will be ignored.

Intel: Hey, just want to let you know that we have removed support for Knights Corner accelerators since icc 18. Now you either keep using older icc, or buy a brand new server with our brand new Knights Landing CPU.

And AMD: Sorry that Vega is a let-down, but hey, ours are cheaper!