You are currently browsing the archives for the C/C++ category.
- 3D Stuff (12)
- AI (1)
- BumpTop (5)
- C/C++ (22)
- Open Source (8)
- Radiant (11)
- Seneca (6)
- Stuff (17)
- The Mortal Realm (2)
- Uncategorized (14)
- win32 (12)
- July 9, 2010: On Visual Studio 2010...
- December 22, 2009: Efficient Rendering, A La Mark.
- December 3, 2009: A Simple Opponent
- December 3, 2009: Blog++
- September 7, 2009: Food Budgeting
- July 3, 2009: Too Busy...
- March 26, 2009: How Do Patents Apply To Me?
- February 27, 2009: U.S. And Human Rights
- February 7, 2009: I've Been Busy...
- November 10, 2008: Radiant Update
Archive for the C/C++ Category
On Visual Studio 2010…
July 9, 2010 by Mark.
When I look at Visual Studio, I see a large toolbox that is well organized and labeled. Much so is the case with VS2010 as it was with its predecessor. However, my analogy is inadequate when it comes time to use VS2010 on a production level. To give you some back story, I’ve been using it since it was in the beta stages and like all beta software, it had its ugly side. It’s flashy GUI makes the user feel like they are working with a paintbrush rather than a chisel. Yes, the GUI is hardware accelerated and relies heavily on the graphics card for its eye pleasing outfit. The anal minimalist side of me started screaming the instant I found this out. Why should a development tool be using the graphics card for anything??
I compare the jump from VS2008 to VS2010 like the jump from Windows XP to Vista. You went from a product that was designed to be fast and responsive to a lumber hulk of over designed and needless fluff that pegs your hardware when too many tabs are open. Visual Studio is supposed to be a tool, not a piece of art. When you start weighing it down with flashy effects and ‘themes’, it becomes something akin to a video game, not a development environment.
Moving on, I was under the assumption that the Microsoft team improved the short comings of VS2008. With VS2010, they actually took a step (or several steps) backwards. You get up-to-date Intellisense errors as you type your code (like C# does), which is great. However, if you try to look up a function declaration, it won’t be able to find it, even if it’s in the same file, 20 lines up.
On a brighter note, the team actually fixed multi-core compiles. If you have a quad core machine, it will properly utilize the cores and compile your source much faster. This I like. It has a built in testing environment that is much better than VS2008’s version. Code coverage actually works well. Custom visualizers work better now and won’t crash the IDE when a complex data structure is thrown at it (like a hashmap).
VS2010 has the potential to be decent but if you really want to jump head first into it, I would suggest you wait for a service pack.
Posted in C/C++, win32 | No Comments »
Efficient Rendering, A La Mark.
December 22, 2009 by Mark.
Rendering efficiently is one of those topics that is widely spoken about in the world of 3D graphics. Asking a question like ‘What is the best way to render a bunch of Objects’ is as open ended as asking ‘What is the best way to cook chicken soup.’ It is all based on application and preference and in all likelihood, there is no universal answer to this question. However, there are a series of specific solutions to this problem that can help in creating a mechanism that is best for the particular situation.
My problem is rather generic and will require a generic solution. I have a bunch of objects that need to be sorted by certain criteria in order to minimize state changes. It has to also support Shaders (Cg in my case) and it should minimize Shader state change between object rendering. Furthermore, an object must be generic enough to support complex models with bones and animations. On top of that, it should be easy to use. To start, we might need to break this down into smaller parts.
Objects:
For the time being, lets refer to an Object as a list of vertices inside a vertex buffer. It may or may not be accompanied by an index buffer, but in most cases it will. This Object will be shuffled to the graphics card to be rendered for each Object that exists in our world. This is inevitable until we support something complex like hardware based instancing.
State Changes:
Unless you want all objects to be rendered in the same way, in the same spot, and with the same vertices, you probably want some sort of state change. A state change is a change in any part of the system, whether it is the position of the camera, a new Object to be drawn, or a new effect. To quantify a state change, it is best to organize it into the types of state changes: swapping Render Targets, Shaders, Technique, Shader parameters, and using a different vertex or index buffer to draw an object. The order of the state changes, as listed above, matters because the changes at the beginning of the list are the most expensive and the changes at the end of the list are least expensive.
The RenderGraphNode:
This is a generic interface to which many types of nodes will be derived from. Each derivation of the node will be the embodiment of the changes listed above. In addition to the state change, the node will also be a container for child nodes. Usually the node will be generic enough to contain any type of node. However, in our case, we want to preserve an order to our nodes so that we optimize the state changes. The root of our tree will be a change in Render Targets. For the most part, there will only be one Render Target, the backbuffer (our screen). When a child node is added, it will automatically be sorted into the correct place in order to minimize the state change. This is especially important for Shader parameter changes because there can be multiple parameters in one Shader.
The RenderGraph:
In order to encapsulate all this, I need a class that will be the owner of Render Targets. It will be the only thing passed into the Renderer for drawing. At that point it will traverse the tree and render.
Sounds simple right? Yeah, but something doesn’t feel good about this design.
If we leave the design at this point, we are left with a bunch of nodes in which the user has to put together. This design is acceptable by some. In fact, OpenSceneGraph uses such a design for its SceneGraph. It is a bunch of classes that fit together in a tree fashion. Throw in a Visitor pattern into the mix for easy iteration and you have an engine. I’m not quite as happy with that design as my OpenSceneGraph counterparts are. The problem is, in my eyes, that it’s very verbose. Putting together a simple scene with an airplane in it was quite lengthy. You have to add a GeometryNode to a TechniqueNode to a ShaderNode to a RenderingTarget, and so on.
So back to my original question, what is the best way to implement something like this? When I figure it out, I’ll write about it.
Posted in Radiant, 3D Stuff, C/C++, Stuff | No Comments »
A Simple Opponent
December 3, 2009 by Alex.
The current game project, “The Mortal Realm”, involves a battle system which is turn based and played on a hex grid. Thus, it requires an AI opponent. Currently, the outline of the AI mind is fairly simple.
Firstly, there is the long-term plan. This is achieved via a genetic algorithm. A computer player would have a number of units, up to ten, that can be fielded into a battle at any given time. The genetic algorithm determines the long-term goal of each unit. Note that, this does not determine the turn to turn actions of a unit. The general setup of this one goes like this:
a) The Solution Representation is, like most other genetic algorithms, an array, where each slot represents the long term goal of a unit. The long-term goals are typically actions such as “Take and Hold x Position” or “Set up Ambush at x Position” or “Charge recklessly at the enemy army”.
b) Mutations simply change a value of a long-term goal in a random slot inside a solution. For instance, slot 6 might be “Take and Hold x Position”. It could change to “Take and Hold y Position” or “Set up Ambush at x position”.
c) Crossover is a simple single point crossover. Choose a random slot, between 1-10, as the crossover point. The first child takes all the genes of the first parent before the crossover point and all the genes of the second parent after the crossover point.
As a simple explantion, the genetic algorithm works something like this. First, you have a population of solutions. In my case, that means I have a collection of arrays, each array representing a long-term battle plan. Each slot in an array is considered a gene, the long term plan for a single unit. The initial population is created at random, that is, the solutions I come up with are completely arbitrary. Then, I have a method, called the objective function, which calculates the value of a solution. This objective function takes into account the terrain, the position of enemy troops and also the particular arrangement of friendly troops. Noting that I have to take into account the arrangement of friendly troops, you cannot calculate the value of a gene independently because it changes based on what the other genes are. So now I have a population of randomly created “individuals” (solutions) and I have a way to calculate their fitness with my objective function (que Nazi references).
Next, you create the next generation of individuals. This is a stochastic process based on fitness. The more fit an individual is, the more likely it gets to reproduce. In order to create offspring, two individuals are selected at random, with a higher preference given to people who have higher fitness. They then create offspring via the crossover method. Two parents produce two children via crossover (ie. each child will somehow share the genes of its parents). After enough offspring is created for the next generation we then check if any will undergo a mutation. Unlike real-life, genetic algorithms do not allow mutations to produce non-viable offspring. A mutant is always viable. However, the rate of mutation is very low.
Now you have the next generation of offspring, some of which may have mutated. Then you decide which of the parents and offspring survive to make the next generation. Like before, it is a stochastic process where individuals are randomly chosen, with a preference toward higher fitness levels. Then once this is complete, you repeat the process.
Once you are done (it may take hundreds of generations to produce a good solution) you’ve proven evolution. Also, we have a long-term battle plan for the computer opponent. This battle plan shapes the turn to turn actions it takes with its units, as it tries to stick to the plan and also react to transient issues. Next post, I’ll talk about how the computer opponents determines its turn to turn actions for each unit.
-Alex
Posted in AI, The Mortal Realm, C/C++ | No Comments »
Blog++
December 3, 2009 by Mark.
I’m converting my blog to something a bit more useful. My long rants about my game engine were all leading towards a game of some sort. In the process I have recruited a friend to help me realize that dream. So, give a kind welcome to Alex.
Our first title will be a strategy turned-based war game by the name of ‘The Mortal Realm.’ It will feature my 3D engine and a robust battle system. As far as complexity goes, this game is one of the simplest we have come up with. It’s a simple point and click style of game with very minimal artwork. I’m hoping it will be a great test bed for my engine as well as Alex’s AI.
Posted in The Mortal Realm, Radiant, 3D Stuff, C/C++, Stuff | No Comments »
Food Budgeting
September 7, 2009 by Mark.
A food budget is a little bit different then a financial budget because you are budgeting quantities of ingredients rather then a lump sum of money. It is something that my wife just introduced me to and I am very excited to start doing it. Say you purchase a pound of ground beef but you only use up half of it. For example, rather then making the same dish again in order to use up the rest of the beef, you could make another dish with that exact amount of beef. However, she is having a difficult time trying to manage the data especially when you have more then one or two ingredients to work with.
So, I’m setting out on a journey to build her an application that would manage a database of ingredients. It would link the ingredients table with a table of recipes, making it easy to search. To be honest, I’m not a database person. In fact I have not done any DB work since first year at Seneca. I might need to pull out my old text books in order to re-learn how to use a DB. I’m thinking of using SQLlite for the back end and straight up C++ on the front end (though C# has crossed my mind). It will be all open source obviously.
Posted in Open Source, C/C++, Seneca | No Comments »
How Do Patents Apply To Me?
March 26, 2009 by Mark.
I’ve been diligently working on a scene partitioning system which combines an Octree with a Uniform Grid. Basically, the way it works is that you build a loose Octree, which starts 4 levels deep. When each node reaches a critical mass, it subdivides into another level. The max levels you can have (While still being optimal) is 7. So, let’s assume that we have a detailed scene with a 7 level Octree. At the bottom of the Octree, each node is 128th the size of the entire area you are encompassing and it is also uniformly proportional to the entire area. You can build a Uniform Grid out of the bottom most nodes giving you the best of both worlds.
When all this is built, to add and remove items from the grid is a matter of doing simple division of finding out the exact spot in the Uniform Grid where the object belongs. Since pointers are being shared between Octree Nodes and Uniform Grid Nodes, you essentially add an item to the Octree in O(1) time (Adding to a Tree structure usually Takes O(Log n) time). Collision detection with simple objects is O(1) time while with complex objects it is O(Log n) time. What I have done is made the Octree a bit faster in some areas. Good idea, isn’t it?
Here is my problem. While randomly googling on this topic, I found a patent for this idea. The patent is very similar to what I just described. What I want to know (For all you Law junkies out there) is how does this effect me? Can I get sued? Does it matter that my implementation is my own and not copied from the patent? Does it matter that my implementation is Open Source? Are there ways to get around this patent (My implementation is different but algorithmically similar)?
Any suggestions are welcome.
Posted in Radiant, Open Source, 3D Stuff, C/C++, Stuff | No Comments »
Radiant Update
November 10, 2008 by Mark.
I held a bet with my brother to see who can guess the number of lines of code (or at least, close to it) my rendering engine is comprised of. Neither of us were close but I got a good sense of how much work went into this giant mash of code. About 25,000 lines is the total. That total is comprised of approximately 12,000 lines of computational code and about 13,000 lines of comments. This number does not include blank lines and such things. Regardless, it’s a staggering number for a project that is being worked on by one person, part time.
The engine itself is about 45% complete, with the majority of planning done. One of the components, my math module (it handles math stuffs and collision detection), is finally finished. I can breath a sigh of relief, it’s not easy stuff. Unfortunately I didn’t write any unit tests for it so I don’t know if it actually works or not. The project is open source. So, if anyone is masochistic enough to write a tests for my math module, by all means :).
Posted in Radiant, 3D Stuff, C/C++, Stuff, win32 | No Comments »
Primary Export: Pain
October 28, 2008 by Mark.
Everyone knows (or should know) that when you put together a DLL, you need to export functionality so that programs using your DLL know where to find your functions. This is usually done by prefixing classes or functions with __declspec(dllexport) or manually writing a definition file. Straight forward and right to the point. But what happens when you need to export something that does not have a name. Say for example, an overloaded new operator. What the hell does a new operator look like as a definition symbol?
I’ll give you a hint: its not human readable!
So, before I actually spoil the beans and tell you what I did, I have to explain why I did it, because its rather interesting. Radiant, my game engine, is split into 6 DLLs, all of which touch and create dynamically allocated memory somewhere. The problem with allocating memory all over the place is that you need to delete it in the same address space (or DLL) as you allocated it in. With that said, to make it more complex, I had to overload the new and delete operators in order to wrap around _aligned_malloc() and _aligned_free() calls. This is a special type of allocation that allows you to align dynamic memory to an address that is divisible by 16 (or any other value). This is crucial if your using SSE or any special instruction set because all values need to be aligned to at least 16 bytes.
Anyway, going back to the problem at hand, I have a bunch of overloaded operator functions that cannot be exported because if I try to add the __declspec(dllexport) prefix to them, the compiler will scream and tell you that the declarations of the functions do not match up with what is defined internally. Basically, what I am stuck with are a handful of functions that cannot exported programmatically. This is where the definition file comes into play. Exporting a function or class is as easy as entering its name in the definition file under the heading of EXPORTS. But here is the kicker, the overloaded operators of ‘new’ and ‘delete’ do not have a name! They are declared internally in a header that exists in the compiler’s own static data, and there’s no way to override inclusion of that header. Therefore, the only way is to manually enter the function’s mangled name into the definition file.
The mangled name looks something like the following:
| ??2@YAPAXI@Z | (void * __cdecl operator new(unsigned int)) |
| ??3@YAXPAX@Z | (void __cdecl operator delete(void *)) |
| ??_U@YAPAXI@Z | (void * __cdecl operator new[](unsigned int)) |
| ??_V@YAXPAX@Z | (void __cdecl operator delete[](void *)) |
In fact, those mangled names are fairly generic and may not match up correctly. But their names are very similar to what they should be. A more specific example of the name would be located in the Visual Studio directory under VC\crt\src\intel\_sampld_.def. This file contains a slew of definitions. What your looking for are the first four definitions that look very similar to the ones posted above. If you are running under a x64 or Itanium architecture, there are definition files for those architectures as well.
After a successful compile, all dynamic memory is allocated and deallocated in a single DLL’s memory space. This prevents the Heap Corruption errors I was getting before and allows me to further enhance the allocation and deallocation of dynamic memory. Woot!
I would suggest reading the following link because it contains a very good description of how this process works. Unfortunately, I stumbled upon this file AFTER I already fixed this problem. Alas, C’est La Vie.
Posted in Radiant, C/C++, Stuff, win32 | No Comments »
Results
September 7, 2008 by Mark.
I finished writing my own Thread Pool subsystem and then put it through its paces. The results are obviously not that shocking because anything that is multi threaded is more efficient on dual core machines. The machine I was running it on has a AMD Turion 64 X2 CPU and sports two 2.0Ghz cores. It’s not the best machine but its quite speedy for what it is.
Anyway, as I mentioned in the previous entry, threads are great and run best when they have a dedicated core. When there are more threads then cores, the OS then has to time-slice in order to give the threads equal time on the CPU. Having a dual core machine, the optimal amount of threads that I can handle is 2. The following is a graph of the time it took to process 50,000 square root calculations, 100 times in succession:

On the first run, I did not use any threads. Rather, I let the calculations run in sequential order on the main process. The blue bar represents the thread priority at normal and the purple bar represents the thread priority at Highest. I did this in order to measure the speed difference between the normal and highest priority setting. I should also note that even though the thread priority can be manipulated, it is up to the OS to enforce that. In some cases the OS may decide not to enforce the request for higher priority and give the processing power to other threads.
The second and subsequent runs were using the Thread Pool with an increasing allotment of threads. Each 50,000 calculations were plugged into its own Job and sent off to a worker thread. Having only one thread was not much of a boost over a single process (Took about 1920ms). The main process was put to sleep using the WaitForSingleObject() function call while the worker thread did the processing. At two threads there is a massive increase in time. Just as one would assume, the amount of work was spread over two cores and the time it took to process it all was cut in half (About 950ms). This is the optimal amount of work my CPU can handle because each thread has a dedicated CPU core. Increasing the amount of threads actually increased the amount of time it took to process the calculations. The reason being is that the OS had to time-slice the different threads on both cores. The time increased by about 20ms each time I increased the number of threads.
Thread Pools are very efficient at what they do. As mentioned in the previous entry, creating a thread and destroying a thread could have increased the amount of time required to process a batch of 100 calculations. Regardless, the work I done is Open Source and as is my engine. You can download it here (I’m not responsible for unexplained fires, deaths, or alien abductions due to using this code).
Posted in Radiant, Open Source, 3D Stuff, C/C++, win32 | No Comments »
Multicore Processing And Game Engines
September 5, 2008 by Mark.
I have been passively researching multicore processing for the last few weeks and I came to the conclusion that it is rather easy to implement. In its simplest form, all you need to do is create threads and have them do Jobs. The OS will then schedule a thread to be run on a dedicated core. Having multiple cores makes those threads run at the same time as opposed to the old time-slicing method of single core processors. But, at the very base level, it’s rather primitive and can actually be improved upon.
Creating threads and closing them is fairly fast but may be a bottle neck if the engine does that consistently. The best way to handle this is to not do it, obviously. This is where a Thread Pool comes in handy. It creates a bunch of worker threads that don’t get destroyed until the program exits. Each thread will sit idle until a job has been passed into it to be processed. This involves the use of critical sections and semaphores to accomplish and is much faster then allocating and deallocating threads. A critical section is optimized for speed as compared to any other form of asynchronous data sharing and messaging (alternatives include Mutexes, Events, and so forth). The rule of thumb is to create enough threads so that the OS does not have to time-slice. This is usually done by allocating [num of cores] + 1 threads.
In order for a Thread Pool to work properly, it requires a few things. Firstly, a Job queue. This is a long list of jobs that will get distributed between the threads once threads become available. Secondly, some sort of thread state management. It includes a set of states that the threads can be at. The basic types are ‘Working’ and ‘Idle’, but it can vary on the amount of complexity you add to the Thread Pool. Lastly, it requires data sharing. I suggest writing an object that wraps data around a locking/unlocking mechanism (Semaphores come in handy for this task). Once these aspects are implemented, the Thread Pool is basically finished.
Usage is another key role. Lets assume that you either use the built in Win32 Threading pool or roll your own, it doesn’t matter which one you do. Furthermore, you have some very repetitive code that you want to multithread. If you don’t quite know what is multithreadable, the best place to start looking is in any for loop. The place where I’m going to use my Thread Pool is in a loop where I would have to update some world object, such as a player state or even scene management. For example, this loop might call your world object and cause it to return collision information with its nearest neighbors. Plug the world objects into the Thread Pool, have it run asynchronously and output some data into some shared object. As it’s doing this, have the main thread wait or do some other processing until the output is realized. Once its all done, the Thread Pool will suspend its threads and the main thread can resume doing its job.
What this Thread Pool is designed to do is to complete small tasks asynchronously. Sticking a dedicated piece of code on one thread (such as a sound subsystem, or networking) is rather counter productive to a Thread Pool because it utilizes the thread until the end of the program. I would suggest that a subsystem that is substantially heavy be on a separately spawned thread instead. Another word of advice that I came across is to keep the amount of writing done on each thread to a minimum because it requires locks. The best approach is to have each thread write to its own dedicated memory that is attached to the Job that its processing. Keep the shared data read only when possible.
I’m in the process of implementing my own Thread Pool and once its done, I’ll post some metrics.
Posted in 3D Stuff, C/C++, Stuff, win32 | No Comments »