Auto Debug Procedure

Have you ever need to debug an application but you couldn’t start it from the debugger. An example is a process that gets launched from another application. Lets say you have a Visual Studio solution which handles 2-3 executable projects. You start one with the debugger and you want to break in another process as soon as it starts.

I wrote a small macro for Visual Studio for which you can easily mark an executable projects as to Auto Debug when it gets executed. It used Microsoft jitdebugger registry entry to make this works.

First you need to import this macro into Visual Studio:

Imports System
Imports EnvDTE
Imports EnvDTE80
Imports EnvDTE90
Imports EnvDTE90a
Imports EnvDTE100
Imports System.Diagnostics
Imports Microsoft.VisualStudio.VCProject
Imports Microsoft.VisualStudio.VCProjectEngine
 
Public Module Quickies
 
    Sub RegKeySave(ByVal i_RegKey As String, _
               ByVal i_Value As String, _
      Optional ByVal i_Type As String = "REG_SZ")
        Dim myWS As Object
 
        'access Windows scripting
        myWS = CreateObject("WScript.Shell")
        'write registry key
        myWS.RegWrite(i_RegKey, i_Value, i_Type)
 
    End Sub
 
    Function GetMiscDumpPane() As OutputWindowPane
 
        Dim ow As OutputWindow = DTE.Windows.Item(Constants.vsWindowKindOutput).Object
        Dim pane As OutputWindowPane
 
        Try
            pane = ow.OutputWindowPanes.Item("MyMacrosPane")
        Catch ex As Exception
            pane = ow.OutputWindowPanes.Add("MyMacrosPane")
        End Try
        Return pane
    End Function
 
    Sub SetAutoDebug(ByVal state As Boolean)
 
        Dim linkerOutput As String
        Dim itemName As String
        Dim projectName As String
        Dim project As EnvDTE.Project
 
        If DTE.ActiveSolutionProjects.Length <> 1 Then
            MsgBox("Select one project within the Solution Explorer, then re-run this macro.")
            Exit Sub
        End If
 
        Dim pane As OutputWindowPane = GetMiscDumpPane()
 
        project = DTE.ActiveSolutionProjects(0)
        itemName = project.FullName()
 
        ' Get linker option
        If project.Kind = vcContextGuids.vcContextGuidVCProject Then
            Dim vcProj As VCProject = project.Object
            Dim configs As IVCCollection = vcProj.Configurations
 
            projectName = vcProj.Name
 
            Dim cfg As VCConfiguration = configs.Item(1)
            If cfg Is Nothing Then
                pane.OutputString("Project " & vcProj.Name & " has no valid configuration" & vbCr)
                Exit Sub
            End If
 
            Dim tools As IVCCollection = cfg.Tools
            Dim linkerTool As VCLinkerTool = tools.Item("VCLinkerTool")
            If linkerTool Is Nothing Then
                pane.OutputString("Project " & vcProj.Name & " has no output" & vbCr)
                Exit Sub
            End If
 
            linkerOutput = linkerTool.OutputFile
            linkerOutput = linkerOutput.Substring(linkerOutput.IndexOf("$(OutDir)") + 9)
 
        End If
 
        If state = True Then
            ' On
            RegKeySave("HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\" & linkerOutput & "\debugger", "vsjitdebugger.exe")
 
            pane.OutputString("Project " & linkerOutput & " => Auto debug ON" & vbCr)
        Else
            ' Off
            RegKeySave("HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\" & linkerOutput & "\debugger", "")
 
            pane.OutputString("Project " & linkerOutput & " => Auto debug OFF" & vbCr)
        End If
 
    End Sub
 
    Sub SetAutoDebugOn()
        SetAutoDebug(True)
    End Sub
 
    Sub SetAutoDebugOff()
        SetAutoDebug(False)
    End Sub
 
End Module

Then follow the the steps above to install and use the macro:

  • Import the script Quickies.vb into VS2010 in the Macro Explorer

-         

  • Then open the customize tool in VS2010 by right clicking on the menu bar and select Customize…
  • Goto the Commands tab
  • Select ‘Toolbar’ radio button
  • Select in the list ‘Context Menus | Project and Solution Context Menus | Project’

-         

  • Then do Add Command…
  • Select the category ‘Macros’
  • Select the Macros called ‘Macros.MyMacros.Quickies.SetAutoDebugOn (repeat the same thing for SetAutoDebugOff)
  • Then you can change de label using the ‘Modify Selection’ button
  • Then finally, when you right click on a project you can set it to AutoDebug On or off like this:

         

  • One last thing, in the Macro Explorer under the Reference thing you need to add two references:

-         

Then when Auto Debug is on, then and the process gets launched of any manor, then you’ll get the option to debug it.

Posted in Tool | Tagged , | Leave a comment

INF4715: This year projects (2012)

Here’s a few videos on this year projects for the course I give at École Polytechnique de Montréal. All these games were made using C++ and Vicuna 2012, a small academic game engine that I maintained.

Rocketman

Toy Tank

Fantomas

Killforms

Rasinjas

Hotakadake

Posted in Gaming, News | Tagged , , | Leave a comment

C++11 Certified!

Yes I am now C++11 Certified!

This week we got a nice C++11 course giving by the guys from develop.com, over-viewing all the nice features of C++11.

My three favorite features are:
- auto

auto element = map_of_something.begin()->second;

- template alias

template<typename T>
using VCNHashTable = std::unordered_map<std::string, T>;
// ...
VCNHashTable<VCNEffect*> mEffects;

- and range for (not in VC10, but in VC11)

for( auto effect : mEffects )
{
  effect->RenderMesh(...);
}

See http://herbsutter.com/elements-of-modern-c-style/ for more info.

But why in hell, did they not add more nice features to std::string (trim(), split(), multiple favors of replace(), etc)? They just had too take a look at QString, String in C#. Bah! All other languages and popular libraries has nice string classes, but we are still with a low feature string class.

Posted in C++ | Tagged | Leave a comment

Check out Skyline and Space Madness at GDC 2012



Our game team at Autodesk worked really hard on Skyline and Space Madness for GDC and you can watch what we’ve made so far at http://area.autodesk.com/gdc2012.

Space Madness is a small game we made at Autodesk in a small period of time to showcase all our middlewares in one game.
http://area.autodesk.com/gdc2012/featured/fs-hypermadness?KeepThis=true&#ooid=s0NDBwMzpodiATMffzVuDvj39-l5Lq6R

Skyline is the product I directly work on, and its goal is to build a platform to use a high-end product such as Maya and easily edit your game content in real-time. At the moment, you can do animation authoring in real-time for your game with Skyline.

Posted in News | Tagged , , | Leave a comment

Named Return Value Optimization in Visual Studio 2010

I’ve made a few tests with VS2010 for Named Return Value optimization (NRVO). NRVO is a mechanism compilers use to pass the return capture of a statement and passes it as an argument to a function for you. For example, if you do

std::string MyStringFunc()
{
  return std::string( "The answer to life, the universe and everything is 42" );
}
std::string str = MyStringFunc();

Then the compiler guarantees that only one string will be created, the returned value, and that “str” will store that value. So what this means, is that you’ll save a copy. But one thing must be said about this, VS2010 only enable this optimisation with /O2 meaning that you won’t get the same behavior in Debug and Release builds, so caution must be taken.
In the following snippet, you’ll see that we don’t get the same result in Debug and Release:

#include <tchar.h>
#include <iostream>
#include <vector>
struct MyStruct
{
  // Default constructor
  MyStruct()
  {
    std::cout << "First" << std::endl;
    floats.resize( 1000000 );
    floats[0] = 76;
  }
  // Copy constructor
  MyStruct(const MyStruct& r) 
    : i(r.i)
    , j(r.j)
    , floats(r.floats)
  { 
    std::cout << "Copy" << std::endl; 
  }
  // Move constructor
  MyStruct(const MyStruct&& r) 
    : i(r.i)
    , j(r.j)
    , floats(std::move(r.floats))
  { 
    std::cout << "Move" << std::endl; 
  }
  // Destructor
  ~MyStruct()
  {
    std::cout << "Destruct" << std::endl; 
  }
  int i;
  int j;
  std::vector<float> floats;
};
 
const MyStruct GetVar()
{
  MyStruct s; // First
  s.i = 42;
  s.j = 24;
  return s; // Copy or Move or Nothing with /O2
}
 
int _tmain(int argc, _TCHAR* argv[])
{
  const MyStruct r = GetVar();
  std::cout << "Result: " << r.i << " " << r.j << " " << r.floats[0] << std::endl;
  return 0;
}

If you run this in debug, you’ll get :

First
Move
42 24 76

And in Release you’ll get :

First
42 24 76

Saving the copy that can be costly. You get the same behavior with or without the explicit copy or move constructor. The move constructor is used by default if defined.

So the lesson is: don’t stop yourself from returning structures, but be aware that the code won’t flow the same in debug and release.

Posted in C++, Coding, Snippet | Tagged | Leave a comment

Vicuna 2012.02

I am releasing a new version of Vicuna 2012.02.

Download Here (~34 MB)

Vicuna is a simple, academic game engine integrating many middlewares.

Here’s the change log since the previous version:

 +-----------------+
 | 2012.02 (@r100) |
 +-----------------+
 Major refactoring
 Integrates FMOD
 Adds Shadow mapping
 Adds support for .X importation
 Adds Basic integration of PhysX 3.2
 Adds 3dsmax documentation
 Adds a method (RandomVector3) to generate random vectors
 Adds basic support to set the initial window position
 Adds deallocation of nodes to node allocator
 Adds packaging tools
 Adds PhysX camera visual debugging support
 Adds PhysX dynamic sphere support
 Adds PhysX support to load a static mesh from a VCNMesh
 Adds static terrain support
 Adds support for dynamic bodies
 Adds support to create an physic actor from a node
 Adds support to load .x files as Vicuna models.
 Cleans up shaders
 Cleans up the exporter a bit
 Cleans up the HUD
 Cleans up the menus
 Cleans up the project settings
 Deletes unused files
 Enables PhysX Profiling in debug builds
 Improves assertion dialog UI
 Extracts height from static terrain
 Fixes fullscreen mode
 Fixes node hierarchy transformation
 Fixes some .x vertex adjacencies errors
 Improves effects
 Improves SSAO (still bad when mixed with transparency)
 Improves Sun entity
 Moves PixProf.h to VCNRenderer module and overrides it in VCND3D9
 Optimize Awesomium rendering
 Reduces size of button in the assert dialog
 Refactors loading a mesh from a .x file.
 Refactors terrain effect
 Removes FMOD dependencies in GameApp
 Removes some unused sounds
 Renames precompiled headers
 Renames Terrain to ProceduralTerrain
 Replaces Game headers
 Replaces VCN D3D9 module headers
 Replaces VCNAudio headers
 Replaces VCNCore headers
 Replaces VCNFMOD headers
 Replaces VCNImporter headers
 Replaces VCNNodes headers
 Replaces VCNParticle module headers
 Replaces VCNPhysic module headers
 Replaces VCNPhysX module headers
 Replaces VCNRenderer module headers
 Replaces VCNResources module headers
 Replaces VCNTests module headers
 Replaces VCNUI module headers
 Replaces VCNUtils module headers
 Replaces VCNWindows module headers
 Updates sound configuration

Here’s a few shots of the engine in action:



Posted in Application, C++, Gaming | Tagged , , | Leave a comment

Skyrim only 6 GB?


Currently downloading Skyrim. The game is only 6 GB which is kinda small for today’s game of this importance. I’ll try to dig what were the techniques they used to keep the game this small.

Can’t wait to play it!

Posted in Gaming, News | Tagged | 2 Comments

Building or not a platform

The General Problem

Recently I am struggling with this simple question: Should we develop a generic platform? To put more context, should we develop a generic platform to build a specific application first? Let’s say you are doing an Next-Gen animation system, should you invest an important amount of time and energy to build that platform that could solve all type of system? My opinion on that matter is that you should do the less possible on the platform side and focus on the application you want to deliver. I am not saying that you shouldn’t try to make a good platform or framework, I am just saying that if you try to develop that platform at the same time, there is good chance you’ll have a lot of problem in the long run. Its like those game company that try to make a game engine and a game both at the same time from day one, most of them fails to do so. It is not much different for application frameworks.

In example, Unreal Engine wasn’t made to create Unreal, Unreal was created and out of this success story, they then made a more useful engine that they were able to deploy to other teams and companies.

I really think, that you should focus on doing the best application you can, and then, when you know your application is good enough, invest some time and effort to extract the good stuff to build your platform slowly. Is it not why refactoring exists?

Anyway, don’t get me wrong, I am not saying a framework is not important, and that you should go and hack your system from day one, I am saying that its best to show that your application works before than having a framework that pretends to solve everything generically but fails to solve your main goal.

People who prefer to have a sexy framework tend to write an complex API before writing code that will eventually call these API calls. What a error this is! Because most of them, are the type of person who would kill an ant with a Bazooka! They generally over-engineered their interface with templates, abstract names that means nothing, etc. Also, it is important to note that more your code is generic, more slowly it runs in the general case! The bad performance of these frameworks is most of the time detected to late in the development and really hard to solve.

So here my short list of rules I tend to follow in my software development cycles:

1. Always focus on the application, not the framework -> People buys applications, not platforms (ok SAP is the exception!)
2. Write client code before service code -> code that never gets called is useless
3. Only implement stuff that gets used -> when you over-engineer you tend to make stuff that is hard to debug and also stuff that don’t get used from the start tend to be more bogus
4. Design things that are easy to debug -> code easy to debug, make your development velocity much better on the long run, keep template and complex class hierarchy to a minimum
5. Fix your bugs when they are found -> otherwise you are looking for bigger problems (read broken window theory)
6. Make sure everyone on your team are on the same page -> Cohesion, convergence and complicity are the keys to productivity!

Good luck

Posted in Application, Gaming, News | Tagged , | Leave a comment

3devlog

3devlog logo

Some friends of mine started their service company. Visit them if you need software development services. http://3devlog.wordpress.com/

Posted in News | Tagged | Leave a comment

Floating points: don’t fix what ain’t broken!


Here’s an example that demonstrate two things. First, casting a double to a float back to a double can’t give you the same result auto-magically. Second, when you have a program that outputs double or single precision to strings, make you sure you don’t try to specify the highest precision yourself, since you might make the user blink an eye.

That’s what happened to me today. We have a program which we don’t directly control the source code and that program only handles double precision floating point values as input and output, but our plugin to that program stores single floating point values for memory and performance concerns. So the user enters numeric value in string format that gets converted to double, then we take that number and store it in our database using floats. Then at some point, the user queries that value later and realize that 0.3 = 0.30000001192092896, blinks an eye, says WTF, come to your desk, tell you that your stuff is all wrong, you cry, you try to fix that thing by doing floating point magic, your magic only works for ONE case, then cry again and then you realized, AH HA… that you can’t do nothing for that poor QA guy that just want 0.3 to equal 0.3!

Here what happened: that program which we don’t control the source, decided to print on the screen using cout << setprecision(18) << double_value; the numeric value. If that program would have used something like sprintf( buf, “%f”, value ) to build the string to print, the user would have got the right result (0.3 = 0.3!), since sprintf would have use round-trip to format the right value.

So all that said, casting from double to float back to double or float to double back to float (or whichever fucking-asking-for-trouble-casting-order) will most of the time never give you the same numeric value, and setting the precision at which you display info to the user won’t serve no one! Also if you do automation with stuff that gets manipulated as such, please don’t compare floating numbers together directly. As an example, you can use the code below to validate your input with the program’s output:

fabs(d1 - d2) < EPSILON ? "equal" : "not equal";

Summary:
1- Don’t do try to do magic with floating point numbers! You won’t serve anyone.
2- Only set the precision for numeric value if YOU KNOW what precision to use!

Here’s a small program that demonstrate what I talk about above.

#include <tchar.h>
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <iostream>
#include <math.h>
#include <iomanip>
#include <sstream>
 
#define ASSERT( expr ) printf("%s is %s\n", #expr, expr ? "true" : "false")
 
const char* manipulate(const double dInput1, const char* input, char* output)
{
  const double dInput2 = strtod( input, NULL );
  const float fInput = static_cast<float>( dInput2 );
  const double dOutput = static_cast<double>( fInput );
 
  std::stringstream ss;
  // < BAD DON'T DO THIS IF YOU DON'T REALLY HAVE A REASON
  ss << std::setprecision(18) << dOutput;
 
  // > DO SOMETHING SIMPLER LIKE THIS THAT WILL HANDLE THE PRECISION MORE NICELY
  sprintf( output, "%f", dOutput );
 
  // I hope it is true!
  ASSERT( dInput1 == dInput2 ); 
 
  // That's why you shouldn't specify the highest precision yourself!
  ASSERT( strcmp(ss.str().c_str(), output) == 0); 
 
  // Can't happen! If you know how, send me a mail!
  ASSERT( dInput2 == dOutput );
 
  return output;
}
 
int _tmain(int argc, _TCHAR* argv[])
{
  char bufferOutput[32] = { '\0' };
 
#define TEST(dvalue) printf( "%s = %s\n", \
                #dvalue, manipulate(dvalue, #dvalue, bufferOutput) )
 
  TEST( 0.3 );
  TEST( 0.123 );
  TEST( 0.10 );
 
  return 0;
}
Output for 0.3:
input   = "0.3"
output  = "0.300000" // GOOD AND WANTED
ss.c_str()  = "0.30000001192092896" // GOOD BUT UNWANTED
dInput1 = 0.29999999999999999
dInput2 = 0.29999999999999999
fInput  = 0.30000001
dOutput = 0.30000001192092896	

// As expected, inputs are equal, Ouf!
dInput1 == dInput2 is true

// Strings aren't equal, someone decided to use an unjustified hard-coded precision!
strcmp(ss.str().c_str(), output) == 0 is false

// That's normal, IEEE-754 ain't magic, don't try to fix it, just make sure you print something meaningful to the user!
dInput2 == dOutput is false
Posted in C++, Coding | Tagged , | Leave a comment