Skip navigation

I didn’t initialize the filename member:

GetOpenFileName fails if you do _not_ write a blank string to ofn.lpstrFile

Be sure to

 

sprintf( ofn.lpstrFile, “” ) ;

 

before calling OpenFileName

A simple template, to find the minimum of 3 numbers.

Can you find the bug in this code?

  template<typename T> inline T min3( const T& a, const T& b, const T& c )
  {
    if( a < b && a < c )  return a ;
    else if( b < a && b < c ) return b ;
    else return c ;
  }

Hint: Actually I’m not going to give you any hints. But it is possible for the above function to return the incorrect value.

Sibernik Cathedral

(Download links dead), now available on web archive: .max | 3ds | lp

SPONZA ATRIUM

I got an AMD FX-8150 chip in a new PC build.

_It sucks._ It’s no better than the AMD 1090T, which incidentally was taken _off_ the market by AMD. Now I know why. The 1090T performs very similarly (with no overclocking at all, either chip) to the “new” AMD 8 core.

I was already using an AMD 1090T to do parallel raytraces. I thought I’d get a second machine as a workhorse. Built one for $500. Shoulda gone with Intel. I’m running the same raytrace in parallel, one on this machine (which I’m also using to write this post) and I’m leaving the FX 8150 alone. The FX 8150 spawned 8 threads to raytrace on (7 for raytracing and 1 for the UI) because 8 cores were detected, here on the 1090T only 5 raytracing threads are running, +1 for the UI thread.

So far they are neck and neck, even though I am using this machine to write this post. The FX 8150 machine has completed 119/300 jobs (each “job” is 2 800 pixel long rows), this machine 117/300 jobs. Totally terrible. I expected _some sort_ of improvement, with a 400 MHz faster clock speed and 2 extra cores, but you get absolutely nothing.

It’s the SAME core as the 1090T, far as I’m concerned.

Further proof

So, there’s always this question of “what’s the difference between rotation*translation matrix VS translation*rotation”?

DOES TRANSLATION VS ROTATION ORDER MATTER?

__YES IT DOES__.

From here on in, we will assume a COLUMN major matrix. This means that vectors are POST MULTIPLIED by matrices.

MATRIX1 * MATRIX2 * SOME_VECTOR

means SOME_VECTOR gets “hit” by MATRIX2 first, then MATRIX1. Matrix multiplication is associative, so it doesn’t matter if we multiply through (MATRIX1*MATRIX2) first, then multiply THAT resultant 4×4 matrix by SOME_VECTOR. The result will be the same if we do (MATRIX1*MATRIX2)*SOME_VECTOR or if we do MATRIX1*(MATRIX2*SOME_VECTOR). That’s associativity for matrices.

BUT IT DOES matter if we do

MATRIX2 * MATRIX1 * SOME_VECTOR

You will get a completely different result vs when you do MATRIX1*MATRIX2*SOME_VECTOR.

If you do translation*rotation, the effect is __spinning in place__, because ROTATE about axis (we are still @ origin), then translate.

translation * rotation, produces SPINNING effect, column major

translation * rotation, produces SPINNING effect, column major

If you do rotation*translation, the effect is __ORBITING__ around an axis, because trans FIRST, then rotate about the axis (which is now far away)

rotation * translation, produces ORBITING effect, column major

rotation * translation, produces ORBITING effect, column major

Final note, if you are using ROW MAJOR matrices, then these results are reversed (ie backward).

I’ve seen this _more than once_ and always seem to look to the wrong things..

# Problem: patchy renders

# Diagnosis: Eye is TOO CLOSE to the surfaces when rendering hemicubes.

– turn OFF backface rendering (CULL THE BACKFACES!!)
– move the eye 1e-9 units in the direction of the eyeToLook vector (to move it JUST ABOVE the surface of the patch you are getting the hemicube for)

error FTK1011: could not create the new file tracking log file: The file exists.

This error means visual studio 2010 is unhappy about a DEBUG/RELEASE/BUILD folder already existing. You need to go to your project folder and delete ALL build folders (/Debug, /Release) and then rebuild the project.

We all know d/dx sin( x ) = cos( x ).

Also noted that constitutes a +90 degree phase shift in sin( x )

Page 283 of Ashdown’s Radiosity text and page 9 of ppsloan’s cube projection both use this.

The reason r is sqrt( 1 + u^2 + v^2 ) is:

Since a week or so MSDN pages scraped by google have been meant for small devices like the iPad.

Here’s the msdn unshit scriptlet, which just replaces the /windows/desktop/ part of the url with nothing:

javascript:window.location = String(window.location).replace(/(.*)\/windows\/desktop(.*)/, ‘$1$2′ ) ;

This is easy but usually tricky to get the hang of at first

EVERY VECTOR HERE IS A UNIT VECTOR EVEN IF IT DOESN’T APPEAR SO IN THE DIAGRAMS

If you have an incident vector hitting a surface (that has a normal defined for it!), then you can calc the angle of the reflected vector like so:


EVERY VECTOR HERE IS A UNIT VECTOR EVEN IF IT DOESN’T APPEAR SO IN THE DIAGRAMS

ANSWER:

reflected = incident – 2 × (normal ⋅ incident) normal

WHY?


EVERY VECTOR HERE IS A UNIT VECTOR EVEN IF IT DOESN’T APPEAR SO IN THE DIAGRAMS

All you’ve gots to do is look at the angle the incident makes with the normal. That’s what the formula I gave says anyway.

But also consider this. If the incident is perpendicular to the normal, then the reflected angle has pretty much no change from the incident angle. IE AT the case where the incident vector has an angle of 90 degrees with the normal of the surface, the “reflected” vector (if you can call it that!) is in the same direction as the “incident” vector. That is because the dot product (normal ⋅ incident) goes to 0 when the angle between incident and normal is 90 degrees, so:

reflected = incident – 2 × (normal ⋅ incident) normal
reflected = incident – 2 × (0) normal
reflected = incident

So that’s interesting. Now consider the other case where the angle between the normal and incident is 180 degrees (ie the ray hits the surface head-on):


EVERY VECTOR HERE IS A UNIT VECTOR EVEN IF IT DOESN’T APPEAR SO IN THE DIAGRAMS

reflected = incident – 2 × (normal ⋅ incident) normal
reflected = incident – 2 × (-1) normal
reflected = incident + 2 × normal

IE reflected turns completely around.

For everything else in between, there’s cosine.

So there is LESS change in the direction of the reflected angle as the incident-normal angle grows. This is encoded by the dot product/cosine in the normal reflection.

Ok, here’s the math for it.

Using this diagram:


EVERY VECTOR HERE IS A UNIT VECTOR EVEN IF IT DOESN’T APPEAR SO IN THE DIAGRAMS

The angle THETA there is going to be the cosine of the NORMAL and the INCIDENT

The SMALLER ANGLE GAMMA is going to be (THETA – 90) because the normal is at an angle of 90 degrees with the surface. That’s why its a normal, duh!

Now then some simple vector math will give you:

The length of the pink side X (perp distance to surface from INCIDENT vector:)

X = sin( GAMMA ) (remember incident is a unit vector)

So, now

REFLECTED = INCIDENT + 2 (sin (GAMMA)) ( NORMAL )

This makes sense because WHEN (sin(GAMMA)) is small, (angle between INCIDENT and NORMAL == nearly 90 degrees) we don’t need to add a large “displacement” in the direction of the normal to get the reflected vector (we add 0 x normal in the extreme case of a 90 degree INCIDENT angle with NORMAL). As the angle between NORMAL and INCIDENT INcreases, so does the displacement we need to use to the reflected vector, until we get to the other extreme case where the REFLECTED = INCIDENT + 2 * NORMAL.

Ok then, simplify.

REFLECTED = INCIDENT + 2 (sin (GAMMA)) ( NORMAL )
REFLECTED = INCIDENT + 2 (sin (THETA – 90)) (NORMAL)
REFLECTED = INCIDENT + 2 (sin (THETA)cos(90) – sin(90)cos(THETA)) (NORMAL)

cos(90)=0, sin(90)=1

REFLECTED = INCIDENT + 2 (-cos(THETA)) (NORMAL)

cos(THETA) = INCIDENT ⋅ NORMAL

REFLECTED = INCIDENT – 2 ( INCIDENT ⋅ NORMAL ) (NORMAL)

And there you have it.

LightWave 3D OBJ Export v2.1 is completely screwed up

In this model I have, it does the most ODD things.

One thing it does (but this is valid, just I didn’t expect it) is it uses negative texcoord indices sometimes (so f 5/-1 126/-2 140/-3 52/-4). Negative indices just means to use the last vt, 2nd last vt, etc.

The thing it does apparently wrong is it DOES NOT include any newmtl statements, or a mtllib file, and it uses usemtl statements as if they are _IMAGE FILENAMES_ (really its supposed to be map_kd, or map_ka).

The quick fix is to add code:
– if usemtl is attempted but that mtl doesn’t exist, create it and see if there is an image with the same filename as the mtl. If there is, load it and use it for that mtl.
– check the vt index and if it is negative, use the -whatever vt coordinate from your current point in the file

These aren’t _that bad_, but they really should follow the file format correctly

Also, it exports non-convex polygons.

if( sh ) then: puts( “Yeah it was sh” ) ;

D3D9 Vertex buffer and index buffer sample code

//
// Nice MSDN article on vertex/index buffer draw scenarios
// http://msdn.microsoft.com/en-us/library/bb147325(VS.85).aspx
//

#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#include <d3d9.h>      // core direct3d
#include <d3dx9.h>     // aux libs

#include <dxerr.h>    // detailed error messages

#pragma comment(lib, "d3d9.lib")
#pragma comment(lib, "d3dx9.lib")  // aux libs
#ifdef _DEBUG
#pragma comment(lib,"d3dx9d.lib")
#else
#pragma comment(lib,"d3dx9.lib")
#endif

#pragma comment(lib, "dxerr.lib")

// Macros.
#define SAFE_RELEASE(ptr) if(ptr) { ptr->Release(); ptr = NULL; }
#define CAST_AS_DWORD(x) *((DWORD*)&x)
#define PI 3.14159

#pragma region define the Vertex structure
struct Vertex
{
  float x,y,z ;
  DWORD color ;

  // Ctor starts you at origin in black
  // with alpha (opacity) set to 100%
  Vertex()
  {
    x=y=z = 0.0f;
    color = D3DCOLOR_XRGB( 0,0,0 ) ;
  }

  Vertex( float ix, float iy, float iz )
  {
    x=ix;y=iy;z=iz;
    color = D3DCOLOR_XRGB( 255,255,255 ) ;
  }

  // Ctor.
  Vertex( float ix, float iy, float iz,
    unsigned char ir, unsigned char ig, unsigned char ib )
  {
    x=ix;y=iy;z=iz;
    color = D3DCOLOR_XRGB( ir, ig, ib ) ;
  }

  // Ctor that lets you pick alpha
  Vertex( float ix, float iy, float iz,
    unsigned char ir, unsigned char ig, unsigned char ib, unsigned char ALPHA )
  {
    x=ix;y=iy;z=iz;
    color = D3DCOLOR_ARGB( ALPHA, ir, ig, ib ) ;
  }
} ;
#pragma endregion

struct Globals
{
  struct _Win
  {
    HINSTANCE hInstance;    // window app instance
    HWND hwnd;              // handle for the window
    HWND hConsole ;         // handle for the console window

    int width, height;
  } win ;

  IDirect3D9 * d3d ;
  IDirect3DDevice9 * gpu ; 

  // Vertex buffer contains the vertices
  IDirect3DVertexBuffer9 *vb ;
  IDirect3DIndexBuffer9 *ib ; // order to draw the vertices in
};

///////////////////////////
// GLOBALS
Globals g;

///////////////////////////
// FUNCTION PROTOTYPES
inline bool CHECK( HRESULT hr, char * msg, bool stop=true ) ;  // checks for errors on the HR passed.
bool initD3D() ;         // function to initialize the BEAST that is Direct3D9
void update() ;          // changes geometry of the scene
void drawAxes() ;        // draws the ever-important axes (for finding your way around your own scene!)
void draw() ;            // drawing function containing Direct3D drawing calls

LRESULT CALLBACK WndProc( HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam );
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR szCmdLine, int iCmdShow );

/////////////////////////
// FUNCTION IMPLEMENTATIONS
inline bool CHECK( HRESULT hr, char * msg, bool stop )
{
  if( FAILED( hr ) )
  {
    printf( "%s. %s:  %s\n",
            msg, DXGetErrorStringA( hr ), DXGetErrorDescriptionA( hr ) ) ;

    // Pause so we can see the error and deal with it.
    if( stop )  system("pause") ;

    return false ;
  }

  else
    return true ;

}

/// Initializes Direct3D9.  Returns true on success.
bool initD3D()
{
  // start by nulling out both pointers:
  g.d3d = 0 ;
  g.gpu = 0 ;

  g.d3d = Direct3DCreate9( D3D_SDK_VERSION ) ;

  if( g.d3d == NULL )
  {
    // DEVICE CREATION FAILED!!!! OH NO!!!
    puts( "Oh.. PHOOEY!!!!!  Device creation FAILED!!! WHAT NOW???\n" ) ;
    return false ;
  }

  puts( "Direct3D9 creation success!" ) ;

  D3DPRESENT_PARAMETERS pps = { 0 } ;

  pps.Windowed = true ;
  pps.BackBufferCount = 1 ;
  pps.SwapEffect = D3DSWAPEFFECT_DISCARD ;
  pps.BackBufferFormat = D3DFMT_UNKNOWN ;
  pps.EnableAutoDepthStencil = true ;
  pps.AutoDepthStencilFormat = D3DFMT_D16 ;

  HRESULT hr = g.d3d->CreateDevice(

    D3DADAPTER_DEFAULT, // primary display adapter
    D3DDEVTYPE_HAL,     // use HARDWARE rendering (fast!)
    g.win.hwnd,
    D3DCREATE_HARDWARE_VERTEXPROCESSING,
    &pps,
    &g.gpu

  ) ;

  if( !CHECK( hr, "OH NOS!! I could not initialize Direct3D!  Bailing...\n" ) )
  {
    return false ;
  }

  puts( "Direct3D9 GPU device creation successful" ) ;

  hr = g.gpu->SetFVF( D3DFVF_XYZ | D3DFVF_DIFFUSE ) ;
  CHECK( hr, "SetFVF FAILED!" ) ;

  D3DVERTEXELEMENT9 pos ;

  pos.Usage = D3DDECLUSAGE_POSITION ;
  pos.UsageIndex = 0 ;
  pos.Stream = 0 ;
  pos.Type = D3DDECLTYPE_FLOAT3 ;
  pos.Offset = 0 ;

  pos.Method = D3DDECLMETHOD_DEFAULT ; 

  D3DVERTEXELEMENT9 col;

  col.Usage = D3DDECLUSAGE_COLOR ;
  col.UsageIndex = 0 ;
  col.Stream = 0 ;
  col.Type = D3DDECLTYPE_D3DCOLOR ;
  col.Offset = 3*sizeof( float ) ;
  col.Method = D3DDECLMETHOD_DEFAULT ;

  D3DVERTEXELEMENT9 vertexElements[] =
  {
    pos,
    col,

    D3DDECL_END()

  } ;

  IDirect3DVertexDeclaration9 * Vdecl ;

  hr = g.gpu->CreateVertexDeclaration( vertexElements, &Vdecl ) ;
  CHECK( hr, "CreateVertexDeclaration FAILED!" ) ;

  hr = g.gpu->SetVertexDeclaration( Vdecl ) ;
  CHECK( hr, "SetVertexDeclaration FAILED!" ) ;

  hr = g.gpu->SetRenderState( D3DRS_COLORVERTEX, TRUE ) ;
  CHECK( hr, "SetRenderState( COLORVERTEX ) FAILED!" ) ;

  hr = g.gpu->SetRenderState( D3DRS_LIGHTING, FALSE ) ;
  CHECK( hr, "Lighting off" ) ;

  hr = g.gpu->SetRenderState( D3DRS_CULLMODE, D3DCULL_NONE ) ;
  CHECK( hr, "cull mode off" ) ;






  int vbSize = 3*sizeof( Vertex );


  // CReate a vertex buffer
  // http://msdn.microsoft.com/en-us/library/bb174364(VS.85).aspx
  g.gpu->CreateVertexBuffer(
    vbSize,  // Length: Size of the vertex buffer, in bytes.
    0,       // Usage: 0 for when using hardware vertex processing (which we are!)
    0,       // FVF: I'm not using FVF, (I used a custom vertex declaration above)
    D3DPOOL_MANAGED, // D3DPOOL. Using a managed pool is good because it automatically
    // mirrors your data on the gpu and in system memory (so if the device is lost,
    // you don't have to re-create the vb)
    &g.vb,   // the vertex buffer
    NULL );  // always NULL

  Vertex* vbData ;
  // http://msdn.microsoft.com/en-us/library/bb205917(VS.85).aspx
  CHECK( g.vb->Lock(
    0, //Offset into the vertex data to lock, in bytes
    0,  // SECRET MSDN TIP:  "To lock the entire vertex buffer, specify 0 for both (OffsetToLock,SizeToLock) parameters"
    (void**)&vbData,
    0 // no special flags
  ), "Lock vb" ) ;
  {
    // write the data in. The vertex buffer is locked now,
    // and must be unlocked before we can draw it.
    vbData[ 0 ] = Vertex( -1, 0, 0, 255, 19, 0 ) ; // Red vertex @ ( -1, 0, 0 )
    vbData[ 1 ] = Vertex(  0, 1, 0, 0, 255, 0 ) ;  // Green vertex @ ( 0, 1, 0 )
    vbData[ 2 ] = Vertex(  1, 0, 0, 0, 0, 255 ) ;  // Blue vertex @ ( 1, 0, 0 )
  }
  CHECK( g.vb->Unlock(), "Unlock vb" ) ;




  // Create the index buffer
  CHECK( g.gpu->CreateIndexBuffer( 
    3*sizeof( short ), // size of index buffer, in bytes.  notice i have commited to use 16-bit indices here (I'm not
    // drawing more than 65536 vertices per draw call..)
    0, // Usage
    D3DFMT_INDEX16, // I'm using 16-bit indices
    D3DPOOL_MANAGED,
    &g.ib,
    NULL
  ), "Create index buffer" ) ;

  short* ibData ;
  CHECK( g.ib->Lock( 0, 0, (void**)&ibData, 0 ), "Lock ib" ) ;
  {
    ibData[0] = 0 ;
    ibData[1] = 1 ;
    ibData[2] = 2 ;
  }
  CHECK( g.ib->Unlock(), "Unlock ib" ) ;
  



  return true ;
}

void update()
{
}

////////////////////////
// DRAWING FUNCTIONS
void drawAxes()
{

  static float axisLen = 2.0f ;
  static Vertex axis[] = {

    // x-axis is red
    Vertex( -axisLen, 0, 0, 255, 0, 0 ),
    Vertex( +axisLen, 0, 0, 255, 0, 0 ),

    // y-axis green
    Vertex( 0, -axisLen, 0, 0, 255, 0 ),
    Vertex( 0, +axisLen, 0, 0, 255, 0 ),

    // z-axis blue
    Vertex( 0, 0, -axisLen, 0, 0, 255 ),
    Vertex( 0, 0, +axisLen, 0, 0, 255 )

  } ;

  HRESULT hr = g.gpu->DrawPrimitiveUP( D3DPT_LINELIST, 3, axis, sizeof( Vertex ) ) ;
  CHECK( hr, "DrawPrimitiveUP FAILED!" ) ;

  static float pointSize = 8.0f ;

  g.gpu->SetRenderState( D3DRS_POINTSIZE, CAST_AS_DWORD( pointSize ) ) ;

  // Draw points at end of axis.
  static Vertex points[] = {
    Vertex( axisLen, 0, 0, 255, 0, 0 ),
    Vertex( 0, axisLen, 0, 0, 255, 0 ),
    Vertex( 0, 0, axisLen, 0, 0, 255 ),
  } ;

  hr = g.gpu->DrawPrimitiveUP( D3DPT_POINTLIST, 3, points, sizeof( Vertex ) ) ;
  CHECK( hr, "DrawPrimitiveUP FAILED!" ) ;

}

void draw()
{
  HRESULT hr ;

  hr = g.gpu->Clear( 0, 0, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER,
    D3DCOLOR_ARGB( 255, 25, 25, 25 ), 1.0f, 0 ) ;
  CHECK( hr, "Clear FAILED!" ) ;

  #pragma region set up the camera
  D3DXMATRIX projx ;

  D3DXMatrixPerspectiveFovRH( &projx, PI/4, (float)g.win.width/g.win.height, 1.0f, 1000.0f ) ;

  g.gpu->SetTransform( D3DTS_PROJECTION, &projx ) ;

  D3DXMATRIX viewx ;

  D3DXVECTOR3 eye( 4, 2, 4 ) ;
  D3DXVECTOR3 look( 0, 0, 0 ) ;
  D3DXVECTOR3 up( 0, 1, 0 ) ;
  D3DXMatrixLookAtRH( &viewx, &eye, &look, &up ) ;
  g.gpu->SetTransform( D3DTS_VIEW, &viewx ) ;
  #pragma endregion

  hr = g.gpu->BeginScene() ;
  CHECK( hr, "BeginScene FAILED!" ) ;

  #pragma region ACTUALLY __draw__

  drawAxes();

  // DRAW
  
  g.gpu->SetStreamSource( 0, g.vb, 0, sizeof( Vertex ) ) ; // SET THE VERTEX BUFFER
  //CHECK( g.gpu->DrawPrimitive( D3DPT_TRIANGLELIST, 0, 1 ), "Draw raw vb" ) ; // You can draw from the vertex buffer directly

  g.gpu->SetIndices( g.ib ) ;  // SET THE INDEX BUFFER

  // DrawIndexedPrimitive: http://msdn.microsoft.com/en-us/library/bb174369(VS.85).aspx
  CHECK( g.gpu->DrawIndexedPrimitive(
    D3DPT_TRIANGLELIST,
    0, // BaseVertexIndex: Offset from the start of the vertex buffer to the first vertex
    0, // MinIndex: Minimum vertex index for vertices used during this call. This is a zero based index relative to BaseVertexIndex.
    3, // NumVertices: Number of vertices used during this call. The first vertex is located at index: BaseVertexIndex + MinIndex.
    0, // StartIndex: Index of the first index to use when accesssing the vertex buffer. Beginning at StartIndex to index vertices from the vertex buffer.
    1  // PrimitiveCount: Number of primitives to render.
  ), "Draw indexed prim" ) ; // or you can draw using the index buffer as well

  #pragma endregion

  hr = g.gpu->EndScene() ;
  CHECK( hr, "EndScene FAILED!" ) ;

  // And finally, PRESENT what we drew to the backbuffer
  g.gpu->Present( 0, 0, 0, 0 ) ;

}

int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR szCmdLine, int iCmdShow )
{
  //////////////////
  // First we'll start by saving a copy of
  // the hInstance parameter inside our
  // "glob" of globals "g":
  g.win.hInstance = hInstance;
  // In case we need it later, we'll have it
  // with firsthand easy access.

  #pragma region part 0 - attach a console
  // Attach a console
  AllocConsole();
  AttachConsole( GetCurrentProcessId() ) ;
  freopen( "CON", "w", stdout ) ; // redirect stdout to console
  freopen( "CON", "w", stderr ) ; // redirect stderr to console

  // Move the console over to the top left
  g.win.hConsole = GetConsoleWindow();
  MoveWindow( g.win.hConsole, 0, 0, 400, 400, true ) ;

  printf( "* * Computer Program Begin * *\n" ) ;
  #pragma endregion

  #pragma region part 1 - create a window
  // The next few lines you should already
  // be used to:  create a WNDCLASSEX
  // that describes the properties of
  // the window we're going to soon create.
  // A.  Create the WNDCLASSEX
  WNDCLASSEX wcx = { 0 } ;
  wcx.cbSize = sizeof( WNDCLASSEX );
  wcx.hbrBackground = (HBRUSH)GetStockObject( BLACK_BRUSH );
  wcx.hCursor = LoadCursor( NULL, IDC_ARROW );
  wcx.hIcon = LoadIcon( NULL, IDI_APPLICATION );
  wcx.hInstance = hInstance;
  wcx.lpfnWndProc = WndProc;
  wcx.lpszClassName = TEXT("Philip");
  wcx.lpszMenuName = 0;
  wcx.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;

  // Register that class with the Windows O/S..
  RegisterClassEx( &wcx );

  int width = 800, height = 600;
  int leftEdge = 400, topEdge = 25 ;
  RECT rect;
  SetRect( &rect,
    leftEdge,  // left
    topEdge,   // top
    leftEdge + width, // right
    topEdge  + height ); // bottom

  // Save width and height off.
  g.win.width = rect.right - rect.left;
  g.win.height = rect.bottom - rect.top;

  // Adjust it.
  DWORD windowStyle = WS_OVERLAPPEDWINDOW ; // typical features of a normal window
  DWORD windowExStyle = 0 ; // I want the window to be topmost

  AdjustWindowRectEx( &rect, windowStyle, false, windowExStyle );

  g.win.hwnd = CreateWindowEx(
    windowExStyle,
    TEXT("Philip"),
    TEXT("DIRECT3D WINDOW"),
    windowStyle,
    rect.left, rect.top,  // adjusted x, y positions
    rect.right - rect.left, rect.bottom - rect.top,  // adjusted width and height
    NULL, NULL,
    hInstance, NULL);

  // check to see that the window
  // was created successfully!
  if( g.win.hwnd == NULL )
  {
    FatalAppExit( NULL, TEXT("CreateWindow() failed!") );
  }

  // and show.
  ShowWindow( g.win.hwnd, iCmdShow );

  // JUMP to the initD3D() method.
  if( !initD3D() )
  {
    FatalAppExit( 0, TEXT("SORRY!!!  DEVICE CREATION FAILED!!! YOU LOSE, WITHOUT EVEN PLAYING THE GAME!!!" ) ) ;
  }

  #pragma endregion

  #pragma region message loop
  MSG msg;

  while( 1 )
  {
    if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) )
    {
      if( msg.message == WM_QUIT )
      {
        break;
      }

      TranslateMessage( &msg );
      DispatchMessage( &msg );
    }
    else
    {
      update();
      draw();
    }
  }
  #pragma endregion

  //////////////
  // clean up
  SAFE_RELEASE( g.gpu ) ;
  SAFE_RELEASE( g.d3d ) ;

  // and a cheesy fade exit
  AnimateWindow( g.win.hwnd, 200, AW_HIDE | AW_BLEND );

  printf( "* * This Computer Program Has Ended * *\n" ) ;

  return msg.wParam;
}

////////////////////////
// WNDPROC
// Notice that WndProc is very very neglected.
// We hardly do anything with it!  That's because
// we do all of our processing in the draw()
// function.
LRESULT CALLBACK WndProc(   HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam )
{
  switch( message )
  {
  case WM_CREATE:
    Beep( 50, 10 );
    return 0;
    break;

  case WM_PAINT:
    {
      HDC hdc;
      PAINTSTRUCT ps;
      hdc = BeginPaint( hwnd, &ps );
      // don't draw here.  would be waaay too slow.
      // draw in the draw() function instead.
      EndPaint( hwnd, &ps );
    }
    return 0;
    break;

  case WM_KEYDOWN:
    switch( wparam )
    {
    case VK_ESCAPE:
      PostQuitMessage( 0 );
      break;
    default:
      break;
    }
    return 0;

  case WM_SIZE:
    {
      int width = LOWORD( lparam ) ;
      int height = HIWORD( lparam ) ;
      printf( "RESIZED TO width=%d height=%d\n", width, height ) ;
    }
    break;

  case WM_DESTROY:
    PostQuitMessage( 0 ) ;
    return 0;
    break;
  }

  return DefWindowProc( hwnd, message, wparam, lparam );
}

Its not hard

Using Rich Edit controls
How to format text in rich edit controls

#include <windows.h>
#include <CommCtrl.h>
#include <Richedit.h>
#include <stdio.h>

HWND main, re;
#pragma comment( lib, "comctl32.lib" )

LRESULT CALLBACK WndProc( HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam );
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR szCmdLine, int iCmdShow );


void setColor( HWND richEditCtrl, COLORREF textColor, COLORREF bgColor )
{
  CHARFORMAT2 cf ;

  cf.cbSize = sizeof( CHARFORMAT2 ) ;
  cf.dwMask = CFM_COLOR | CFM_BACKCOLOR | CFM_EFFECTS2 ; // I'm setting only the style information
  
  cf.crTextColor = textColor ;
  cf.crBackColor = bgColor ;
  cf.dwEffects = CFE_BOLD ;
  
  SendMessage( richEditCtrl, EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&cf ) ;
}

int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPInst, char* line, int show)
{
	InitCommonControls() ;
  LoadLibrary(TEXT("Msftedit.dll"));
  

  WNDCLASSEX wc = { 0 };
  wc.cbSize = sizeof( WNDCLASSEX ) ;
  wc.hbrBackground = (HBRUSH)GetStockObject( WHITE_BRUSH );
  wc.hCursor = LoadCursor( NULL, IDC_ARROW );
  wc.hIcon = LoadIcon( NULL, IDI_APPLICATION );
  wc.hInstance = hInstance;
  wc.lpfnWndProc = WndProc ;
  wc.lpszClassName = TEXT("rt");
  wc.style = CS_HREDRAW | CS_VREDRAW;

  if( !RegisterClassEx(&wc) )
    FatalAppExitA( 0, "Couldn't register window class!" ) ;
	
  main=CreateWindowEx( 0, L"rt",L"title",WS_OVERLAPPEDWINDOW,64,64,640,480,0,0,hInstance,0);
  if( !main ) 
    FatalAppExitA( 0, "Couldn't create main!" ) ;
	
  // http://msdn.microsoft.com/en-us/library/bb774367(VS.85).aspx
  re=CreateWindowEx(0, MSFTEDIT_CLASS, TEXT("Hi!  Click anywhere on the bar above.\n"),
        WS_VISIBLE | WS_CHILD | WS_VSCROLL |
        ES_MULTILINE | ES_LEFT | ES_NOHIDESEL | ES_AUTOVSCROLL | ES_READONLY,
        0, 0, 640, 480, 
        main, NULL, hInstance, NULL);
  if( !re )
    FatalAppExitA( 0, "Couldn't create your rich text box!" ) ;

  CHARFORMAT2 cf ;
  cf.cbSize = sizeof( CHARFORMAT2 ) ;
  cf.dwMask = CFM_COLOR | CFM_BACKCOLOR | CFM_EFFECTS2 ; // I'm setting only the style information
  cf.crTextColor = RGB( 255, 0, 0 ) ;
  cf.crBackColor = RGB( 255,255,255 ) ;
  cf.dwEffects = CFE_BOLD ;
  SendMessage( re, EM_SETCHARFORMAT, SCF_ALL, (LPARAM)&cf ) ;
	
  ShowWindow(main,show);
  ShowWindow(re,show);

	MSG Msg={0};
	while (GetMessageA(&Msg,0,0,0))
	{
		TranslateMessage(&Msg);
		DispatchMessageA(&Msg);
	}
	return 0;
}


LRESULT CALLBACK WndProc( HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam )
{
  switch( message )
  {
  case WM_CREATE:
    // upon creation, let the speaker beep at 50Hz, for 10ms.
    Beep( 50, 10 );
    return 0;
    break;

  case WM_PAINT:
    {
      // we would place our Windows painting code here.
      HDC hdc;
      PAINTSTRUCT ps;
      hdc = BeginPaint( hwnd, &ps );

      // draw a circle and a 2 squares
      Ellipse( hdc, 20, 20, 160, 160 );
      Rectangle( hdc, 50, 50, 90, 90 );
      Rectangle( hdc, 100, 50, 140, 90 );

      EndPaint( hwnd, &ps );
    }
    return 0;
    break;

  case WM_SIZE:
    {
      int w = LOWORD( lparam ) ;
      int h = HIWORD( lparam ) ;
      MoveWindow( re, 0, 0, w, h, true ) ;
    }
    break;

  case WM_CHAR:
    switch( wparam )
    {
      case VK_ESCAPE: 
        PostQuitMessage( 0 ) ;
        break ;
    }
    break ;

  case WM_NCHITTEST:
  case WM_LBUTTONDOWN:
    {
      int x = LOWORD( lparam ) ;
      int y = HIWORD( lparam ) ;
      TCHAR buf[280];
      wsprintf( buf, L"Mouse is @ (%d, %d)\n", x, y ) ;

      // Move the caret to the end
      CHARRANGE crg = { LONG_MAX, LONG_MAX } ;
      SendMessage( re, EM_EXSETSEL, 0, (LPARAM)&crg ) ;

      // select random text color
      setColor( re, RGB( rand()%256, rand()%256, rand()%256 ), RGB( rand()%256, rand()%256, rand()%256 ) ) ;
      
      SendMessage( re, EM_REPLACESEL, TRUE, (LPARAM)buf ) ;
       

    }
    break ;

  case WM_RBUTTONDOWN:
    {
      // clear it with SETTEXTEX
      SETTEXTEX st ;
      st.codepage = CP_ACP ; // ansi codepage
      st.flags = ST_KEEPUNDO ;

      SendMessage( re, EM_SETTEXTEX, (WPARAM)&st, (LPARAM)"Cleared" ) ; // OVERWRITES all text
    }
    break ;

  case WM_DESTROY:
    PostQuitMessage( 0 ) ;
    return 0;
    break;

  }

  return DefWindowProc( hwnd, message, wparam, lparam );
}

D3D11: ERROR: ID3D11DeviceContext::Draw: A Vertex Shader is always required when drawing, but none is currently bound. [ EXECUTION ERROR #341: DEVICE_DRAW_VERTEX_SHADER_NOT_SET ]
D3D11: ERROR: ID3D11DeviceContext::Draw: Rasterization Unit is enabled (PixelShader is not NULL or Depth/Stencil test is enabled and RasterizedStream is not D3D11_SO_NO_RASTERIZED_STREAM) but position is not provided by the last shader before the Rasterization Unit. [ EXECUTION ERROR #362: DEVICE_DRAW_POSITION_NOT_PRESENT ]

These errors occur if you forget to have an output with the output semantic :COLOR on your pixel shader in d3d11.

Its a bit weird, but IDXGIKeyedMutex::AcquireSync has a parameter called Key. The docs state:

Key [in]
Type: UINT64

A value that indicates which device to give access to. This method will succeed when the device that currently owns the surface calls the IDXGIKeyedMutex::ReleaseSync method using the same value. This value can be any UINT64 value.

Observations:

  • - The first AcquireSync call __Must__ be made on 0, otherwise the app hangs forever
  • - If you Acquire on 0, and you release on 1, then the next person to pick up __must__ pick up on 1

Useful if ordering. Say A picks up the mutex on 0. Then, there are 2 objects B and C that must go in the order B, C. So:

– A PICKS UP 0, RELEASES on 1
– B picks up 1, releases 2
– C picks up 2, releases 0

Now they are going in a cycle, A,B,C,A,B,C…

C cannot go before B (because it will block until B releases on 2).

If you’re not ordering, you can just always use 0 for the key.

I didn’t know this, but an HINSTANCE is apparently a pointer to an IMAGE_DOS_HEADER struct.

int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow )
{
  IMAGE_DOS_HEADER* header = (IMAGE_DOS_HEADER*)(hInstance) ;
  // ...
}

See this

Its weird to choke in dtor, but I had this situation where I was _inserting into a vector_, and getting a weird bug.

Naturally I start to think “must be a compiler bug..”

And you know when you get that thought, there’s something to be learned. So keep searching.

It turned out I was doing pushes of the form

vector<AABB> vec ;
vec.push_back( AABB( min, max ) ) ;

So the AABB was being

1. CONSTRUCTED with the AABB(min,max) ctor call
2. Copy constructed into the vector
3. destructed (item that was originally AABB(min,max) ctor created must be destroyed after copy into the vector)

So it was crashing on the dtor bit.

Turned out I had a non-initialized object ptr in AABB, and in ~AABB it was attempted to destroy that non-init ptr. Forgot to include init to 0 in AABB(min,max) ctor.

I had this problem where some of my polygons were flickering. At first I wasn’t sure what was going on, then I realized I had 2 present calls in the same frame.

Thanks D3D11 for removing BEGINSCENE/ENDSCENE??!! Anyway, that was an annoying bug to find.

An amazing error,

D3D11: ERROR: ID3D11DeviceContext::Draw: Vertex Shader – Pixel Shader linkage error: Signatures between stages are incompatible. Semantic ‘TEXCOORD’ is defined for mismatched hardware registers between the output stage and input stage. [ EXECUTION ERROR #343: DEVICE_SHADER_LINKAGE_REGISTERINDEX ]

What this error means is you didn’t match up EXACTLY the ORDER of the OUTPUTS you your vertex shader with the INPUTS of your pixel shader.

For example, the following CG shader triggers the error:

Pixel shader

void vertexMain(
   in float4 ip : POSITION,
   in float3 N : NORMAL,
   in float4 ic : COLOR,
  
  // 4 outputs, in this order
  out float4 op : POSITION,
  out float4 oc : COLOR,
  out float4 posToPxShader : TEXCOORD0, // original space pos
  out float3 normToPxShader : TEXCOORD1,// original space normal
  
  // the concatenated modelview-projection matrix
  uniform float4x4 modelViewProj
{
  // vx shader code..
}

void pixelMain(
  //THIS PIXEL SHADER MUST RECEIVE
  // ALL 4 OUTPUTS OF THE VERTEX SHADER,
  // IN THE EXACT ORDER THAT THE VERTEX SHADER
  // OUTPUT THEM, OR YOU WILL GET AN ERROR
  // COMMENTING OUT THE LINE BELOW TRIGGERS THE ERROR
  //in  float4 tp : POSITION, // transformed space position // must rx b/c is output of vshader stage
  in  float4 ic : COLOR,
  in  float4 ip : TEXCOORD0,
  in  float3 N : TEXCOORD1
{
  // pixel shader code..
}

I was having a problem with a common C++ pattern:

//file1.h #include "file2.h" // file2.h #include "file1.h"

The header cross-inclusion sometimes results in compilation errors if “file1.h” requires a type from “file2.h” to be fully defined, and vice-versa.

So, what I started doing is stop #including every header file in every other header file and use forward declarations instead, and include the required header file in the code file that uses the class definition.

This can happen if you forget to call cgD3D9SetDevice( NULL ) ; before closing your application.

It is my opinion that globals are necessary __sometimes__.

You just can’t get around the fact that you need them, at times.

You can think of a member variable as actually .. a global variable.. within that class!

The best reasons NOT to use globals are

The problem with global variables is that since every function has access to these, it becomes increasingly hard to figure out which functions actually read and write these variables.

So to understand how the application works, you pretty much have to take into account every function which modifies the global state. That can be done, but as the application grows it will get harder to the point of being virtually impossible (or at least a complete waste of time).
- Brian Rasmussen

It’s better to talk about size of scope than whether or not something is global. “Global” just means maximum scope. Instead of saying “global variables are bad,” I think it’s more helpful to say “minimize variable scope.”

A global variable in a 100-line program has a scope of 100 lines. But a member variable in a 1000-line class has a scope of 1000 lines. The latter may be worse.

John D. Cook

Some say globals are seen as bad because of their bright scope.

References

  1. Are global variables bad?
  2. Global variables: When ARE they acceptable?
  3. ok , global variable is condemned, singleton is despised, what’s the alternative?
  4. When is it ok to use a global variable in C?
  5. ibm.com: Use your singletons wisely
  6. code.google.com: Why Singletons Are Controversial

Error 1 error C2825: ‘_Alloc’: must be a class or namespace when followed by ‘::’ c:\program files (x86)\microsoft visual studio 10.0\vc\include\vector 1544


Error 2 error C2039: ‘difference_type’ : is not a member of ‘`global namespace” c:\program files (x86)\microsoft visual studio 10.0\vc\include\vector 1544
Error 3 error C2146: syntax error : missing ‘,’ before identifier ‘difference_type’ c:\program files (x86)\microsoft visual studio 10.0\vc\include\vector 1544
Error 4 error C2065: ‘difference_type’ : undeclared identifier c:\program files (x86)\microsoft visual studio 10.0\vc\include\vector 1544
Error 5 error C2955: ‘std::_Iterator012′ : use of class template requires template argument list c:\program files (x86)\microsoft visual studio 10.0\vc\include\vector 1548
Error 6 error C2825: ‘_Alloc’: must be a class or namespace when followed by ‘::’ c:\program files (x86)\microsoft visual studio 10.0\vc\include\vector 1550
Error 7 error C2039: ‘size_type’ : is not a member of ‘`global namespace” c:\program files (x86)\microsoft visual studio 10.0\vc\include\vector 1550
Error 8 error C2146: syntax error : missing ‘;’ before identifier ‘_Sizet’ c:\program files (x86)\microsoft visual studio 10.0\vc\include\vector 1550
Error 9 error C4430: missing type specifier – int assumed. Note: C++ does not support default-int c:\program files (x86)\microsoft visual studio 10.0\vc\include\vector 1550
Error 10 error C2061: syntax error : identifier ‘_Sizet’ c:\program files (x86)\microsoft visual studio 10.0\vc\include\vector 1558
Error 11 error C2061: syntax error : identifier ‘_Sizet’ c:\program files (x86)\microsoft visual studio 10.0\vc\include\vector 1565
Error 12 error C2146: syntax error : missing ‘;’ before identifier ‘_Myoff’ c:\program files (x86)\microsoft visual studio 10.0\vc\include\vector 1582
Error 13 error C4430: missing type specifier – int assumed. Note: C++ does not support default-int c:\program files (x86)\microsoft visual studio 10.0\vc\include\vector 1582
Error 14 error C4430: missing type specifier – int assumed. Note: C++ does not support default-int c:\program files (x86)\microsoft visual studio 10.0\vc\include\vector 1582

Not really an error, occurs when you misuse STL function swap() by adding a type parameter.

Example of code producing the error:

#include <vector>
using namespace std ;

int main()
{
  int a=7, b=5 ;

  swap<int>(a,b) ; // This should be just swap( a, b ) ; with NO <TYPE>
}

A reference for me


GIT REPO CREATE:
# login to remote server
ssh git@REMOTE_SERVER

# once logged in
mkdir example.git
cd example.git
git --bare init

# TO EXPORT THE SERVER TO THE INTERNET

http://www.kernel.org/pub/software/scm/git/docs/user-manual.html#setting-up-a-public-repository

SERVER:
1.  Start up git-daemon &
2.  touch git-daemon-export-ok

CLIENT:
git clone git://myserverip/home/git/example.git



GIT REPO PUSH:
mkdir example
cd example
git init
touch README
git add README
git commit -m 'first commit'
git remote add origin git@REMOTE_SERVER:example.git
git push origin master




# TO PUSH AT A LATER TIME, USING USER OVERRIDE SETTINGS
$ git config --global user.name "Tekkub"
$ git config --global user.email "tekkub@gmail.com"

# PER REPO BASIS
$ cd my_other_repo
$ git config user.name "Not Tekkub"
$ git config user.email "not@tekkub.net"




# you can only push using ssh
GIT PUSH
========
git push ssh://git@255.10.10.1/home/git/REPO master

FRom:

http://groups.google.com/group/gitorious/browse_thread/thread/978f2b506286f425/1c55538158adf28a

GIT REPO CLONE:

To get the lab #2 starting code base:

1. Download and install the most recent version of msysgit

2. Once you have it installed, open git bash. In git bash:

cd /c
mkdir repodir
cd repodir

git clone git://github.com/username/projectname

Later, to retrieve updates to the code:

git pull git://github.com/username/projectname


That command will pull the latest updates to the code to your machine



see what you added
==================
git status


UNDO adding
===========
git reset --hard






BRANCHING
=========
git branch branchName     # create a new branch from where you are
git checkout branchName   # switch to using the branch

work on the branch then commit it using

PUSH BRANCH
===========
git push ssh://git@255.10.10.1/home/git/repoTest BRANCHNAME

if you do'nt include BRANCHNAME it assumes ou want to push "master".



Cloning a branch
================
XXXXXgit clone git://255.10.10.1/home/git/repoTest master  # gets
you the master branch..

git clone git://255.10.10.1/home/git/repoTest

no WAIT.  the whole point of GIT is you get EVERYTHING.
NO WAIT.  you DON'T.  there ar eREMOTE branches whihc you see by

git branch -r # SHOWS REMOTE BRANCHES

git show-branch # shows you the curent branch and commit summary

git checkout -b (new_branch_name) creates and switches to a branch




To check out the actual code though, after CLONE, you hvae to
git checkout origin/branchName

this also seems to work:
git pull git://255.10.10.1/home/git/repoName branchName

the funy thing is i'm still on *(no branch), not the actual bracn i'm
supposed to be on



VERY OOD USMMARY

http://git.or.cz/course/svn.html

git log



ah, i see.  a remote branch "you never mess with remote branches", -
meaning its somebody elses' bracnh they're working on and is liable
for seroius chagne so why would you formally say you'r echekcing it
out/  you can't.

so you instead can TRACK their bracnh, which is sort of informally
saying "mirror that to me" but you can't formally WORK ON THEIR BRACNH
unless they are commited to HEAD

git checkout --track -b raster-test-mine origin/raster-test

this "branch raster-test-mine set up to track remote branch
refs/remotes/origin/raster-test

the REMOTES branches it seems are REMOTE TO THE REPOSITORY, not to
YOU.  its SOME USER SOMEHWERE IN SPACE that is REMOTE to the SERVER.

so once you work on your branch a bit, you can PUSH your branch ot the
server by commiting etc

Well I always forget this pattern, so without further ado,

#include <ctime>
#include <stdio.h>

tm* getCurrentTime()
{
  static time_t raw ;
  
  // grab the current time
  time( &raw ) ;

  // Now create that timeinfo struct
  static tm* timeinfo ;
  timeinfo = localtime( &raw ) ;

  return timeinfo ;
}

void printCurrentTime()
{
  // write time into timeBuff
  static char timeBuf[ 256 ] ;
  strftime( timeBuf, 255, "%a %b %d %Y %X", getCurrentTime() ) ; // See here for % meanings

  puts( timeBuf ) ;
}

int main()
{
  printCurrentTime() ;
}

C++ pointer to a member function simple example

Original understanding from this


#include <stdlib.h>
#include <iostream>
using namespace std ;

class Obj
{
public:
  double fcn( int p1, int p2 )
  {
    return p1+p2;
  }
};

typedef double (Obj::*  /*AS*/FcnPtrType/*(end of name)*/  )( int, int ) ;

int main()
{
  // Create a pointer to A MEMBER FUNCTION OF THE "Obj" class, THAT RETURNS DOUBLE;
  // WHOSE INSTANCE NAME IS fcnPtr;
  // WHO ACCEPTS 2 ARGUMENTS, BOTH OF TYPE INT
  double (Obj::*  fcnPtr  )( int, int ) = &Obj::fcn ;

  // Let me break that down for you in steps:
  //double (Obj::*  // Create a pointer to A MEMBER FUNCTION OF "Obj" class, THAT RETURNS DOUBLE;
  //fcnPtr  )       // WHOSE INSTANCE NAME IS fcnPtr;
  //( int, int ) ;  // WHO ACCEPTS 2 ARGUMENTS, BOTH OF TYPE INT

  // Function pointer naming syntax is tricky to get the hang of,
  // but the tricky part is the NAME of the function pointer instance
  // is IN BRACKETS, BEFORE the parameter type listing.  This is
  // counter to what you'd normally expect in C++, where the
  // instance name always appears LAST in the line (breaks the
  // principle of least surprise, I suppose).
	
  // Now lets create an object (whose member function we will call
  // via the function pointer)

  Obj obj ;

  printf( "%f\n", (obj.*fcnPtr)( 3, 7 ) ) ;

  return 0;
}

A simple example that shows how to create a thread in C++ on Win32 platform

    #include <Windows.h>
    #include <stdio.h>
    
    struct Point
    {
      float x,y,z ;
    } ;
    
    DWORD WINAPI threadStartPoint( LPVOID data )
    {
      Sleep( 1000 ) ;
      Point *p = (Point*)data ;
      printf( "%f %f %f\n", p->x, p->y, p->z ) ;
      puts( "Thread job done" ) ;
      return 0 ;
    }
    
    // From main
    int main()
    {
      DWORD threadId ;
      Point p ;
      p.x=2, p.y=3, p.z=4 ;
      HANDLE handle = CreateThread( 0, 0, 
        threadStartPoint,
        (LPVOID)&p,
        0,
        &threadId
      ) ;
    
      if( !handle )
      {
        // Thread creation failed
        puts( "start fail\n" );
      }
      else
      {
        printf( "started on threadid=%d\n", threadId ) ;
      }
    
      WaitForSingleObject( handle, 2000 ) ; // wait up to 2000 ms for the other thread to complete before moving on
    
      puts( "main thread Exiting.." ) ;
      //system( "pause" ) ;
    }

Expression: vector iterator not dereferencable

A common problem C++ newbs encounter is

Expression: vector iterator not dereferencable

The deal with this statement is it usually occurs in a program like

#include <iostream>
#include <vector>
#include <deque>
using namespace std ;

int main()
{
  vector<int> a ;

  for( int i = 0 ; i < 10; i++ )
    a.push_back( i );

  for( vector<int>::iterator i = a.begin() ; i != a.end() ; ++i )
  {
    if( *i == 5 )
      a.erase( i ) ; // ERROR!!

    cout << *i << endl ;
  }
}

So on the line that says // ERROR!! is where the source of the problem is.

When you .erase from a std::vector, you actually invalidate all existing iterators. So doing ++i then, once you hit the loop repeat, is invalid now.

To fix this, simply UPDATE i AFTER YOU CALL ERASE like so:

      i = a.erase( i ) ;

What this does is SET i TO BEING THE ELEMENT AFTER THE ONE YOU JUST DELETED. The result is the program works and you don’t get the error.

Full program:

#include <iostream>
#include <vector>
#include <deque>
using namespace std ;

int main()
{
  vector<int> a ;

  for( int i = 0 ; i < 10; i++ )
    a.push_back( i );

  for( vector<int>::iterator i = a.begin() ; i != a.end() ; ++i )
  {
    if( *i == 5 )
      i = a.erase( i ) ; // Better!!

    cout << *i << endl ;
  }
}

Finish this thought later, but a capacitor is like filling up a balloon, it resists current flow when the capacitor is full.

The equation talks about “the rate of change of charge” (ie the CURRENT) is equal to

dq/dt + q/RC = V/R

Or
I(t) = Vs/R – q/RC

Where Vs is the voltage of the source, and q/RC is a measure of how much charge is on the plates so far.

That means the current is SLOWING DOWN as the difference between (VoltageSource/R – charge stored) becomes smaller.

and an inductor is like kinks in a hose (slows down change in current flow).

dI/dt + I R/L = V/L

Or
LdI/dt + I R = V

Which means the rate of change of CURRENT is
dI/dt = V/L – I R/L

Ie the rate of change of current is going to depend on CURRENT CURRENT, so like how fast it changes, depends on how much current is already flowing. The inductor slows down RATE OF CHANGE OF CURRENT because the higher the inductance L, the lower dI/dt is.

Its annoying how they hide these, but they’re all available on the web.

SERVICE PACK 3

SERVICE PACK 2

Total derivatives vs Partial derivatives

So what’s the diff? Ha ha. Get it?

The total derivative is what you’re introduced to in elementary calculus.

Its the one where you have an equation like:

P(x) = 2*x2 + x

and then you take the (total) derivative with respect to x:

P’(x) = 4*x + 1

Intuitively a derivative is how fast something changes, as you change another thing.

So P’(x) describes the rate of change (how fast P(x) changes) as you change the x value.

So when x=2, P’(x)=9, which means P(x) is increasing fairly rapidly at x=2.

Now, take this formula for the Volume Of a Cone (imagine: the amount of water a dunce cap can hold or something).

Here, there are two independent variables: the radius r and the height h.

Uh oh. That means there are two ways to change the volume of a cone!! One is by increasing its height (holding the width constant, so the dunce cap becomes taller) and the other is by increasing its width (holding the height constant, so making the cap fit a fatter dunce’s head).

Of course, we could ALSO make it so the HEIGHT of the hat DEPENDS ON the WIDTH of the hat. And THAT’S what the total derivative is “afraid of”. That’s why there are two terms in the total derivative, as we’ll see next:

Let’s take the total derivative of V with respect to r:

Hey!! Why do we have that dh/dr term.

THAT dh/dr term is there JUST IN CASE there is a dependence of height (h) on radius (r). If we want the hat to always have the same cone-ish shape as we increase the width of the hat, (like we don’t want it to become a fat flat cone), then we have to make the HEIGHT of the hat DEPENDENT on the RADIUS.

Say we want the height of the cone to always be 3x the radius. Then we’d say:

h = 3r

Then

dh
-- = 3
dr

If we DON’T care to maintain the same aspect ratio of the cone as we widen the hat, then we could say the height of the hat DOESN’T have a dependence on the width of the hat, then

dh
-- = 0
dr

So in that case the total derivative of the volume of the hat with respect to radius reduces to

2 PI r h
-------
    3

(The PI r2/3 term vanished because dh/dr was 0).

So the TOTAL DERIVATIVE INCLUDES ACCOUNTING FOR THE CASE WHERE THERE IS DEPENDENCE OF ONE INDEPENDENT VARIABLE ON ANOTHER.

Partial derivatives don’t do that.

When you take the partial derivatives of volume with respect to radius, you get:

So you can see that we assumed h is a CONSTANT as we take the derivative in r. This means we ignore any possible dependence h might have on r with the partial derivative.

I hate the blue ring in windows 7 pen input. Using a wacom tablet, I can

Kill WispTis.exe

Restart wacom driver

Voila, no blue ring on right click.

Inking doesn’t work anymore in this mode however.

visual studio keyboard shortcut to collapse a region

To collapse the region that the cursor is currently in in Visual Studio 2010 just type CTRL+M, CTRL+S,

Edit.CollapseCurrentRegion

Collapses the region that contains the cursor to show just the top line of the region, followed by an ellipsis. Regions are indicated by triangles on the left edge of the document window

The distance to initiate drag ‘n drop is controlled through this api..

Increasing their values helps to avoid accidental Copy of files into the same directory

#include <Windows.h>
#include <stdio.h>
int main()
{
  // DEFAULT VALUES ARE 4 and 4
  int cx,cy;
  cx = GetSystemMetrics( SM_CXDRAG ) ;
  cy = GetSystemMetrics( SM_CYDRAG ) ;
  
  printf( "cx=%d, cy=%d\n", cx, cy ) ;

  SystemParametersInfoA( SPI_SETDRAGHEIGHT, 90, 0, SPIF_SENDCHANGE | SPIF_UPDATEINIFILE ) ;
  SystemParametersInfoA( SPI_SETDRAGWIDTH, 90, 0, SPIF_SENDCHANGE | SPIF_UPDATEINIFILE ) ;


  cx = GetSystemMetrics( SM_CXDRAG ) ;
  cy = GetSystemMetrics( SM_CYDRAG ) ;
  
  printf( "cx=%d, cy=%d\n", cx, cy ) ;

 
}

From this SO question/answer, we’re managing a tree data structure from a MySQL database.

We have:

mysql> desc nodes ;
+-------------+--------------+------+-----+---------+----------------+
| Field       | Type         | Null | Key | Default | Extra          |
+-------------+--------------+------+-----+---------+----------------+
| id          | int(11)      | NO   | PRI | NULL    | auto_increment |
| name        | varchar(255) | YES  |     | NULL    |                |
| leftSibling | int(11)      | NO   |     | 0       |                |
+-------------+--------------+------+-----+---------+----------------+
3 rows in set (0.00 sec)

mysql> desc adjacencies;
+------------+---------+------+-----+---------+----------------+
| Field      | Type    | Null | Key | Default | Extra          |
+------------+---------+------+-----+---------+----------------+
| relationId | int(11) | NO   | PRI | NULL    | auto_increment |
| parent     | int(11) | NO   |     | NULL    |                |
| child      | int(11) | NO   |     | NULL    |                |
| pathLen    | int(11) | NO   |     | NULL    |                |
+------------+---------+------+-----+---------+----------------+
4 rows in set (0.00 sec)

So here’s a picture of a tree:

That tree is stored in the database with an entry in the nodes table for each of the 10 nodes of the tree as follows:


mysql> select * from nodes ;
+----+--------------------------+-------------+
| id | name                     | leftSibling |
+----+--------------------------+-------------+
|  1 | node 1                   |           0 |
|  2 | node 1.1                 |           0 |
|  3 | node 2                   |           1 |
|  4 | node 1.1.1               |           0 |
|  5 | node 2.1                 |           0 |
|  6 | node 1.2                 |           2 |
|  7 | node 1.3                 |           0 |
|  8 | hi there, new child of 7 |           0 |
|  9 | 2nd child of 7           |           8 |
| 10 | 3rd child of 7           |           9 |
+----+--------------------------+-------------+
10 rows in set (0.00 sec)

Node 0 is fictional and serves as the root of the tree. There is no node 0 entry in the nodes table, however.

Notice the leftSibling property of each node is a reference to
its SISTER NODE to its left. If a node is a “leftmost child” (no sisters to the left of it) then it has a 0 for its left sibling.

The leftSibling property is what will allow us to keep the children
in the correct order.

Now, to store all the parent child relationships in the tree, we use a “closure table” called adjacencies.

mysql> select * from adjacencies ;
+------------+--------+-------+---------+
| relationId | parent | child | pathLen |
+------------+--------+-------+---------+
|          1 |      1 |     1 |       0 |
|          2 |      0 |     1 |       1 |
|          3 |      2 |     2 |       0 |
|          4 |      1 |     2 |       1 |
|          5 |      0 |     2 |       2 |
|          6 |      3 |     3 |       0 |
|          7 |      0 |     3 |       1 |
|          8 |      4 |     4 |       0 |
|          9 |      2 |     4 |       1 |
|         10 |      1 |     4 |       2 |
...

32 rows in set (0.00 sec)

So this is the WEIRDEST TABLE and takes some getting used to. In order to understand why this is done this way, think of a traditional adjacency list. The reason you can’t use a plain old adjacency list in MySQL is because plain old adjacency lists would require MULTIPLE queries to pull out all the children of say, node 1. Think about it, and try looking up Bill Karwin’s SQL antipatterns book for further reading.

So, all the adjacencies table does is list ALL OF A CHILD’S PARENTS.
This makes it dead simple to retrieve all the ids of all the children of any given node in one fell swoop:

    -- All children of node 1:
    select child
    from adjacencies
    where parent=1 ;

And.. getting all the parents/grandparents of any given node (say node=7) is just as easy:

     -- ALL MY PARENTS,grandparents
    select a.parent
    from adjacencies a
    where child=7
    and parent!=7 ;

So, there is a bit of redundancy in the table, and lots of repeated entries. This may make your SQL-sense tingle but that is normal.

On with the code. Run the script and examine the tables created. Try the addNode(), move() and deleteNode() procedures.

So, you can see that Node=1 has only 2 entries in this table where it is the child. The first entry above has ( parent=1, child=1, pathLen=0 ). That means we actually consider 1 as a parent of itself.

drop table if exists nodes ;

create table nodes (
  id int not null primary key auto_increment,
  name varchar( 255 ),
  leftSibling int not null default 0
) ;

insert into nodes values

  ( 1, 'node 1', 0 ),
  ( 2, 'node 1.1', 0 ),
  ( 3, 'node 2', 1 ),
  ( 4, 'node 1.1.1', 0 ),
  ( 5, 'node 2.1', 0 ),
  ( 6, 'node 1.2', 2 ),
  ( 7, 'node 1.3', 6 )
  
;






drop table if exists adjacencies ;

create table adjacencies(
  
  relationId int not null primary key auto_increment,
  parent int not null,
  child int not null,
  pathLen int not null

) ;
-- do parenthood for each node.
insert into adjacencies( child, parent, pathLen ) values
  -- node 1 is a top level node, child of the root
  -- I chose to add an entry linking each node to
  -- "node 0" for nicer syntax on "select whole tree"
  -- also avoids null in "whose parent is" subquery
  
  
  ( 1, 1, 0 ),
  ( 1, 0, 1 ),
  
  -- node 2:
  ( 2, 2, 0 ),
  ( 2, 1, 1 ),
  ( 2, 0, 2 ),
  
  
  -- node 3
  ( 3, 3, 0 ),
  ( 3, 0, 1 ),
  
  ( 4, 4, 0 ),
  ( 4, 2, 1 ),
  ( 4, 1, 2 ),
  ( 4, 0, 3 ),
  
  ( 5, 5, 0 ),
  ( 5, 3, 1 ),
  ( 5, 0, 2 ),
  
  ( 6, 6, 0 ),
  ( 6, 1, 1 ),
  ( 6, 0, 2 ),
  
  ( 7, 7, 0 ),
  ( 7, 1, 1 ),
  ( 7, 0, 2 ) 
;
  




-- ------------------------------
-- ------------------------------
--       stored procedures
-- ------------------------------
-- ------------------------------
  
DELIMITER //

-- 1. getRightMostChild
drop function if exists getRightMostChild //
create function getRightMostChild(

  i_ofNode int

)
returns int
READS SQL DATA
BEGIN
  
return(
  select -- RIGHTMOST CHILD
    adjacencies.child as 'rightMostChildId'

  from
    adjacencies
      
  where
    -- children of this @node
    adjacencies.parent  = i_ofNode

    -- direct adjacencies only
    and adjacencies.pathLen=1
      
    -- if this node is named
    -- an leftSibling for any other node,
    -- then it CANNOT be the rightmost node
    and adjacencies.child NOT IN (
      SELECT nodes.leftSibling from nodes
      -- rather than do a join in the subquery
      -- i chose to leave it at just "this node
      -- won't be named as "leftSibling" for ANY node
      -- if indeed it is the rightmost child
      -- of a parentNode.
    ) ) ;
  
END //


-- 2.  AddNode
drop procedure if exists addNode //
create procedure addNode(

  i_name varchar(255),
  i_parent int

)

modifies sql data

BEGIN
  DECLARE newNodeId int ;
  DECLARE nodeToLeft int ;
  
  -- get the node that this one will go
  -- right of
  -- by selecting the RIGHTMOST existing child
  -- of i_parent
  select getRightMostChild( i_parent ) into nodeToLeft ;
  
  if nodeToLeft is null then
    -- it means this parent has no children yet
    SET nodeToLeft = 0 ; -- first child points to 0 to indicate its leftmost
  end if ;
  
  -- insert
  -- ADD ((ID)) AS LAST CHILD:
  insert into nodes( name, leftSibling ) value ( i_name, nodeToLeft ) ;
  
  -- get the id of the new node we just created
  -- to finish the tie up 
  select last_insert_id() into newNodeId ;
  
  -- now tie up child stuff
  -- the insertions into 'adjacencies' is going to be
  -- ( 8, 8, 0 ) -- self reference 0 depth
  -- AS A DESCENDANT OF ALL PARENTS OF (1) BECAUSE YOU ADDED AS CHILD OF (1)

  -- get ALL parents of i_parent, and
  -- make them also parent newNode, at
  -- a +1 depth level
  insert into adjacencies( parent, child, pathLen )
  
  -- (8, 8, 0)
  SELECT newNodeId, newNodeId, 0  -- the 0-length self referential entry each node needs
  
  UNION
  
  select 
    parent, newNodeId, pathLen+1

  from
    adjacencies

  where
    child = i_parent
  
  ;
  
  -- because of the self-ref entry (parentId,parentId,0), the above query
  -- will also automatically do (parentId,child,1)
  -- (the direct parent assignment) as well
  
END //



-- 3.  DeleteNode
drop procedure if exists deleteNode //
create procedure deleteNode(
  i_nodeId int
)
BEGIN

  drop temporary table if exists adjsToRemove ;
  create temporary table adjsToRemove( ids int ) ;

  -- Get all adjacency relations WHERE
  -- any of MY GRANDPARENTS
  -- are pointing to any of MY CHILDREN:
  insert into adjsToRemove( ids )

  select
    relationId
  from
    adjacencies
  where
    parent in 
  (
  -- ALL MY PARENTS,grandparents
    select a.parent
    from adjacencies a
    where child=i_nodeId
    and parent!=i_nodeId
  )

  -- only concerns the relations of my
  -- grandparents WHERE MY CHILDREN ARE CONCERNED
  and child in
  -- get all my children
  (
    select child
    from adjacencies
    where parent=i_nodeId
  )

;

  -- those relations need be deleted
  delete from adjacencies where relationId in ( select ids from adjsToRemove ) limit 10000 ;

END //



-- 4.  MoveNode
-- --------------
-- --------------
-- ---- move ----
-- --------------
-- --------------
drop procedure if exists move //
create procedure move(
  i_nodeId int,
  i_newParent int
)

modifies sql data

BEGIN

  DECLARE myOldLeftSibling int ;
  DECLARE myNewLeftSibling int ;
  
  -- anyone who thinks i am his leftSibling
  -- needs to be updated to now think
  -- that myOldLeftSibling is now their leftSibling
  select id into myOldLeftSibling
  from nodes 
  where id=i_nodeId ;
  
  -- tell them i'm gone, if any
  update nodes set leftSibling=myOldLeftSibling where leftSibling=i_nodeId limit 1 ;
  
  
  
  -- my new left sibling will be the last child of
  -- my new parent
  select getRightmostChild( i_newParent ) into myNewLeftSibling ;
  
  -- avoid null values, use 0 instead
  if myNewLeftSibling is NULL then SET myNewLeftSibling=0 ; end if ;
  
  update nodes set leftSibling=myNewLeftSibling where id=i_nodeId limit 1 ;
  
  
  
  
  
  
  
  -- tell all my children to
  -- stop thinking my old parents
  -- are still their parents
  -- now tell all my children to stop considering
  -- ALL MY CURRENT PARENTS as their parents



  drop temporary table if exists adjsToRemove ;
  create temporary table adjsToRemove( ids int ) ;

  -- Get all adjacency relations WHERE
  -- any of MY GRANDPARENTS
  -- are pointing to any of MY CHILDREN:
  insert into adjsToRemove( ids )

  select
    relationId
  from
    adjacencies
  where
    parent in 
  (
  -- ALL MY PARENTS,grandparents
    select a.parent
    from adjacencies a
    where child=i_nodeId
    and parent!=i_nodeId
  )

  -- only concerns the relations of my
  -- grandparents WHERE MY CHILDREN ARE CONCERNED
  and child in
  -- get all my children
  (
    select child
    from adjacencies
    where parent=i_nodeId
  )

;

  -- those relations need be deleted
  delete from adjacencies where relationId in ( select ids from adjsToRemove ) limit 10000 ;

  
  
  
  



  -- this magic query forms all possible combinations
  -- of (grandparent1, child1) (grandparent2, child1) etc..
  -- so EVERY CHILD "meets" EVERY GRANDPARENT
  insert into adjacencies( parent, child, pathLen )
  select
    adjParent.parent,
    adjChild.child,
    
    adjParent.pathLen+1+adjChild.pathLen
    
  from
    adjacencies adjParent
  CROSS JOIN
    adjacencies adjChild
  on
    adjParent.child=i_newParent
    and adjChild.parent=i_nodeId
  
  ; 


END //
DELIMITER ;
-- no more procs
-- -------------
-- -------------





-- Tests:
call addNode( 'hi there, new child of 7', 7 ) ;
call addNode( '2nd child of 7', 7 ) ;
call addNode( '3rd child of 7', 7 ) ;

call move( 7, 5 ) ;

-- after the call move command above, the tree looks like this:




You can return a resultset from a MySQL function (well procedure, really).


DELIMITER //

drop procedure if exists doit //
create procedure doit()

BEGIN
  select * from table;
END //

DELIMITER ;

CALL doit() ;

When you CALL doit() ; the last SELECT statement in the doit procedure there gets returned as the result.

I installed PHP with all extensions. The extensions sometimes fail and prevent php from booting.

ON PHP 5.3.4, Apache 2.2.17 as of today, the following extensions don’t work by default and need to be commented out.

[PHP_BZ2]
extension=php_bz2.dll
[PHP_CURL]
extension=php_curl.dll
[PHP_FILEINFO]
extension=php_fileinfo.dll
[PHP_GD2]
extension=php_gd2.dll
[PHP_GETTEXT]
extension=php_gettext.dll
[PHP_IMAP]
extension=php_imap.dll
[PHP_INTL]
extension=php_intl.dll
[PHP_MBSTRING]
extension=php_mbstring.dll
[PHP_MYSQL]
extension=php_mysql.dll
[PHP_MYSQLI]
extension=php_mysqli.dll
;[PHP_OCI8]
;extension=php_oci8.dll
;[PHP_OCI8_11G]
;extension=php_oci8_11g.dll
[PHP_OPENSSL]
extension=php_openssl.dll
[PHP_PDO_MYSQL]
extension=php_pdo_mysql.dll
;[PHP_PDO_OCI]
;extension=php_pdo_oci.dll
[PHP_PDO_ODBC]
extension=php_pdo_odbc.dll
[PHP_PDO_PGSQL]
extension=php_pdo_pgsql.dll
[PHP_PDO_SQLITE]
extension=php_pdo_sqlite.dll
[PHP_PGSQL]
extension=php_pgsql.dll
[PHP_SHMOP]
extension=php_shmop.dll
[PHP_SOAP]
extension=php_soap.dll
[PHP_SOCKETS]
extension=php_sockets.dll
[PHP_SQLITE]
extension=php_sqlite.dll
[PHP_SQLITE3]
extension=php_sqlite3.dll
;[PHP_SYBASE_CT]
;extension=php_sybase_ct.dll
[PHP_TIDY]
extension=php_tidy.dll
[PHP_XMLRPC]
extension=php_xmlrpc.dll
[PHP_XSL]
extension=php_xsl.dll
[PHP_EXIF]
extension=php_exif.dll

pullout.bat

@echo on & setLocal EnableDELAYedExpansion

@SET /a a = 1
for /r "C:\folder" %%f in (*.*) do (
  
  @move "%%f" "C:\destfolder"
)

run40Clients.bat

path=.
for /L %%x in (1,1,5) do start /b c:\putty.exe -load "_lab_1_"

pause

renamedirs.vbs

' shell script that renames dirs
  
Dim ofso
Set ofso = CreateObject( "Scripting.FileSystemObject" ) 

Dim re
Set re = new RegExp
're.Pattern = "\("
' the pattern looks for " M*(", basically for the "Mr. (" or "Mrs. (" or "Miss. ("
re.Pattern = "[\s][M][.\S]*[\s]\("

Dim folder
Set folder = ofso.GetFolder( "." )

' check EVERY subfolder
Dim osub
For Each osub In folder.SubFolders
  
  Dim name
  name = osub.Name
  
  Dim matches
  Set matches = re.Execute( osub.Name )
  
  Dim match
  For Each match In matches
    Dim ind
    ind = match.FirstIndex
    Dim str
    str = Left( name, ind )
    'WSH.Echo( str )
    
    osub.Name = str
    
    Next
  
  Next


WSH.Echo( "Done" )




' now let's try replace

re.Pattern = "r"
re.Global = True  ' GREEDY
Dim testStr
testStr = "herro there this is a string with r"
Dim result
result = re.Replace( testStr, "X" )

WSH.Echo( result ) 


'  
'Sub ShowTree( folder )
'  Dim osub
'  WSH.Echo folder.Path
'  For Each osub In folder.SubFolders
'    ShowTree osub
'  Next
'End Sub
'

The newest Google chrome update (which they push out to the browsers oh-so quietly), made pdf on the web all the more annoying.

“This type of file can harm your computer. Are you sure you want to download this.pdf?”

Yes. Yes I do. I want to download all the PDF’s I click on. Stop asking, and download.

So, winamp is good

Using Advanced Title Format you can make titles appear in the playlist exactly as you want.

I currently use:

$PathLTrim(%filename%, 3)

Basic windows starter

// Win32

#include <windows.h>
#include <stdio.h>

LRESULT CALLBACK WndProc( HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam );
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR szCmdLine, int iCmdShow );

int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR szCmdLine, int iCmdShow )
{
  AllocConsole() ;
  AttachConsole( GetCurrentProcessId() ) ;
  freopen( "CON", "w", stdout ) ;
  puts( "************** Program start **************" ) ;
  WNDCLASSEX wcx = { 0 };
  wcx.cbSize = sizeof( WNDCLASSEX ) ;
  wcx.hbrBackground = (HBRUSH)GetStockObject( WHITE_BRUSH );
  wcx.hCursor = LoadCursor( NULL, IDC_ARROW );
  wcx.hIcon = LoadIcon( NULL, IDI_APPLICATION );
  wcx.hInstance = hInstance;
  wcx.lpfnWndProc = WndProc;
  wcx.lpszClassName = TEXT("BasicWindow");
  wcx.style = CS_HREDRAW | CS_VREDRAW;
  RegisterClassEx( &wcx );
  
  HWND hwnd = CreateWindowEx(
    0,
    TEXT("BasicWindow"),
    TEXT("Window title!"),
    WS_OVERLAPPEDWINDOW,
    10, 10,
    200, 200,
    NULL, NULL,
    hInstance, NULL );

  ShowWindow(hwnd, iCmdShow );
  UpdateWindow(hwnd);

  MSG msg;
  while( GetMessage( &msg, NULL, 0, 0 ) )
  {
    TranslateMessage( &msg );
    DispatchMessage( &msg );
  }

  return msg.wParam ;
}

LRESULT CALLBACK WndProc( HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam )
{
  switch( message )
  {
  case WM_CREATE:
    {
      // Stuff to do when the window is created
    }
    return 0;
    
  case WM_PAINT:
    {
      // we would place our Windows painting code here.
      HDC hdc;
      PAINTSTRUCT ps;
      hdc = BeginPaint( hwnd, &ps );

      // draw a circle and a 2 squares
      Ellipse( hdc, 20, 20, 160, 160 );
      Rectangle( hdc, 50, 50, 90, 90 );
      Rectangle( hdc, 100, 50, 140, 90 );

      EndPaint( hwnd, &ps );
    }
    return 0;

  case WM_KEYDOWN:
    {
      if( wparam == VK_ESCAPE )
      {
        PostQuitMessage( 0 ) ;
        return 0 ;
      }
    }
    break ;

  case WM_DESTROY:
    {
      PostQuitMessage( 0 ) ;
    }
    return 0;
  }

  return DefWindowProc( hwnd, message, wparam, lparam );
}

I keep losing this, it came originally from Game Audio Programming by James Boer:

    Frequencies for equal tempered tuning
    1    2    3     4     5    6     7     8     ( octave )
C   32   65   131   262   523  1047  2093  4186
C#  35   69   139   277   554  1109  2218  4435
D   37   73   147   294   587  1175  2349  4699
D#  39   78   156   311   622  1245  2489  4978
E   41   82   165   330   659  1319  2637  5274
F   44   87   175   349   698  1397  2794  5588
F#  46   93   185   370   740  1480  2960  5920
G   49   98   196   392   784  1568  3136  6272
G#  52   104  208   415   831  1661  3322  6645
A   55   110  220   440   880  1760  3520  7040
A#  58   117  233   466   932  1865  3729  7459
B   61   123  247   494   988  1976  3951  7902

/////////////////////////////////////////////////////////////////
// AddingATimer.cpp                                            //
// Shows how to add a timer that causes Windows to pass us
// a WM_TIMER message every few seconds.
/////////////////////////////////////////////////////////////////
// USING THE WINDOWS TIMER:
// DEFINE some constants for the timers.
#define TIMER_SECOND 1		// first timer identified by integer 1
#define TIMER_MINUTE 2		// second timer identified by integer 2
// we will use these constants when we first create the timers,
// then Windows will use these numbers to notify us when each
// timer event has occurred.

#include <windows.h>



// Prototype for WndProc function
LRESULT CALLBACK WndProc ( HWND, UINT, WPARAM, LPARAM );

/////////////////////////////////////////////////////////////////
// WinMain:  Application entry point for Windows applications. //
//                                                             //
// Just as said every C++ program starts at main,              //
// every Windows program will start at WinMain.                //
/////////////////////////////////////////////////////////////////
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance,
  LPSTR lpCmdLine, int nShowCmd )
{
  // String used to identify our application
  TCHAR applicationClassName[] = TEXT("FirstWindowApp");

#pragma region -_1.  CREATE THE WNDCLASSEX STRUCTURE/OBJECT_-
  WNDCLASSEX window;		// Look at members of this struct.
  // Below, we initialize all of them.

  window.cbClsExtra		= 0;						// extra bytes
  window.cbSize			= sizeof(WNDCLASSEX);		// keeps track of its own size
  window.cbWndExtra		= 0;						// extra bytes
  window.hbrBackground	= (HBRUSH) GetStockObject(WHITE_BRUSH);
  window.hCursor			= LoadCursor(NULL, IDC_HAND);	// load hand cursor
  //Tip:  type in IDC_ then press CTRL+SPACE to get a list of avail. cursors

  window.hIcon			= LoadIcon(NULL, IDI_APPLICATION);	// large icon
  window.hIconSm			= LoadIcon(NULL, IDI_APPLICATION);	// small icon that shows up in top left of window
  window.hInstance		= hInstance;				// program's instance handle that was first passed to WinMain by windows when program was first run
  window.lpfnWndProc		= WndProc;					// function pointer to WndProc function
  window.lpszClassName	= applicationClassName;		// window class name.. defined above
  window.lpszMenuName		= NULL;						// main menu
  window.style			= CS_OWNDC | CS_HREDRAW | CS_VREDRAW;	// redraw on horizontal or vertical resize
#pragma endregion

#pragma region -_2.  REGISTER THAT WNDCLASSEX STRUCTURE WITH WINDOWS O/S + CREATE WINDOW_-
  if(!RegisterClassEx( &window ))
  {
    MessageBox(NULL, TEXT("Something's wrong.. quitting"), TEXT("error"), MB_OK);
    return 1;		// return from WinMain.. i.e. quit
  }

  // CREATE THE WINDOW AND KEEP THE HANDLE TO IT.
  HWND		hwnd;			// declare a handle to a window
  hwnd = CreateWindowExW(	WS_EX_TOPMOST,			// extended window style.. this sets the window to being always on top
    applicationClassName,	// window class name.. defined above
    TEXT("WINDOW TITLE"),	// title bar of window
    WS_OVERLAPPEDWINDOW,	// window style
    CW_USEDEFAULT, 40,		// initial x, y start position of window
    // CW_USEDEFAULT means "let Windows choose it"

    400, 160,				// initial width, height of window
    NULL, NULL,				// parent window, window menu
    hInstance, NULL);		// program instance handle, creation params

  // now we show and paint our window, so it appears
  ShowWindow(hwnd, nShowCmd );		// you have to ask that your Window be shown to see it
  UpdateWindow(hwnd);					// paint the window

#pragma endregion

#pragma region -_3.  MESSAGE LOOP_-

  MSG			msg;
  // this is the struct that holds the message
  // msg.hwnd - handle to the window to whom the message is for
  // msg.message - type of message for the window (mouse click, key press, key up, etc)
  // msg.lParam - a parameter that contains data.  the data it contains DEPENDS ON THE MESSAGE!!
  // msg.wParam - a parameter that contains data.  the data it contains DEPENDS ON THE MESSAGE!!
  // msg.time - the time the message was created
  // msg.pt - cursor position in screen coordinates when message was posted

  // enter the message loop
  while(GetMessage(&msg, NULL, 0, 0))
  {
    TranslateMessage(&msg);	
    DispatchMessage(&msg);	// send off to WndProc for processing
  }
#pragma endregion

  return 0;	// end program once we exit the message loop
}

////////////////////////////////////////////////////////////////////////
// WndProc - "Window procedure" function -- this function gets called
// by Windows whenever there is a "message" available for
// your window.
// A "message" is available for your window whenever something "happens"
// to it -- i.e. the user clicks on it, or the user types a key when your
// window has "input focus"
LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
  HDC			hdc;
  PAINTSTRUCT	ps;
  RECT		rect;

  // this switch looks at the message that was passed to the WndProc function.
  // There are tons of possible messages..
  // WM_CREATE:	// message passed to WndProc when the window is first created
  // WM_PAINT:	// message passed when there is a request from O/S to paint window
  // WM_KEYDOWN:	// message passed when a key is being pressed down.. see MSDN for more

  // Generally, all messages to the window will start with WM_
  switch(message)
  {
  case WM_CREATE:			// WndProc gets sent the WM_CREATE message when
    {					// the window is first created

      // (if you don't have the 8254 chip (lots of modern pc's don't!))
      MessageBeep( 1 ) ;

      // upon creation, beep 3 times @ 500Hz
      //Beep( 500, 10 );
      //Beep( 500, 10 );
      //Beep( 500, 10 );


      // Upon window creation, we want to initialize the timers:
      SetTimer( hwnd, TIMER_SECOND, 1000, NULL );
      SetTimer( hwnd, TIMER_MINUTE, 60000, NULL );
      return 0;		// return from WndProc
    }
    break;

  case WM_PAINT:
    {
      // if the message was "paint the window", just draw the text "This is my window..."
      hdc = BeginPaint(hwnd, &ps);		// hdc is a "handle to a device context"
      GetClientRect(hwnd, &rect);			// the "client rectangle" is the window area but
      // EXCLUDING the title bar and borders
      DrawText(hdc, TEXT("This is my window..."), -1, &rect, DT_SINGLELINE | DT_BOTTOM | DT_VCENTER );
      EndPaint(hwnd, &ps);
      return 0;
    }
    break;

  case WM_DESTROY:
    {
      PostQuitMessage(0);
      return 0;
    }
    break;

    // +++ new.
  case WM_TIMER:
    {
      switch(wParam)
      {
      case TIMER_SECOND:
        //Beep(200, 20);		// just tick every time the WM_TIMER message is passed
        MessageBeep( 1 ) ;
        break;
      case TIMER_MINUTE:
        //Beep(700, 100);		// beep higher every minute
        MessageBeep( 1 ) ;
      }
      return 0;
    }
    break;

  }

  // If message was NOT handled by us, we pass it off to
  // the windows operating system to handle it.
  return DefWindowProc(hwnd, message, wParam, lParam);
}




GDI+ from C++ windows basic example


#include <windows.h>
#include <gdiplus.h>
#include <stdio.h>
using namespace Gdiplus;

#pragma comment( lib, "gdiplus.lib" )

LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);

INT WINAPI WinMain(HINSTANCE hInstance, HINSTANCE, PSTR, INT iCmdShow)
{
  // attach a console
  AllocConsole() ;
  AttachConsole( GetCurrentProcessId() ) ;
  freopen( "CON", "w", stdout ) ;

  // Start up GDI+.
  GdiplusStartupInput gdiplusStartupInput;
  ULONG_PTR gdiplusToken;
  GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);

  WNDCLASS wndClass;
  wndClass.style          = CS_HREDRAW | CS_VREDRAW;
  wndClass.lpfnWndProc    = WndProc;
  wndClass.cbClsExtra     = 0;
  wndClass.cbWndExtra     = 0;
  wndClass.hInstance      = hInstance;
  wndClass.hIcon          = LoadIcon(NULL, IDI_APPLICATION);
  wndClass.hCursor        = LoadCursor(NULL, IDC_ARROW);
  wndClass.hbrBackground  = (HBRUSH)GetStockObject(WHITE_BRUSH);
  wndClass.lpszMenuName   = NULL;
  wndClass.lpszClassName  = TEXT("GDIPLUSWINDOW");

  if(!RegisterClass(&wndClass)){ puts( "problem registering wndclass" ) ; }

  HWND hWnd;
  hWnd = CreateWindow(
    TEXT("GDIPLUSWINDOW"),   // window class name
    TEXT("Welcome to GDI+!"),  // window caption
    WS_OVERLAPPEDWINDOW,      // window style
    20,            // initial x position
    20,            // initial y position
    640,            // initial width
    480,            // initial height
    NULL,                     // parent window handle
    NULL,                     // window menu handle
    hInstance,                // program instance handle
    NULL);                    // creation parameters

  ShowWindow(hWnd, iCmdShow);
  UpdateWindow(hWnd);


  MSG msg;
  while(GetMessage(&msg, NULL, 0, 0))
  {
    TranslateMessage(&msg);
    DispatchMessage(&msg);
  }

  GdiplusShutdown(gdiplusToken);
  return msg.wParam;
}

LRESULT CALLBACK WndProc(HWND hWnd, UINT message, 
                         WPARAM wParam, LPARAM lParam)
{
  HDC hdc;
  PAINTSTRUCT ps;

  switch(message)
  {
  case WM_PAINT:
    {
      // "Start painting"
      // The HDC "handle to a device context"
      // is the 'surface' on which you draw.
      // You don't draw directly to a window.
      // Rather you draw to a "device context".
      // The reason its this way is it makes it so
      // you can draw to ANY SURFACE 
      hdc = BeginPaint(hWnd, &ps);
      
      #pragma region painting code
      // Create a Graphics object for our window's hdc
      Graphics g( hdc ) ;
      
      // Create a pen.
      Pen bluePen( Color( 128, 0, 0, 255 ) ) ;
      bluePen.SetWidth( 8.0 ) ;

      g.DrawLine( &bluePen, 0, 0, 100, 100 ) ;
      g.DrawEllipse( &bluePen, 0, 0, 40, 40 ) ;
      g.DrawEllipse( &bluePen, 0, 0, 50, 50 ) ;

      SolidBrush blueBrush( Color( 120, 0, 0, 255 ) ) ;
      g.FillRectangle( &blueBrush, 60, 60, 190, 180 ) ;

      SolidBrush redBrush( Color( 123, 255, 0, 0 ) ) ;
      Font arialFont( TEXT("Arial"), 12.0 ) ;
      PointF pTextPos( 20, 20 ); 

      g.DrawString( TEXT("This is GDI+!"),
                 strlen( "This is GDI+!" ),
                 &arialFont, pTextPos, &redBrush ) ;
      g.FillRectangle( &redBrush, 30, 30, 100, 180 ) ;

      #pragma endregion



      // "Wrap it up"
      EndPaint( hWnd, &ps );
      printf( "Your window has been painted\n" ) ;
    }
    return 0;
  case WM_LBUTTONDOWN:
    {
      UpdateWindow(hWnd);
    }
    break;
  case WM_DESTROY:
    PostQuitMessage(0);
    return 0;
  default:
    return DefWindowProc(hWnd, message, wParam, lParam);
  }
} // WndProc
Loop invariant
Given a data structure called STRUCTURE and an algorithm called ALGORITHM There’s a property that is true of STRUCTURE (the structure we are operating on) on every loop of the ALGORITHM, even as it runs.

Here’s an implementation of the MD5 algorithm in C++.

Simply copy and paste into a file “md5.h”. Only dependencies are on <string.h> and <stdio.h>.

Originally adapted from the C reference implementation on this page

Tested in Visual Studio 2010.
Sample use:

Main.cpp

#include "md5.h"

int main()
{
  MD5 md5 ;
  puts( md5.digestString( "HELLO THERE I AM MD5!" ) ) ;

  // print the digest for a binary file on disk.
  puts( md5.digestFile( "C:\\WINDOWS\\notepad.exe" ) ) ;

  return 0;
}

md5.h

(No .cpp file)

#ifndef MD5_H
#define MD5_H

// Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All
// rights reserved.

// License to copy and use this software is granted provided that it
// is identified as the "RSA Data Security, Inc. MD5 Message-Digest
// Algorithm" in all material mentioning or referencing this software
// or this function.
//
// License is also granted to make and use derivative works provided
// that such works are identified as "derived from the RSA Data
// Security, Inc. MD5 Message-Digest Algorithm" in all material
// mentioning or referencing the derived work.
//
// RSA Data Security, Inc. makes no representations concerning either
// the merchantability of this software or the suitability of this
// software for any particular purpose. It is provided "as is"
// without express or implied warranty of any kind.
//
// These notices must be retained in any copies of any part of this
// documentation and/or software.



// The original md5 implementation avoids external libraries.
// This version has dependency on stdio.h for file input and
// string.h for memcpy.
#include <stdio.h>
#include <string.h>

#pragma region MD5 defines
// Constants for MD5Transform routine.
#define S11 7
#define S12 12
#define S13 17
#define S14 22
#define S21 5
#define S22 9
#define S23 14
#define S24 20
#define S31 4
#define S32 11
#define S33 16
#define S34 23
#define S41 6
#define S42 10
#define S43 15
#define S44 21






static unsigned char PADDING[64] = {
  0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};

// F, G, H and I are basic MD5 functions.
#define F(x, y, z) (((x) & (y)) | ((~x) & (z)))
#define G(x, y, z) (((x) & (z)) | ((y) & (~z)))
#define H(x, y, z) ((x) ^ (y) ^ (z))
#define I(x, y, z) ((y) ^ ((x) | (~z)))

// ROTATE_LEFT rotates x left n bits.
#define ROTATE_LEFT(x, n) (((x) << (n)) | ((x) >> (32-(n))))

// FF, GG, HH, and II transformations for rounds 1, 2, 3, and 4.
// Rotation is separate from addition to prevent recomputation.
#define FF(a, b, c, d, x, s, ac) { \
  (a) += F ((b), (c), (d)) + (x) + (UINT4)(ac); \
  (a) = ROTATE_LEFT ((a), (s)); \
  (a) += (b); \
  }
#define GG(a, b, c, d, x, s, ac) { \
  (a) += G ((b), (c), (d)) + (x) + (UINT4)(ac); \
  (a) = ROTATE_LEFT ((a), (s)); \
  (a) += (b); \
  }
#define HH(a, b, c, d, x, s, ac) { \
  (a) += H ((b), (c), (d)) + (x) + (UINT4)(ac); \
  (a) = ROTATE_LEFT ((a), (s)); \
  (a) += (b); \
  }
#define II(a, b, c, d, x, s, ac) { \
  (a) += I ((b), (c), (d)) + (x) + (UINT4)(ac); \
  (a) = ROTATE_LEFT ((a), (s)); \
  (a) += (b); \
  }
#pragma endregion

typedef unsigned char BYTE ;

// POINTER defines a generic pointer type
typedef unsigned char *POINTER;

// UINT2 defines a two byte word
typedef unsigned short int UINT2;

// UINT4 defines a four byte word
typedef unsigned long int UINT4;


// convenient object that wraps
// the C-functions for use in C++ only
class MD5
{
private:
  struct __context_t {
    UINT4 state[4];                                   /* state (ABCD) */
    UINT4 count[2];        /* number of bits, modulo 2^64 (lsb first) */
    unsigned char buffer[64];                         /* input buffer */
  } context ;

  #pragma region static helper functions
  // The core of the MD5 algorithm is here.
  // MD5 basic transformation. Transforms state based on block.
  static void MD5Transform( UINT4 state[4], unsigned char block[64] )
  {
    UINT4 a = state[0], b = state[1], c = state[2], d = state[3], x[16];

    Decode (x, block, 64);

    /* Round 1 */
    FF (a, b, c, d, x[ 0], S11, 0xd76aa478); /* 1 */
    FF (d, a, b, c, x[ 1], S12, 0xe8c7b756); /* 2 */
    FF (c, d, a, b, x[ 2], S13, 0x242070db); /* 3 */
    FF (b, c, d, a, x[ 3], S14, 0xc1bdceee); /* 4 */
    FF (a, b, c, d, x[ 4], S11, 0xf57c0faf); /* 5 */
    FF (d, a, b, c, x[ 5], S12, 0x4787c62a); /* 6 */
    FF (c, d, a, b, x[ 6], S13, 0xa8304613); /* 7 */
    FF (b, c, d, a, x[ 7], S14, 0xfd469501); /* 8 */
    FF (a, b, c, d, x[ 8], S11, 0x698098d8); /* 9 */
    FF (d, a, b, c, x[ 9], S12, 0x8b44f7af); /* 10 */
    FF (c, d, a, b, x[10], S13, 0xffff5bb1); /* 11 */
    FF (b, c, d, a, x[11], S14, 0x895cd7be); /* 12 */
    FF (a, b, c, d, x[12], S11, 0x6b901122); /* 13 */
    FF (d, a, b, c, x[13], S12, 0xfd987193); /* 14 */
    FF (c, d, a, b, x[14], S13, 0xa679438e); /* 15 */
    FF (b, c, d, a, x[15], S14, 0x49b40821); /* 16 */

    /* Round 2 */
    GG (a, b, c, d, x[ 1], S21, 0xf61e2562); /* 17 */
    GG (d, a, b, c, x[ 6], S22, 0xc040b340); /* 18 */
    GG (c, d, a, b, x[11], S23, 0x265e5a51); /* 19 */
    GG (b, c, d, a, x[ 0], S24, 0xe9b6c7aa); /* 20 */
    GG (a, b, c, d, x[ 5], S21, 0xd62f105d); /* 21 */
    GG (d, a, b, c, x[10], S22,  0x2441453); /* 22 */
    GG (c, d, a, b, x[15], S23, 0xd8a1e681); /* 23 */
    GG (b, c, d, a, x[ 4], S24, 0xe7d3fbc8); /* 24 */
    GG (a, b, c, d, x[ 9], S21, 0x21e1cde6); /* 25 */
    GG (d, a, b, c, x[14], S22, 0xc33707d6); /* 26 */
    GG (c, d, a, b, x[ 3], S23, 0xf4d50d87); /* 27 */
    GG (b, c, d, a, x[ 8], S24, 0x455a14ed); /* 28 */
    GG (a, b, c, d, x[13], S21, 0xa9e3e905); /* 29 */
    GG (d, a, b, c, x[ 2], S22, 0xfcefa3f8); /* 30 */
    GG (c, d, a, b, x[ 7], S23, 0x676f02d9); /* 31 */
    GG (b, c, d, a, x[12], S24, 0x8d2a4c8a); /* 32 */

    /* Round 3 */
    HH (a, b, c, d, x[ 5], S31, 0xfffa3942); /* 33 */
    HH (d, a, b, c, x[ 8], S32, 0x8771f681); /* 34 */
    HH (c, d, a, b, x[11], S33, 0x6d9d6122); /* 35 */
    HH (b, c, d, a, x[14], S34, 0xfde5380c); /* 36 */
    HH (a, b, c, d, x[ 1], S31, 0xa4beea44); /* 37 */
    HH (d, a, b, c, x[ 4], S32, 0x4bdecfa9); /* 38 */
    HH (c, d, a, b, x[ 7], S33, 0xf6bb4b60); /* 39 */
    HH (b, c, d, a, x[10], S34, 0xbebfbc70); /* 40 */
    HH (a, b, c, d, x[13], S31, 0x289b7ec6); /* 41 */
    HH (d, a, b, c, x[ 0], S32, 0xeaa127fa); /* 42 */
    HH (c, d, a, b, x[ 3], S33, 0xd4ef3085); /* 43 */
    HH (b, c, d, a, x[ 6], S34,  0x4881d05); /* 44 */
    HH (a, b, c, d, x[ 9], S31, 0xd9d4d039); /* 45 */
    HH (d, a, b, c, x[12], S32, 0xe6db99e5); /* 46 */
    HH (c, d, a, b, x[15], S33, 0x1fa27cf8); /* 47 */
    HH (b, c, d, a, x[ 2], S34, 0xc4ac5665); /* 48 */

    /* Round 4 */
    II (a, b, c, d, x[ 0], S41, 0xf4292244); /* 49 */
    II (d, a, b, c, x[ 7], S42, 0x432aff97); /* 50 */
    II (c, d, a, b, x[14], S43, 0xab9423a7); /* 51 */
    II (b, c, d, a, x[ 5], S44, 0xfc93a039); /* 52 */
    II (a, b, c, d, x[12], S41, 0x655b59c3); /* 53 */
    II (d, a, b, c, x[ 3], S42, 0x8f0ccc92); /* 54 */
    II (c, d, a, b, x[10], S43, 0xffeff47d); /* 55 */
    II (b, c, d, a, x[ 1], S44, 0x85845dd1); /* 56 */
    II (a, b, c, d, x[ 8], S41, 0x6fa87e4f); /* 57 */
    II (d, a, b, c, x[15], S42, 0xfe2ce6e0); /* 58 */
    II (c, d, a, b, x[ 6], S43, 0xa3014314); /* 59 */
    II (b, c, d, a, x[13], S44, 0x4e0811a1); /* 60 */
    II (a, b, c, d, x[ 4], S41, 0xf7537e82); /* 61 */
    II (d, a, b, c, x[11], S42, 0xbd3af235); /* 62 */
    II (c, d, a, b, x[ 2], S43, 0x2ad7d2bb); /* 63 */
    II (b, c, d, a, x[ 9], S44, 0xeb86d391); /* 64 */

    state[0] += a;
    state[1] += b;
    state[2] += c;
    state[3] += d;

    // Zeroize sensitive information.
    memset((POINTER)x, 0, sizeof (x));
  }

  // Encodes input (UINT4) into output (unsigned char). Assumes len is
  // a multiple of 4.
  static void Encode( unsigned char *output, UINT4 *input, unsigned int len )
  {
    unsigned int i, j;

    for (i = 0, j = 0; j < len; i++, j += 4) {
      output[j] = (unsigned char)(input[i] & 0xff);
      output[j+1] = (unsigned char)((input[i] >> 8) & 0xff);
      output[j+2] = (unsigned char)((input[i] >> 16) & 0xff);
      output[j+3] = (unsigned char)((input[i] >> 24) & 0xff);
    }
  }

  // Decodes input (unsigned char) into output (UINT4). Assumes len is
  // a multiple of 4.
  static void Decode( UINT4 *output, unsigned char *input, unsigned int len )
  {
    unsigned int i, j;

    for (i = 0, j = 0; j < len; i++, j += 4)
      output[i] = ((UINT4)input[j]) | (((UINT4)input[j+1]) << 8) |
      (((UINT4)input[j+2]) << 16) | (((UINT4)input[j+3]) << 24);
  }
  #pragma endregion


public:
  // MAIN FUNCTIONS
  MD5()
  {
    Init() ;
  }

  // MD5 initialization. Begins an MD5 operation, writing a new context.
  void Init()
  {
    context.count[0] = context.count[1] = 0;
  
    // Load magic initialization constants.
    context.state[0] = 0x67452301;
    context.state[1] = 0xefcdab89;
    context.state[2] = 0x98badcfe;
    context.state[3] = 0x10325476;
  }

  // MD5 block update operation. Continues an MD5 message-digest
  // operation, processing another message block, and updating the
  // context.
  void Update(
    unsigned char *input,   // input block
    unsigned int inputLen ) // length of input block
  {
    unsigned int i, index, partLen;

    // Compute number of bytes mod 64
    index = (unsigned int)((context.count[0] >> 3) & 0x3F);

    // Update number of bits
    if ((context.count[0] += ((UINT4)inputLen << 3))
      < ((UINT4)inputLen << 3))
      context.count[1]++;
    context.count[1] += ((UINT4)inputLen >> 29);

    partLen = 64 - index;

    // Transform as many times as possible.
    if (inputLen >= partLen) {
      memcpy((POINTER)&context.buffer[index], (POINTER)input, partLen);
      MD5Transform (context.state, context.buffer);

      for (i = partLen; i + 63 < inputLen; i += 64)
        MD5Transform (context.state, &input[i]);

      index = 0;
    }
    else
      i = 0;

    /* Buffer remaining input */
    memcpy((POINTER)&context.buffer[index], (POINTER)&input[i], inputLen-i);
  }

  // MD5 finalization. Ends an MD5 message-digest operation, writing the
  // the message digest and zeroizing the context.
  // Writes to digestRaw
  void Final()
  {
    unsigned char bits[8];
    unsigned int index, padLen;

    // Save number of bits
    Encode( bits, context.count, 8 );

    // Pad out to 56 mod 64.
    index = (unsigned int)((context.count[0] >> 3) & 0x3f);
    padLen = (index < 56) ? (56 - index) : (120 - index);
    Update( PADDING, padLen );

    // Append length (before padding)
    Update( bits, 8 );

    // Store state in digest
    Encode( digestRaw, context.state, 16);

    // Zeroize sensitive information.
    memset((POINTER)&context, 0, sizeof (context));

    writeToString() ;
  }

  /// Buffer must be 32+1 (nul) = 33 chars long at least 
  void writeToString()
  {
    int pos ;

    for( pos = 0 ; pos < 16 ; pos++ )
      sprintf( digestChars+(pos*2), "%02x", digestRaw[pos] ) ;
  }


public:
  // an MD5 digest is a 16-byte number (32 hex digits)
  BYTE digestRaw[ 16 ] ;

  // This version of the digest is actually
  // a "printf'd" version of the digest.
  char digestChars[ 33 ] ;

  /// Load a file from disk and digest it
  // Digests a file and returns the result.
  char* digestFile( char *filename )
  {
    Init() ;

    FILE *file;
    
    int len;
    unsigned char buffer[1024] ;

    if( (file = fopen (filename, "rb")) == NULL )
      printf( "%s can't be opened\n", filename ) ;
    else
    {
      while( len = fread( buffer, 1, 1024, file ) )
        Update( buffer, len ) ;
      Final();

      fclose( file );
    }

    return digestChars ;
  }

  /// Digests a byte-array already in memory
  char* digestMemory( BYTE *memchunk, int len )
  {
    Init() ;
    Update( memchunk, len ) ;
    Final() ;
    
    return digestChars ;
  }

  // Digests a string and prints the result.
  char* digestString( char *string )
  {
    Init() ;
    Update( (unsigned char*)string, strlen(string) ) ;
    Final() ;

    return digestChars ;
  }
} ;

#endif

Mutex locks can be used to create blocking functions, a lot like the socket api’s recv() function.

Using Mutex objects
CreateMutex
WaitForSingleObject
ReleaseMutex


#include <stdio.h>
#include <conio.h>
#include <Windows.h>

// Super-short example that shows how to
// create a blocking function with mutex
// locks in MSVC++.

#define IsDown(x) (GetAsyncKeyState(x) & 0x8000)
HANDLE lock ;

DWORD WINAPI block( LPVOID data )
{
  puts( "Thread 2:  I have started.  I will check the lock.." ) ;
  WaitForSingleObject( lock, INFINITE ) ; // THE THREAD WILL BLOCK HERE
  // forever until the "lock" object is Released() by
  // the main thread
  puts( "Thread 2:  I AM FREE TO GO!!" ) ;

  return 0 ;
}

int main()
{
  // Get a lock on the lock variable
  lock = CreateMutexA(
    0,
    TRUE,  // When the mutex lock is created, start with it already "taken"
    "Main lock" // name for the lock
  ) ;

  puts( "Thread 1:  Starting new thread.." ) ;
  CreateThread( 0, 0, &block, 0, 0, 0 ) ;
  puts( "Thread 1:  Entering main loop.  Press the SPACEBAR to release the lock "
    "(to UNBLOCK) thread 2" ) ;
  while( 1 )
  {
    if( IsDown( VK_SPACE ) )
    {
      ReleaseMutex( lock ) ; // RELEASE OUR HANDLE ON THE
      // MUTEX LOCK, meaning the 'block()' function will
      // be free to continue execution
    }

    if( IsDown( VK_ESCAPE ) )
    {
      break ; // end the program
    }
  }

}


Trying to install Apache 2.2 and PHP on a Windows 7 x64 system, I got this error:

[crit] (OS 1813)The specified resource type cannot be found in the image file. : master_main: create child process failed. Exiting.

What you have to do is open PHP.ini and go to the bottom of the file and start commenting out extensions.

Basically some of the extensions don’t work, so you have to keep commenting them out until you find the culprit.

Best to keep it to the bare minimum extensions you know you will use..

Function pointer syntax is one of those weird, weird things that just doesn’t seem right.

double (*fun)(int,int,double*)

Can you read that?

In less than 2 paragraphs, you will!

First things first. What is a function pointer anyway? Why, its simply a variable that, instead of pointing to an object (like an int* will point to an integer, and a double* will point to a double), this weird, weird “function pointer” will actually point to __A FUNCTION__!!

WHAT?? You say. POINT TO A FUNCTION! Why, yes! It is no different than me pointing to a recipe. Its one thing to have a copy of the recipe for chocolate mousse in hand (an actual function body), and its another thing to have a hyperlink that merely __points__ to that chocolate mousse recipe (a pointer to the function). When you have a pointer to a function (hyperlink to a recipe) you can still execute it (make the recipe) but you need to remember to dereference the pointer first (follow the hyperlink to pull up the recipe).

Does that make a little bit of sense? Me hopes so.

Moving on to function pointer syntax then, it is actually not that bad to read. Say you had a function:

void SayIt()
{
  puts( "It. There.  Happy now?" ) ;
}

And you wanted to declare a function pointer to the SayIt() function in your main function:

int main()
{
  // DECLARE A FUNCTION POINTER TO THE
  // SayIt() function by the name of ptrSayIt
  void (*ptrSayIt)() ;
  // The above is probably the weirdest, non-C++ish
  // syntax you've come across.  It looks weird because
  // it is.  No, really, function pointer declaration
  // syntax is kind of mixed up.
  // 1.  First, the word VOID specifies the
  // return type of the function that you
  // will point to...
  // 2.  Second is (*ptrSayIt).  The * there
  // says THIS IS A FUNCTION POINTER NOT
  // A FUNCTION DECLARATION, (else C++ would
  // think you're trying to create a function,
  // not simply point to one!)
  // 3.  Third, the trailing brackets at the end ()
  // say that the function we are pointing to
  // won't accept any arguments when it is called.

  // If it helps, you can look at it as:
  // void(*)().  That is the type of the
  // ptrSayIt variable.  The "mixed up" part
  // is because this breaks the usual C declaration
  // syntax of TYPE    InstanceName,
  // and so its really weird to look at at first.
  // Then you kind of get used to it.  Keep reading!

  // Now the ptrSayIt variable points to the
  // SayIt function..
  ptrSayIt = &SayIt ; // you don't really need the & in front
  // but I put it to be clear

  // Now we can call the SayIt function __through__
  // the ptrSayIt pointer we just declared and set up!
  (*ptrSayIt)() ; // (*DEREFERENCE) the pointer first!
  // OUTPUTS:  "It.  There.  Happy now?"
  // TRY IT YOURSELF!
}

So this all seems very weird. But the program above works, I guarantee!

Lets do some more examples.

Declare a function pointer named Foo that points to a function marked by prototype:

int add( int a, int b ) ;

Answer:

int (*Foo)(int,int) ;

Reasoning: the return type of the function you are about to point to goes first.

int        // function pointer will point
// to a function returning int..

Then, you do this mixed up thing where you write the name of the pointer variable NOW, in brackets, with a * in front:

int (*Foo) // function pointer VARIABLE
// identifier/handle is Foo.  This is actually
// the WEIRDEST part of the syntax.

Then you follow up with the types of arguments that the function you are trying to point to will contain:

int (*Foo)( int, int )   // will point 
// to a function accepting 2 ints

Further reading

So what’s the use of function pointers? Why, many, many uses!

Now you can write functions that accept pointers to functions.. and so you can have a function have variable behavior based on what function you passed it…-

But you probably already think function pointers are cool. That’s why you stopped in to read about them!

In creating a Vector or Matrix4x4 class, it is tempting to think its a good idea to overload the == operator __not__ with an element by element comparison for exact equality (as it __should__ be!) but instead to equate it to some version of a .Near() method (where we check that each element is within some EPSILON of the corresponding element in the other matrix)

It turns out this is __not__ a very good idea for the following reason

Say you want to make a std::map<Matrix> for some reason. Now finding is based on operator== and operator<.

So you have a huge problem if you overloaded operator== to mean “approximately equal”!

More expensive key lookup, (lots of fabs()), and worse, more collisions where you may not want them!

Autohotkey script to do copy paste qwerty style on dvorak keyboard

#,::Send ^w
#a::Send ^a
#q::Send ^x
#j::Send ^c
#k::Send ^v
#;::Send ^z
#f::Send ^y

To see the collation of a MySQL table, use

SHOW CREATE TABLE tablename ;

This post

*
{
  font-size: 0.8em;
}

int main()
{
  return 0 ;
}

Man, what a …

I can’t believe it. I spent about an hour debugging this problem and it wasn’t even a problem..

OpenGL textures are addressed upside down from d3d ones.

Direct3d texture address mode, notice (0,0) in top left

OpenGL texture address mode. Notice (0,0) in bottom right

The title is just so i can find it easily..

entry point

The address to which the OS passes CONTROL to once the program has been loaded into memory

obfuscate
any attempt to hide the true meaning of something (idapro)
static analysis
(With respect to code) means “reading the code to learn something” (idapro, 6)
dynamic analysis
means “watching the code execute in a controlled environment to learn something”
fuzzing
When you throw a very large number of inputs at a program, trying to find one that will make the program fail. Then use this input to exploit the program
subtend
The amount of field of view something takes.

See this java applet

Using RAWINPUT, based off the example, except this one is in a d3d window


#pragma region includes
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#include <d3d9.h>      // core direct3d
#include <d3dx9.h>     // aux libs

#include <dxerr.h>    // detailed error messages

#pragma comment(lib, "d3d9.lib")
#pragma comment(lib, "d3dx9.lib")  // aux libs
#ifdef _DEBUG
#pragma comment(lib,"d3dx9d.lib")
#else
#pragma comment(lib,"d3dx9.lib")
#endif

#pragma comment(lib, "dxerr.lib")

// Macros.
#define SAFE_RELEASE(ptr) if(ptr) { ptr->Release(); ptr = NULL; }
#define CAST_AS_DWORD(x) *((DWORD*)&x)
#define PI 3.14159
#pragma endregion

#pragma region define the Vertex structure
struct Vertex
{
  float x,y,z ;
  DWORD color ;
  
  // Ctor starts you at origin in black
  // with alpha (opacity) set to 100%
  Vertex()
  {
    x=y=z = 0.0f;
    color = D3DCOLOR_XRGB( 0,0,0 ) ;
  }

  Vertex( float ix, float iy, float iz )
  {
    x=ix;y=iy;z=iz;
    color = D3DCOLOR_XRGB( 255,255,255 ) ;
  }

  // Ctor.
  Vertex( float ix, float iy, float iz,
    unsigned char ir, unsigned char ig, unsigned char ib )
  {
    x=ix;y=iy;z=iz;
    color = D3DCOLOR_XRGB( ir, ig, ib ) ;
  }

  // Ctor that lets you pick alpha
  Vertex( float ix, float iy, float iz,
    unsigned char ir, unsigned char ig, unsigned char ib, unsigned char ALPHA )
  {
    x=ix;y=iy;z=iz;
    color = D3DCOLOR_ARGB( ALPHA, ir, ig, ib ) ;
  }
} ;
#pragma endregion

struct Globals
{
  struct _Win
  {
    HINSTANCE hInstance;    // window app instance
    HWND hwnd;              // handle for the window
    HWND hConsole ;         // handle for the console window

    int width, height;
  } win ;

  IDirect3D9 * d3d ;
  IDirect3DDevice9 * gpu ; 
};

///////////////////////////
// GLOBALS
Globals g;

///////////////////////////
// FUNCTION PROTOTYPES
void printWindowsLastError( char *msg ) ;
inline bool CHECK( HRESULT hr, char * msg, bool stop=true ) ;  // checks for errors on the HR passed.
bool initD3D() ;         // function to initialize the BEAST that is Direct3D9
void initRawinput( HWND hwnd ) ;
void update() ;          // changes geometry of the scene
void drawAxes() ;        // draws the ever-important axes (for finding your way around your own scene!)
void draw() ;            // drawing function containing Direct3D drawing calls

LRESULT CALLBACK WndProc( HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam );
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR szCmdLine, int iCmdShow );


void printWindowsLastError( char *msg )
{
  LPSTR errorString = NULL ;

  int result = FormatMessageA( FORMAT_MESSAGE_ALLOCATE_BUFFER |
                 FORMAT_MESSAGE_FROM_SYSTEM,
                 0,
                 GetLastError(),
                 0,
                 (LPSTR)&errorString,
                 0,
                 0 );

  printf( "%s %s\n", msg, errorString ) ;
  
  LocalFree( errorString ) ;
}

inline bool CHECK( HRESULT hr, char * msg, bool stop )
{
  if( FAILED( hr ) )
  {
    printf( "%s. %s:  %s\n",
            msg, DXGetErrorStringA( hr ), DXGetErrorDescriptionA( hr ) ) ;

    // Pause so we can see the error and deal with it.
    if( stop )  system("pause") ;

    return false ;
  }

  else
    return true ;
}

/// Initializes Direct3D9.  Returns true on success.
bool initD3D()
{
  // start by nulling out both pointers:
  g.d3d = 0 ;
  g.gpu = 0 ;

  g.d3d = Direct3DCreate9( D3D_SDK_VERSION ) ;

  if( g.d3d == NULL )
  {
    // DEVICE CREATION FAILED!!!! OH NO!!!
    puts( "Oh.. PHOOEY!!!!!  Device creation FAILED!!! WHAT NOW???\n" ) ;
    return false ;
  }

  puts( "Direct3D9 creation success!" ) ;

  D3DPRESENT_PARAMETERS pps = { 0 } ;

  pps.Windowed = true ;
  pps.BackBufferCount = 1 ;
  pps.SwapEffect = D3DSWAPEFFECT_DISCARD ;
  pps.BackBufferFormat = D3DFMT_UNKNOWN ;
  pps.EnableAutoDepthStencil = true ;
  pps.AutoDepthStencilFormat = D3DFMT_D16 ;

  HRESULT hr = g.d3d->CreateDevice(

    D3DADAPTER_DEFAULT, // primary display adapter
    D3DDEVTYPE_HAL,     // use HARDWARE rendering (fast!)
    g.win.hwnd,
    D3DCREATE_HARDWARE_VERTEXPROCESSING,
    &pps,
    &g.gpu

  ) ;

  if( !CHECK( hr, "OH NOS!! I could not initialize Direct3D!  Bailing...\n" ) )
  {
    return false ;
  }

  puts( "Direct3D9 GPU device creation successful" ) ;


  #pragma region setup interleaved arrays
  D3DVERTEXELEMENT9 pos ;

  pos.Usage = D3DDECLUSAGE_POSITION ;
  pos.UsageIndex = 0 ;
  pos.Stream = 0 ;
  pos.Type = D3DDECLTYPE_FLOAT3 ;
  pos.Offset = 0 ;

  pos.Method = D3DDECLMETHOD_DEFAULT ; 

  D3DVERTEXELEMENT9 col;

  col.Usage = D3DDECLUSAGE_COLOR ;
  col.UsageIndex = 0 ;
  col.Stream = 0 ;
  col.Type = D3DDECLTYPE_D3DCOLOR ;
  col.Offset = 3*sizeof( float ) ;
  col.Method = D3DDECLMETHOD_DEFAULT ;

  D3DVERTEXELEMENT9 vertexElements[] =
  {
    pos,
    col,
    D3DDECL_END()
  } ;

  IDirect3DVertexDeclaration9 * Vdecl ;

  hr = g.gpu->CreateVertexDeclaration( vertexElements, &Vdecl ) ;
  CHECK( hr, "CreateVertexDeclaration FAILED!" ) ;

  hr = g.gpu->SetVertexDeclaration( Vdecl ) ;
  CHECK( hr, "SetVertexDeclaration FAILED!" ) ;
  #pragma endregion

  
  hr = g.gpu->SetRenderState( D3DRS_COLORVERTEX, TRUE ) ;
  CHECK( hr, "SetRenderState( COLORVERTEX ) FAILED!" ) ;

  hr = g.gpu->SetRenderState( D3DRS_LIGHTING, FALSE ) ;
  CHECK( hr, "Lighting off" ) ;

  hr = g.gpu->SetRenderState( D3DRS_CULLMODE, D3DCULL_NONE ) ;
  CHECK( hr, "cull mode off" ) ;

  initRawinput( g.win.hwnd ) ;

  return true ;
}

void initRawinput( HWND hwnd )
{
  puts( "Starting up rawinput devices..." ) ;

  // After the window has been created, 
  // register raw input devices
  RAWINPUTDEVICE Rid[2] ;
        
  Rid[0].usUsagePage = 0x01 ;  // magic numbers
  Rid[0].usUsage = 0x02 ;      // magically means mouse
  Rid[0].dwFlags = 0 ; // (use this if you DO NOT WANT to capture mouse)
  //Rid[0].dwFlags = RIDEV_CAPTUREMOUSE | RIDEV_NOLEGACY ;  // (use this to CAPTURE MOUSE)
  Rid[0].hwndTarget = hwnd ;

  Rid[1].usUsagePage = 0x01 ;  // magic numbers
  Rid[1].usUsage = 0x06 ;      // magically means keyboard
  Rid[1].dwFlags = 0 ;         // use RIDEV_NOHOTKEYS for no winkey
  Rid[1].hwndTarget = hwnd ;

  if( !RegisterRawInputDevices( Rid, 2, sizeof(Rid[0]) ) )
  {
    //registration failed. Check your Rid structs above.
    printWindowsLastError( "RegisterRawInputDevices" ) ;
    puts( "Could not register raw input devices. Check your Rid structs, please." ) ;
    exit(1);
  }
}

void update()
{
}

////////////////////////
// DRAWING FUNCTIONS
void drawAxes()
{

  static float axisLen = 2.0f ;
  static Vertex axis[] = {

    // x-axis is red
    Vertex( -axisLen, 0, 0, 255, 0, 0 ),
    Vertex( +axisLen, 0, 0, 255, 0, 0 ),

    // y-axis green
    Vertex( 0, -axisLen, 0, 0, 255, 0 ),
    Vertex( 0, +axisLen, 0, 0, 255, 0 ),

    // z-axis blue
    Vertex( 0, 0, -axisLen, 0, 0, 255 ),
    Vertex( 0, 0, +axisLen, 0, 0, 255 )

  } ;

  HRESULT hr = g.gpu->DrawPrimitiveUP( D3DPT_LINELIST, 3, axis, sizeof( Vertex ) ) ;
  CHECK( hr, "DrawPrimitiveUP FAILED!" ) ;

  static float pointSize = 8.0f ;

  g.gpu->SetRenderState( D3DRS_POINTSIZE, CAST_AS_DWORD( pointSize ) ) ;

  // Draw points at end of axis.
  static Vertex points[] = {
    Vertex( axisLen, 0, 0, 255, 0, 0 ),
    Vertex( 0, axisLen, 0, 0, 255, 0 ),
    Vertex( 0, 0, axisLen, 0, 0, 255 ),
  } ;

  hr = g.gpu->DrawPrimitiveUP( D3DPT_POINTLIST, 3, points, sizeof( Vertex ) ) ;
  CHECK( hr, "DrawPrimitiveUP FAILED!" ) ;

}

void draw()
{
  HRESULT hr ;

  hr = g.gpu->Clear( 0, 0, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER,
    D3DCOLOR_ARGB( 255, 25, 25, 25 ), 1.0f, 0 ) ;
  CHECK( hr, "Clear FAILED!" ) ;

  #pragma region set up the camera
  D3DXMATRIX projx ;

  D3DXMatrixOrthoRH( &projx, 5, 5, 1, 100 ) ;
  //D3DXMatrixPerspectiveFovRH( &projx, PI/4, (float)g.win.width/g.win.height, 1.0f, 1000.0f ) ;

  g.gpu->SetTransform( D3DTS_PROJECTION, &projx ) ;

  D3DXMATRIX viewx ;

  int x = 2 ;
  int y = 2 ;
  D3DXVECTOR3 eye( x, y, 4 ) ;
  D3DXVECTOR3 look( x, y, 0 ) ;
  D3DXVECTOR3 up( 0, 1, 0 ) ;
  D3DXMatrixLookAtRH( &viewx, &eye, &look, &up ) ;
  g.gpu->SetTransform( D3DTS_VIEW, &viewx ) ;
  #pragma endregion

  hr = g.gpu->BeginScene() ;
  CHECK( hr, "BeginScene FAILED!" ) ;


  drawAxes();


  hr = g.gpu->EndScene() ;
  CHECK( hr, "EndScene FAILED!" ) ;

  // And finally, PRESENT what we drew to the backbuffer
  g.gpu->Present( 0, 0, 0, 0 ) ;

}

int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR szCmdLine, int iCmdShow )
{
  //////////////////
  // First we'll start by saving a copy of
  // the hInstance parameter inside our
  // "glob" of globals "g":
  g.win.hInstance = hInstance;
  // In case we need it later, we'll have it
  // with firsthand easy access.

  #pragma region part 0 - attach a console
  // Attach a console
  AllocConsole();
  AttachConsole( GetCurrentProcessId() ) ;
  freopen( "CON", "w", stdout ) ; // redirect stdout to console

  // Move the console over to the top left
  g.win.hConsole = GetConsoleWindow();
  MoveWindow( g.win.hConsole, 0, 0, 400, 400, true ) ;

  printf( "* * Computer Program Begin * *\n" ) ;
  #pragma endregion

  #pragma region part 1 - create a window
  // The next few lines you should already
  // be used to:  create a WNDCLASSEX
  // that describes the properties of
  // the window we're going to soon create.
  // A.  Create the WNDCLASSEX
  WNDCLASSEX wcx = { 0 } ;
  wcx.cbSize = sizeof( WNDCLASSEX );
  wcx.hbrBackground = (HBRUSH)GetStockObject( BLACK_BRUSH );
  wcx.hCursor = LoadCursor( NULL, IDC_ARROW );
  wcx.hIcon = LoadIcon( NULL, IDI_APPLICATION );
  wcx.hInstance = hInstance;
  wcx.lpfnWndProc = WndProc;
  wcx.lpszClassName = TEXT("Philip");
  wcx.lpszMenuName = 0;
  wcx.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;

  // Register that class with the Windows O/S..
  RegisterClassEx( &wcx );

  int width = 800, height = 600;
  int leftEdge = 400, topEdge = 25 ;
  RECT rect;
  SetRect( &rect,
    leftEdge,  // left
    topEdge,   // top
    leftEdge + width, // right
    topEdge  + height ); // bottom

  // Save width and height off.
  g.win.width = rect.right - rect.left;
  g.win.height = rect.bottom - rect.top;

  // Adjust it.
  DWORD windowStyle = WS_OVERLAPPEDWINDOW ; // typical features of a normal window
  DWORD windowExStyle = 0 ; // I want the window to be topmost

  AdjustWindowRectEx( &rect, windowStyle, false, windowExStyle );

  g.win.hwnd = CreateWindowEx(
    windowExStyle,
    TEXT("Philip"),
    TEXT("DIRECT3D WINDOW"),
    windowStyle,
    rect.left, rect.top,  // adjusted x, y positions
    rect.right - rect.left, rect.bottom - rect.top,  // adjusted width and height
    NULL, NULL,
    hInstance, NULL);

  // check to see that the window
  // was created successfully!
  if( g.win.hwnd == NULL )
  {
    FatalAppExit( NULL, TEXT("CreateWindow() failed!") );
  }

  // and show.
  ShowWindow( g.win.hwnd, iCmdShow );

  // JUMP to the initD3D() method.
  if( !initD3D() )
  {
    FatalAppExit( 0, TEXT("SORRY!!!  DEVICE CREATION FAILED!!! YOU LOSE, WITHOUT EVEN PLAYING THE GAME!!!" ) ) ;
  }

  #pragma endregion

  #pragma region message loop
  MSG msg;

  while( 1 )
  {
    if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) )
    {
      if( msg.message == WM_QUIT )
      {
        break;
      }

      TranslateMessage( &msg );
      DispatchMessage( &msg );
    }
    else
    {
      update();
      draw();
    }
  }
  #pragma endregion

  //////////////
  // clean up
  SAFE_RELEASE( g.gpu ) ;
  SAFE_RELEASE( g.d3d ) ;

  // and a cheesy fade exit
  AnimateWindow( g.win.hwnd, 200, AW_HIDE | AW_BLEND );

  printf( "* * This Computer Program Has Ended * *\n" ) ;

  return msg.wParam;
}

////////////////////////
// WNDPROC
// Notice that WndProc is very very neglected.
// We hardly do anything with it!  That's because
// we do all of our processing in the draw()
// function.
LRESULT CALLBACK WndProc(   HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam )
{
  switch( message )
  {
  case WM_CREATE:
    Beep( 50, 10 );
    return 0;
    break;

  case WM_PAINT:
    {
      HDC hdc;
      PAINTSTRUCT ps;
      hdc = BeginPaint( hwnd, &ps );
      // don't draw here.  would be waaay too slow.
      // draw in the draw() function instead.
      EndPaint( hwnd, &ps );
    }
    return 0;
    break;

  case WM_KEYDOWN:
    switch( wparam )
    {
    case VK_ESCAPE:
      PostQuitMessage( 0 );
      break;
    default:
      break;
    }
    return 0;



  case WM_INPUT: 
    {
      UINT dwSize;

      GetRawInputData((HRAWINPUT)lparam, RID_INPUT, NULL, &dwSize, 
        sizeof(RAWINPUTHEADER));
      LPBYTE lpb = new BYTE[dwSize];
      if (lpb == NULL) 
      {
        return 0;
      } 

      int readSize = GetRawInputData( (HRAWINPUT)lparam, RID_INPUT, lpb, &dwSize, sizeof(RAWINPUTHEADER) ) ;

      if( readSize != dwSize )
        puts( "ERROR:  GetRawInputData didn't return correct size!" ) ; 

      RAWINPUT* raw = (RAWINPUT*)lpb;

      if (raw->header.dwType == RIM_TYPEKEYBOARD) 
      {
        if( raw->data.keyboard.VKey == VK_SPACE )
        {
          puts( "You are pressing space" ) ;
        }
      }
      else if (raw->header.dwType == RIM_TYPEMOUSE) 
      {
        int dx = raw->data.mouse.lLastX ;
        int dy = raw->data.mouse.lLastY ;

        printf( "%d %d\n", dx, dy ) ;
      } 

      delete[] lpb; 
      return 0;
    } 

  case WM_SIZE:
    {
      int width = LOWORD( lparam ) ;
      int height = HIWORD( lparam ) ;
      printf( "RESIZED TO width=%d height=%d\n", width, height ) ;
    }
    break;

  case WM_DESTROY:
    PostQuitMessage( 0 ) ;
    return 0;
    break;
  }

  return DefWindowProc( hwnd, message, wparam, lparam );
}

Well, this post was looking for the same thing I was, and nobody seemed to know of any.

The problem with algebra tricks is they’re so context dependent. There’s really only a few things that math books and tests use to make “wicked” problems (list being expanded).

  • 1. Multiplying by the conjugate
  • 2. Factoring using the +C -C trick (complete the square method)

Really the “hard” problems require an algebraic twist, a keen eye, insight – stuff you only get after having practiced with hundreds of problems (and checking the solutions!).

So first,
sosmath: Derivative of sin, cos, tan, csc, sec, cot

Mathworld: Inverse trig functions

trig identities

Now, the rest of this post is just examples of the trick (by name) and a couple of examples that illustrate the trick in action (list being expanded!) (Bear with the non-mathmlness for now!)

1. Multiplying by the conjugate

INTEGRAL( dx / (1 + cos x) )

To solve, you have to multiply the numerator and denominator by ( 1 – cos x ) to get sin2x in the denominator..

2. Factoring using the +C -C trick

INTEGRAL( dx / (x2 + 10x + 30) )

You have to factor (wactor! as my friend used to say) the denominator into ((x+5)2 + 5) by:

x2 + 10x + 25 - 25 + 30
= (x + 5)2 + 5

You know to do +25, -25 BECAUSE half of 10 is 5, and 52 is 25. That method in general is called completing the square and you have to do it all the time.

Code to get a unicode string from an ascii string

wchar_t* getUnicode( wchar_t* unicodeDest, char* asciiSrc )
{
  int len = strlen( asciiSrc ) ;

  MultiByteToWideChar( CP_ACP, 0, asciiSrc, len, unicodeDest, len ) ;
  unicodeDest[ len ] = 0 ; // add null terminator

  return unicodeDest ;
}
Follow

Get every new post delivered to your Inbox.