Sunday, December 18, 2016

Opening cash drawer without printing

Programming an accounting software was probably the most boring thing I have ever done. There was however one interesting problem. The software was recording transactions from customers and printing bills, very simple. The printer was a small cashier style printer connected to cash drawer with RJ11 connector.


Now everytime the bill was printed the drawer was opened automatically. It is a standard behavior of a cashier printer and can be enabled in driver settings. One of the program features was to make a function that opens the cash drawer without printing any bill.

The tricky part is that the cash drawer is connected only to the printer and not the computer itself. So the opening command must come from the printer. By looking into printer's documentation I found series of commands required for generating pulse to open the drawer.


As you can see the command contains five ASCII characters:

16 + 20 + 1 + 0 + 3


In .NET there is a helper object called RawPrinterHelper provided by Microsoft which can be used for sending raw commands to the printer. The code can be found on this website. I added the code into the project and ended up making this function:


private void OpenDrawer()
{
   var command = 
   Char.ConvertFromUtf32(16) +
   Char.ConvertFromUtf32(20) +
   Char.ConvertFromUtf32(1) +
   Char.ConvertFromUtf32(0) +
   Char.ConvertFromUtf32(3);

   RawPrinterHelper.SendStringToPrinter(printer.PrinterSettings.PrinterName, command);
}


Calling OpenDrawer() does really open the drawer without printing any paper.

Friday, March 18, 2016

Playing with lambdas

With the new version of C++ we got a chance to start using lambda functions. It's a great way to simplify the code. Imagine this traditional sorting scenario:

bool comparator(int a, int b)
{
    return a < b;
}

void sort(std::vector<int>& array)
{
    std::sort(array.begin(), array.end(), comparator);
}


With lambda we can simplify it into one function:

void sortLambda(std::vector<int>& array)
{
    std::sort(array.begin(), array.end(), [](int a, int b) -> bool
    {
        return a < b;
    });
}


Pretty cool, now let's try something more interesting. Lambda function is just a function without name, so it can't be declared in a traditional way. But it can be used as a variable:

auto lambda = [](std::string param) { std::cout << param; };

lambda("Hi!");


Lambda function can't be used as a type directly because the type is unknown, but it can be used in a combination with std::function<> template. This way we can declare a type and use it as a class member:

struct Object
{
    void registerCallback(const std::function<void(std::string)>& callback)
    {
        m_callback = callback;
    }

    std::function<void(std::string)> m_callback;
};


Now we use the Object to register lambda as a callback:

Object object1;
object1.registerCallback(lambda);
object1.m_callback("Hi!");


Or we can declare and register the lambda at the same time:

Object object2;
object2.registerCallback([](std::string param)
{
    std::cout << "Object 2: " << param;
});

object2.m_callback("Hi!");


Another nice example of using lambda is when creating a thread. Now it can be done in one line call!

std::thread thread([]()
{
    std::cout << "Hi from the other thread!";
});


Now when you want to use an external object inside the lambda scope, you can capture it inside the brackets. Lambda capture is a mechanism for passing an external variable to the lambda scope. A typical example is to capture this as a class instance pointer:

auto lambda = [this]()
{
    // now I can access any member of this class
};


Variables can be captured by pointer, reference or name. However we must be careful about validity of captured objects, because lambda does not extend their lifetime. For example this will crash:

auto object = new Object();
auto lambda = [object]()
{
    object->sayHi();
};

// ....

delete object;
object = nullptr;

lambda(); // crash! captured object was deleted


Similar problem will happen when passing local variable by reference. When the lambda is called after exiting the variable scope the capture becomes a dangling reference:

std::function<void()> lambda;

{
    auto number = 4;

    lambda = [&number]()
    {
        std::cout << number;
    };
}

//! now the captured "number" became a dangling reference
lambda();


But after understanding these simple rules there are no other drawbacks of using lambda. In fact after some time I don't see any reason why NOT to use lambdas. The way how it simplifies the code is just amazing. I can say that it completely changed the way how I code and think about program flow and architecture. It's a very fresh wind to C++ language.

I have to recommend one excellent book from Scott Meyers Effective Modern C++ for more in depth examples and explanations behind lambdas and other techniques.

Monday, January 4, 2016

Smoother camera spring effect

Recently I came across an interesting problem where I had to follow a moving game object with the camera. The object was physical based with rigid body and the camera movement had to be delayed with a spring effect. I am using Unity Engine. The implementation was pretty straightforward, the camera position is continuously interpolated to the object position. The object is moving, the camera is following, simple. 

Now the problem was that there was a visible object jittering. When the spring effect was turned off and the camera was in fixed distance from the object the jittering disappeared. How the spring effect on camera is related to object jittering?

The answer is frequency. The physics subsystem use a different updating frequency. Game physics is usually updated with a fixed time step and does not depend of the frame rate. Camera on the other hand is a part of the main game loop with variable speed.


Frequency graph


The graph shows the difference between physical subsystem and the game loop. Physics is updated constantly regardless of the frame rate, game loop frequency is only limited by the performance of the game (or the limit is set by design).

But how does this help with jittering? To understand the problem let's look at the next two examples. On the first image there is a moving capsule that represents a physical based object followed by a camera with fixed distance (no spring effect). The capsule is moving in constant time steps and because the camera is in fixed distance it always points on the object correctly without jittering.


Fixed camera distance


Second image shows the camera on the spring. The capsule is being moved with fixed time step same as before but the camera distance is now more dynamic. The spring makes the camera delayed while the capsule is moving, when the capsule is stopped the camera is still moving towards the original distance. Now because of the camera position is updated on a game frequency and the capsule position is updated on a frequency of physics the capsule object start being jittery.

Camera with variable distance (spring effect)


The jittering is more obvious when the the strength of the spring is smaller. In the world space everything seems to look correct, the capsule is moving forward and the camera is moving towards the capsule. The jittering is a side effect of the fact that we are seeing the world with a camera eye object and everything outside of its frequency becomes jittery.

Fixing the issue wasn't so obvious, I tried to update the spring with fixed time step same as the capsule but it didn't make anything better, the jittering became even worse. After some research I came to these conclusions:

  • Camera must be updated on the game update for the smoothest possible feeling of the game
  • Spring effect must be calculated on the game update for the same reason
  • Capsule must be updated on the physics update in order to work properly

After going back and forward I realized that the capsule (or any moving object) can be split into 2 parts - physical body and visual geometry. Physical body can have all the physical properties like rigid body, collision geometry etc; and the visual geometry object is the actual capsule that you see on the screen. Now the physical body is updated with fixed time step and the visual body is interpolated to physical body within the game loop. The camera is now moving towards the the visual body without any jittering side effects.
Smooth camera with spring effect.


This solution has proved to be robust in variable framerate due to the fact that the camera and the capsule geometry are updated with the same time step.