All Blog Entries

All blog entries, ordered from most recent. Entry count: 1010.

Pages: 1 2 3 ... 127 >

Nov 2015

type_safe_ptr - Idea for Type-Safe void* Pointer

I was thinking recently about passing raw data pointers (like void* or char*), which we have to do sometimes in C++. Is there any way to check if the type that we cast it to is the same as the type of last assigned value? I came up with an idea of implementing a "smart pointer" class using RTTI (specifically typeof operator) to store type information next to the actual pointer. Example usage:

int i = 123;
type_safe_ptr ptr{&i};
int j = *ptr.get_typed<int>(); // OK
float f = *ptr.get_typed<float>(); // Error

Initially I wanted to store pointer to const type_info struct returned by typeid operator, and it seems to work in Visual Studio 2015, but language standard defines the object returned by typeid as temporary, so it is not formally correct. Finally I decided to store typeid(T).hash_code(). You can find my implementation of classes type_safe_ptr and type_safe_const_ptr in file: type_safe_ptr.hpp. Here is example tesing program:

#include <cstdio>
#include "type_safe_ptr.hpp"

int main()
    type_safe_ptr ptr1;
    // ptr1 is null.
    assert(ptr1.get() == nullptr);

    int i = 123;
    type_safe_ptr ptr2{&i};
    // ptr2 is pointer to int.
    assert(*ptr2.get_typed<int>() == 123);
    // It would activate assert inside type_safe_ptr.get_typed, because ptr2 is int not float.
    //assert(*ptr2.get_typed<float>() == 123.f);

    struct STest { int i; } obj;
    // itr2 is now pointer to STest.
    ptr2 = &obj;
    ptr2.get_typed<STest>()->i = 124;
    assert(obj.i == 124);
    // It would activate assert inside type_safe_ptr.get_typed, because ptr2 is now STest not int.
    //assert(*ptr2.get_typed<int>() == 123);
    type_safe_const_ptr cptr = type_safe_const_ptr(ptr2);
    // cptr is pointer to const STest.
    assert(cptr.get_typed<STest>()->i == 124);

    const int* constIntPtr = &i;
    // cptr is now pointer to const int.
    assert(*cptr.get_typed<int>() == 123);

Some issues and open question regarding my solution are:

Final question is, whether this whole idea of "type-checking void* smart pointer" makes any sense? I am not sure about that, but anyway it was a funny experiment :)

Comments (0) | Tags: c++ visual studio | Author: Adam Sawicki | Share

Nov 2015

The Virtual Reality of Code

In my opinion, coding is a virtual reality with its own set of rules unlike in the physical world. In physical world, each thing has its specific location at the moment, things don't appear or disappear instantly, we have laws of energy and mass conservation. Inside a computer, we have data in memory (which is actually linear - 1D) and processors, processes and threads executing instructions of a program over time.

I have been trying for years to imagine some nice way editing or at least visualizing code, which would be more convenient (and look more attractive) than the text representation we all use. I am unsuccessful, because even if we render some nice looking depiction of a function code, its instructions, conditions and loops, drawing all the connections with variables and functions that this code uses would clutter the image too much. It's just like this virtual world doesn't fit into a 2D or 3D world.

Movie depiction of computer programs is often visually attractive, but far from being practical. This one comes from "Hackers" movie.

Of course there are ways of explaining a computer program on a diagram, e.g. entity diagrams or UML notation. I think that electrical diagrams are something in between. Electrical devices end up as physical things, but on a diagram, the shape, size and position of specific elements doesn't match how they will be arranged on a PCB. Logical representation and electrical connections between them is the only thing that matters.

Today it occured to me that this virtual reality of code also has "dimensions", in its own sense. It's evident when learning programming.

1. First, one has to understand control flow - that the processor executes subsequent instructions of the program over time and that there can be jumps caused by conditions, loops, function calls and returns. It's called dynamic aspect of the code. It can be depicted e.g. by UML sequence diagram or activity diagram.

I still remember my colleague at university who couldn't understand this. What's obvious to every programmer, was a great mystery to him as first year's computer science student. He thought that when there is a function above main(), instructions of that function are executed first and then instructions of the main function. He just couldn't imagine the concept of calling one function from the other and returning from it.

2. Then, there is so called static aspect - data structures and objects that are in memory at given moment in time. This involves understanding that objects can be created in one place and destroyed in another place and at later time, that there may be a collection of multiple objects (arrays, lists, trees, graphs and other data structures), objects may be connected to one another (the concept of pointers or references). Various relationships are possible, like one-to-one and one-to-many. In object-oriented methodologies, there is another layer of depth here, as there are classes and interfaces (with inheritance, composition etc.) and there are actual objects in memory that are instances of these classes. It can be depicted for example by entity diagram or UML class diagram.

3. Finally, one has to learn about version control systems that store history of the code. This adds another dimension to all the above, as over successive commits, developers make changes to the code - its structure and the way it works, including format of data structures it uses. Branches and merges add even more complexity to it. GUI apps for version control systems offer some way of visualizing this, whether it's showing a timeline with commits ("History") or showing who and when commited each line of a file ("Blame").

There is even more to it. Source is organized into files and directories, which may be more or less related to the structure of contained code. Multithreading (and coprocessing e.g. with GPU, SIMD, and all kinds of parallel programming) complicates imagining (and especially debugging!) control flow of the program. Program binaries and data may be distributed into multiple programs and machines that have to communicate.

It fascinates me how software is so multidimensional in its own way, while so flat at the same time (after all, computer memory is linear). I believe that becoming a programmer is all about learning how to imagine, navigate and create stuff in this virtual reality.

Comments (0) | Tags: philosophy software engineering | Author: Adam Sawicki | Share

Oct 2015

Poznań Game Arena + Game Industry Conference 2015

Last weekend Poznań Game Arena together with Game Industry Conference (former ZTG - Zjazd Twórców Gier) took place in Poznań, Poland. I have been there, just like in previous years and I liked it a lot. PGA is advertised as "biggest multimedia and entertainment event in this region of Europe." There were multiple halls filled with exhibitors of various kinds, of course all related to gaming. Lots of gaming hardware have been shown, as well as T-shirts and other fan accessories. I had an opportunity to try Oculus Rift and Samsung Gear VR. Samsung's product seems to have higher resolution, but bigger lag between accelerometer and displayed image. Unfortunately I didn't try HTC Vive (the queue was too long), while they say it is the best of all virtual reality solutions. There was also one hall dedicated to indie games, with lots of productions available to play and discuss with their creators.

While PGA was targeted mostly to gaming fans, game developers gathered in the same time and place for GIC, which consisted of almost 100 talks, panels, workshops and other activities. Industry professionals talked about their games, academics showed their research, enthusiasts discussed their ideas and prototypes... Traditionally, most of the topics were not technical, but rather related to game design or business. Well, most games are made in Unity these days anyway, so probably there is not need to discuss quirks of DirectX or OpenGL for an average game developer. But I still believe that the opportunity for expanding knowledge beyond everyday work, for networking, catching new ideas and getting motivation boost make such events worth attending.

Comments (0) | Tags: events | Author: Adam Sawicki | Share

Sep 2015

Direct3D 12 - Watch out for non-uniform resource index!

DirectX 12 allows us to use arrays of resources (descriptor tables) and refer to them from a shader code by an index. The index can be constant or variable. But there is a big trap waiting for shader developers doing that! Microsoft just updated their public documentation in this regard (see Resource Binding in HLSL), so now I can talk about it.

In D3D12, resource index is expected to be uniform (convergent) by default. It means the index, even if dynamic, should be the same across whole draw call (all vertices/pixels/etc.). For example, it can be a result of some calculations, which depend on parameters coming from a constant buffer. Example code:

Texture2D<float4> textures[16] : register(t0);
SamplerState samp : register(s0);
struct SConstantBuffer
    uint MaterialId;
ConstantBuffer<SConstantBuffer> cb : register(b0);

float4 PS(
    in float2 texCoords : TEXCOORD0 ) : SV_Target
    uint materialId = cb.MaterialId;
    return textures[materialId].Sample(samp, texCoords);

Why is it this way? That is because on low level, GPU-s are made of SIMD processors. Each of its small processors executes shader instructions over multiple "SIMD threads" (or "warps", or "wavefronts", however you call them), not a single (scalar) value. Because of that, knowing that the resource index will always be the same on all SIMD threads can result in some optimizations and more efficient execution.

Resource indices in Direct3D 12 actually can be non-uniform (divergent) - different in every vertex/pixel/etc., like when they are result of some calculations based on vertex attributes or pixel position. But they must be then surrounded by a special, "pseudo"-function in HLSL, called NonUniformResourceIndex. For example:

Texture2D<float4> textures[16] : register(t0);
SamplerState samp : register(s0);

float4 PS(
    in float2 texCoords : TEXCOORD0,
    in uint materialId : MATERIAL_ID ) : SV_Target
    return textures[NonUniformResourceIndex(materialId)].Sample(samp, texCoords);

This may look a bit unintuitive, so I expect many developers will make the mistake and omit this function. If you use a non-uniform value as resource index, but forget to mark it with NonUniformResourceIndex, HLSL compiler probably won't warn you about it. It may even work in some cases and on some GPU-s, while it will give invalid (undefined) results on others. So similarly to the issue with reduced precision in normalize/length operations in GLSL, this is a thing to be careful with when coding your shaders in HLSL using new Shader Model 5.1.

Comments (2) | Tags: directx | Author: Adam Sawicki | Share

Sep 2015

Syntax of C++ Templates - Comparison

I noticed recently how C++ syntax differs when you define a class template, template instantiation, specialization or partial specialization. Here is an example:

// Template class definition.
template<typename T>
class Class1
    void Print() { printf("Class1 template\n"); }

// Template class instantiation.
class Class1<int>;

// Template class specialization.
class Class1<double>
    void Print() { printf("Class1 specialization for double\n"); }

// Template class partial specialization.
template<typename T>
class Class1<T*>
    void Print() { printf("Class1 partial specialization for pointers\n"); }

Having these classes defined, following code fragment:

Class1<int> objInt;
Class1<double> objDouble;
Class1<int*> objPointer;

Produces following output:

Class1 template
Class1 specialization for double
Class1 partial specialization for pointers

Here is how the syntax can be compared:

Comments (2) | Tags: c++ | Author: Adam Sawicki | Share

Sep 2015

Unicode w Visual C++ - My Old Article

I just noticed that my old article "Unicode w Visual C++" (in Polish) was a dead link and restored it back online:

Unicode w Visual C++

It may not be "politically correct" if you believe in what they say in UTF-8 Everywhere manifesto, but I think the information that I have put there are still relevant and useful despite being 7 years old.

Comments (0) | Tags: c++ visual studio | Author: Adam Sawicki | Share

Sep 2015

Music Visualizations - Plans for the Future

Last weekend I was showing my music visualizations on two parties. First one was in a club, projected on flat screen, while the second one was an open-air party (my 7th and last one in this summer season :) with the image projected on trees. For this one I had to prepare something different - simple, contrast shapes and single color only, so it could be clearly visible. Here is a small video:

It doesn't look like this because I wanted it exactly this way or because that was my "artistic vision", but just because showing some rotating images downloaded from the Internet and blending transformed feedback from previous frame was the easiest way to start with something interestingly looking.

Now I have tons of ideas to improve this program as soon as I find some free time. Next to some small technical tasks like refactoring code or simply adding new graphical effects, I plan following big TODO-s (with no particular order decided yet):

Comments (2) | Tags: events music psytrance vj | Author: Adam Sawicki | Share

Aug 2015

Adventures with Porting Code to Visual Studio 2015 and No DirectX SDK

I just installed new Visual Studio 2015 Community Edition and ported my personal project to it. At the same time, I uninstalled old DirectX SDK Jun 2010 and started using new DirectX headers bundled with Windows SDK, which is installed together with Visual Studio. These two transitions are not connected - I could already switch to new DX headers years ago, but I decided to do it now. While transition to VS 2015 was smooth, abandoning DirectX SDK caused some problems, because new DirectX doesn't contain D3DX library. Here is a dump of the problems and solutions that I encountered during this effort:

1. I uninstalled DirectX SDK Jun 2010, Visual Studio 2013 Community Edition and all other components that seemed related to it, like Microsoft SQL. I left all "Microsoft Visual C++ XX Redistributable" though, because these are required by many applications and intended to be installed on target machine, not necessarily as a part of development environment.

Next, I downloaded and installed new Visual Studio 2015 Community Edition. During this long process, I was thinking what should I expect from the new IDE... Whether Microsoft did a good job this time? On one hand, it is suprising that C++ is now an optional installation component, so it seems like native code is in shadow comparing to all these new and trendy cloud/web/mobile/managed technologies. On the other hand, table: C++11/14/17 Features In VS 2015 RTM shows that the new C++ compiler caught up with many features of new C++11/14/17 language, which gives hope that authors still treat native code development seriously.

2. The looks of new IDE is so similar to the previous version it is hard to notice any differences. After launching it, I had to first recompile static libraries that my project depends on. That was zlib 1.2.8 and my CommonLib. Converting project to new version, as well as the build itself went smoothly, without any problems - which is unusual with C/C++ libraries :) Just as in previous version, headers and libs of standard C library, standard C++ library (STL) and WinAPI are already bundled with the Visual Studio, so there is no need to install or configure anything additional before you can use them.

Read full entry > | Comments (1) | Tags: visual studio directx c++ | Author: Adam Sawicki | Share

Pages: 1 2 3 ... 127 >

STAT NO AD [Stat] [Admin] [STAT NO AD] [pub] [Mirror] Copyright © 2004-2015 Adam Sawicki
Copyright © 2004-2015 Adam Sawicki