Back to posts.

# Math

Dot product

The dot product supplies as measure of the difference between the direction in which the two vectors point. The dot product of two vectors is given by sum of the products of each component.

How to calculate

`A • B  = (A.x * B.x) + (A.y * B.y) + (A.z * B.z)`

Angle between vectors

`A • B = |A| * |B| cos(rad)`
• A and P are perpendicular when: A • B = 0 (orthogonal)
• The sign tells us how close the vectors are pointing in the same direction
• When we consider a plane, passing through the origin and perpendicular to a vector A, then any vector lying on the same side of the plane as A will give a positive dot product, when it's lying on the opposite side, it will give a negative dot product.

Calculating a perpendicular vector based on another one

Sam Hocevar wrote an excellent article on how to get an perpendicular vector based on another one. You can read the article here

```// - the current vector does not need to be normalized
// - does not normalize the output
// - works when the vector is non-zero

Vec3 orthogonal(Vec3 v) {
return abs(v.x) > abs(v.z) ? vec3(-v.y, v.x, 0.0)
: vec3(0.0, -v.z, v.y);
}```

**Convert one range of number to another range*** Lets say you have one range of values between -100 and 300 (A and B), and another range between 400 and 500 (C and D), then you can convert a value (V) from the first range to the second range using:

`value = ((V-A) / (B - A)) * (D - C) + C`

Rotating, positioning and scaling a 3D model to two 3D points

Lets say you have a 3D model in unit size and two 3D points and you want to position, rotate and scale the 3D model in such a way that it aligns with the vector between the two points. I had to find a solution for this when I had to draw cylinders between two arbitrary points.

I'll describe the solution I used to position, scale, rotate a 3D cylinder with two points. Lets say you have two points A and B. To create a model matrix that will position your model in such a way that it correctly starts drawing at point A and scales length of the cylinder so it touches B, you need to rotate, scale and position. First lets look how to rotate. The model matrix contains all the operations that are needed to draw your 3D model at any position, scale and rotation that you want. The indices of the matrix have a specific meaning:

Assume `m` is a martrix 4x4, these are the axis of a identity matrix

```// The X-axis
m[0] = 1.0;
m[1] = 0.0;
m[2] = 0.0;

// The Y-axis
m[4] = 0.0;
m[5] = 1.0;
m[6] = 0.0;

// The Z-axis
m[8] = 0.0;
m[9] = 0.0;
m[10] = 1.0;```

The above indices form what I call the Orientation Matrix, also called a LookAt matrix. Basically the values for the separate axis are used to draw those orientation arrows in 3D software:

First thing we need to do is decide what axis we want to align with our direction vector. In my case I wanted to align the up vector of my 3D model with the direction vector (B-A), which was the Y-axis. So this simply becomes:

`Vec3 y_axis = (b-a);`

The next steps are getting the perpendicular axis of this direction vector which will make the X-axis (or z-axis, but those lie in the same plane and are interchangeable in my case). Once we have the y_axis and the x_axis we use the cross product to give us a perpendicular axis of these two. As you might know all the axis of a orientation matrix are perpendicular. So to get all the axis, we use:

```Vec3 y_axis = (b-a); // this is the direction vector onto which we want to align the up vector (y-axis) of our model
Vec3 x_axis = abs(y_axis.x) > abs(y_axis.z) ? Vec3(-y_axis.y, y_axis.x, 0.0) : Vec3(0.0, -y_axis.z, y_axis.y); // this gets us a perpendicular vector of the y-axis, which we call x-axis (we can exchange x-axis <> z-axis here)
Vec3 z_axis = cross(x_axis, y_axis); // we cross the x and y axis to get z-axis.```

MAKE SURE TO NORMALIZE THE AXIS! and create the model matrix

When you don't normalize the axis the axis will also have a scaling factor; as I don't want that I'm normalizing them. If you do want to take the scale into account then simply omit the normalize operations. Once we have the 3 axis, we simply fill in our matrix. Indices 12, 13 and 14 are used for the position.

```Mat4 m;
m[0]  = x_axis.x;  m[1]  = x_axis.y;  m[2]  = x_axis.z; // x-axis
m[4]  = y_axis.x;  m[5]  = y_axis.y;  m[6]  = y_axis.z; // y-axis
m[8]  = z_axis.x;  m[9]  = z_axis.y;  m[10] = z_axis.z; // z-axis
m[12] = a.x;       m[13] = a.y;       m[14] = a.z;      // a = start position```

All code combined (using v1,v2,v3 for the axis)

```// v1 = x-axis, v2 = y-axis, v3 = z-axis
Vec3 v2 = (b-a);
Vec3 v1 = abs(v2.x) > abs(v2.z) ? Vec3(-v2.y, v2.x, 0.0) : Vec3(0.0, -v2.z, v2.y);
Vec3 v3 = cross(v1, v2);

float len = v2.length(); // scale the Y direction of the cylinder

v1.normalize();
v2.normalize();
v3.normalize();

v2 *= len * 0.5;

Mat4 m;
m[0]  = v1.x;  m[1]  = v1.y;  m[2]  = v1.z; // x-axis
m[4]  = v2.x;  m[5]  = v2.y;  m[6]  = v2.z; // y-axis
m[8]  = v3.x;  m[9]  = v3.y;  m[10] = v3.z; // z-axis
m[12] = a.x;   m[13] = a.y;   m[14] = a.z;  // position```

# Step to a certain value

This will step to values of 0.01:

```float step = 0.01;
float value = 3.346;
value = floorf( (value/step) + 0.5 ) * step;```

References:

• NAT Types This is so exciting, in this article I dive into some of the different ways a NAT device translates addresses which is important for peer-to-peer connections.
• Building Cabinets In this post I dive into the design and construction of a cabinet with an interact LED strip. I also explain how I dynamically change the colors of the LEDs over TCP/UDP.
• Compiling GStreamer from source on Windows How to compile GStreamer on Windows from Source using Visual Studio 2019 and the meson build system.
• Debugging CMake Issues In this post I explain a process you can follow to debug issues with CMake by focusing on a specific target and making the output verbose.
• Dual Boot Arch Linux and Windows 10 How to install Arch Linux and Windows 10 Pro as dual boot. A step by step tutorial how to create bootable installers, partition and setup a dual boot menu.
• Mindset Updated Edition, Carol S. Dweck (Book Notes) Paragraphs I marked from the book "Mindset" from Carol S. Dweck.
• How to setup a self-hosted Unifi NVR with Arch Linux A step by step HOW-TO that explain show to setup a Unifi Video Controller with an NFS share with Arch Linux.
• Blender 2.8 How to use Transparent Textures Follow this node setup when you want to use an image with transparency as a "sticker".
• Compiling FFmpeg with X264 on Windows 10 using MSVC A couple of steps to compile FFmpeg on Windows using MSVC.
• Blender 2.8 OpenGL Buffer Exporter The following Blender script creates a [name].h and [name].cpp for the selected object and stores the positions, normals and UVs.
• Blender 2.8 Baking lightmaps Light maps are a cheap way to add a lot of realism to you static scenes and have been used forever.
• Blender 2.8 Tips and Tricks Use Environment Map only for reflections; create a floor plane for a Product Render, diffuse texture for roughness and more!
• Setting up a Bluetooth Headset on Arch Linux Learn how to setup a Sennheiser PXC 550 Bluetooth headset on Arch Linux.
• Compiling x264 on Windows with MSVC Compile the excellent x264 source on Windows using MSYS2 and MSVC.
• C/C++ Snippets Is a number divisible by four?
• Reading Chunks from a Buffer Some thoughts on reading bytes from a file; handy for reading NALs.
• Handy Bash Commands Bash scripts: removing white space, lowercase filenames, backup using tar, etc.
• Building a zero copy parser Simple solution to parse data in a pretty performant way. Used this for a RTSP protocol parser.
• Kalman Filter A very simple yet powerful filter which works great when you have to smooth noisy data. Used for the Nike Rise 2.0 project.
• Saving pixel data using libpng Do you have raw RGBA data that you want to save? Use this snippet to save it into a PNG file.
• Compile Apache, PHP and MySQL on Mac 10.10 Setup you own PHP, MySQL and Apache and with virtual document roots.
• Fast Pixel Transfers with Pixel Buffer Objects Using Pixel Buffer Objects (PBO) for fast asynchronous data transfers and OpenGL.
• High Resolution Timer function in C/C++ Wait...... wait.. fast high resolution timer funtions (Windows, Linux, Mac)
• Rendering text with Pango, Cairo and Freetype My never ending obsession with font rendering. A complex beast to do well. Use Pango and FreeType for the heavy lifting.
• Fast OpenGL blur shader Make things look blurry ... and fast using this OpenGL blur shader.
• Spherical Environment Mapping with OpenGL An old trick to get great lighting effects using Environment Maps and OpenGL.
• Using OpenSSL with memory BIOs OpenSSL is a great library with lots of abstractions. In this post I discuss how to break some of these abstractions and use your own memory buffers.
• Attributeless Vertex Shader with OpenGL A simple way to render a fullscreen quad without a vertex buffer with OpenGL.
• Circular Image Selector Some thoughts on a different way to select images from a huge collection in a compact UI.
• Decoding H264 and YUV420P playback Using libav to demux and playback with OpenGL.
• Fast Fourier Transform Analyse your audio using the Fastest Fourier Transform in the West.
• OpenGL Rim Shader Pretty glowy edges using a GLSL rim shader.
• Rendering The Depth Buffer Render the non-linear OpenGL Depth Buffer.
• Delaunay Triangulation Do you need to triangulate some shape: use the “Triangle” library.
• RapidXML RapidXML is a versatile and fast XML parser with a simple API. Check out these examples.
• Git Snippets Some simple GIT snippets; added here to remind myself.
• Basic Shading With OpenGL A couple of basic GLSL shaders with explanation.
• Open Source Libraries For Creative Coding Collection of great open source libraries for you creative programming projects.
• Bouncing particle effect Snippet that can be used to create a bouncy particle effect; basic, effective, simple but nice.
• OpenGL Instanced Rendering Want to render thousands and thousands of objects? Use OpenGL instanced rendering. The solution...the only solution.
• Mapping a texture on a disc Ever heard about projective interpolation related to texture mapping? Learn about this intertesting issue with OpenGL and texture mapping.
• Download HTML page using CURL When you want a quick solution to perform a HTTP(S) request CURL is always a quick an simple solution. Check out this example code.
• Height Field Simulation on GPU Although not a Navier-Stokes implementation ... still a very nice and enjoyable effect.
• OpenCV Optical Flow: when doing anything with tracking you've probably heard of it. See this simple example code using OpenCV and OpenGL.
• Some notes on OpenGL FBOs and Depth Testing, using different Attachment Points, a YUV420p shader, ...
• Math Meaning of the Dot Product in 3D graphics, calculating a perpendicular vector using Sam Hocevar's solution, orientation matrix and more.
• Gists to remember Some gists that I want to remember, often use, etc...
• Reverse SSH Do you want to login, into a remote PC but the remote PC is behind a firewall? Then use this simple reverse SSH trick which doesn't require changing your firewall rules.
• Working Set Having issues with your compiler? Or during linking? Check these common issues and their solutions. I also list several tools that you can use to get a some useful info.
• Consumer + Producer model with libuv Example of a common Multi Threaded Consumer/Producer Model using LibUV.
• Parsing binary data Learn about the basic of a binary protocol and how to create one easily yourself.
• C++ file operation snippets Reading a file into a string, vector, checking the file size, change to a position, etc. A collection of C++ file operation snippets.
• Importance of blur with image gradients Do you want to experiment with OpenGL and aligning Brush Strokes along Image Gradients? Then check out this post about the importance of blurring.
• Real-time oil painting with openGL Code snippet for fake "oil painting" effect with OpenGL using instanced rendering.
• x264 encoder Basic example on how to use libx264 to encode image data using libav
• Generative helix with openGL Screenshots of a project I worked on with that generates a DNA helix.
• Mini test with vector field Screenshots while experimenting with a vector field; nothing much to see here.
• Protractor gesture recognizer Testing the amazing One Dollar \$1 gesture recognizer. The simplest and very good gesture recognizer.
• Hair simulation Example code that implements the "Fast Simulation of Inextensible Hair and Fur" paper from M. Müller, T.Y. Kim and N.Chentanez.
• Some glitch screenshots Glitch screenshots.
• Working on video installation Screenshots of some experiments of a video installation.
• Generative meshes I enjoy creating physics based simulations and render them on high res. Here are some experiments I did a time ago.
• Converting video/audio using avconv Examples that show you how to use avconv to manipulate video and audio files.
• Auto start terminal app on mac Automatically start you application whe Mac boots and make sure that it restarts your app when it exists. Handy for interactive installations.
• Export blender object to simple file format Export the selected object in Blender into a .h and .cpp file that prepresents the buffer.