First, Install Boost and be sure to choose the regex package when you install it.

Regex matching in C++ using BOOST

Regex replace in C++ using BOOST

Regex extract in C++ using BOOST

See example below.

#include <iostream>
#include <string>
#include <boost/regex.hpp> // add boost regex library
using namespace std ;

int main()
{
  // http://www.boost.org/doc/libs/1_35_0/more/getting_started/windows.html#get-boost

  // To practice regular expressions, use
  // http://weitz.de/regex-coach/
  bool quitting = false ;
  string input ;

  puts( " *** Regex MATCH test ***" ) ;
  puts( " ------------------------" ) ;
  while( !quitting )
  {
    boost::regex EXPR( "[0-9][0-9][A-Za-z]" ) ;

    cout << "The expression is:" << endl ;
    cout << EXPR << endl << endl ;

    cout << "Enter a string to match it, or just type Q to move on" << endl ;
    getline( cin, input ) ;

    bool matches = boost::regex_match( input, EXPR ) ;
    if( matches )
    {
      puts( "Congrats, you entered a string that matches the expression." ) ;
    }
    else if( input == "q" || input == "Q" )
    {
      puts( "Bye!" ) ;
      quitting = true ;
    }
    else
    {
      puts( "NO, that string didn't match" ) ;
    }
  }

  puts( "\n" ) ;
  puts( " *** Regex REPLACE test ***" ) ;
  puts( " --------------------------" ) ;
  quitting = false ;

  while( !quitting )
  {
    boost::regex EXPR( "e" ) ;
    string REPLACEMENT = "X" ;

    cout << "I am replacing: " << EXPR << " with: " << REPLACEMENT << endl ;
    cout << EXPR << endl << endl ;

    cout << "Enter a string with lowercase 'e' in it, or just type Q to quit." << endl ;
    getline( cin, input ) ;

    if( input == "q" || input == "Q" )
    {
      puts( "Bye!" ) ;
      quitting = true ;
    }
    else
    {
      string replaced = boost::regex_replace( input, EXPR, REPLACEMENT, boost::match_default | boost::format_sed ) ;
      cout << replaced << endl;
    }
  }

  // Finally, a test showing capturing
  boost::regex EXPR( "<food>([A-Za-z]+)</food>" ) ;
  string xmlData = "<food>pizza</food>" ;

  string replaced = boost::regex_replace(

    xmlData,  // the data

    EXPR,     // the regex

    "\\1",    // Don't forget to DOUBLE backslash
              // your regex escape sequences!!

    boost::match_default | boost::format_sed
    // You can get perl-style regex strings,
    // "sed" style regex strings,
    // or you can use boost's own
    // extended format style strings.
    // See http://www.boost.org/doc/libs/1_33_1/libs/regex/doc/format_syntax.html
  ) ;
  cout << "EXPR: " << EXPR << endl;
  cout << "Data: " << xmlData << endl;
  cout << "The extracted data was: " << replaced << endl ;
}

Uh, I’m applying to EA now. This post is to prove to the EA people that I am who I say I am… :)

Will let you know if I get it!

Here’s how you do it.

NSString to char*

NSString* nsstr = @"My NSString" ;
const char * cstr = [ nsstr cStringUsingEncoding:ASCIIEncoding ] ;

// There's also
const char * cstr2 = [ nsstr UTF8String ] ;

These are covered in the docs page for NSString, basically.

char * to NSString

// Here you simply want to use one of the static method constructors
const char * cstyleString = "HELLO!!" ;
NSString * nsstr = [ NSString stringWithUTF8String:cstyleString ] ;

Or an instance method
NSString * nsstr2 = [[ NSString alloc ] initWithUTF8String:cstyleString ]

(( just a note that any methods labelled with + method are static methods and methods labelled with - are instance methods ))

sprintf() for NSString

Use initWithFormat

[ [ NSString alloc ] initWithFormat:@"%s is %d years old", "Bobby", 45 ]

This seems to be a trivial and is an inherently subjective question but I want to know what the best practice is __with reasons__.

I used to write

    char * var ;

But I started writing

    char* var ;

Because I thought that the type of var is simply char* so the * pointer should be stuck to the type so its read in “one eyeful.”

THEN I ran into a bug recently where I didn’t notice that I had declarations

    char* var1, var2 ;

And I actually didn’t realize that var2 was type char, not char*. Hmm. Then I thought, well, this way makes the most sense then:

    char *var1, *var2 ;

Currently I’m thinking the last way is the correct way now.

“End of the football.”

http://www.youtube.com/watch?v=aVhYN7NTIKU

this isn’t just funny to watch, its _real_!

this isn’t funny in an “aha look at him sort” of way,

look at her expression at 1:00, and his answers to some of the questions is quite hilarious.

You can use mplayer as follows:

  1. Download mplayer from here if you’re on a windows machine. If that stops working, pick another installer package from this list. If you’re not on windows start here, you may choose to build from source if you’re a masochist.
mplayer -dumpstream -dumpfile stream.wmv mms://lang.stanford.edu/courses/ee380/050216-ee380-100.wmv

from here

Right now i’m not able to rip the stream the connection keeps timing out thouhg

Sufficient condition

An event A is said to be a sufficient condition for an event B iff

The truth/occurrence of event A guarantees the truth/occurrence of event B

Necessary condition

An event A is said to be necessary for an event B
iff the falsity/nonoccurrence of event A GUARANTEES
the falsity/nonoccurrence of event B.

Barycentric coordinates

Plane plane = new Plane( a, b, c ) ;

float areaABC = Vector3.Dot( plane.Normal, Vector3.Cross( b - a, c - a ) ) ;
float areaPBC = Vector3.Dot( plane.Normal, Vector3.Cross( b - P, c - P ) ) ;
float areaPCA = Vector3.Dot( plane.Normal, Vector3.Cross( c - P, a - P ) ) ;

float alpha = areaPBC / areaABC ;
float beta = areaPCA / areaABC ;
float gamma = 1.0f - alpha - beta ;

“watching nonprogrammers trying to run software companies is like watching someone who doesn’t know how to surf trying to surf”

I read that, and i’m like THANK YOU

LOL!! joel refers to the 1984 mac commercial on page 32. He starts to point at how the whole MAC thing.. macusers have a distinct groovy personality from pc users. or something.

Instead of fighting with libcurl you could just use WinInet for your http needs if you are married to the Windows platform.

A quick example follows, great article, and as usual pretty difficult to navigate msdn docs

#include <windows.h>
#include <wininet.h>

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

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

int main()
{
  HINTERNET hInternet = InternetOpenA("InetURL/1.0", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0 );

  HINTERNET hConnection = InternetConnectA( hInternet, "mohammad.appspot.com", 80, " "," ", INTERNET_SERVICE_HTTP, 0, 0 );

  HINTERNET hData = HttpOpenRequestA( hConnection, "GET", "/", NULL, NULL, NULL, INTERNET_FLAG_KEEP_CONNECTION, 0 );

  char buf[ 2048 ] ;

  HttpSendRequestA( hData, NULL, 0, NULL, 0 ) ;

  DWORD bytesRead = 0 ;
  DWORD totalBytesRead = 0 ;
  // http://msdn.microsoft.com/en-us/library/aa385103(VS.85).aspx
  // To ensure all data is retrieved, an application must continue to call the
  // InternetReadFile function until the function returns TRUE and the
  // lpdwNumberOfBytesRead parameter equals zero.
  while( InternetReadFile( hData, buf, 2000, &bytesRead ) && bytesRead != 0 )
  {
    buf[ bytesRead ] = 0 ; // insert the null terminator.

    puts( buf ) ;          // print it to the screen.

    printf( "%d bytes read\n", bytesRead ) ;

    totalBytesRead += bytesRead ;
  }

  printf( "\n\n END -- %d bytes read\n", bytesRead ) ;
  printf( "\n\n END -- %d TOTAL bytes read\n", totalBytesRead ) ;

  InternetCloseHandle( hData ) ;
  InternetCloseHandle( hConnection ) ;
  InternetCloseHandle( hInternet ) ;

}

google app engine

index.py

class Person( db.Model ) :
  name = db.StringProperty()

class TPerson( webapp.RequestHandler ) :
  def get( self ) :

    # run once
    '''
    people = [ 'John Hopkins', 'Bob Jordan', 'Mike Bobs' ]

    for person in people :
      p = Person()
      p.name = person
      p.put()
    '''

    people = db.GqlQuery( 'select * from Person' ).fetch( 1000 ) 

    # if you don't .fetch(), then the addition of dynamic
    # properties won't work here.
    for person in people :
      person.shortname = person.name[ 0:2 ]

    self.response.out.write( template.render( 'TPerson.html', { 'people' : people } ) )

application = webapp.WSGIApplication([

  ( '/TPerson', TPerson ),

  ], debug=True )

def main():
  run_wsgi_app(application)

if __name__ == "__main__":
  main()

TPerson.html

{% for p in people %}
<p>{{ p.name }}</p>
<p>{{ p.shortname }}</p>
{% endfor %}

I got this error in my google app engine application

it says something to the effect of

<type ‘exceptions.ImportError’> Python 2.5.4: c:\python25\python.exe
Wed Sep 09 12:29:14 2009
A problem occurred in a Python script. Here is the sequence of function calls leading up to the error, in the order they occurred.

c:\program files (x86)\google\google_appengine\google\appengine\tools\dev_appserver.py in _HandleRequest(self=)
2921 infile,
2922 outfile,
2923 base_env_dict=env_dict)
2924 finally:
2925 self.module_manager.UpdateModuleFileModificationTimes()
base_env_dict undefined, env_dict = {‘APPLICATION_ID’: ‘mohammad’, ‘CURRENT_VERSION_ID’: ‘1.1′, ‘REMOTE_ADDR’: ‘127.0.0.1′, ‘REQUEST_METHOD’: ‘GET’, ‘SERVER_NAME’: ‘localhost’, ‘SERVER_PORT’: ‘8080′, ‘SERVER_PROTOCOL’: ‘HTTP/1.0′, ‘SERVER_SOFTWARE’: ‘Development/1.0′}

Really the problem was I has put a leading slash in my app.yaml where one should not be

- url: /home
  script: /home/index.py

Really this should be

- url: /home
  script: home/index.py

So there was no leading slash on script: EVER.

There is an easy solution for this, if you just installed HL2, you have to LAUNCH THE GAME AND LET IT UPDATE before trying to launch the Hammer map editor.

Windows 7 has this security feature that makes some of your old software stop working.

Every vendor has to “register” a software driver to make one work.

Start > All Programs > Accessories > Right click on command prompt > Run as administrator

bcdedit /set loadoptions DDISABLE_INTEGRITY_CHECKS

REBOOT, and that’s it! “Windows requires a digitally signed driver???” No he doesn’t!

Try this page out.

Remove the <!doctype> declaration at the top of the page to see quirks mode in action.


<!doctype html>
<html>
<head>
<style>
ul
{
  list-style-type: none;
}

li
{
  /*
    ie old rules width referred to
    the combination of borders,
    padding, AND what's inside the element.

    standards say WIDTH EXCLUDES PADDING, borders.
  */
  margin: 20px ;
  padding: 20px 40px;
  width: 250px;
  border: solid 2px black;
  background-color: #eee;
}
</style>
</head>

<body>
  <ul>
    <li>Digger</li>
    <li>Styx</li>
    <li>Heroes of might and magic</li>
    <li>world of warcraft</li>
  </ul>
</body>
</html>

this picture says it all..

So, I rarely use my live account, but now when I try to, it crashes firefox 3.0.11.

Not cool Microsoft. Not cool.

There has been a tendency for Microsoft to not support other browsers. I think they need to realize that this actually hurts them more than it compels users to open up IE and use that browser.

this page has a note about how to do an MSI dump (and a great DirectX book too!)

msiexec /a %MSI%

The VARIANT datatype is the worst, most error prone piece of shit i’ve ever seen.

look at this bug:


  for( int s = 0 ; s < count ; s++ )
  {
    _variant_t vi( s ) ;

    ADOField * field ;

    if( CHECK( fields->get_Item( vi, &field ), "Getting field item" ) )
    {
      BSTR name ;

      CHECK( field->get_Name( &name ), "getting name" ) ;

      wprintf( L"| %10s |", name );
    }

  }

Why did it crash? I’ll paste the correct non-crashing code below and see if you can find it


  for( short s = 0 ; s < count ; s++ )
  {
    _variant_t vi( s ) ;

    ADOField * field ;

    if( CHECK( fields->get_Item( vi, &field ), "Getting field item" ) )
    {
      BSTR name ;

      CHECK( field->get_Name( &name ), "getting name" ) ;

      wprintf( L"| %10s |", name );
    }

  }

See it? When I declared the counter variable s as an int, the variant type was the wrong type (it was an INT type instead of a SHORT type).

I only GUESSED this was the problem not from the amazing documentation that ms keeps on this, but from this article looking at how they browsed the thing.

I was shocked and amazed that the VARIANT type was ever in use by anyone at any point in time, and how EXTENSIVELY its used in ADO.

I mean, its an ugly type and this is a STUPID reason for a bug to exist.

i’m sick of these broken links to old microsoft articles.

i can’t understand WHY they remove their KB articles.

this has happened to me on more than one occassion. There is no need to DELETE kb articles, ever.

microsoft’s attitude towards the web needs to change.

OK, here it is.

Pure torture.


#define _CRT_SECURE_NO_DEPRECATE

// Before running this program, make sure you have a
// mysql32 dsn set up to connect to the 'test' database.

// Run these queries:
/*
create table users( id int, name varchar( 255 ) );

insert into users( id, name ) values ( 1, 'bob' ), ( 2, 'john' ) ;

select * from users ;
*/

#include <windows.h>
#include <stdio.h>
#include <stddef.h>     // for offsetof()
#include <cguid.h>

#include <oledb.h>
#include <oledberr.h>
#include <msdaguid.h>
#include <msdasql.h>

#include <comdef.h>     // for _com_error()

#include <vector>
using namespace std ;

#define FIELD_NAME_LEN 255

struct User
{
  int id ;

  // Because the field is a varchar(255), we
  // represent that here as a char array with
  // 255 bytes maximum.
  char name[ FIELD_NAME_LEN ] ;

  User()
  {
    id = 1 ;
    strcpy( name, "unnamed user" ) ;
  }

  User( int i_id, char * i_name )
  {
    id = i_id ;
    strcpy( name, i_name ) ;
  }
} ;

///
/// Dump an error to the console,
/// including any information we can
/// get from the system about
/// the specific error.
///
void DumpError( HRESULT hr )
{
  printf( "HRESULT: %d\n", hr ) ;

  _com_error err( hr ) ;
  BSTR bstr = err.Description() ;
  printf( "Description: %s\n", bstr );
  wprintf( L"_com_error.ErrorMessage(): %s\n", err.ErrorMessage()  ) ;

  IErrorInfo * errorInfo ;
  GetErrorInfo( 0, &errorInfo );
  if( errorInfo )
  {
    BSTR description;
    errorInfo->GetDescription( & description );

    // description will be a more descriptive error message than just formatting the
    // HRESULT because it is set by the COM server code at the point of the error

    wprintf( L"\nIErrorInfo says:  %s\n", description ) ;
  }

  printf("\n");
}

/// Its very important to CHECK ALL return codes.
/// Its a real ass-biter when something goes wrong
/// and the notification is hidden because you
/// didn't check the HRESULT of every command.
bool CHECK( HRESULT hr, char * msg, bool printSucceededMsg=false, bool quit=true )
{
  if( SUCCEEDED( hr ) )
  {
    if( printSucceededMsg )  printf( "%s succeeded\n", msg ) ;

    return true ;
  }
  else
  {
    printf( "%s has FAILED!!\n", msg ) ;

    DumpError( hr ) ;

    if( quit )  FatalAppExitA( 0, msg ) ;

    return false ;
  }
}

/// Gets you an ICommandText interface to
/// the database connected to in db.
/// ICommandText's let you send SQL queries
/// to the database.
ICommandText * GetCommand( IDBInitialize * dbInit )
{
  #pragma region talk about QueryInterface
  // QueryInterface is a funky method.

  // Basically you use it to "ask" the COM object you
  // are working with here WHETHER OR NOT IT SUPPORTS
  // ("implements") a specific interface.

  // To quote an excellent MSDN article:
  // "If an object supports an interface, it supports
  // all of the methods within that interface."
  //    http://msdn.microsoft.com/en-us/library/ms810892.aspx

  // If you're curious, take a look at the
  // "sampprov" project that comes with
  // the Windows SDK sample set
  // C:\Program Files\Microsoft SDKs\Windows\v6.1\Samples\dataaccess\oledb\sampprov

  // Therein, an implementation of the QueryInterface
  // method lies:

  /*
STDMETHODIMP CCommand::QueryInterface
(
	REFIID riid,				//@parm IN | Interface ID of the interface being queried for.
	LPVOID * ppv				//@parm OUT | Pointer to interface that was instantiated
)
{
	if( ppv == NULL )
		return ResultFromScode(E_INVALIDARG);

	//	This is the non-delegating IUnknown implementation
	if( riid == IID_IAccessor )
		*ppv = (LPVOID)m_pIAccessor;
	else if( riid == IID_ICommand )
		*ppv = (LPVOID)m_pICommandText;
	else if( riid == IID_ICommandText )
		*ppv = (LPVOID)m_pICommandText;
	else if( riid == IID_ICommandProperties )
		*ppv = (LPVOID)m_pICommandProperties;
	else if( riid == IID_IColumnsInfo )
		*ppv = (LPVOID)m_pIColumnsInfo;
	else if( riid == IID_IConvertType )
		*ppv = (LPVOID)m_pIConvertType;
	else if( riid == IID_IUnknown )
		*ppv = (LPVOID)this;
	else
		*ppv = NULL;
}
*/
  // OK Isn't that COOL?  All what happens is,
  // QueryInterface looks to see if "riid"
  // is one of the interface types this object
  // supports.

  // If it DOES support the interface you're
  // asking for, then it just points "ppv" to
  // its local member instance of that class.

  // If the object DOES NOT support the interface
  // you're querying for, then you get a null pointer back.

  // ISN'T THAT SIMPLE?  Its a lot simpler internally
  // than I initially thought.  Basically QueryInterface
  // is a Get_* method, only its very very generic.

  // Nothing is created in a QueryInterface method.
  // You get something that already exists within the
  // object.  QueryInterface lets you simply access it.

  // Also note that as a RULE, once a COM interface
  // is published, YOU CANNOT ADD OR REMOVE METHODS
  // FROM THAT INTERFACE.  Instead, you have to
  // define a NEW interface (hence why DirectX has
  // IDirect3D9, IDirect3D7.. etc.)
  #pragma endregion

  // So now, I ultimately want a COMMAND interface,

  // ICommandText <- IDBCreateCommand <- IDBCreateSession <- IDBInitialize
  // cmdText      <- cmdFactory       <- sessionFactory   <- dbInit
  // In words:
  // 1.  IDBInitialize spawns an IDBCreateSession
  // 2.  That IDBCreateSession is used to create an IDBCreateCommand
  // 3.  That IDBCreateCommand is used to create an ICommandText
  // 4.  The ICommandText is returned

  IDBCreateSession * sessionFactory ;
  HRESULT hr = dbInit->QueryInterface(

    IID_IDBCreateSession,      // I want an IID_IDBCreateSession interface.. which
    // I shall use to MAKE a session.

    (void**)&sessionFactory // and put it into sessionFactory variable.

  ) ;

  CHECK( hr, "creating session factory" ) ;

  // Get a command factory out of the session factory
  // We need the command factory to create ICommandText's,
  // ICommandText will hold our SQL queries eventually.
  IDBCreateCommand * cmdFactory ;
  CHECK( sessionFactory->CreateSession( NULL, IID_IDBCreateCommand, (IUnknown**)&cmdFactory ), "CreateSession" ) ;

  // Then throw away the session creator object.
  CHECK( sessionFactory->Release(), "releasing the session factory" ) ;

  // Create the command, saving in cmdText.
  // ICommandText interface contains text of an SQL query, eventually
  ICommandText * cmdText ;
  CHECK( cmdFactory->CreateCommand( NULL, IID_ICommandText, (IUnknown**) &cmdText ), "cmdFactory->CreateCommand()" ) ;
  CHECK( cmdFactory->Release(), "cmdFactory->Release()" ) ;

  return cmdText ;
}

///
/// Execute a prepared INSERT statement with parameters.
///
void runInsertWithParameters( IDBInitialize * db )
{

  //////////
  // // DBPARAMINFO.
  // This array of structs
  // will tell OLE DB the DATATYPE and NAME of the
  // columns of the table we are running our
  // prepared INSERT statement against.

  vector<DBPARAMBINDINFO> bindInfo ;

  // Standard type name | Type indicator table
  // contains "DBTYPE_I4" => DBTYPE_I4 mappings
  // Basically you just quote all of them, except for example
  // "DBTYPE_CHAR" => DBTYPE_STR, and
  // "DBTYPE_VARCHAR" => DBTYPE_STR as well.
  DBPARAMBINDINFO firstColumnBindInfo = { 0 } ;
  firstColumnBindInfo.pwszDataSourceType = OLESTR( "DBTYPE_I4" ) ;  // !!CAN ALSO BE "int"
  firstColumnBindInfo.pwszName = NULL ;   // The name of the __parameter__
  // Most of the time this should be NULL.
  // DO NOT SET THIS to OLESTR( "id" ),
  // or OLESTR( "@id" ), or something like this.
  // MySQL doesn't seem to support named parameters.
  // Named parameters look like this:
  //   insert into tablename (col1, col2) values ( :param1, :param2 )
  // vs UNNAMED parameters:
  //   insert into tablename (col1, col2) values ( ?, ? )
  // We're using UNNAMED parameters here.  Don't
  // mistaken this field for the name of the COLUMN
  // in the table.  Because its not that.  EVEN THOUGH
  // the MSDN example DOES get this wrong.  See this post.
  firstColumnBindInfo.ulParamSize = 4 ;   // size in bytes (obviously 4 bytes for an I4 (int-4) field)
  firstColumnBindInfo.dwFlags = DBPARAMFLAGS_ISINPUT | DBPARAMFLAGS_ISSIGNED  ; // http://msdn.microsoft.com/en-us/library/ms714917(VS.85).aspx
  firstColumnBindInfo.bPrecision = 11 ;  // bPrecision is the maximum number of digits, expressed in base 10
  firstColumnBindInfo.bScale = 0 ;

  bindInfo.push_back( firstColumnBindInfo ) ;

  DBPARAMBINDINFO secondColumnBindInfo = { 0 } ;
  secondColumnBindInfo.pwszDataSourceType = OLESTR( "DBTYPE_VARCHAR" ) ; // !!can also be "varchar(255)"
  //secondColumnBindInfo.pwszName = NULL ;
  secondColumnBindInfo.ulParamSize = FIELD_NAME_LEN ;
  secondColumnBindInfo.dwFlags = DBPARAMFLAGS_ISINPUT  ;
  secondColumnBindInfo.bPrecision = 0 ;
  secondColumnBindInfo.bScale = 0 ;

  bindInfo.push_back( secondColumnBindInfo ) ;

  // now, cmdText is the variable we're working with.
  // The command requires the actual text
  // as well as an indicator of its language.
  ICommandText * cmdText = GetCommand( db ) ;

  // Set the SQL query that will run.
  CHECK( cmdText->SetCommandText( DBGUID_DBSQL, OLESTR("insert into users ( id, name ) values (?, ?)") ), "SetCommandText" ) ;

  // Now go down into the cmdWithParams and
  // Set its ParameterInfo with the BINDINFO
  // that we just specified above.
  ICommandWithParameters * cmdWithParams ;
  CHECK( cmdText->QueryInterface( IID_ICommandWithParameters, (void**)&cmdWithParams ), "get cmdWithParams" ) ;

  // the ORDER that parameter infomation will come in inside bindInfo
  ULONG ordinals[ 2 ] = { 1, 2 } ;
  CHECK( cmdWithParams->SetParameterInfo( bindInfo.size(), ordinals, &bindInfo[ 0 ] ), "SetParameterInfo" ) ;
  CHECK( cmdWithParams->Release(), "cmdWithParams release" ) ;

  // Prepare the command.
  // MSDN:  This optional interface encapsulates command optimization,
  // a separation of compile time and run time, as found in traditional
  // relational database systems. The result of this optimization is
  // a command execution plan.
  // http://msdn.microsoft.com/en-us/library/ms713621(VS.85).aspx

  ICommandPrepare * cmdPrepare ;
  CHECK( cmdText->QueryInterface( IID_ICommandPrepare, (void**)&cmdPrepare ), "Get ICommandPrepare interface" ) ;
  CHECK( cmdPrepare->Prepare( 0 ), "Command preparation" ) ;
  CHECK( cmdPrepare->Release(), "ICommandPrepare release" ) ;

  // Create parameter accessors.
  #pragma region create parameter accessors

  IAccessor * accessor ;
  CHECK( cmdPrepare->QueryInterface( IID_IAccessor, (void**)&accessor ), "Getting IAccessor interface" ) ;

  // DBBINDING
  vector<DBBINDING> bindings ;

  DBBINDING firstColumnBinding = { 0 } ;
  firstColumnBinding.iOrdinal = 1 ;
  firstColumnBinding.dwPart = DBPART_VALUE ;
  firstColumnBinding.dwMemOwner = DBMEMOWNER_CLIENTOWNED ;
  firstColumnBinding.eParamIO = DBPARAMIO_INPUT ;
  firstColumnBinding.cbMaxLen = 4 ;

  firstColumnBinding.wType = DBTYPE_I4 ;
  firstColumnBinding.obValue = offsetof( User, id ) ;  // get byte offset of id member
  printf( "offset of id field is %d\n", firstColumnBinding.obValue ) ;

  bindings.push_back( firstColumnBinding ) ;

  DBBINDING secondColumnBinding = { 0 } ;
  secondColumnBinding.iOrdinal = 2 ;
  secondColumnBinding.dwPart = DBPART_VALUE ;
  secondColumnBinding.dwMemOwner = DBMEMOWNER_CLIENTOWNED ;
  secondColumnBinding.eParamIO = DBPARAMIO_INPUT ;
  secondColumnBinding.cbMaxLen = FIELD_NAME_LEN ;

  secondColumnBinding.wType = DBTYPE_STR ;
  secondColumnBinding.obValue = offsetof( User, name ); // get byte offset of name member.
  printf( "offset of name field is %d\n", secondColumnBinding.obValue ) ;

  bindings.push_back( secondColumnBinding ) ;

  // used to get information about the validity of our binding attempt
  vector<DBBINDSTATUS> rgStatus ;
  rgStatus.resize( 2 ) ;

  // The hAccessor will tie the BINDING information
  // to the actual dataset used.
  HACCESSOR hAccessor ;
  printf( "%d\n", sizeof( User ) ) ;

  HRESULT hr = accessor->CreateAccessor(

    DBACCESSOR_PARAMETERDATA,    // Accessor that will be used to specify parameter data

    bindings.size(),    // Number of parameters being bound

    &bindings[0],       // Structure containing bind information

    sizeof( User ), // Size of parameter structure.  This MUST be a FIXED SIZE,
    // so you cannot use a generic char* pointer in User that points to
    // a variable length string (must be predetermined size, as it is
    // char[FIELD_NAME_LEN] in this example.)

    &hAccessor,     // will contain accessor handle after this function call

    &rgStatus[0]        // will contain information about binding validity
    // after this function call is complete

  ) ;

  if( !CHECK( hr, "Parameter accessor creation" ) )
  {
    printf( "binding status validity: %d %d (0 means OK)\n", rgStatus[ 0 ], rgStatus[ 1 ] ) ;
    puts(
      "DBBINDSTATUS_OK = 0,\n"
	    "DBBINDSTATUS_BADORDINAL = 1,\n"
	    "DBBINDSTATUS_UNSUPPORTEDCONVERSION = 2,\n"
	    "DBBINDSTATUS_BADBINDINFO = 3,\n"
	    "DBBINDSTATUS_BADSTORAGEFLAGS = 4,\n"
	    "DBBINDSTATUS_NOINTERFACE = 5,\n"
	    "DBBINDSTATUS_MULTIPLESTORAGE = 6\n" ) ;
  }

  #pragma endregion

  #pragma region create data and insert it.
  // Create the data to insert and put it
  // into a struct.
  vector<User> users ;

  User user1( 55, "bobobo" ) ;
  users.push_back( user1 ) ;

  User user2( 56, "waniel" ) ;
  users.push_back( user2 ) ;

  // ICommand::Execute page, DBPARAMS is in it
  DBPARAMS dbParams;

  // pData is a pointer to an array of
  // data that contains data in the order
  // described by bindInfo.
  dbParams.pData = &users[ 0 ] ;   // the data to insert.
  dbParams.cParamSets = users.size() ;  // Number of sets of parameters
  dbParams.hAccessor = hAccessor ; // Accessor to the parameters.  tells
  // dbParams how the byte array of data
  // in pData is divided up.

  // Execute the command.
  long cRowsAffected ;
  hr = cmdText->Execute( NULL, IID_NULL, &dbParams, &cRowsAffected, NULL ) ;

  CHECK( hr, "Execute for the insert statement" ) ;
  printf( "%d rows inserted.\n", cRowsAffected ) ;

  CHECK( accessor->ReleaseAccessor( hAccessor, NULL ), "Accessor ReleaseAccessor" ) ;
  CHECK( accessor->Release(), "Release Accessor" ) ;
  CHECK( cmdText->Release(), "Release commandText" ) ;
  #pragma endregion

}

///
///  Delete rows just added using simple execution.
///
void myDelete( IDBInitialize*  pIDBInitialize )
{
  ICommandText* pICommandText = GetCommand( pIDBInitialize ) ;

  // Set the command text for first delete statement and execute
  // the command
  pICommandText->SetCommandText(

    DBGUID_DBSQL,
    OLESTR( "delete from users where id=6" )

  ) ;

  long cRowsAffected ;
  pICommandText->Execute( NULL, IID_NULL, NULL, &cRowsAffected, NULL ) ;

  printf( "%d rows deleted.\n", cRowsAffected ) ;

  // Do it again.
  pICommandText->SetCommandText(

    DBGUID_DBSQL,
    OLESTR( "delete from users where id=7" )

  ) ;

  pICommandText->Execute(NULL, IID_NULL, NULL, &cRowsAffected, NULL);

  printf("%d rows deleted.\n", cRowsAffected);

  pICommandText->Release();

  return;
}

void SetBSTRProperty( DBPROP & props, DWORD propertyId, OLECHAR * stringValue )
{
  props.dwPropertyID = propertyId ;
  props.vValue.vt = VT_BSTR ;
  props.vValue.bstrVal = SysAllocString( stringValue ) ;
}

DBPROP preinitDBPROP()
{
  DBPROP prop ;
  VariantInit( &prop.vValue ) ; // equivalent: prop.vValue.vt = VT_EMPTY ;
  prop.dwOptions = DBPROPOPTIONS_REQUIRED ;
  prop.colid = DB_NULLID ;
  return prop ;
}

int main()
{
  // Init OLE and set up the DLLs.
  CoInitialize( NULL ) ;

  // We start with the IDBInitialize interface.
  // The purpose of IDBInitialize is to Initializes a data source object
  IDBInitialize * db = NULL;

  // Get the task memory allocator.
  // At this point, the original example creates
  // an IMalloc interface.
  // IMalloc can be used to allocate and manage memory.  It doesn't seem to be used in this
  // example, but I'm leaving it here for now.
  IMalloc * iMalloc = NULL;
  CHECK( CoGetMalloc( MEMCTX_TASK, &iMalloc ), "GetMalloc" ) ;

  #pragma region Initialize the data source

  // Create an instance of the MSDASQL (ODBC) provider.
  // ODBC is for connecting to an sql-based data source
  CHECK( CoCreateInstance( CLSID_MSDASQL, NULL, CLSCTX_INPROC_SERVER, IID_IDBInitialize, (void**)&db), "starting db" ) ;

  #pragma region talk about variants
  // Set properties for this connection.
  // Declaring the properties for establishing
  // a connection to the database.

  // VARIANT PROPERTY SET.
  // Now HERE is a weird structure you don't see every day.
  // The VARIANT.

  // You might think this data structure is weird.
  // That's because it is.

  // A VARIANT encapsulates ALL the primitive types
  // that are possible in a database.  Look at its
  // struct definition in the header file or on msdn if you wish.

  // Notice how it has inside it like EVERY CONCEIVABLE
  // datatype:  DATE*, SHORT*, BYTE*, and even IUnknown.

  // It also has a property VARTYPE.  VARTYPE is set to
  // one of the values in the VARENUM enumeration.
  // So, using a VARIANT as an argument is a way to ANY
  // data type, specifying WHAT TYPE this VARIANT ACTUALLY
  // represents (i.e. what type its internal byte data
  // is to be interpretted as.).

  // MSDN about the vt field:  Contains the type code for the variant,
  //                           which governs how the variant is interpreted.
  #pragma endregion

  // Initialize common property options.

  // You "have to" call VariantInit() before
  // passing a variant to a function.  What VariantInit does is
  // simply set the vt field to VT_EMPTY.

  vector<DBPROP> props ;

  // Level of prompting that will be done
  // to complete the connection process.
  DBPROP initPrompt = preinitDBPROP() ;

  initPrompt.dwPropertyID = DBPROP_INIT_PROMPT ;
  initPrompt.vValue.vt = VT_I2 ;      // 2 byte integer (short).
  initPrompt.vValue.iVal = DBPROMPT_NOPROMPT ; 

  props.push_back( initPrompt ) ;

  // Data source name-- using the same one we set up
  // in the ODBC example http://bobobobo.wordpress.com/2009/07/11/working-with-odbc-from-c/
  DBPROP dsn = preinitDBPROP() ;
  SetBSTRProperty( dsn, DBPROP_INIT_DATASOURCE, OLESTR( "mysql32" ) ) ;
  //SetBSTRProperty( dsn, DBPROP_INIT_DATASOURCE, OLESTR( "sqlserver" ) ) ;
  props.push_back( dsn ) ;

  DBPROP username = preinitDBPROP() ;
  SetBSTRProperty( username, DBPROP_AUTH_USERID, OLESTR( "root" ) ) ;   // User ID
  props.push_back( username ) ;

  DBPROP pass = preinitDBPROP() ;
  SetBSTRProperty( pass, DBPROP_AUTH_PASSWORD, OLESTR( "" ) ) ; // Password
  props.push_back( pass ) ;

  // Set up the propSet, and
  // link it to the DBPROP array
  // we just created above.
  DBPROPSET propSet ;

  // Now this is an initialization property set.
  propSet.guidPropertySet = DBPROPSET_DBINIT ;

  // tell it the # of properties specified
  propSet.cProperties = props.size() ;

  // And now we assign our properties structure
  propSet.rgProperties = &props[ 0 ] ;

  // Retrieve the IDBProperties interface.
  IDBProperties * dbProperties ;
  db->QueryInterface( IID_IDBProperties, (void**)&dbProperties );
  CHECK( dbProperties->SetProperties( 1, &propSet ), "Set properties" ) ;

  #pragma region free and unload
  // Free the BSTRs that were allocated using SysAllocString()
  SysFreeString( dsn.vValue.bstrVal ) ;
  SysFreeString( username.vValue.bstrVal ) ;
  SysFreeString( pass.vValue.bstrVal ) ;

  CHECK( dbProperties->Release(), "dbprops release" ) ;
  #pragma endregion

  #pragma endregion

  // Now, after we have set the properties, fire up the database by initalizing it
  CHECK( db->Initialize(), "db->Initialize" ) ;

  // now set up for batch insertion
  // I want to batch insert.  In order for
  // Sets of multiple parameters
  // (cParamSets is greater than one) can be specified only if
  // DBPROP_MULTIPLEPARAMSETS is VARIANT_TRUE

  // Note that we CANNOT set this property inline with
  // the previous batch of property state settings because
  // DBPROP_MULTIPLEPARAMSETS belongs to the DBPROPSET_DATASOURCEINFO,
  // and NOT the DBPROPSET_DBINIT set.
  props.clear();

  DBPROP multipleParamsets = preinitDBPROP() ;

  multipleParamsets.dwPropertyID = DBPROP_MULTIPLEPARAMSETS ;
  multipleParamsets.vValue.vt = VT_BOOL ;
  multipleParamsets.vValue.boolVal = VARIANT_TRUE ;

  props.push_back( multipleParamsets ) ;

  // reset the propset and reuse it
  // Now this is "Data Source Information" property set,
  // which supports setting the DBPROP_MULTIPLEPARAMSETS item
  propSet.guidPropertySet = DBPROPSET_DATASOURCEINFO ;

  // tell it the # of properties specified
  propSet.cProperties = props.size() ;

  // And now we assign our properties structure
  propSet.rgProperties = &props[ 0 ] ;

  // re-get the dbProperties interface.
  db->QueryInterface( IID_IDBProperties, (void**)&dbProperties );
  CHECK( dbProperties->SetProperties( 1, &propSet ), "Set properties 2" ) ;

  CHECK( dbProperties->Release(), "dbprops release 2" ) ;

  // Execute a prepared statement with parameters.
  runInsertWithParameters( db ) ;

  // Delete rows just added.
  myDelete( db ) ;

  if( db != NULL )
  {
    db->Uninitialize() ;
    db->Release() ;
  }

  if( iMalloc != NULL )
    iMalloc->Release() ;

  CoUninitialize() ;

  return 0 ;
}

// Glossary:  (Extracted from http://msdn.microsoft.com/en-us/library/ms810892.aspx
// DATA PROVIDER:  A data provider is one that owns data and exposes it in a tabular form.
// Some examples are relational database systems and spreadsheets.

// SERVICE PROVIDER:  A service provider is any OLE DB component
// that does not own the data but encapsulates some service by
// producing and consuming data through OLE DB interfaces.
// Examples are query processors and transaction managers.

// BSTR:  http://msdn.microsoft.com/en-us/library/ms221069.aspx

// The BSTR is a strange animal.  It is like a Pascal string
// in that its LENGTH is stored in the first (4) bytes.
// The character data itself then follows, then there are
// TWO null terminators at the end, regardless of whether
// _UNICODE is #defined or not.

// You're supposed to create BSTR's with SysAllocString()
// and to delete them with SysFreeString().

// Important links and pages.

// ADO faq:  http://support.microsoft.com/kb/183606

// Listing of ALL OLE DB Interfaces (objects that start with I):
// http://msdn.microsoft.com/en-us/library/ms709709(VS.85).aspx

// Listing of ALL OF THE OLE DB Structures And Enumerated Types with LINKS to each
// http://msdn.microsoft.com/en-us/library/ms716934(VS.85).aspx

// Listing of ALL OLE DB PROPERTIES
// http://msdn.microsoft.com/en-us/library/ms723066(VS.85).aspx

// Data type mappings:  maps VARIANT types to OLE DB data types
// (e.g. BOOLEAN => DBTYPE_BOOL)
// http://msdn.microsoft.com/en-us/library/bb231286(VS.85).aspx

// PROPERTIES BY PROPERTY GROUPS:  This is the page that tells
// you which DBPROP_* fits under what DBPROPSET_*
// http://msdn.microsoft.com/en-us/library/ms714404(VS.85).aspx

// Fixed-Length and Variable-Length Data Types
// http://msdn.microsoft.com/en-us/library/ms715955(VS.85).aspx

Download code from esnips (thanks esnips!)

While the OLE DB for the ODBC Programmer article is excellent, there is a mistake in it.

The rgParamBindInfo array should not have names for the parameters (they should be NULL) because the prepared statement doesn’t use named parameters (they are unnamed (?,?,?,?)’s)

Because the author does not check the HRESULTS that come back from his SetParameterInfo() invokation, he doesn’t know about this error. But if you check this line:

pICmdWithParams->SetParameterInfo(nParams, rgParamOrdinals,
        rgParamBindInfo);

with

if( FAILED( pICmdWithParams->SetParameterInfo(nParams, rgParamOrdinals,
        rgParamBindInfo) )
{
  puts( "The 1997 article by Michael Pizzo, Jeff Cochran has a mistake in it" ) ;
}

you find it throws an error because rgParamBindInfo is wrong (it should look like this:)


  DBPARAMBINDINFO     rgParamBindInfo[] =
        {
        OLESTR("DBTYPE_CHAR"),  0 /* OLESTR("CustomerID")*/,    5,
             DBPARAMFLAGS_ISINPUT, 0, 0,
        OLESTR("DBTYPE_VARCHAR"), 0 /* OLESTR("CompanyName")*/,  40,
             DBPARAMFLAGS_ISINPUT, 0, 0,
        OLESTR("DBTYPE_VARCHAR"), 0 /* OLESTR("ContactName") */,  30,
             DBPARAMFLAGS_ISINPUT, 0, 0,
        OLESTR("DBTYPE_VARCHAR"), 0 /* OLESTR("ContactTitle") */, 30,
             DBPARAMFLAGS_ISINPUT, 0, 0,
        OLESTR("DBTYPE_VARCHAR"), 0 /* OLESTR("Address") */,      60,
             DBPARAMFLAGS_ISINPUT, 0, 0,
        OLESTR("DBTYPE_VARCHAR"), 0 /* OLESTR("City") */,         15,
             DBPARAMFLAGS_ISINPUT, 0, 0,
        OLESTR("DBTYPE_VARCHAR"), 0 /* OLESTR("Region") */,       15,
             DBPARAMFLAGS_ISINPUT, 0, 0,
        OLESTR("DBTYPE_VARCHAR"), 0 /* OLESTR("PostalCode") */,   10,
             DBPARAMFLAGS_ISINPUT, 0, 0,
        OLESTR("DBTYPE_VARCHAR"), 0 /* OLESTR("Country") */,      15,
             DBPARAMFLAGS_ISINPUT, 0, 0,
        OLESTR("DBTYPE_VARCHAR"), 0 /* OLESTR("Phone") */,        24,
             DBPARAMFLAGS_ISINPUT, 0, 0,
        OLESTR("DBTYPE_VARCHAR"), 0 /* OLESTR("FAX") */,          24,
             DBPARAMFLAGS_ISINPUT, 0, 0,
        };

Because the prepared statement looks like this:

  WCHAR               wSQLString[] =
    OLESTR("insert into Customers (CustomerID, CompanyName, ContactName,")
    OLESTR(" ContactTitle, Address, City, Region, PostalCode, Country,")
    OLESTR(" Phone, Fax)")
    OLESTR(" values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");

If the prepared statement used named parameters, it would look something like this:

  WCHAR               wSQLString[] =
    OLESTR("insert into Customers (CustomerID, CompanyName, ContactName,")
    OLESTR(" ContactTitle, Address, City, Region, PostalCode, Country,")
    OLESTR(" Phone, Fax)")
    OLESTR(" values (:CustomerID, :CompanyName, :ContactName, ")
    OLESTR(" :ContactTitle, :Address, :City, :Region, :PostalCode, :Country, ")
    OLESTR(" :Phone, :Fax)");

That’s why the docs also say The name of the parameter; it is a null pointer if there is no name. Names are normal names. The colon prefix (where used within SQL text) is stripped.

See I wasn’t aware of offsetof.

Its really good.

Its defined as:

#define offsetof(s,m)   (size_t)&reinterpret_cast<const volatile char&>(((s *)0)->m)

So when you do:

offsetof( STRUCT_TYPE, MEMBER_NAME )

You really get:

(size_t)&(char&)(((STRUCT_TYPE *)0)->MEMBER_NAME)

So its pretty neat. Basically what happens is, you get the number of bytes that MEMBER_NAME is from the beginning of the struct. .. refers to the address of member m in this object. Since the start address of this object is 0 (NULL), the address of member m is exactly the offset.

PRETTY cool. I can’t believe I’ve been listing numerical byte counts for this long..

and the hand of experience.

If you try and compile and run the microsoft sdk sampClnt using their instructions they leave out one important detail:

running sampclnt.exe
Sun Jul 12 11:22:41 2009

Connecting to the SampProv sample data provider...
Error at file: c:\program files\microsoft sdks\windows\v6.1\samples\dataaccess\oledb\sampclnt\sampclnt.cpp  line: 317
CoCreateInstance: Returned <unknown>
Error at file: c:\program files\microsoft sdks\windows\v6.1\samples\dataaccess\oledb\sampclnt\sampclnt.cpp  line: 206
GetSampprovDataSource: Returned <unknown>
Error at file: c:\program files\microsoft sdks\windows\v6.1\samples\dataaccess\oledb\sampclnt\sampclnt.cpp  line: 122
DoTests: Returned <unknown>

so the fix for this is to first compile the sampprov project, then switch into C:\Program Files\Microsoft SDKs\Windows\v6.1\Samples\dataaccess\oledb\sampprov\Debug, (like, open a command prompt..)

cd C:\Program Files\Microsoft SDKs\Windows\v6.1\Samples\dataaccess\oledb\sampprov\Debug
regsvr32 sampprov.dll

THEN you can run the sampclnt example, making sure to put the .csv file it uses in the same directory as its executable.

I only knew this from a hint from this post, where he says

Hi, what is the problem with the OLEDB sample client, obtained from Data
Acess SDK 2.8?
I registered the sample provider as regsvr32 \sampprov, which was
successful.

Here is the log:

running sampclnt.exe
Thu Jun 23 12:44:52 2005

Connecting to the SampProv sample data provider…
Getting a DBSession object from the data source object…
Getting a rowset object from the DBSession object…
Error at file: c:\msdn\sample\sampclnt\sampclnt.cpp line: 517
IOpenRowset::OpenRowset: Returned DB_E_NOTABLE
Error at file: c:\msdn\sample\sampclnt\sampclnt.cpp line: 224
GetRowsetFromDBCreateSession: Returned DB_E_NOTABLE
Error at file: c:\msdn\sample\sampclnt\sampclnt.cpp line: 119
DoTests: Returned DB_E_NOTABLE

WHAT IS WITH Microsoft and just CHANGING Things.

They recently changed their hashing scheme on SkyDrive so that links were rewritten. I’m SO glad I’ve been using esnips and NOT skydrive (i’m not even linking there.. who knows, it may change) for anything on here.

They changed it so the URLs get COMPLETELY rewritten. The URL went from:

http://n61ofw.blu.livefilestore.com/y1pXBOTt7tQ5TePwcrFto_lrQ_qD5D_RZiP9TZpOINsRJ7omqZLzyVPG5osK3Zk73AIIV9-hicdVOEyB6WtNpJCaw/myfile.txt
http://n61ofw.blu.livefilestore.com/y1pMRpZHLOl6gwTmcXcdqiVu1DnwOdXF5XNM9rJfD4PCBXdCK35hNK5qeZzb-SV91Sn6odVUj_97CXE18b8VFiwBw/myfile.txt

The lower url is the new one.

CAN YOU BELIEVE THEY DID THAT? I can’t. They just broke.. well over a MILLION links on the web if they did this to everybody. I can’t BELIEVE they did that. It sends me reeling. I’d NEVER use SkyDRive now, knowing that this is something they MIGHT just arbitrarily decide to do in the future.

Setting up MySQL for use through ODBC.

First, recognize that THERE ARE several ways you can connect to a MySQL database from an application.

MDAC


click for larger

The 3 main ways are:

  • Native C api – compile and link-in code that can talk to MySQL WITHIN your app. This is ALMOST like making MySQL “part of your program”

  • ODBC (this article). ODBC stands for Ol’ Dirty Bastard Connector.. :) Just kidding. But it should. ODBC was first released in 1992. ODBC is short for Open Database Connectivity.

    Basically your application TALKS TO the ODBC driver THROUGH A COMMON SET OF API FUNCTIONS – the ODBC API library. The ODBC driver in turn, talks to the actual database for you. So you achieve a certain level of database API independence: you use ODBC in the same way whether programming to a MySQL database, or an MS-SQL Server database, or an Oracle database – you use the same functions and it works, as long as you have an ODBC driver for that database. So using ODBC is just ONE LEVEL of abstraction above the native C API. ODBC is still alive and kicking today and works fine.

    Aside:

    If you’re familiar with how the HAL works in Direct3D, ODBC is a little bit like the HAL.

    Direct3D function calls ODBC function calls
    HAL (hardware abstraction layer) ODBC driver
    GPU hardware itself Database software itself

    In this case, the “database” is like the GPU, and ODBC driver is that layer which transforms standard ODBC function calls into function calls that the actual database being used underneath can understand.

    If that just didn’t make any sense, ignore this whole block

    The advantage of using ODBC above the MySQL functions directly is .. well, just that you don’t have to program to the MySQL function set directly anymore. So, say you already had experience with setting up a database connection under C++/Oracle, and you want to quickly get up and running on a C++/MySQL program. Instead of going and figuring out how the MySQL native api works, you actually wouldn’t have to know any of that at all, you’d just install the ODBC driver and program “to” ODBC – this is what we’ll show how to do in this article.

  • OLE DB

    Just ANOTHER, newer, more recent library of functions that is supposed to replace ODBC. OLE DB is a low-level, high-performance interface to a variety of data stores. OLE DB, like ODBC as shown in this article, has a C-style API.

    OLE DB’s advantage over ODBC is that the underlying data provider when using OLE DB does NOT have to be a relational database.

    In fact, according to page 8 of this book

    ODBC as we have just seen, is an excellent technology for accessing SQL-based data. OLE DB incorporates this proven technology with a particular component that allows OLE DB consumers to communicate directly with ODBC providers. In other words, use OLE DB to access SQL-based data, and you gain the advantage of being able to access both relational and other forms of data with the same code.

    So it looks like this:

  • Finally, ADO, (also, ADO.NET).

    ADO is a high-level, easy-to-use interface to OLE DB.

    ADO is the NEWEST and is probably the most commonly used technology for accessing databases from MS apps. Ever heard of hibernate? Well, ADO, (which stands for ActiveX Data Objects) is BASICALLY the same idea as Hibernate. You can interact with the database through a series of functions WITHOUT EVER WRITING A LINE OF SQL. You interact with the database instead through the functionset provided by ADO.

    Can you see the layers? You can see that you should expect ADO to be somewhat slower than using ODBC directly.

    ADO is accessible in two flavors: ADO “regular” and ADO.NET. ADO.NET, clearly, is part of the .NET framework and so if you’re using a .NET application, then data access through ADO.NET is the natural standard for you.

    If you’re programming a native C++ app on the other hand, the choice whether to use native MySQL function calls, ODBC, OLE DB (directly), ADO, or ADO.NET kind of looms before you.

So, ok, on with it.

Accessing a MySQL database through ODBC

1. The first step is to install a MySQL database and create a table or two. Do it do it do it!!

2. Ok, now the SECOND step is to GET THE MySQL ODBC 5.1 DRIVER. GET THE 32-BIT DRIVER ONLY, PLEASE, EVEN IF YOU ARE ON A 64-bit MACHINE. Unless you know EXACTLY what you’re doing FOR SURE and you KNOW your compiler pushes out 64-bit applications (Visual Studio 2005/2008 pushes out 32-bit applications by default ONLY!! EVEN IF you are on a 64-bit platform!)

3. Once you’ve got that installed, OPEN UP Start -> Administrative Tools -> Data Sources (ODBC).

Note: If you DO NOT SEE “Administrative Tools” on your start menu RIGHT CLICK TASKBAR > PROPERTIES > START MENU TAB > CUSTOMIZE > FIND AND SELECT THE “DISPLAY ADMINISTRATIVE TOOLS” checkbox.

4. Ok, now in the Ol’ Dirty Bastard Connections window (ODBC Window) that you just opened in step 3, select the System DSN tab

IMPORTANT NOTE: IF YOU ARE ON A 64-BIT MACHINE, __DO NOT__, I REPEAT, __DO NOT__ USE THE ODBC Window that is accessible from the taskbar. Instead, go to START > RUN > C:\Windows\SysWOW64\odbcad32.exe.

The reason is when developing in Visual Studio 2005/2008, under normal circumstances you in fact cannot publish 64-bit applications, so you CANNOT USE the 64-bit ODBC drivers from your 32-bit application. So you must set up and use the __32-bit__ ODBC drivers instead. This is a REAL assbiter. See jlgdeveloper’s master-genius answer at http://forums.devarticles.com/microsoft-sql-server-5/data-source-name-not-found-and-no-default-driver-specified-8346.html#postmenu_203344 (repeated at bottom of this page for permanence)

5. Click ADD. You see a menu

IF YOU DO NOT SEE “MySQL ODBC 5.1 DRIVER” there, CALL 911. Or, try installing the correct version of the ODBC driver.

6. Now, pick the ODBC 5.1 item and click “FINISH” (you’re not done yet though..)

7. Fill out the connection params. This is how I filled out mine.

When you’re done click TEST. You should see the box that I see “Connection successful”

If you see this box

CALL 911, or double check your parameters and make sure your MySQL daemon is running.

8. Now that you’re done that, you should see this:

REMEMBER THAT NAME, “mysqldata” or whatever name you gave the connection in the top box. This is the name you’ll refer to from your program.

9. Now run this program. Once again I remind you IF YOU ARE ON A 64-BIT MACHINE, BE SURE TO HAVE SET UP YOUR ODBC CONNECTIONS IN THE C:\Windows\SysWOW64\odbcad32.exe WINDOW, AND NOT THE ODBC WINDOW ACCESSIBLE FROM THE START MENU. YOU HAVE BEEN WARNED.


///////////////////////////////////////////
//                                       //
// WORKING WITH OL' DIRTY BASTARD (ODBC) //
//                                       //
// You found this at bobobobo's weblog,  //
// http://bobobobo.wordpress.com         //
//                                       //
// Creation date:  July 10/09            //
// Last modified:  July 10/09            //
//                                       //
///////////////////////////////////////////
// Note also nice sample comes with
// WinSDK in C:\Program Files\Microsoft SDKs\Windows\v6.1\Samples\dataaccess\odbc\odbcsql

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

#include <sql.h>
#include <sqltypes.h>
#include <sqlext.h>

// Here is the complete Ol' Dirty Bastard function reference:
// http://msdn.microsoft.com/en-us/library/ms714562(VS.85).aspx

// This article says you need
// to link with odbc32.lib, but taking the next line of code OUT
// doesn't seem to harm anything
#pragma comment( lib, "odbc32.lib" )

bool CHECK( SQLRETURN rc, char * msg, bool printSucceededMsg=false, bool quit=true )
{
  if( SQL_SUCCEEDED( rc ) )
  {
    if( printSucceededMsg )  printf( "%s succeeded\n", msg ) ;

    return true ;
  }
  else
  {
    printf( "NO!!!  %s has FAILED!!\n", msg ) ;

    if( quit )  FatalAppExitA( 0, msg ) ;

    return false ;
  }
}

void status( SQLSMALLINT handleType, SQLHANDLE theHandle, int line )
{
  SQLCHAR sqlState[6];
  SQLINTEGER nativeError;
  SQLCHAR msgStr[256];
  SQLSMALLINT overBy ; // the number of characters that msgStr buffer was TOO SHORT..

  // http://msdn.microsoft.com/en-us/library/ms716256(VS.85).aspx
  // This must be the WEIRDEST ERROR REPORTING FUNCTION I've EVER seen.
  // It requires 8 parameters, and its actually pretty .. silly
  // about the amount of state information it expects YOU to keep track of.

  // It isn't so much a "GetLastError()" function
  // as it is a "GetMeStatus( something very, very specific )" function.

  SQLRETURN retCode ;

  for( int i = 1 ; i < 20 ; i++ )
  {
    retCode = SQLGetDiagRecA(

      handleType,  // the type of object you're checking the status of
      theHandle,   // handle to the actual object you want the status of

      i, // WHICH status message you want.  The "Comments" section at the
      // bottom of http://msdn.microsoft.com/en-us/library/ms716256(VS.85).aspx
      // seems to explain this part well.

      sqlState,    // OUT:  gives back 5 characters (the HY*** style error code)
      &nativeError,// numerical error number
      msgStr,      // buffer to store the DESCRIPTION OF THE ERROR.
      // This is the MOST important one, I suppose

      255,         // the number of characters in msgStr, so that
      // the function doesn't do a buffer overrun in case it
      // has A LOT to tell you
      &overBy      // again in case the function has A LOT to tell you,
      // the 255 character size buffer we passed might not be large
      // enough to hold the entire error message.  If that happens
      // the error message will truncate and the 'overBy' variable
      // will have a value > 0 (it will measure number of characters
      // that you 'missed seeing' in the error message).

    ) ;

    if( CHECK( retCode, "SQLGetDiagRecA" ) )
    {
      printf( "LINE %d:  [%s][%d] %s\n", line, sqlState, nativeError, msgStr ) ;
    }
    else
    {
      // Stop looping when retCode comes back
      // as a failure, because it means there are
      // no more messages to tell you
      break ;
    }
  }
}

int main()
{
  // Following this example, just adding a bit more
  // color and making it work with our specific example.

  // 1.  Create a handle for the environment.
  SQLHANDLE hEnv ;
  SQLRETURN retCode ;

  retCode = SQLAllocHandle( SQL_HANDLE_ENV, SQL_NULL_HANDLE, &hEnv ) ;

  CHECK( retCode, "allocate environment handle" ) ;

  // 2.  Next, set the version of ODBC to use to ODBC version 3.
  // Format of this command is a bit weird, we cast the value we're passing
  // to (void*) because the function requires it, but then we say that the
  // length of the "string" we've passed in is 0 characters long, so I assume
  // that means SQLSetEnvAttr should know to interpret the "pointer value" that
  // we passed in as actually an integer value (which is what it is).
  retCode = SQLSetEnvAttr( hEnv, SQL_ATTR_ODBC_VERSION, (void*)SQL_OV_ODBC3, 0 ) ; 

  CHECK( retCode, "setting the environment attribute setting to ODBC version 3" ) ;

  // 3.  Allocate the connection handle.  Note this doesn't
  // connect us to the database YET.  We're still "ALLOCATING",
  // whatever that means :) (Hey i know what allocating is,
  // but this is an awful number of steps to follow if you
  // ask me, microsoft!!  Whatever happened to a simple init()
  // function?
  SQLHANDLE hConn ;

  CHECK( SQLAllocHandle( SQL_HANDLE_DBC, hEnv, &hConn ), "allocate handle" ) ;

  // HOOK IT UP!!  Actually connect to the database.
  SQLCHAR* dsnName = (SQLCHAR*)"mysqldata" ;  // MUST BE THE SAME
  // as the name of the ODBC data source you set
  // in the Microsoft ODBC Administrator window.

  SQLCHAR* userid = (SQLCHAR*)"root";
  SQLCHAR* password = (SQLCHAR*)"";  // using a BLANK
  // Above are my own correct userid and password credentials to
  // be used when logging into the MySQL database server.

  // 4.  Open database connection.
  retCode = SQLConnectA(

    hConn,

    dsnName,  // name of data source we are connecting to,
    // AS PER REGISTERED IN ODBC Data Source Administrator.

    // If you are on a 64-bit machine, and you
    // DO NOT USE THE 64-bit driver.  As long as
    // your compiler publishes a 32-bit .exe (which
    // Visual Studio does), you'll keep getting:

    // [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified

    // SO DON'T USE THE 64-BIT DRIVERS!  Instead, install
    // the 32-bit driver, and then managing/using
    // your 32-bit datasources in
    // c:\windows\syswow64\odbcad32.exe

    // Note that on a 64-bit windows machine, the 32-bit
    // drivers and the 64-bit drivers are managed
    // from COMPLETELY SEPARATE, BUT IDENTICAL-LOOKING
    // windows.  Its really weird.

    // On a 64-bit machine:
    // c:\windows\system32\odbcad32.exe    // 64-bit version [even though it SAYS system32_ in the path, this is the __64__ bit version on a 64-bit machine]
    // c:\windows\syswow64\odbcad32.exe    // 32-bit version [even though it SAYS syswow64_ in the path]

    // Call it stupid, scream, pull your hair out,
    // that's what it is.
    // http://stackoverflow.com/questions/949959/why-do-64bit-dlls-go-to-system32-and-32bit-dlls-to-syswow64-on-64bit-windows

    // and

    // http://blogs.sepago.de/helge/2008/04/20/windows-x64-all-the-same-yet-very-different-part-7/

    // Thanks again, Microsoft,
    // for making the 64-bit programming experience
    // such a pleasure.
    SQL_NTS,  // the DSN name is a NULL TERMINATED STRING, so "count it yourself"

    userid,
    SQL_NTS,  // userid is a null-terminated string

    password,
    SQL_NTS   // password is a null terminated string

  ) ;
  if( !CHECK( retCode, "SqlConnectA", false ) )
  {
    // if this fails, I want that extra status
    // information about WHY the failure happened.
    // status function is defined above.

    status( SQL_HANDLE_DBC, hConn, __LINE__ ) ;
  }

  // 6.  Create and allocate a statement
  SQLHANDLE hStmt ;
  CHECK( SQLAllocHandle( SQL_HANDLE_STMT, hConn, &hStmt ), "allocate handle for statement" ) ;

  // 7.  Form a query to run and attach it to the hStmt
  // this basically connects the hStmt up with
  // some results.
  SQLCHAR* query = (SQLCHAR*)"SELECT * from user" ;
  CHECK( SQLExecDirectA( hStmt, query, SQL_NTS ), "execute query" ) ;

  // 8.  Read data results that are now in the hStmt.
  retCode = SQLFetch( hStmt ) ;

  CHECK( retCode, "first sqlFetch" ) ;

  // How many rows got returned?
  SQLLEN numRows ;
  retCode = SQLRowCount( hStmt, &numRows ) ;
  printf( "%d rows were fetched, ruff.\n", numRows ) ;

  // With a query like the one we wrote (SELECT *),
  // we don't know how many columsn should be in
  // the result set at this point.
  // So we ask ODBC to tell us!
  SQLSMALLINT numCols ;
  retCode = SQLNumResultCols( hStmt, &numCols ); // SqlNumResultCols

  // Now print the column names.
  // SQLDescribeCol function
  SQLCHAR colName[ 256 ] ;

  SQLSMALLINT colNameLen, dataType, numDecimalDigits, allowsNullValues ;
  SQLUINTEGER columnSize ;

  for( int i = 1 ; i <= numCols ; i++ )
  {
    retCode = SQLDescribeColA( hStmt, i, colName, 255, &colNameLen, &dataType, &columnSize, &numDecimalDigits, &allowsNullValues ) ;
    if( CHECK( retCode, "SQLDescribeCol" ) )
    {
      printf( "Column #%d: '%s', datatype=%d size=%d decimaldigits=%d nullable=%d\n",
                       i,colName,   dataType, columnSize,  numDecimalDigits, allowsNullValues ) ;
    }
  }

  for( int i = 1 ; i <= numRows ; i++ )
  {
    // Datatypes
    // SQLGetData

    char buf[256];
    SQLINTEGER numBytes ;

    for( int j = 1 ;   // column counter starts at __1__, not 0.
      j <= numCols ;   // numCols retrieved above
      j++ )
    {
      retCode = SQLGetData(

        hStmt,
        j,           // COLUMN NUMBER of the data to get
        SQL_C_CHAR,  // the data type that you expect to receive
        buf,         // the place to put the data that you expect to receive
        255,         // the size in bytes of buf (-1 for null terminator)
        &numBytes    // size in bytes of data returned

      ) ;

      if( CHECK( retCode, "SqlGetData", false ) )
      {
        // Print the data we got.
        printf( "%10s", buf ) ;
      }

    } // end for.

    puts("");

    // Try and fetch the next result.
    // fall out of the loop if fetch fails
    // (meaning, no more data to get)
    retCode = SQLFetch( hStmt ) ;
    if( !SQL_SUCCEEDED( retCode ) )
    {
      // SQLFetch FAILS AS IT FETCHES the last row of data.
      printf( "And %d is the LAST row.. we're not getting any more after this one\n", i ) ;
    }
  }

  // So we used a FOR loop above to fetch
  // exactly numRows rows from the results.

  // The other (perhaps more common)
  // way to do this is to use a loop like

  // while( SQL_SUCCEEDED( SQLFetch( hStmt ) ) )
  // {
  //   // Work with result data
  // }

  // When we do it that way,
  // WE EXPECT/RELY ON SQLFetch TO TELL US
  // IT FAILED when we've reached the
  // LAST row of data.

  // free up resources.
  SQLFreeHandle( SQL_HANDLE_STMT, hStmt ) ;
  SQLFreeHandle( SQL_HANDLE_DBC, hConn ) ;
  SQLFreeHandle( SQL_HANDLE_ENV, hEnv ) ;
}

// Assbiters:
// 1. Be careful not to use the SUCCEEDED() macro
// instead of the SQL_SUCCEEDED() macro when
// checking your SQLRESULT values.
//
// 2. Do not use 64-bit ODBC drivers, even if on
// a 64-bit machine.  See information above.

/*
     ____   __   __      __   __  ___
    / _  \ /  / /  /    /  /  \ \/  /
   / _/ / /  / /  /    /  /    \   /
  / _/ \ /  / /  /__  /  /__   /  /
 /_____//__/ /______//______/ /__/

*/

Master genius John

[Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified

I had this error and want to let you know how it was resolved.

First, this was an ASP web application using a vb 6.0 dll to get data from a sql server 2005 database on a 64 bit windows server 2008 enterprise (vista like) server. I could only get the dll to work in component services as opposed to simply registering it.

It all worked fine upon setup, but after four windows updates one night, the error above was posted in the event viewer, and the web app crashed.

Here is the resolution:

In a 64 bit windows server operating system, there are TWO odbc managers. When you pull up the usual menu for the odbc / dsn system, it is for the 64 bit odbc manager, and 32 bit applications (vb 6.0) will not work using these dsn’s.

This is where the 32 bit odbc manager is:

C:\Windows\SysWOW64\odbcad32.exe

I hope you do not have to go through what I and three Microsoft Support engineers had to to figure this out.

Jonathan

Download the code package courtesy of esnips (thanks esnips!)

Q: How do I do an overloaded constructor in PHP?

A: You don’t need them

Consider the following

class Foo
{
  var $name ;
  function __construct()
  {
    # if the default ctor is invoked, name
    # this instance "unnamed"
    $this->name = 'unnamed' ;
  }

  # Fine and dandy, but what if
  # we want to supply a name
  # in an overloaded ctor?
  
  function __construct( $iname )
  {
    $this->name = $iname ; #doesn't work
    # because overloaded ctors of this style
    # aren't supported in PHP!!
  }
  
}

OK. Well I promised in the title of this post that you didn’t need overloaded constructors in php Here’s why.

Redefine class Foo as follows:


class Foo
{
  var $name ;

  # specify a single ctor, WITH DEFAULT VALUES
  # FOR PARAMETERS.  This is equivalent, and in my
  # opinion a better syntax
  # for getting overloaded constructors to work.
  function __construct( $iname = 'unnamed' )
  {
    $this->name = $iname ;
  }
}

There. Fewer lines of code, less mess, same effect. This was an excellent design decision by the php group.

Refactoring
Rewriting something so that it is written differently, but ultimately “means” the same thing. E.g. in Math, you can refactor x + xy to x( 1 + y ). These two statements (x+xy) and (x(1+y)) mean exactly the same thing mathematically, but they’re just written differently. e.g. 2 in programming, refactor is used more loosely. You can refactor a bunch of code which means you rewrite the code to do the same intended thing, but in a better way (more efficiently, or with more adherence to OOP principles, or rewrite it to remove bugs).

Ok, so say I have:

class Thing abstract
{

} ;

class Person : public Thing
{
  void MoveTo( Point p ) ;
} ;

class Building : public Thing
{
  // does NOT have MoveTo( Point p ) ;
} ;

I’m maintaining a vector<Thing*> to keep track of everything in the world.

When hittesting, a user might click on either a Building or a Person. Regardless, there’s a pointer stored to the currently selected Thing* in selectedThing.

Now, depending on what TYPE of thing is currently selected, the user can do different actions with that Thing. If the Thing* is really Person*, then a right-click somewhere on the map means one thing (i.e. move there) or for a building, a right click means (do nothign) or (set rally point).

So, if selectedThing is IN FACT a Person*, then we should call MoveTo() on the selectedThing (method exists!). But if selectedThing is NOT a person, then we should NOT call MoveTo() on it, because MoveTo() is not defined for a Building*.

What’s the best way to manage this problem?

1. typeid() reflection (which is bad because its implementation dependent and just _seems_ wrong?)
i.e. find if typeid() says selectedThing is Person* or Building*

if( typeid( selectedThing ) == classTypePerson )
{
  selectedThing->MoveTo( p ) ;
}
else
{
  // its not a person, so it can't move.
}

2. or maintaining separate vectors and going:

vector<Person*> people ;
vector<Building*> buildings ;

vector<Thing*> things ;

// FIND whether the selectedThing is in Person* vector or Building* vector.
for( int i = 0 ; i < people.size() ; i++ )
{
  if( people[i] == selectedThing )
  {
    // selected Thing is a person, so it can be cast
    // to Person* and MoveTo() can be executed on it
    dynamic_cast( selectedThing )->MoveTo( p ) ;
    break ;
  }
}

(( ANSWER: THE PROBLEM IS WRONG. class Thing should provide handles to “right click here” and “left click there” and the CONCRETE CLASSES should provide the implementation details. You’ve used inheritance incorrectly here and the Thing* interface DOESN’T HAVE ENOUGH METHODS if this is your problem.

So, the answer to this question is:

class Thing abstract
{
  virtual void MoveTo( Point p ) { /*do nothing by default*/ }
} ;

class Person : public Thing
{
  // actually move the person
  void MoveTo( Point p ) override ;
} ;

class Building : public Thing
{
  // does NOT (bother overriding) MoveTo( Point p ) ;
} ;

Then the code simply reduces to:

selectedThing->MoveTo( p ) ;

And so, IF the selectedThing is indeed a Building*, then selectedThing->MoveTo() boils down to (nothing happening), and if its a Person*, selectedThing->MoveTo() boils down to actual movement. Later you could build out the MoveTo command to MEAN SOMETHING ELSE to a Building, and this is EXACTLY what polymorphism is supposed to do: make different objects behave differently given the same command.

class Animal abstract { virtual void Speak() { } } ;

class Dog : public Animal {
  void Speak() { puts("Woof") ; }
} ;

class Cat : public Animal {
  void Speak() { puts("Meow") ; }
} ;

I get this adobe acrobat bug where when i resize the window, the document doesn’t resize

i don’t want to apply any 3 hour patches, so all I do is WINDOW->SPLIT then WINDOW->REMOVE SPLIT and it makes it work!

I kept on getting this STUPID error when programming this big project when I’d try to #include header files that had class definitions in them.

The compiler would pretend like it didn’t know the type, even though I GAVE IT THE HEADER FILE.

The answer was to provide a STUPID forward declaration of the type:

class Typename ;

EVEN THOUGH I FULLY INCLUDED THE HEADER!!

How do you programmatically disable vertical sync (vsync) in Direct3D9?

Just set your PresentationInterval in your D3DPRESENT_PARAMETERS struct to D3DPRESENT_INTERVAL_IMMEDIATE

It would seem that

Ax + By + C = 0

doesn’t really have a direction. Its just an infinite line, right?

WRONG.

take

-x + y = 0

This is the line through the origin, forming the line y = x.

1. Does this line have a direction?

2. Is there another line with a different equation that DESCRIBES THE SAME LINE?

Yes there is, to the second question, and YES IT DOES, to the first question.

The answer to 2.: The equivalent line is x – y = 0. That line is EXACTLY the same as -x + y = 0, only it “points” in the opposite direction.

So which “way” is -x + y pointing, and which way is x – y = 0 pointing?

Well, I’ll tell you.

x – y = 0 points “down and to the left”

-x + y = 0 points “up and to the right”

the reason for this is clear when you use vectors and the equations

A = y1 – y2
B = x2 – x1
C = x1y2 – x2y1

Then, if you use the points

P1 = (1,1)
P2 = (0,0)

You get the equation

A = 1 – 0 = 1
B = 0 – 1 = -1
C = 0

Then

x – y = 0
POINTS DOWN AND LEFT!!

And so, the opposite equation
-x + y = 0
POINTS UP AND RIGHT!!

On the “left side” of a line is +
On the “right side” of a line is -

Taking the one that goes up and right:
plug in ( 2, 0 )
-x + y = 0
-2 + 0 = -2

So, (2,0) is negative in that line equation, meaning (2,0) is “right” of -x + y = 0

Taking (-2,0)
2 + 0 = 2
so, (-2,0) is “left” of -x + y = 0

Here’s a simple Direct3D starter that you can copy and paste into a Visual Studio 2005/2008 project.

Assumes you have the DirectX sdk installed… many of the comments from the original were deleted in this one.


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

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

#include <dxerr9.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, "dxerr9.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 ; 

  struct _data
  {
    Vertex verts[ 3 ] ;

    _data()
    {
      // some global data to draw and manipulate
      // for this example

      // Red vertex @ ( -1, 0, 0 )
      verts[ 0 ] = Vertex( -1, 0, 0, 255, 19, 0 ) ;

      // Green vertex @ ( 0, 1, 0 )
      verts[ 1 ] = Vertex(  0, 1, 0, 0, 255, 0 ) ;

      // Blue vertex @ ( 1, 0, 0 )
      verts[ 2 ] = Vertex(  1, 0, 0, 0, 0, 255 ) ;

    }
  } data ;
};

///////////////////////////
// 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, DXGetErrorString9A( hr ), DXGetErrorDescription9A( 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" ) ;

  return true ;
}

void update()
{
  static float change = 0.01f ;
  g.data.verts[0].x += change;

  if( g.data.verts[0].x < -0.5f )
    change = 0.01f;
  else if( g.data.verts[0].x > 0.5f )
    change = -0.01f;
}

////////////////////////
// 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();

  hr = g.gpu->DrawPrimitiveUP( D3DPT_TRIANGLELIST, 1, g.data.verts, sizeof( Vertex ) ) ;
  CHECK( hr, "DrawPrimitiveUP FAILED!" ) ;

  #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 = 800, 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 );
    }

    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 );
}

i heard somewhere i can’t remember i think it was an interview with that guy who created the SOLID principles – but he says “migrate your complexity into the data”

WHERE was that from again?

software complexity

This is a very long, very long, very long tutorial about how to get started with D3D in C++.

Check it out!

//////////////////////////////////////////
//                                      //
// Direct3D basics                      //
//                                      //
// You found this at bobobobo's weblog, //
// http://bobobobo.wordpress.com        //
//                                      //
// Creation date:  July 1/09 (HAPPY CANADA DAY! ) //
// Last modified:  July 3/09            //
//                                      //
//////////////////////////////////////////

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

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

#include <dxerr9.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, "dxerr9.lib")

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

struct Globals
{
  // Wrapping the Win32-related variables up
  // together in their own struct so they don't
  // get in the way of the Direct3D ones
  struct _Win
  {
    HINSTANCE hInstance;    // window app instance
    HWND hwnd;              // handle for the window
    HWND hConsole ;         // handle for the console window

    int width, height;      // the desired width and
    // height of the CLIENT AREA
    // (DRAWABLE REGION in Window)
  } win ;

  #pragma region DIRECT3D9 stuff
  ////////////////////////////
  // Declare The IDirect3D9 INTERFACE!!
  // IDirect3D9 interface
  IDirect3D9 * d3d ;        // represents the BEAST
  // that is Direct3D9 itself.  What's it for?

  // MSDN SAYS about the IDirect3D9 interface:
  // "Applications use the methods of the IDirect3D9 interface
  // to create Microsoft Direct3D objects and set up the
  // environment. This interface includes methods for
  // enumerating and retrieving capabilities of the device."

  // IDirect3DDevice9
  IDirect3DDevice9 * gpu ;  // represents the GPU

  // MSDN SAYS about the IDirect3DDevice9:  "Applications use the
  // methods of the IDirect3DDevice9 interface to perform
  // DrawPrimitive-based rendering, create resources, work
  // with system-level variables, adjust gamma ramp levels,
  // work with palettes, and create shaders."
  ////////////////////////////

  // The ABOVE TWO variables are
  // very important to this application.

  // For both of these, notice how they
  // are BOTH POINTERS to an INTERFACE.

  // What's an interface?  Well, in a few words,
  // an INTERFACE is something you "face" to
  // interact with something.  Thru means of
  // the "INTERFACE" you get information from
  // the underlying system, or send commands
  // to the underlying system, without really
  // having to understand the underlying system
  // at all to do it.  You just have to know what
  // types of commands it expects to get.

  // For example, your car.

  // The "interface" of your car is its steering wheel,
  // its dials on the dash telling you what speed
  // you're going and the RPM's you're at so you
  // don't blow the engine redlining, and also,
  // the gas and brakes, so you can send commands
  // to the car to stop and go.

  // Notice how you don't have to know a THING
  // about how an internal combustion engine works
  // to get the car to go.  Because the car's INTERFACE
  // is SO abstract (simply PUSH THE PEDAL TO GO),
  // working the car becomes incredibly simple.

  // If the car didn't have such an abstract
  // interface (like, if REALLY crummy engineers
  // made a car), then to drive that crummy car,
  // you might have to put your hands into
  // the engine and carefully push
  // vaporized gas underneath a piston, then
  // push down on the piston until it goes POP!
  // Then the car would be going!

  // Anyway, point is, working with a system
  // THROUGH ITS INTERFACE that the system defines
  // makes working with the system SO easy, and
  // the system itself is a black box -- its internal
  // workings are hidden from you.  Like, you
  // don't even have to know what an internal
  // combustion engine IS to be able to
  // work a modern car.  Heck, for all you know,
  // it might not even be an internal combustion
  // engine!  (It might be electric).  That's another
  // beauty about interfaces:  You can swap out
  // the nitty gritty details of the implementation
  // (e.g. software updates / patches, or the
  // difference between Direct3D9 June 2008 release
  // and March 2009 release) without affecting
  // the programs that USE those interfaces, so long
  // as you have not CHANGED the interface itself.

  // IN the case of Direct3D9, an IDirect3DDevice9 *
  // is a pointer to, let's just say the "dashboard" ON TOP
  // OF the Direct3D9 RENDERING MACHINE.

  // Inside, the Direct3D 3D graphics "engine" is VERY complex!
  // Especially when you get to rendering textures in 3D..
  // (see this book if you want to learn that stuff!)

  // But with Direct3D9, you don't have to understand
  // HOW 3d graphics actually gets drawn.  You only have to
  // understand the format that D3D expects, and pass it
  // your data that you want drawn in that format.

  // OK?  So hopefully that made a little bit of sense.
  // To me Direct3D seems slightly more "centralized"
  // than OpenGL does.  With OpenGL, the "interface"
  // is a set of C-style functions that all begin
  // with gl*.  OpenGL doesn't have an "INTERFACE"
  // in the OOP sense (but that set of gl* C functions
  // is still an 'interface' though, its just a very
  // different way of creating one!)

  // Anyway, on with it.
  #pragma endregion
};

///////////////////////////
// GLOBALS
// declare one struct Globals called g;
Globals g;
//
///////////////////////////

///////////////////////////
// FUNCTION PROTOTYPES
// Windows app functions.  If need help
// understanding these, see MostBasicWindow
// and FastWindowsProgram
LRESULT CALLBACK WndProc( HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam );
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR szCmdLine, int iCmdShow );

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 printSystemInfo() ; // function that prints some system info.  can ignore if not interested
void draw() ;            // drawing function containing Direct3D drawing calls

//
///////////////////////////

/// If there was an error, the ErrorString is printed out for you to see at the console.
inline bool CHECK( HRESULT hr, char * msg, bool stop )
{
  if( FAILED( hr ) )
  {
    printf( "%s. %s:  %s\n",
            msg, DXGetErrorString9A( hr ), DXGetErrorDescription9A( hr ) ) ;

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

    return false ;
  }

  else
    return true ;

}

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

  // Create the IDirect3D9 (d3d) object now.  We need the d3d object
  // in order to be able to create the IDirect3DDevice9 interface.
  // We can also use the d3d object to find out additional information
  // about the system we are on (such as the number of displays it has, etc).

  // [[ I know, I know.  If you think its confusing/stupid to have
  // two separate Direct3D9 things both starting with I,
  // just bear with it because you'll see that these two objects
  // will do VERY different things, and you'll see it does
  // make a whole lot of sense to separate them out into two things.
  // Granted, they could have been named a little more distinctly,
  // but whaddya gonna do... ]]

  // So, the IDirect3D9 object (variable 'd3d') is the "interface"
  // or means by which we will access the Direct3D9
  // beast

  // And the IDirect3DDevice9 (called 'gpu') is THE
  // variable that IS OUR PROGRAMMATIC HANDLE TO THE GPU and
  // we will use it A LOT to send down triangles and stuff to the
  // gpu to be drawn.

  // we'll be using 'gpu' a lot more than 'd3d'.

  // So now, to create our 'd3d' interface.
  // Remember, FROM this interface will come
  // our 'gpu' interface.

  // Direct3DCreate9
  g.d3d = Direct3DCreate9( D3D_SDK_VERSION ) ;  // Always use D3D_SDK_VERSION

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

  // Ok, if we get here without returning, it means device creation succeeded.
  puts( "Device creation SUCCESS!!!!\nWe're in business now, son..\n" ) ;

  // Next we'll just print a few details about the system
  // just because we can..
  // Note how we use PURELY the 'd3d' object
  // to do this (NOT the 'gpu' device, which hasn't
  // even been created yet!)
  ///// printf( "I will now tell you some \nthings ABOUT your system.\n" );
  ///// printSystemInfo(); // BOOOOORING.

  puts( "Ok, Now to CREATE the 'gpu' device!!" ) ;

  // First, create the D3DPRESENT_PARAMETERS structure.
  // This structure will basically "explain" to the
  // IDirect3D9 interface EXACTLY WHAT we want the
  // GPU rendering surface to look like once
  // it has been created.

  // D3DPRESENT_PARAMETERS structure
  D3DPRESENT_PARAMETERS pps = { 0 } ;  // Start structure all 0'd out.

  // We're using a windowed mode, NOT fullscreen in this
  // example.  Its really annoying to program little test
  // apps in fullscreen mode.  Also when using windowed mode
  // we don't have to (in fact, we should not) specify
  // some of the other parameters, such as the refresh rate.
  pps.Windowed = true ;

  // How many backbuffers do we want?  One.
  pps.BackBufferCount = 1 ;

  // This one's interesting
  // Backbuffering.  Imagine Leonardo Davinci doing
  // a live animation for you.

  // Imagine he stood in front of the canvas,
  // and blazingly quickly, painted a live scene for you.
  // Then to make the animation effect happen, he'd have
  // to erase the canvas (paint over it in all white?) then
  // paint over that white the next frame.

  // Not that great for watching an "animation!"  even if
  // he moved blazing fast, it'd still be "flickery" having
  // to "see" the canvas get all cleared out, then see each
  // shape get drawn on.

  // So instead, Davinci has a better idea.  He will
  // use TWO canvases.  He will draw to the canvas
  // in a HIDDEN place, where you can't see it.

  // When he's done painting hte first frame, BAM,
  // he slams it in your face and you can see it.
  // He then takes a SECOND canvas, and paints to it
  // blazing fast, what should be the next frame you see.
  // Then, BAM, he slams that second canvas right in your face,
  // where you can see it.  He then quietly pulls away
  // that first canvas that had the first frame on it
  // (which you can't see anymore, because you're looking
  // at the SECOND canvas he just slammed in your face),
  // and quickly paints the NEXT (3rd) frame onto it.
  // Then, BAM, he slams that first canvas in your face
  // again, but now it has the 3rd frame on it.  He then
  // takes the SECOND canvas, and draws the 4th frame on it...

  // Do you see what's happening here?  Read it again
  // if not... the whole point is to give a MUCH smoother
  // and continuous presentation of image frames.  If you
  // didn't use a backbuffer, then the animation presented
  // would look all awful and flickery and horrible because
  // you'd basically be WATCHING the gpu do its drawing work,
  // instead of looking at nice finished product painted scenes instead.

  // Swap chains
  pps.SwapEffect = D3DSWAPEFFECT_DISCARD ; // You start with
  // 2 buffers, one that displays what you're currently
  // looking at (the "frontbuffer") and
  // one that is hidden from you (the "backbuffer").

  // Basically FLIP means that
  // d3d should DRAW to the BACKBUFFER first, then
  // when its done doing that, it should BAM, slam
  // that backbuffer in your face, so you can see it.
  // The former front buffer, is then DISCARDED.

  // SO, the former "backbuffer" is NOW the FRONTBUFFER.
  // And the former front buffer, we will treat
  // as the NEW "backbuffer".

  // SO draw to the OTHER buffer now (which is considered
  // as the backbuffer at the moment), when you're done,
  // BAM, slam that backbuffer in the user's face
  // (so again, the former "backbuffer" has flipped
  // and become the frontbuffer).

  // The OTHER way to do this is to DRAW TO
  // the backbuffer, then to COPY OUT the backbuffer
  // in its entirety to the front buffer.  That's
  // less efficient though, for obvious reasons
  // (copying about 2,000,000 pixels has gotta take
  // at least some time!).  Discard is nice, but
  // using it REQUIRES that you completely update
  // ALL the pixels of the backbuffer before presenting it
  // (because there's NO TELLING what will happen to
  // the frontbuffer once you've "discarded" it!
  // Microsoft says "we might do anything to it..."
  // The Clear() operation is sufficient to touch every
  // pixel on the buffer, so as long as you're calling
  // Clear() every frame, there's nothing to worry about.
  // You'll see Clear() in use a bit later in this tutorial.)

  // Pixel format to use on the backbuffer.
  pps.BackBufferFormat = D3DFMT_UNKNOWN ;   // So, this doesn't mean
  // we don't KNOW the pixel format we want.. its more
  // like saying "D3DFMT_CHOOSE_IT_FOR_ME!"

  // What really happens is "color conversion is done by the hardware"

  // But you can think of it as D3D should picking
  // the appropriate pixel format to use.

  // Now, we WANT Direct3D to create and manage
  // a depth buffer for this surface.  That means
  // if we draw two triangles and one is "closer"
  // than the other, then the "closer" one should
  // be drawn on top of the "further" one.  That's
  // achieved using the depth buffer
  pps.EnableAutoDepthStencil = true ;
  // Now we have to say "how deep" is the depth buffer.
  // Kind of.  How precise are the depth values?
  // The more bits you use, the more "slots of depth"
  // your depth buffer can handle.  If your depth buffer
  // used 2 bits, it might be able to handle 4 levels
  // of depth.  With 16 bits, there's a lot more levels of
  // depth.  Having many different levels of depth is
  // really important because if two objects are
  // like thought by the gpu to be at the exact same
  // "depth", then there will be "z-fighting"
  // z-fighting sample1
  // Apparently some users experienced problems
  // with z-fighting when playing GTA 4 on ATI hardware.

  // We choose a fairly "deep" pixel format (16 bits)
  // Could also choose 24 bits.
  pps.AutoDepthStencilFormat = D3DFMT_D16 ;

  // Finally, make the gpu device.
  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  // THIS IS where you get
    // the ACTUAL return value (the
    // GPU device!) from this function.
    // Because this function has its
    // return value as an HRESULT,
    // the return value is used to
    // indicate success or failure.

  ) ;

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

  // Successfully created direct3d9 devices
  printf( "WHOO!  We SUCCESSFULLY created the Direct3D9 GPU device\n" ) ;

  return true ;
}

////////////////////////
// DRAWING FUNCTION
void draw()
{
  HRESULT hr ;

  #pragma region clear
  // First, we will clear the backbuffer.  This is a VERY general use
  // function and has way more capabilities than we care to use
  // at the moment.  For example, you can choose to clear little
  // sub-rectangles of the screen ONLY instead of clearing the whole
  // screen with the first 2 params.  we're not interested in that though,
  // we just wanna clear the whole screen.

  // IDirect3DDevice9::Clear()
  hr = g.gpu->Clear(

    0, // NUMBER of sub rectangles to clear.  We set to 0 because
       // we don't want to even clear any subrectangles.. we just
       // want to clear the WHOLE thing!

    0, // you can choose to clear only a sub-region of the
       // backbuffer.  But we wanna clear the WHOLE back buffer!
       // so we pass 0 here and d3d will automatically clear the WHOLE THING for us.

    // D3DCLEAR
    D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER /* | D3DCLEAR_STENCIL */,  // next is weird, but
    // here we specify WHAT exactly we want cleared.  Because a 3d
    // buffer is actually made of several LAYERS (color layer,
    // and depth layer, and stencil layer), you choose
    // what exactly what you want cleared.  If you weren't
    // doing 3d graphics for example (you used direct3d9 to draw
    // 2d graphics, which you can!) you would have no need for
    // the depthbuffer.  So you could save a bit of time
    // (clearing a buffer is a relatively expensive operation)
    // by NOT clearing the buffers you aren't going to use.

    // In this example we are NOT using the stencil buffer,
    // but we ARE using the color BUFFER ITSELF (like color values)
    // hence specification of D3DCLEAR_TARGET,
    // and we ARE using the depth buffer (D3DCLEAR_ZBUFFER)
    // but we are NOT using the stencil buffer (hence me omitting
    // D3DCLEAR_STENCIL).  There's no sense in clearing out a
    // buffer that's not in use.  That's like vaccumming a room
    // that's just been vaccummed squeaky clean.
    // If you're not going to be picking up any extra dirt,
    // cleaning it again is really just a waste of time and energy.

    D3DCOLOR_ARGB( 255, 125, 25, 237 ),  // The color to clear
    // the backbuffer out to.

    1.0f, // value to clear the depth buffer to.  we clear
    // it to 1.0f because 1.0f means ("furthest away possible
    // before being out of range")

    // So we clear every value in the depth buffer to this
    // value so when something is rendered that is in view range,
    // it will definitely be closer than 1.0f!
    // (0.0f means right in our faces).

    0  // value to clear the stencil buffer to.  since we
    // chose NOT to clear the stencil buffer (omitted
    // D3DCLEAR_STENCIL from above), this value is
    // actually going to be ignored.

  ) ;
  CHECK( hr, "Clear FAILED!" ) ;

  #pragma endregion

  #pragma region set up the camera

  // First we start by setting up the viewport.
  // the viewport "Defines the window dimensions of
  // a render-target surface onto which a 3D volume projects."
  D3DVIEWPORT9 viewport ;

  // Very clear explanations of each (and advice! :) )
  // of these members are on msdn.
  viewport.X = 0 ;
  viewport.Y = 0 ;
  viewport.Width = g.win.width ;
  viewport.Height = g.win.height ;
  viewport.MinZ = 0.0f ;
  viewport.MaxZ = 1.0f ;

  g.gpu->SetViewport( &viewport ) ;

  // Technically we don't need to set the viewport here
  // BUT you can use viewport setting to draw "picture in picture" -

  // Form the 

  // Set projection matrix
  D3DXMATRIX projx ;

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

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

  // Create the view matrix
  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

  // Preparing to draw
  // FVF.  WTF is an FVF?
  // MSDN:  "Flexible Vertex Format Constants, or FVF codes,
  //   are used to describe the contents of vertices
  //   interleaved in a single data stream that will
  //   be processed by the fixed-function pipeline."

  // FVF stands for "FLEXIBLE VERTEX FORMAT".  If you're familiar with
  // OpenGL, this is a completely (but some might say a little bit better..)
  // way of allowing a person to say WHAT data each vertex has tagged along
  // with it.

  // So let's tell Direct3D what data exactly each VERTEX
  // will have.  A position?  A color?  A normal?  A texture
  // coordinate?  What do you WANT TO specify for each vertex.

  hr = g.gpu->SetFVF(

    D3DFVF_XYZ  // THe most OBVIOUS (and most important?) aspect of a VERTEX is
    // that it have a POSITION, XYZ.  Specifying that our vertex format
    // includes an XYZ position

    | D3DFVF_DIFFUSE // We also specify a diffuse color for each vertex.

  ) ;
  CHECK( hr, "SetFVF FAILED!" ) ;

  // So there we have it.  We just told d3d to expect
  // to get vertices that each have an XYZ coordinate
  // AND a color specified for them.

  // SO NOW, before DRAWING anything, we have to
  // do 2 more things:
  //   #1)  Create a D3DVERTEXELEMENT9 structure
  //       which will represent our vertex format.

  //   #2)  Create an array of vertices to draw!

  //   #3)  Just draw it!

  // #1)  This part is a bit confusing at first,
  // but if you read through it carefully, it should
  // make sense.

  // What we need to do here is create a SPECIAL
  // kind of structure called a "VERTEX DECLARATION"
  // This VertexDeclaration will MATCH UP with
  // the "FVF" format that we set up just a couple
  // of lines ago.  Read on!

  // In the specification, we actually have to
  // obey the FVF mapping
  // on msdn.

  /////////////
  #pragma region // <position vertex element decl>
  // IDirect3DVertexDeclaration9

  // OK in the FVF above, we promised d3d that
  // EACH AND EVERY vertex would have a POSITION
  // and a COLOR.

  // So we declare and set up TWO D3DVERTEXELEMENT9
  // structures which explain to d3d the EXACT format
  // and nature of each vertex -

  // IS this a bit redundant?  Kind of, yes.  Getting
  // on with it.

  D3DVERTEXELEMENT9 pos ;

  // Here is where we say that this part
  // of the vertex will specify a POSITION
  // in space.
  pos.Usage = D3DDECLUSAGE_POSITION ;

  // This part makes sense if you understand
  // that sometimes, you want to send MORE THAN
  // one position coordinate for each vertex.
  // If that makes less sense, then think about
  // sending down more than one COLOR for each
  // vertex, for some type of funky color blending.
  pos.UsageIndex = 0 ;

  pos.Stream = 0 ; // Vertex shaders have a concept
  // of "stream".

  // So what's a "stream" you ask?
  // This really is QUITE an advanced topic, so my honest advice
  // to you is to completely ignore the below unless you
  // REALLY want to know what streams are.

  // <streams>
  // There is a concept in GPU programming called "shader instancing".
  // Shader instancing is when you specify a model's geometry once,
  // then draw that same model like a million times.

  // 

  // So, you specify the model vertex data with POSITIONS on
  // channel 0, for example.  Then you specify a bunch of
  // positions on channel 1 (1,000,000 positions in your game world,
  // or something) that describe places to draw ALL the vertices
  // that are on channel 0.

  // So its really quite complicated and hard to understand.
  // Channels are like TV -- like the TV station sends like,
  // 500 channels down to your TV in parallel (hey, pretend
  // they do), the vertex data you send down to the GPU
  // all goes down to the GPU in parallel, work at drawing the same thing, kind of.

  // Your tv can tune into one channel at a time only, and the GPU
  // will actually tune into ALL the channels when drawing..
  // </streams>

  // UH, where were we?  Next, we specify the actual data type of
  // the position data.

  pos.Type = D3DDECLTYPE_FLOAT3 ;  // "Vertices will use
  // 3 floats to specify their position in space".

  // If you are familiar with GPU datatypes and HLSL,
  // this would correspond directly with the "float3"
  // datatype in the vertex shader.

  // If you don't know what a vertex shader is,
  // just suffice it to say, that all this means
  // is 3 floats will be used for the POSITION
  // of the vertex.

  // Next we set the "offset":

  pos.Offset = 0 ;

  // In the Vertex STRUCT that WE defined,
  // this is the byte offset from the start
  // of the struct where D3D SHOULD expect
  // to find this data.

  // Using default method.
  pos.Method = D3DDECLMETHOD_DEFAULT ; // here's more info

  #pragma endregion // </position vertex element decl>
  /////////////

  /////////////
  #pragma region // <color vertex element decl>
  // Next we declare the vertex element that
  // will represent the DIFFUSE COLOR component.
  D3DVERTEXELEMENT9 col;

  col.Usage = D3DDECLUSAGE_COLOR ; // its a color
  col.UsageIndex = 0 ; // COLOR0
  col.Stream = 0 ;

  col.Type = D3DDECLTYPE_D3DCOLOR ; // UNFORTUNATELY you MUST
  // chose D3DDECLTYPE_D3DCOLOR when using COLOR0
  // or COLOR1.  If you write your own shader,
  // then you can use a FLOAT4 color.

  // NEXT, the OFFSET.  The offset is
  // 3*sizeof(float) because the 'POSITION'
  // comes first and takes up 3 floats as we
  // specified above.
  col.Offset = 3*sizeof( float ) ;
  col.Method = D3DDECLMETHOD_DEFAULT ;
  #pragma endregion // </color vertex element decl>
  /////////////

  /////////////
  #pragma region create and set vertex declaration
  // Now put the two D3DVERTEXELEMENT9's into
  // an array and create the VertexDeclaration:
  D3DVERTEXELEMENT9 vertexElements[] =
  {
    pos,
    col,

    // VERY IMPORTANT!  D3D doesn't konw
    // HOW MANY elements you will be specifying
    // in advance, so you TELL IT by passing
    // this SPECIAL D3DVERTEXELEMENT9 object
    // which is basically just like the null
    // terminator at the end of C string.
    D3DDECL_END()
  } ;

  IDirect3DVertexDeclaration9 * Vdecl ;

  // Now register in the "vertexElements" array
  // we just created above into the decl
  hr = g.gpu->CreateVertexDeclaration( vertexElements, &Vdecl ) ;
  CHECK( hr, "CreateVertexDeclaration FAILED!" ) ;

  // Now SET IN that vertex declaration into the GPU
  hr = g.gpu->SetVertexDeclaration( Vdecl ) ;
  CHECK( hr, "SetVertexDeclaration FAILED!" ) ;
  #pragma endregion

  #pragma region set render states
  // FINALLY, last thing before drawing, we
  // have to set the renderstate to USE
  // the DIFFUSE component to determine the
  // color of each vertex
  // Per-Vertex Color State
  hr = g.gpu->SetRenderState( D3DRS_COLORVERTEX, TRUE ) ;
  CHECK( hr, "SetRenderState( COLORVERTEX ) FAILED!" ) ;

  // Turn LIGHTING off.  TRUE to enable Direct3D lighting,
  // or FALSE to disable it. The default value is TRUE.
  // __Only vertices that include a vertex normal are properly lit;
  // vertices that do not contain a normal ___employ a dot product of 0___
  // in all lighting calculations.__!

  // So if you don't disable lighting, what will actually happen is,
  // since we don't specify normals for any of our vertices,
  // they will all have a normal vertex of the 0 vector, so
  // the result is they will all be completely black.
  hr = g.gpu->SetRenderState( D3DRS_LIGHTING, FALSE ) ;
  CHECK( hr, "Lighting off" ) ;

  // Turn backface culling off.  Its good to turn this off
  // when starting out because triangles that you wind
  // ccw are discarded if this is on.
  // http://msdn.microsoft.com/en-us/library/bb204882(VS.85).aspx
  hr = g.gpu->SetRenderState( D3DRS_CULLMODE, D3DCULL_NONE ) ;
  CHECK( hr, "Culling off" ) ;

  #pragma endregion

  #pragma region declare a vertex structure, create verts
  // OK?? WHEW!!  THAT was a lot of work!
  // Now let's DRAW SOMETHING!!  First,
  // we have to create a STRUCT which
  // will match up the vertex declaration
  // we specified above.

  // Practically you'd probably want this struct
  // to be declared in global space, but its declared
  // inline here just to preserve the
  // flow of information for you.

  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 ) ;
    }

    // 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 ) ;
    }
  } ;

  // Now create an array full of vertices!
  Vertex verts[] = {

    // Red vertex @ ( -1, 0, 0 )
    Vertex( -1, 0, 0, 255, 19, 0 ),

    // Green vertex @ ( 0, 1, 0 )
    Vertex(  0, 1, 0, 0, 255, 0 ),

    // Blue vertex @ ( 1, 0, 0 )
    Vertex(  1, 0, 0, 0, 0, 255 )

  } ;

  float axisLen = 2.0f ;
  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 )

  } ;

  #pragma endregion

  #pragma region ACTUALLY __draw__
  // IDirect3DDevice9::BeginScene()
  // You must call BeginScene() before you start drawing anything.
  hr = g.gpu->BeginScene() ;
  CHECK( hr, "BeginScene FAILED!" ) ;

  hr = g.gpu->DrawPrimitiveUP( D3DPT_TRIANGLELIST, 1, verts, sizeof( Vertex ) ) ;
  CHECK( hr, "DrawPrimitiveUP FAILED!" ) ;

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

  float pointSize = 8.0f ;

  // A DWORD is 4 bytes (a WORD is 2 bytes).
  // So, what we need to do is basically cast
  // pointSize to (DWORD).  Its a bit complicated
  // about how you actually do it, so I made a macro for it.
  // The general idea is you need to "trick" SetRenderState
  // into taking your float value.. SetRenderState "thinks"
  // its a DWORD, while its actually a float.. and D3D
  // internally somehow gets it and knows to treat it as a float.
  // Kind of clunky, eh, but what can you do.
  g.gpu->SetRenderState( D3DRS_POINTSIZE, CAST_AS_DWORD( pointSize ) ) ;

  // Draw points at end of axis.
  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!" ) ;

  // endscene, and present
  // IDirect3DDevice9::EndScene()
  // You must call EndScene() to signify to the gpu that
  // you are finished drawing.  Must pair up with
  // a BeginScene() call that happened earlier.
  hr = g.gpu->EndScene() ;
  CHECK( hr, "EndScene FAILED!" ) ;

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

}

// function that prints some system info.  can ignore this part
// if you are not interested in it.
void printSystemInfo()
{
  UINT numAdapters = g.d3d->GetAdapterCount() ;
  printf( "\n\n* * * * System information * * * *\n" ) ;
  printf( "Owner name:  Dorky Dorkinson (haha, just kidding, little easter egg there..)\n" ) ;
  printf( "Ok, the rest of this information IS real!\n" ) ;

  printf( "You have %d adapters\n  * (this number is bigger than 1 if you have dualview)\n", numAdapters ) ;

  // Scroll through all adapters and print some info about each
  for( int i = 0 ; i < numAdapters ; i++ )
  {
    printf( "\n\n-- ADAPTER #%d --\n", i ) ;
    printf( "On monitor #%d\n", g.d3d->GetAdapterMonitor( i ) ) ;

    // Object into which display mode info will be saved
    // by GetAdapterDisplayMode
    D3DDISPLAYMODE displayMode ;
    g.d3d->GetAdapterDisplayMode( i, &displayMode ) ;

    printf( "Has Format=%d Height=%d Width=%d RefreshRate=%d\n", displayMode.Format, displayMode.Height, displayMode.Width, displayMode.RefreshRate ) ;
    printf( "  * (format refers to the D3DFMT_ pixel mode.. e.g. 22=D3DFMT_X8R8G8B8 which is 24 bit color)\n" ) ;

    D3DADAPTER_IDENTIFIER9 id ; // Will hold info about the adapter
    // after call to GetAdapterIdentifier

    g.d3d->GetAdapterIdentifier( i, 0, &id ) ;
    // At this point you can see how WEIRD the API gets.
    // All I want is the adapter identifier, and here MSDN
    // says the API offers to "connect to the Internet
    // and download new MS Windows Hardware Quality Labs certificates."
    // Holy cow.  I don't want to do THAT.  So leave the flag at 0.

    // There's PLENTY of info here we don't care about,
    // but some of it is interesting!!  I've printed
    // only the most interesting members, leaving parts
    // like the GUID out.
    printf( "<device driver info>\n" ) ;
    printf( "  Description: %s\n  Device Id: %d\n  Device name: %s\n  Driver: %s\n",
      id.Description, id.DeviceId, id.DeviceName, id.Driver ) ;
    printf( "</device driver info>\n" ) ;

    UINT modeCount ;

    // I guess this next part just shows.. how FEW modes are
    // actually supported on a GPU.. I have an NVIDIA 8800GTS,
    // and it only supports 28 modes on D3DFMT_X8R8G8B8,
    // and 28 modes on D3DFMT_R5G6B5.  The rest, 0 modes are
    // reported as supported!

    modeCount = g.d3d->GetAdapterModeCount( i, D3DFMT_R8G8B8 ) ;
    printf( "D3DFMT_R8G8B8   %d modes supported\n", modeCount ) ;

    modeCount = g.d3d->GetAdapterModeCount( i, D3DFMT_A8R8G8B8 ) ;
    printf( "D3DFMT_A8R8G8B8 %d modes supported\n", modeCount ) ;

    modeCount = g.d3d->GetAdapterModeCount( i, D3DFMT_X8R8G8B8 ) ;
    printf( "D3DFMT_X8R8G8B8 %d modes supported\n", modeCount ) ;

    modeCount = g.d3d->GetAdapterModeCount( i, D3DFMT_R5G6B5 ) ;
    printf( "D3DFMT_R5G6B5   %d modes supported\n", modeCount ) ;

    modeCount = g.d3d->GetAdapterModeCount( i, D3DFMT_X1R5G5B5 ) ;
    printf( "D3DFMT_X1R5G5B5 %d modes supported\n", modeCount ) ;

    modeCount = g.d3d->GetAdapterModeCount( i, D3DFMT_A1R5G5B5 ) ;
    printf( "D3DFMT_A1R5G5B5 %d modes supported\n", modeCount ) ;

    modeCount = g.d3d->GetAdapterModeCount( i, D3DFMT_A4R4G4B4 ) ;
    printf( "D3DFMT_A4R4G4B4 %d modes supported\n", modeCount ) ;

    modeCount = g.d3d->GetAdapterModeCount( i, D3DFMT_R3G3B2 ) ;
    printf( "D3DFMT_R3G3B2   %d modes supported\n", modeCount ) ;

    modeCount = g.d3d->GetAdapterModeCount( i, D3DFMT_A8 ) ;
    printf( "D3DFMT_A8       %d modes supported\n", modeCount ) ;

    modeCount = g.d3d->GetAdapterModeCount( i, D3DFMT_A8R3G3B2 ) ;
    printf( "D3DFMT_A8R3G3B2 %d modes supported\n", modeCount ) ;

    modeCount = g.d3d->GetAdapterModeCount( i, D3DFMT_X4R4G4B4 ) ;
    printf( "D3DFMT_X4R4G4B4 %d modes supported\n", modeCount ) ;

    modeCount = g.d3d->GetAdapterModeCount( i, D3DFMT_A2B10G10R10 ) ;
    printf( "D3DFMT_A2B10G10R10 %d modes supported\n", modeCount ) ;

    modeCount = g.d3d->GetAdapterModeCount( i, D3DFMT_A8B8G8R8 ) ;
    printf( "D3DFMT_A8B8G8R8 %d modes supported\n", modeCount ) ;

    modeCount = g.d3d->GetAdapterModeCount( i, D3DFMT_X8B8G8R8 ) ;
    printf( "D3DFMT_X8B8G8R8 %d modes supported\n", modeCount ) ;

    modeCount = g.d3d->GetAdapterModeCount( i, D3DFMT_G16R16 ) ;
    printf( "D3DFMT_G16R16   %d modes supported\n", modeCount ) ;

    modeCount = g.d3d->GetAdapterModeCount( i, D3DFMT_A2R10G10B10 ) ;
    printf( "D3DFMT_A2R10G10B10 %d modes supported\n", modeCount ) ;

    modeCount = g.d3d->GetAdapterModeCount( i, D3DFMT_A16B16G16R16 ) ;
    printf( "D3DFMT_A16B16G16R16 %d modes supported\n", modeCount ) ;

    // This mode is the MOST LIKELY TO be supported on your machine.
    modeCount = g.d3d->GetAdapterModeCount( i, D3DFMT_X8R8G8B8 ) ;
    for( int j = 0 ; j < modeCount; j++ )
    {
      g.d3d->EnumAdapterModes( i, D3DFMT_X8R8G8B8, j, &displayMode ) ;

      printf( "For format=%d (D3DFMT_X8R8G8B8) Height=%d Width=%d RefreshRate=%d is SUPPORTED\n", displayMode.Format, displayMode.Height, displayMode.Width, displayMode.RefreshRate ) ;

    }

    // At this point you're thinking, "HEY!!  But i'm SURE my gpu supports
    // alpha blending!  Why are all the modes like A8R8G8B8 NOT supported!?"
    // My best stab at this is it makes no sense to DISPLAY something with
    // an alpha component still in it.  For the final image that gets displayed --
    // the alphas should already have been blended -- present day
    // monitors can only display RGB, they don't have the ability to
    // "go transparent".  Maybe one day when we work with those enormous
    // glass screens that people work with in the movies -- kinda like this one:
    // http://business.timesonline.co.uk/multimedia/archive/00339/screen-385_339034a.jpg
    // then having an ALPHA component on the display WOULD make sense.  But for
    // now, all monitors are completely opaque, and they only display colors
    // RGB.  So an alpha component makes no sense on the display itself.
    // That's why displays don't support that display mode.

    // K, FINALLY we get to the device's capabilities.
    // I love how DirectX lets you "reflect" on what
    // the hardware is in fact capable of.  Its nice.

    D3DCAPS9 caps ;
    g.d3d->GetDeviceCaps( i, D3DDEVTYPE_HAL, &caps ) ;

    // Now we have the capabilities of the device.
    // Printing all of them would be meaningless,
    // but if you want to inspect some of them, just
    // use the debugger.

  }
}

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 );

  /////////////////
  // Ok, AT THIS POINT, we'd normally
  // just go ahead and call CreateWindow().
  // And we WILL call CreateWindow(), but
  // there is something I must explain to
  // you first.  That thing is the RECT structure.

  /////////////////
  // RECT:
  //
  // A RECT is just a C struct meant to represent
  // a rectangle.
  //
  // The RECT structure WILL DESCRIBE EXACTLY WHERE
  // AND HOW WE WANT OUR WINDOW TO APPEAR WHEN WE
  // CREATE IT.
  //
  //         TOP
  //       --------
  //       |      |
  // LEFT  |      | RIGHT
  //       --------
  //        BOTTOM
  //
  // So, what we do is, we create the RECT
  // struct for our window as follows:
  RECT rect;
  SetRect( &rect, 420,  // left
    25,  // top
    420 + 800, // right
    25  + 600 ); // 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 = WS_EX_TOPMOST ; // I want the window to be topmost

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

  // AdjustWindowRect() expands the RECT
  // so that the CLIENT AREA (drawable region)
  // has EXACTLY the dimensions we specify
  // in the incoming RECT.

  // If you didn't just understand that, understand
  // this:  "you have to call AdjustWindowRect()",
  // and move on.  Its not THAT important, but its
  // good for the performance of your app.

  ///////////////////
  // NOW we call CreateWindow, using
  // that adjusted RECT structure to
  // specify the width and height of the window.
  g.win.hwnd = CreateWindowEx(
    windowExStyle,
    TEXT("Philip"),
    TEXT("TIGER-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 );
  #pragma endregion

  #pragma region part 2 - initialize direct3d9

  // 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 );
    }

    // 3.  DRAW USING Direct3D.
    // This region right here is the
    // heart of our application.  THE MOST
    // execution time is spent just repeating
    // this draw() function.
    draw();

  }
  #pragma endregion

  //////////////
  // clean up
  #pragma region clean up

  // Release COM objects.
  // What's SAFE_RELEASE()?  Well, lots of people use
  // if( pointer ) pointer->Release() ; to guard
  // against null pointer exceptions.

  // Like the MS examples do, I've defined
  // SAFE_RELEASE at the top of this file and
  // I'm using it here.  All it does is
  // make sure the pointer is not null before releasing it.
  SAFE_RELEASE( g.gpu ) ;
  SAFE_RELEASE( g.d3d ) ;

  #pragma endregion

  // 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 );
}

/*
    ____   __   __      __   __  ___
   / _  \ /  / /  /    /  /  \ \/  /
  / _/ / /  / /  /    /  /    \   /
 / _/ \ /  / /  /__  /  /__   /  /
/_____//__/ /______//______/ /__/

*/

Code package on esnips (thanks esnips!)

error: Usage field contains value that is not a member of D3DDECLUSAGE

Aka CreateVertexDeclaration() returns E_FAIL: An undetermined error occurred

Ever run into this error?

[5108] Direct3D9: Decl Validator: X281: (Element Error) (Decl Element [2]) Usage field contains value that is not a member of D3DDECLUSAGE. Value: 0xcc. Aborting decl validation.

First of all, if you’re still only getting the extent of information that DxErrorDescription9() affords you then you’re not debugging properly (though that post is directed at xna users, it still works exactly the same for d3d c++ users)

In any case, to fix this problem. Did you forget to put a D3DDECL_END() vertex declaration at the END of your vertexElements array?

“Vertex data is defined using an array of D3DVERTEXELEMENT9 structures. Use D3DDECL_END to declare the last element in the declaration.”

The D3DDECL_END() macro just gives you an initializer for a D3DVERTEXELEMENT9 structure that signifies the end of the vertex declaration. Say you intend to create a vertex declaration that has a position and a color:

  D3DVERTEXELEMENT9 vertexElements[ 2 ] =
  {
    pos, // defines a POSITION vertex element
    col   // defines a COLOR vertex element
  } ;

  IDirect3DVertexDeclaration9 * Vdecl ;

  // next line FAILS.
  hr = g.gpu->CreateVertexDeclaration( vertexElements, &Vdecl ) ;

Reason CreateVertexDeclaration fails is because its like calling strlen() on a string that doesn’t have a null-terminator at the end. D3D doesn’t know where to stop.

You get the error “Usage field contains value that is not a member of D3DDECLUSAGE.” because the random garbage memory value when D3D tries to read your “third” element (even though you don’t have one!) makes d3d angry and confused.

So you do this:


  D3DVERTEXELEMENT9 vertexElements[ 2 ] =
  {
    pos,
    col,

    // VERY IMPORTANT!  D3D doesn't konw
    // HOW MANY elements you will be specifying
    // in advance, so you TELL IT by passing
    // this SPECIAL D3DVERTEXELEMENT9 object
    // which is basically just like the null
    // terminator at the end of C string.
    D3DDECL_END()
  } ;

And now it works.

Vertex Declarations in Direct3D9

A lot of API’s do it. BUT WHY?
Passing a pointer to a pointer

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

char * InitArrayGood0( char * a ) ;
void InitArrayGood1( char * &a ) ;
void InitArrayGood2( char ** a ) ;
void InitArrayEvil( char * a ) ;

int main()
{
  char * word = NULL ;

  // This way doesn't work
  InitArrayEvil( word ) ;

  // These 3 ways all work.
  word = InitArrayGood0( word );
  //InitArrayGood1( word );
  //InitArrayGood2( &word );

  if( word == NULL )
  {
    printf("Word is STILL NULL!!!  That init didn't do ANYTHING!!\n") ;
    exit(1);
  }
  else
  {
    word[0] = 'a' ;
    word[1] = 'b' ;
    word[2] = 0 ;

    puts( word ) ;
  }
}

// Does not work
// what happens here is
// the pointer value (0) is
// PASSED BY VALUE to this function.
void InitArrayEvil(char * a)
{
  // Say the array that (a) refers to
  // references a NULL variable.  Well,
  // when we first come into this function,
  //   InitArrayEvil( word ) ;
  // the value of (a) as we start
  // executing this function is 0.

  // We then assign (a) as a new array.

  a = new char[20];  // Fine and dandy.

  // BUT THE value of (word) in the
  // CALLING function is UNCHANGED!
  // You really have to think about why.

  // Its tricky because at first, you
  // should think "BUT I PASSED IT
  // BY REFERENCE!!  So any changes
  // to (a) in this function should
  // affect (word) in the calling function!"

  // PARAMETER PASSING IN THIS FUNCTION
  // is ACTUALLY BY VALUE.

  // What that means is, even though (a)
  // is a pointer to a char,
  // char * a gets initialized by COPYING
  // the value of (word) that is passed to it
  //    InitArrayEvil( word ) ;
  // If word starts out at NULL, then
  // a starts out at null.  If we subsequently
  // change the value of a, that DOES NOT CHANGE
  // the value of word!

  // Its confusing because say we had a function like
  //   void truncate( char * a )
  //   {
  //     a[ 0 ] = 0 ;
  //   }
  //
  // call by:
  //   word = new char[ 20 ] ;
  //   word[0] = 'a'; word[1] = 'b'; word[2] = 0;
  //   truncate( word ) ;

  // THEN this function WOULD change whatever array
  // you passed to it.  Because what gets copied in
  // to (a) IS THE MEMORY ADDRESS VALUE of the variable
  // (word).  (word) is then actually manipulated
  // when (a) is manipulated in the truncate() function.

  // This is hard to wrap your head around, but once
  // you get it, it makes perfect sense.
}

// This function WORKS because
// we RETURN a.
char * InitArrayGood0(char * a)
{
  a = new char[20];

  // Here, we are RETURNING that new
  // memory address value for a.  So
  // as long as you write:
  //    word = InitArrayGood0( word )
  // You'll have no problem using this
  // function.  Actually this function
  // doesn't NEED (a) to come into it,
  // (this function should really take
  // NO parameters), but I left it there
  // for consistency.
  return a;
}

// Works
void InitArrayGood1(char * &a)
{
  // So, oddly, THIS function works,
  // but only in C++.

  // a is set up as a char* pointer,
  // but it is set up as AN ALIAS
  // to (word), the variable that exists
  // in the calling function.

  // As a result, (a) basically
  // "reaches into" the scope of main()
  // and uses THAT SAME VARIABLE (word).

  // So assignment of (a) changes (word).
  // So this function works.
  a = new char[20];
}

// Works
// This function takes a POINTER TO A (char*)
// variable.
// NOW this will work too, and its the most
// common way of handling this type of thing
// (all the DirectX CreateDevice() functions
// use this method).  This way works in
// both C and C++.  Because now the value
// being copied into a is THE MEMORY ADDRESS
// OF THE VARIABLE (word) IN MAIN().
// This means that any change to (*a) directly
// change (word) in main(), which means this
// function can cause (word) to point to something
// new.

// The value COPIED here is the ADDRESS OF A,
// which happens to be a pointer.  Get it?
// its tough, but again once you get it, it makes
// perfect sense.
void InitArrayGood2( char ** a )
{
  *a = new char[20 ] ;
}

Q: If two vectors form a plane in 3 space, then how come two vectors can be “skew” and never intersect?

A: Skew vectors that never intersect do not start both at the origin (of course, because if they did, the origin would be the intersection point and they would not be skew!)

Vectors that are skew never intersect – you have to present them in parametric form so that you’re sure the vector doesn’t start at the origin. An example is:

v1 = ( 1, 0, 0 ) + t( 0, 1, 0 ) ;
v2 = ( -1, 0, 0 ) + t( 0, 0, 1 ) ;

These are the two vectors on either side of the origin. One starts at ( 1, 0, 0 ), so right on the +x-axis, and goes STRAIGHT up.

The other vector starts on the -x-axis, at (-1,0,0) and goes STRAIGHT in the direction of +z.

Because one vector goes straight up and down, and the other vector goes back and forth in z, they’ll never hit each other. But the vectors AREN’T parallel.

WordPress doesn’t allow you to use just ANY tags. These are the tags you CAN use:

the indented part are the attributes those tags can use.

	$allowedposttags = array(
		'address' => array(),
		'a' => array(
			'class' => array (),
			'href' => array (),
			'id' => array (),
			'title' => array (),
			'rel' => array (),
			'rev' => array (),
			'name' => array (),
			'target' => array()),
		'abbr' => array(
			'class' => array (),
			'title' => array ()),
		'acronym' => array(
			'title' => array ()),
		'b' => array(),
		'big' => array(),
		'blockquote' => array(
			'id' => array (),
			'cite' => array (),
			'class' => array(),
			'lang' => array(),
			'xml:lang' => array()),
		'br' => array (
			'class' => array ()),
		'button' => array(
			'disabled' => array (),
			'name' => array (),
			'type' => array (),
			'value' => array ()),
		'caption' => array(
			'align' => array (),
			'class' => array ()),
		'cite' => array (
			'class' => array(),
			'dir' => array(),
			'lang' => array(),
			'title' => array ()),
		'code' => array (
			'style' => array()),
		'col' => array(
			'align' => array (),
			'char' => array (),
			'charoff' => array (),
			'span' => array (),
			'dir' => array(),
			'style' => array (),
			'valign' => array (),
			'width' => array ()),
		'del' => array(
			'datetime' => array ()),
		'dd' => array(),
		'div' => array(
			'align' => array (),
			'class' => array (),
			'dir' => array (),
			'lang' => array(),
			'style' => array (),
			'xml:lang' => array()),
		'dl' => array(),
		'dt' => array(),
		'em' => array(),
		'fieldset' => array(),
		'font' => array(
			'color' => array (),
			'face' => array (),
			'size' => array ()),
		'form' => array(
			'action' => array (),
			'accept' => array (),
			'accept-charset' => array (),
			'enctype' => array (),
			'method' => array (),
			'name' => array (),
			'target' => array ()),
		'h1' => array(
			'align' => array (),
			'class' => array ()),
		'h2' => array(
			'align' => array (),
			'class' => array ()),
		'h3' => array(
			'align' => array (),
			'class' => array ()),
		'h4' => array(
			'align' => array (),
			'class' => array ()),
		'h5' => array(
			'align' => array (),
			'class' => array ()),
		'h6' => array(
			'align' => array (),
			'class' => array ()),
		'hr' => array(
			'align' => array (),
			'class' => array (),
			'noshade' => array (),
			'size' => array (),
			'width' => array ()),
		'i' => array(),
		'img' => array(
			'alt' => array (),
			'align' => array (),
			'border' => array (),
			'class' => array (),
			'height' => array (),
			'hspace' => array (),
			'longdesc' => array (),
			'vspace' => array (),
			'src' => array (),
			'style' => array (),
			'width' => array ()),
		'ins' => array(
			'datetime' => array (),
			'cite' => array ()),
		'kbd' => array(),
		'label' => array(
			'for' => array ()),
		'legend' => array(
			'align' => array ()),
		'li' => array (
			'align' => array (),
			'class' => array ()),
		'p' => array(
			'class' => array (),
			'align' => array (),
			'dir' => array(),
			'lang' => array(),
			'style' => array (),
			'xml:lang' => array()),
		'pre' => array(
			'style' => array(),
			'width' => array ()),
		'q' => array(
			'cite' => array ()),
		's' => array(),
		'span' => array (
			'class' => array (),
			'dir' => array (),
			'align' => array (),
			'lang' => array (),
			'style' => array (),
			'title' => array (),
			'xml:lang' => array()),
		'strike' => array(),
		'strong' => array(),
		'sub' => array(),
		'sup' => array(),
		'table' => array(
			'align' => array (),
			'bgcolor' => array (),
			'border' => array (),
			'cellpadding' => array (),
			'cellspacing' => array (),
			'class' => array (),
			'dir' => array(),
			'id' => array(),
			'rules' => array (),
			'style' => array (),
			'summary' => array (),
			'width' => array ()),
		'tbody' => array(
			'align' => array (),
			'char' => array (),
			'charoff' => array (),
			'valign' => array ()),
		'td' => array(
			'abbr' => array (),
			'align' => array (),
			'axis' => array (),
			'bgcolor' => array (),
			'char' => array (),
			'charoff' => array (),
			'class' => array (),
			'colspan' => array (),
			'dir' => array(),
			'headers' => array (),
			'height' => array (),
			'nowrap' => array (),
			'rowspan' => array (),
			'scope' => array (),
			'style' => array (),
			'valign' => array (),
			'width' => array ()),
		'textarea' => array(
			'cols' => array (),
			'rows' => array (),
			'disabled' => array (),
			'name' => array (),
			'readonly' => array ()),
		'tfoot' => array(
			'align' => array (),
			'char' => array (),
			'class' => array (),
			'charoff' => array (),
			'valign' => array ()),
		'th' => array(
			'abbr' => array (),
			'align' => array (),
			'axis' => array (),
			'bgcolor' => array (),
			'char' => array (),
			'charoff' => array (),
			'class' => array (),
			'colspan' => array (),
			'headers' => array (),
			'height' => array (),
			'nowrap' => array (),
			'rowspan' => array (),
			'scope' => array (),
			'valign' => array (),
			'width' => array ()),
		'thead' => array(
			'align' => array (),
			'char' => array (),
			'charoff' => array (),
			'class' => array (),
			'valign' => array ()),
		'title' => array(),
		'tr' => array(
			'align' => array (),
			'bgcolor' => array (),
			'char' => array (),
			'charoff' => array (),
			'class' => array (),
			'style' => array (),
			'valign' => array ()),
		'tt' => array(),
		'u' => array(),
		'ul' => array (
			'class' => array (),
			'style' => array (),
			'type' => array ()),
		'ol' => array (
			'class' => array (),
			'start' => array (),
			'style' => array (),
			'type' => array ()),
		'var' => array ());

	/**
	 * Kses allowed HTML elements.
	 *
	 * @global array $allowedtags
	 * @since 1.0.0
	 */
	$allowedtags = array(
		'a' => array(
			'href' => array (),
			'title' => array ()),
		'abbr' => array(
			'title' => array ()),
		'acronym' => array(
			'title' => array ()),
		'b' => array(),
		'blockquote' => array(
			'cite' => array ()),
		//	'br' => array(),
		'cite' => array (),
		'code' => array(),
		'del' => array(
			'datetime' => array ()),
		//	'dd' => array(),
		//	'dl' => array(),
		//	'dt' => array(),
		'em' => array (), 'i' => array (),
		//	'ins' => array('datetime' => array(), 'cite' => array()),
		//	'li' => array(),
		//	'ol' => array(),
		//	'p' => array(),
		'q' => array(
			'cite' => array ()),
		'strike' => array(),
		'strong' => array(),
		//	'sub' => array(),
		//	'sup' => array(),
		//	'u' => array(),
		//	'ul' => array(),
	);

This is from kses.php, wordpress source code.

The dot product

1.

Another way to find the dot product is:

2.

Projections of a vector u onto a vector v are found in two ways I can see so far:

3.

Which is 100% equal to:

4.

WHERE is a unit vector pointing in the same direction as v.

SO we can also say:

5.

Where v has become a unit vector, totally.

Keep in mind the difference between equations 4 and 5 is in 4, v isn’t necessarily normalized when its used in the dot product operation, so you need to divided by |v| to “cancel its effect” on the final result. notice in all of these, we divide by v enough times so that the actual magnitude of v PLAYS NO ROLE in projvu, only the direction of v matters.

Finally you’ll see the following definition usually in physics books:

6.

Where t is the angle between vectors u and v.

This 6th formula follows if you study formula 3 and move things around a bit..

taking formula 3:

Notice that from formula 1, we have:

So, re-arranging formula 3 a bit now..

All I did there was add a |u| to the denominator, and separate the |v|2 into |v||v|

Ok?

Next, sub in

Then we get:

Now notice that , (v as a unit vector), so

where is a unit vector pointing in the direction of the vector v you are trying to project u onto.

Technical knowledge, ability to express ideas, assume leadership, inspire enthusiasm in people as “commodities”.

TRACK 1.
8:50: “This BOOK”

TRACK 2.
11:34.
criticism is futile, dangerous. incurs resentment.

humans thirst for approval, are scared of criticism

- hard hat guys. the dudes wouldn’t wear their hats. the foreman told them REGULATIONS SAY YOU MUST WEAR THE HATS. But this didn’t work well.

- then he tried to get them to change by first asking if the hats were uncomfortable, trying to sympathize with them – seeing why they weren’t wearing the hats. THEN he told them why they had to wear the hats — protection — more ppl wore the hats after that.

“Father Forgets” – W. Livingston Learned. A good piece of writing about a father who expected too much from his young son and constantly criticized him.

Principle 1. DOn’t criticize, condemn or complain.

TRACK 4.
Chapter 2. The big secret of dealing with people.

Freud’s 2 desires of men:
1. Desire to be great **
2. Sex urge.

Dewey: Desire to be important — Like Freud’s “desire to be great”

Humans have a CRAVING to be appreciated
- people who have this food will hold control

Humans have a “gnawing desire for attention”

- how people get their feeling of importance determines character…
- criminals from getting their picture in the paper as a great criminal at large
- good people from being recognized for good works

TRACK 5.
6:00 into

Charles Schwab:

- I consider my ability to arouse enthusiasm among my people the greatest asset that I possess. And the way to develop the best that is in a person is by appreciation and encouragement. There is nothing else that so kills the ambition of a person as criticism from superiors. I never criticize anyone. I believe in giving a person incentive to work. So I’m anxious to praise, but loathe to find fault. If I like anything, I am hearty in my approbation and lavish in my praise.

Average people do the exact opposite. complain if bad, if they do like something, they say nothing.

“Once I did bad
and that I heard ever
Twice I did good
but that I heard never”

- people do better work under spirit of approval. moreso then spirit of being derailed and derided.

#1 reason for runaway wives is lack of appreciation.

- flattery is counterfeit.

- flattery is telling other people what you think about yourself.

appreciation vs. flattery:
good bad

TRACK 6. Chapter 3.

He who can do this has the world with him. He who cannot walks a lonely way.

You don’t fish with strawberries (what you like), you use worms.

“bait the hook to suit the fish”.
- you are interested in what you want.
- others are interested in what they want

only way to influence people is to talk in terms of what others want, and show them how to get it.

“Influencing Human Behaviour”

“Arouse in the other person an eager want”

TRACK 7.

(right at the beginning)

Henry Ford

“If there is any one secret of success it lies in the ability to get the other person’s point of view and see things from that person’s angle as well as from your own.”

90% of ppl ignore it 90% of the time.

“people who can put themselves in the place of other people need never worry about what the future has in store for them.”

arousing an eager want for something in another person.

Track 8: Review:
Principle 1. DOn’t criticize, condemn or complain.
Principle 2. Give honest and sincere appreciation
Principle 3. Arouse in the other person an eager want.

Track 9: SIX WAYS TO MAKE PEOPLE LIKE YOU.

Dog as a natural friend. Behind his show of affection, there’s no alterior motive.

- dogs don’t have to work for a living — they make living by giving love

* You can make more friends in 2 months by becoming GENUINELY interested in other people than you can in 2 years by trying to get other people interested in YOU.

- Some people blunder through life trying to get others interested in themselves. This doesn’t work. People are not interested in you or me, people are interested in themselves.

- “I” is the most commonly used word in the English language.

- If we merely try to impress people and get people interested in us, then we will never have many true, sincere friends. Friends, real friends, are not made that way.

Alfred Adler: wrote a book:”What life should mean to you.”
“It is the individual who is not interested in his fellow men who has the greatest difficulties in life and provides the greatest injury to others. It is from among such individuals that ALL human failures spring..”

- If the author doesn’t like people, then people won’t like his writing

- you have to be interested in people to be a successful writer of stories.

- most of this track is about *Genuine interest in others*

12:30
One can win the attention and time and cooperation of even the most sought after people by becoming genuinely interested in them.

how he got some important people to guest lecture at his seminars:
“We admired their work and were deeply interested in getting their advice and learning the secrets of their success. We realize you’re too busy to prepare a lecture, so we enclosed a list of questions to answer about themselves and their methods of WORK.”

13:40 – people _like_ people who have admiration for them.

This dude _tactfully_ got everyone he knows’ birthdays and then sent birthday greetings to each of them.

Pabloious Sirus (100 BC):
- “We are interested in others WHEN they are interested in us”

PART 2 Principle 1: “Become genuinely interested in other people!!”

TRACK 10:

Talk of smiles.

Principle 2: Smile.

TRACK 11: If you don’t do this, you are heading for trouble.

Jim Farley: uncanny ability to remember people’s names.

- Remembering a name advantage
- forget/mispell, disadvantage.
This track was all about names and using names. The effectiveness of using names. Perhaps this was what made my students like me so much. I knew their names.

TRACK 12:
Principle 3: A person’s name is to that person, the sweetest and most important sound in any language.

TRACK 13: EASY WAY TO BECOME A GOOD CONVERSATIONALIST

- some people want an interested listener so she can expand her ego and tell about where she had been.

- interesting conversationalist — called this because listened intently.

- good listening is one of the highest compliments you can pay anyone.

- rapt attention

A good conversationalist as a good listener.

Successful business interviews: exclusive attention to the person speaking to you.

Listening as a form of activity.

Listening attentively shows you care about someone.

Sometimes people don’t want advice. They want an AUDIENCE.

Freud’s manner of listening was concentrated.. mild eyes, low voice, gestures few, but attention he gave, appreciation of what he said — no idea what its like to be listened to LIKE THAT.

- People despise people who NEVER LISTEN TO ANYBODY for long.

- To be a good conversationalist, be an attentive listener.

To be interesting, be INTERESTED.

Ask questions the other person will enjoy answering.

Encourage others to talk about themselves and their accomplishments

People you talk to are 100 times more interested in themselves and their problems than you and your problems.

PRINCIPLE 4: Be a good listener and encourage others to talk about themselves.

Track 14:
CHAPTER 5: How to interest people.
- Researching people’s backgrounds and studying it.. opening conversation based on these things

Anyone who was a guest of Theodore Roosevelt astonished by his range of knowledge

Roosevelt knew what to SAY to people.
- whenever he knew he would have a visitor, he would read up on the subject in which he knew his guest was particularly interested.
- royal road to person’s heart is to talk about things that he/she treasures most.

TRACK 15:

PRINCIPLE 5: Talk in terms of other people’s interests

guy who succeeded at getting past secretary and to bigwig guy to get job..

TRACK 16:

Chapter 6: How to make people like you instantly.
- the guy complemented someone on his head of hair.

LAW: Always make the other person feel important.

John Dewey: “The desire to be important is the deepest urge in human nature”

William James
“The deepest urge in human nature is the craving to be appreciated.”

-This is the urge that differentiates us from animals;
this is the urge that is really responsible for civilization itself;

Important precept:
- “Do unto others as you would have others do unto you”

All the time, everywhere.

6:40
“I’m sorry to trouble you”

Courtesy’s like this “oil the cogs of everyday life”

Rosette considered himself important.

PRINCIPLE 6: Make the other person feel important, and do it sincerely.

TRACK 17: Summary of 6 principles of this chapter.

TRACK 18:

Part 3: How to win people to your way of thinking.

Chapter 1. You can’t win an argument.

- You can measure the size of a person by what makes him or her angry!

PRINCIPLE 1: The only way to get the best of an argument is to avoid it

TRACK 19:
Chapter 2. A sure way of making enemies and how to avoid it.

Telling people they are wrong strikes a direct blow at their intelligence, judgement, pride, self respect. makes them want to strike back.
- you won’t make them change their minds
- you won’t alter their opinions because this hurts them
- “I’m smarter than you are — I’m going to tell you a thing or two and make you change your mind”
- that’s a challenge, arouses opposition and makes listener want to battle.
- If you’re going to prove anything don’t let anybody know it. do it so subtly, so adroitly, that nobody will feel that you are doing it.

Alexander Pope: Men must be taught as if you’d taught them not, and things unknown, proposed as things forgot.

Galileo: You can’t teach a man anything. You can only help him find it within himself.

Lord Chesterfield: Be wiser than other people if you can, but do not tell them so.

Socrates: One thing only I know, and that is that I know nothing.

Quit telling people that they are wrong.

“I may be wrong, I frequently am, let’s examine the facts”

“The mind in the making”

“my father”
“my country”
– my is a powerful-

7:00
- we like to continue to believe what we’ve always believed
- most arguments are made to go on believing as we already do.

TRACK 20:
Read about Benjamin Franklin’s autobiography.

Benjamin Franklin changes use of word “Certainly” to “I believe that…” etc.

making business proposition to bunch of bosses — couldn’t accept because you were telling someone that they are wrong. This makes you unwelcome part of discussion.

Martin Luther King:
“I judge people by their own principles, not my own”

PRINCIPLE 2: Show respect for the other person’s opinions. Never say “You’re wrong”.

TRACK 21: Chapter 3: If you’re wrong, admit it.

Dude takes a walk with his Boston bulldog without a leash or muzzle.

One day, encountered policeman in park that was itching to show his authority.

COP: “That’s against the law!”
MAN: “This little guy wouldn’t hurt anyone!”
COP: “He might! I’ll let you off, but never again.”

Later, policeman catches him again.

He beats the cop to it. “I’m sorry.”

e.g. case of a person who walked his dog in a park without a muzzle.
- week 1: caught. police officer rebukes.
- week 2: caught again, but condemns himself before police officer gets a chance to.
- result: police officer says man is being “too harsh” etc.
- police officer satisfies need to “feel important” by playing down the man’s mistake of walking dog w/o muzzle, where last week, he was considering it a great offense when the man tried to defend himself.

This tends to work with people with very high opinions of themselves and think themselves powerful.

“Isn’t it better to beat the other person to rebuking yourself?”

saying derogetory things about yourself that you know the other person is thinking/intending to say –
Likely, a generous forgiving attitude will be taken and you’ll look better.

4:00 art commissioner.
- very pick manager for art firm
- artist’s eagerness to criticise his own work
took all the fight out of the manager.

8:00 gives one a feeling of nobility and exultation to blame one’s self

Picket’s charge was the beginning of the end. The south was doomed.

Track 22:
- Michael Chaun: Chinese culture causes some problems w/ this system:
- in Chinese tradition, an older person cannot take the first step. this is a loss of face.
- When wrong, let’s admit our mistakes quickly and with enthusiasm. it is a lot more “fun” than trying to defend oneself

- “by fighting, you never get enough, but by yielding, you get more than you expected.”

PRINCIPLE 3: IF you are wrong, admit it quickly and emphatically

Track 23: Chapter 4: A drop of honey.

Woodrow Wilson: If you come at me with your fists doubled – mine will double too.

- This has Rockefeller’s attempt to create friends out of these people who hated him.

If a man is angry with you or hates you, you can’t win them to your side… unless you lead them to by being friendly to them.

Lincoln: “It is an old and true maxim that a drop of honey catches more flies than a gallon gall. So with men. If you would win a man to your cause, first convince him that you are his sincere friend. Therein is a drop of honey that catches his heart, which, say what you will, is the great high road to his reason.”

friendliness begets friendliness. was kind to striking laborours.

the sun can make you take off your coat more readily than the wind can.

PRINCIPLE 4: Begin in a friendly way

Writing good unit test cases is hard and requires you to be paying a lot of attention to catch problems.

Consider for example, this operator/ (vector division) method for a Vector class (NOT STRUCT!)

( Since class Vector is a class and not a struct, vec will be passed by reference. )


  public static Vector operator /( Vector vec, double divider )
  {
    vec.x /= divider;
    vec.y /= divider;

    return vec ;
  }

Above code to be used as in:

Vector v = new Vector( 15, 5 ) ;
Vector w = v / 5 ;

Can you see the bug?

You really have to be paying very close attention to ideas that the original programmer (frequently you) might have overlooked when developing the method.

Remember, Vector is a class, not a struct!

Here’s a naive first attempt at Unit test for the operator/ method:

    [TestMethod()]
    public void op_DivisionTest()
    {
      // make a vector and divide it by a constant
      Vector vec = new Vector( 4.92, 8 ) ;
      double d = 7.7 ;
      Vector actual = vec / d ;

      // Find what it should actually be:
      Vector expected = new Vector( 4.92/d, 8/d ) ;

      // Assert result is what you expect
      Assert.AreEqual( expected, actual );

    }

Can you see the problem? Can you see how this unit test FAILS to catch the real problem with this method?

Look again at the original operator/ method at the top of this page. The problem with the method is it mutates vec, since vec is passed by REFERENCE only and not by value (the method would be FINE if class Vector were struct Vector instead!

So, here’s the better unit test that catches this problem:

    [TestMethod()]
    public void op_DivisionTest()
    {
      // Compute a result, and find expected value as well
      Vector vec = new Vector( 4.92, 8 ) ;
      double d = 7.7 ;
      Vector actual = vec / d ;

      Vector expected = new Vector( 4.92/d, 8/d ) ;

      // Test result is what you expect:
      Assert.AreEqual( expected, actual );

      // This is "writing good unit tests".  TEST FURTHER.
      // What else should be guaranteed by this method / what
      // is the programmer to naturally assume about how the
      // method behaves and what it does to its inputs?

      // 1.  A new object, distinct instance of an object should be produced.
      Assert.AreNotSame( vec, actual ) ;

      // 2.  vec should remain unchanged from its original value
      Assert.AreEqual( vec, new Vector( 4.92, 8 ) ) ;

    }

The corrected operator/ method

For instance, here is an operator/ division method for a Vector class (NOT STRUCT!)
  public static Vector operator /( Vector vec, double divider )
  {
    Vector result = new Vector() ;

    result.x = vec.x / divider;
    result.y = vec.y / divider;

    return result ;
  }

So its easy to write crummy simple unit tests that don’t catch everything!! Unit tests aren’t catch-all.. you have to write them cleverly!

C++ is like C#, only it allows you a great deal more fine tuning than C# does.

I like how in C++:

  • its easy to create a class that has pass-by-value semantics at times, AND pass-by-reference semantics at other times. Thinking of a Matrix class.
  • Const Functions

I recently discovered you can use an implicit operator (TYPENAME) to make implicit conversions happen automatically for your custom types in C#:

public class Vector
{

  public static implicit operator string( Vector v )
  {
    return v.ToString() ;
  }

}

Now you can

Vector v = new Vector();
Console.WriteLine( v ) ;

Instead of

Vector v = new Vector();
Console.WriteLine( v.ToString() ) ;

So, at first I thought, WOW! That’s great. I’m developing a Matrix and Vector class together and its nice to be able to convert the Vector to a System.Drawing.PointF automatically, so instead of defining a property like:

public class Vector
{

  public System.Drawing.PointF PointF{ get {
    return new System.Drawing.PointF( this.x, this.y ) ;
  } }

}

For use in

Vector v = new Vector( 5, 7 ) ;
graphics.FillEllipse( v.PointF, 10 ) ;

I can now:

public class Vector
{

  public static implicit operator System.Drawing.PointF( Vector v )
  {
    return new System.Drawing.PointF( v.x, v.y ) ;
  }

}

So we could actually

Vector v = new Vector( 5, 7 ) ;
graphics.FillEllipse( v, 10 ) ;  // IMPLICIT TYPE CONVERSION
// TO POINTF NOW SUPPORTED!!

So that’s nice.

BUT.

What’s NOT NICE is what the compiler does when you define an implicit operator THAT ALSO has the == operator DEFINED FOR IT, but your class does not.

So, guess what happens if I DON’T define operator== for my Vector class, but I have the implicit operator string defined as shown above?

GUESS WHAT HAPPENS???

Vector v1 = new Vector( 5, 7 );
Vector v2 = new Vector( 5, 7 ) ;
if( v1 == v2 )  // v1 AND v2 ARE CONVERTED TO STRINGS, THEN COMPARED!!
{
}

This is AWFUL!! Instead of the compiler flagging it now, with “operator not defined for type Vector” (as it would have if we didn’t define implicit operator string), the compiler merrily compiles it!

THIS IS BAD!! Not even mentioning efficiency, in my ToString() method, there’s a round off leaving only 2 decimals! This means that 2.581 and 2.589999 are EQUAL in my program right now!!

Bad! BAD .NET!! BAD!!!!!!!!

Mine is:

public static implicit operator string( object o )
{
  ...
}

On Rotation Matrices

A common problem you come across is GIVEN a vector describing a “look” direction, HOW CAN WE MAKE A ROTATION MATRIX THAT WILL “LINE UP” WITH IT? You often want to do something like this when you have a character model that you need to rotate to line up with the direction that the character is currently facing. For example, you are writing a 3d space simulator game and you need the ship’s model to be lined up precisely with the direction the ship is facing.

It turns out, this is easy to do. So easy to do in fact, you’ll kick yourself for not having known this. But it isn’t easy to understand how it works.

So, first, let’s understand the principles of what we’re doing here in 2d, then we’ll extend our answer to 3d.

Rotating something to line up with an object in 2d

Assume you work in a world of vectors. In your 2d game, you need to have the model of your character point in the direction that he is looking.

Have: (red arrow is direction the Triangle character is looking).

But the black triangle and black arrow indicate the stock direction the model faces.

Want:

The most obvious way to solve this problem is just a 2d rotation matrix.

Matrix that rotates a point t degrees counter-clockwise:

The Triangle starts with its Heading vector pointing (1, 0). What we need to do is rotate the Heading vector 60 degrees counter-clockwise.

To make a 60 degree CCW rotation, let’s use the CCW rotation matrix, plugging in 60 degrees for the rotation we want:

So we end up with this set of numbers that promise to rotate a set of points 60 degrees counterclockwise:

Now here’s another way to get that same matrix. Are you ready?

The red vector (which points in the direction we want to face) is called the forward vector. The blue vector, we’ll simply call the side vector. ASSUME BOTH THE forward AND side vectors are UNIT VECTORS (THIS IS VERY IMPORTANT!!)

Since we know the forward vector is a unit vector and it has a 60 degree angle with the x-axis, we can express it as:
xfwd = cos( 60 )
= 0.5

yfwd = sin( 60 )
= 0.86

So a unit vector in the plane, when broken down into its x, y components, is always going to be x=cos(t), y=sin(t) where t is the angle that the vector forms with the +x axis.

The blue vector makes (90+60=150) degree angle with the +x axis. So it can be expressed as:
xperpleft = cos( 150 )
= -0.86

yperpleft = sin( 150 )
= 0.5

So, speaking in terms of the orientation we want, we have two vectors:

forward (describes direction we want to look in)=( 0.5, 0.86 )
perpleft (90 degrees counter-clockwise perpendicular to the forward vector) = ( -0.86, 0.5 )

We could also derive the perpleft vector by noticing that ( -y, x ) is always going to be a 90 degree counter-clockwise rotated perpendicular to any vector you have.

side note:
You are sure that (-y,x) is a perpendicular to (x,y) because the dot product:
(x,y)*(-y,x) = -yx + xy = 0

and so, (-y,x) is always perpendicular to (x,y).

The other way to derive this is to construct the 90 degree CCW rotation matrix and notice that it always comes out to

[ cos(90)   -sin(90) ] [ x ]
[ sin(90)    cos(90) ] [ y ]

[ 0   -1 ] [ x ] = [ -y ]
[ 1    0 ] [ y ]   [  x ]

So, look at those again:

forward: ( 0.5, 0.86 )
perpleft: ( -0.86, 0.5 )

Does that look familiar?

So we can do this:

Assuming you use column vectors and not row vectors. If you’re using row vectors, you have to transpose it.

Isn’t that neat?

This extends to 3D:

At this point, I’ll direct you to Diana Gruber’s article and leave it at that.

You know what makes me mad? System.Windows.Media.Matrix.Transform( System.Windows.Vector ) ACTUALLY IGNORES the translation component.

To get System.Windows.Media.Matrix.Transform to take into account the translation component, you have to pass it a System.Windows.Point, and NOT a System.Windows.Vector.

I want to use System.Windows.Vector for the operator overloading. So this is really inconvenient. After every transformation I have to remember to write

// vecs is an array of Vector[]
matTransform.Transform( vecs ) ;

// Microsoft dumbness:  Matrix.Transform( Vector ) does not apply
// the translation component, so we have to apply it ourselves
for( int i = 0 ; i < vecs.Length ; i ++ )
{
  vecs[ i ].X += matTransform.OffsetX ;
  vecs[ i ].Y += matTransform.OffsetY ;
}

This seems so dumb and unintuitive to me. Yes, a “vector” is being distinguished from a “point” by the idea that a vector is just a magnitude and direction without having an absolute position in space, while a “point” describes a point in space, but PRACTICALLY, this isn’t how I’d think to use it. The System.Drawing.Matrix was a lot smarter, with a System.Drawing.Matrix.TransformPoints method (correctly applies translation) AND a System.Drawing.Matrix.TransformVectors method, in case you want stupid unintuitive behavior of ignoring the translation component.

Its not even documented that this is how System.Windows.Media.Matrix behaves (they must be too embarrassed to admit it, no), you have to infer it from the old version of the documentation.

It makes me so mad because WHY WOULD I EVER want a matrix translation component not to be applied? Me, I’d simply zero out Matrix.OffsetX and Matrix.OffsetY before applying the transformation if I wanted that part to be ignored. I’m used to working in 3D where the transformation matrix is simply applied to the vectors, OBVIOUSLY applying the translation component. It just doesn’t make intuitive sense to me to have VECTORS ignore the translation component.

I see this as a HUGE defect in the library, ESPECIALLY since differing behavior is determined by OVERLOAD.. it just seems SO stupid and unintuitive. Another one for never put a sock in a toaster..

Overloads should DO THE EXACT SAME THING, only on different types of inputs. If you want functions that do different things, then do it right and write two separate functions.

How to programmatically raise an event in C#

Some say you can’t.

Other repeatedly and annoyingly say “just call the callback manually, and pass (null, null) for the args”.

Other still find the answer is YOU CAN!!

So, for a Button:

button1.PerformClick() ;

The form itself has a whole series of functions…

this.OnClick( ... );
this.OnClientSizeChanged( ... ) ;

// And
this.RaiseMouseEvent( ... ) ; // (pretty much) undocumented. nobody seems to know how to use this one!

There’s also this REALLY COMPLICATED way using Interop and the SendMessage() WinAPI function. You don’t have to go there though.

I think its time to get away from Courier New

Now I’m onto Bitstream Vera Sans Mono!

The filenames of this font are “VeraMoBd.ttf”, “VeraMoBI.ttf”, “VeraMoIt.ttf”, “VeraMono.ttf”

is it just me or does anyone else find sports talk boring?

_M_CEE_PURE

fatal error C1083: Cannot open include file: ‘wx/setup.h’: No such file or directory c:\wxwidgets-2.8.10\include\wx\platform.h 196

Solve this by adding C:\wxWidgets-2.8.10\include\msvc to your Visual Studio path settings.

Cannot open include file: ‘../../../lib/vc_lib/mswd/wx/setup.h’: No such file or directory C:\wxWidgets-2.8.10\include\msvc\wx\setup.h

“Obviously you need to build wxwidgets first”

The dsw workspace is in C:\wxWidgets-2.8.10\build\msw

Its not that hard:


using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;

using System;
using System.Runtime.InteropServices;

public class MainWindow : Form
{
  static Bitmap backbuffer;

  const int windowWidth = 640;
  const int windowHeight = 480;

  static int a = 5;

  public MainWindow()
  {
    this.ClientSize = new Size( windowWidth, windowHeight );

    // The OptimizedDoubleBuffer style has no effect due to the way
    // we control this game (drawing would have to be in OnPaint for
    // it to benefit us at all.)
    this.SetStyle( ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.Opaque, true );

    // Create the backbuffer
    backbuffer = new Bitmap( windowWidth, windowHeight );
  }

  public void Render()
  {
    Graphics g = Graphics.FromImage( backbuffer );

    // clear the background.  normally if you weren't using a
    // backbuffer, this would cause severe flicker.
    g.Clear( Color.White );

    // just draw something.  a line that moves
    a++;
    g.DrawLine( new Pen( Color.Blue, 5 ), new Point( 5, 5 ), new Point( a, 500 ) );

    // Flip the backbuffer
    Graphics gFrontBuffer = Graphics.FromHwnd( this.Handle );
    gFrontBuffer.DrawImage( backbuffer, new Point( 0, 0 ) );
  }

  // We're not painting in OnPaint().
  /* protected override void OnPaint( PaintEventArgs e ) { } */

  static void Main()
  {
    // why not to use while(Created){FullRender();Application.DoEvents();}
    //http://blogs.msdn.com/tmiller/archive/2003/11/07/57524.aspx

    // Also here are records of people burned by it (scroll to bottom)
    //http://msdn.microsoft.com/en-us/library/system.windows.forms.application.doevents.aspx

    // alternative approaches to DoEvents loop
    //http://blogs.msdn.com/tmiller/archive/2003/11/24/57532.aspx

    // Using traditional PeekMessage() loop

    // Create-up a window.
    MainWindow mw = new MainWindow();
    mw.Show();
    // (style init stuff is in its constructor)

    Win32.NativeMessage msg = new Win32.NativeMessage();

    while( true )
    {
      if( !mw.Created )
      {
        // Need this here for the application to shutdown gracefully.
        break;
      }

      if( Win32.PeekMessage( out msg, mw.Handle, 0, 0, (uint)Win32.PM.REMOVE ) )
      {
        if( msg.message == (uint)Win32.WindowsMessage.WM_QUIT )
        {
          Console.WriteLine( "QUITTING..." );
          break;
        }
        else
        {
          Win32.TranslateMessage( ref msg );
          Win32.DispatchMessage( ref msg );
        }

      }

      else
      {

        // Run the game simulation

        // Render current state
        mw.Render();

        System.Threading.Thread.Sleep( 2 );

      }

    }

    Application.Exit();

  }
}

public static class Win32
{
  // From http://www.pinvoke.net/default.aspx/user32/PeekMessage.html
  [StructLayout( LayoutKind.Sequential )]
  public struct NativeMessage
  {
    public IntPtr hwnd;
    public uint message;
    public IntPtr wParam;
    public IntPtr lParam;
    public uint time;
    public System.Drawing.Point point;
  }

  [DllImport( "user32.dll" )]
  [return: MarshalAs( UnmanagedType.Bool )]
  public static extern bool PeekMessage( out NativeMessage lpMsg, IntPtr hwnd, uint wMsgFilterMin, uint wMsgFilterMax, uint wRemoveMsg );

  public enum PM : uint
  {
    NOREMOVE = 0,
    REMOVE = 1
  }

  [DllImport( "user32.dll" )]
  public static extern bool TranslateMessage( [In] ref NativeMessage lpMsg );

  [DllImport( "user32.dll" )]
  public static extern IntPtr DispatchMessage( [In] ref NativeMessage lpmsg );

  #region all the sys metrics and WM_ windows message defs
  // from winuser.h
  /*
   * GetSystemMetrics() codes
   */
  public enum SystemMetrics : uint
  {
    SM_CXSCREEN = 0,
    SM_CYSCREEN = 1,
    SM_CXVSCROLL = 2,
    SM_CYHSCROLL = 3,
    SM_CYCAPTION = 4,
    SM_CXBORDER = 5,
    SM_CYBORDER = 6,
    SM_CXDLGFRAME = 7,
    SM_CXFIXEDFRAME = 7,/* ;win40 name change */
    SM_CYDLGFRAME = 8,
    SM_CYFIXEDFRAME = 8,/* ;win40 name change */
    SM_CYVTHUMB = 9,
    SM_CXHTHUMB = 10,
    SM_CXICON = 11,
    SM_CYICON = 12,
    SM_CXCURSOR = 13,
    SM_CYCURSOR = 14,
    SM_CYMENU = 15,
    SM_CXFULLSCREEN = 16,
    SM_CYFULLSCREEN = 17,
    SM_CYKANJIWINDOW = 18,
    SM_MOUSEPRESENT = 19,
    SM_CYVSCROLL = 20,
    SM_CXHSCROLL = 21,
    SM_DEBUG = 22,
    SM_SWAPBUTTON = 23,
    SM_RESERVED1 = 24,
    SM_RESERVED2 = 25,
    SM_RESERVED3 = 26,
    SM_RESERVED4 = 27,
    SM_CXMIN = 28,
    SM_CYMIN = 29,
    SM_CXSIZE = 30,
    SM_CYSIZE = 31,
    SM_CXFRAME = 32,
    SM_CXSIZEFRAME = 32, /* ;win40 name change */
    SM_CYFRAME = 33,
    SM_CYSIZEFRAME = 33,/* ;win40 name change */
    SM_CXMINTRACK = 34,
    SM_CYMINTRACK = 35,
    SM_CXDOUBLECLK = 36,
    SM_CYDOUBLECLK = 37,
    SM_CXICONSPACING = 38,
    SM_CYICONSPACING = 39,
    SM_MENUDROPALIGNMENT = 40,
    SM_PENWINDOWS = 41,
    SM_DBCSENABLED = 42,
    SM_CMOUSEBUTTONS = 43,
    SM_SECURE = 44,
    SM_CXEDGE = 45,
    SM_CYEDGE = 46,
    SM_CXMINSPACING = 47,
    SM_CYMINSPACING = 48,
    SM_CXSMICON = 49,
    SM_CYSMICON = 50,
    SM_CYSMCAPTION = 51,
    SM_CXSMSIZE = 52,
    SM_CYSMSIZE = 53,
    SM_CXMENUSIZE = 54,
    SM_CYMENUSIZE = 55,
    SM_ARRANGE = 56,
    SM_CXMINIMIZED = 57,
    SM_CYMINIMIZED = 58,
    SM_CXMAXTRACK = 59,
    SM_CYMAXTRACK = 60,
    SM_CXMAXIMIZED = 61,
    SM_CYMAXIMIZED = 62,
    SM_NETWORK = 63,
    SM_CLEANBOOT = 67,
    SM_CXDRAG = 68,
    SM_CYDRAG = 69,

    SM_SHOWSOUNDS = 70,
    SM_CXMENUCHECK = 71,   /* Use instead of GetMenuCheckMarkDimensions()! */
    SM_CYMENUCHECK = 72,
    SM_SLOWMACHINE = 73,
    SM_MIDEASTENABLED = 74,
    SM_MOUSEWHEELPRESENT = 75,
    SM_XVIRTUALSCREEN = 76,
    SM_YVIRTUALSCREEN = 77,
    SM_CXVIRTUALSCREEN = 78,
    SM_CYVIRTUALSCREEN = 79,
    SM_CMONITORS = 80,
    SM_SAMEDISPLAYFORMAT = 81,
    SM_IMMENABLED = 82,
    SM_CXFOCUSBORDER = 83,
    SM_CYFOCUSBORDER = 84,

    SM_TABLETPC = 86,
    SM_MEDIACENTER = 87,
    SM_STARTER = 88,
    SM_SERVERR2 = 89,
    SM_CMETRICS = 90,
    SM_REMOTESESSION = 0x1000,
    SM_SHUTTINGDOWN = 0x2000,
    SM_REMOTECONTROL = 0x2001,
    SM_CARETBLINKINGENABLED = 0x2002

  }

  public enum WindowsMessage : uint
  {
    /*
     * Window Messages
     */

    WM_NULL = 0x0000,
    WM_CREATE = 0x0001,
    WM_DESTROY = 0x0002,
    WM_MOVE = 0x0003,
    WM_SIZE = 0x0005,

    WM_ACTIVATE = 0x0006,

    WM_SETFOCUS = 0x0007,
    WM_KILLFOCUS = 0x0008,
    WM_ENABLE = 0x000A,
    WM_SETREDRAW = 0x000B,
    WM_SETTEXT = 0x000C,
    WM_GETTEXT = 0x000D,
    WM_GETTEXTLENGTH = 0x000E,
    WM_PAINT = 0x000F,
    WM_CLOSE = 0x0010,

    //#ifndef _WIN32_WCE
    WM_QUERYENDSESSION = 0x0011,
    WM_QUERYOPEN = 0x0013,
    WM_ENDSESSION = 0x0016,
    //#endif
    WM_QUIT = 0x0012,
    WM_ERASEBKGND = 0x0014,
    WM_SYSCOLORCHANGE = 0x0015,
    WM_SHOWWINDOW = 0x0018,
    WM_WININICHANGE = 0x001A,

    WM_DEVMODECHANGE = 0x001B,
    WM_ACTIVATEAPP = 0x001C,
    WM_FONTCHANGE = 0x001D,
    WM_TIMECHANGE = 0x001E,
    WM_CANCELMODE = 0x001F,
    WM_SETCURSOR = 0x0020,
    WM_MOUSEACTIVATE = 0x0021,
    WM_CHILDACTIVATE = 0x0022,
    WM_QUEUESYNC = 0x0023,

    WM_GETMINMAXINFO = 0x0024,

    WM_PAINTICON = 0x0026,
    WM_ICONERASEBKGND = 0x0027,
    WM_NEXTDLGCTL = 0x0028,
    WM_SPOOLERSTATUS = 0x002A,
    WM_DRAWITEM = 0x002B,
    WM_MEASUREITEM = 0x002C,
    WM_DELETEITEM = 0x002D,
    WM_VKEYTOITEM = 0x002E,
    WM_CHARTOITEM = 0x002F,
    WM_SETFONT = 0x0030,
    WM_GETFONT = 0x0031,
    WM_SETHOTKEY = 0x0032,
    WM_GETHOTKEY = 0x0033,
    WM_QUERYDRAGICON = 0x0037,
    WM_COMPAREITEM = 0x0039,
    WM_COMPACTING = 0x0041,
    WM_COMMNOTIFY = 0x0044,  /* no longer suported */
    WM_WINDOWPOSCHANGING = 0x0046,
    WM_WINDOWPOSCHANGED = 0x0047,

    WM_POWER = 0x0048,
    /*
     * wParam for WM_POWER window message and DRV_POWER driver notification
    #define PWR_OK              1
    #define PWR_FAIL            (-1)
    #define PWR_SUSPENDREQUEST  1
    #define PWR_SUSPENDRESUME   2
    #define PWR_CRITICALRESUME  3
     */

    WM_COPYDATA = 0x004A,
    WM_CANCELJOURNAL = 0x004B,

    /*
     * lParam of WM_COPYDATA message points to...
    typedef struct tagCOPYDATASTRUCT {
        ULONG_PTR dwData;
        DWORD cbData;
        PVOID lpData;
    } COPYDATASTRUCT, *PCOPYDATASTRUCT;
     */

    //#if(WINVER >= 0x0400)
    WM_NOTIFY = 0x004E,
    WM_INPUTLANGCHANGEREQUEST = 0x0050,
    WM_INPUTLANGCHANGE = 0x0051,
    WM_TCARD = 0x0052,
    WM_HELP = 0x0053,
    WM_USERCHANGED = 0x0054,
    WM_NOTIFYFORMAT = 0x0055,

    WM_CONTEXTMENU = 0x007B,
    WM_STYLECHANGING = 0x007C,
    WM_STYLECHANGED = 0x007D,
    WM_DISPLAYCHANGE = 0x007E,
    WM_GETICON = 0x007F,
    WM_SETICON = 0x0080,
    //#endif /* WINVER >= 0x0400 */

    WM_NCCREATE = 0x0081,
    WM_NCDESTROY = 0x0082,
    WM_NCCALCSIZE = 0x0083,
    WM_NCHITTEST = 0x0084,
    WM_NCPAINT = 0x0085,
    WM_NCACTIVATE = 0x0086,
    WM_GETDLGCODE = 0x0087,
    //#ifndef _WIN32_WCE
    WM_SYNCPAINT = 0x0088,
    //#endif
    WM_NCMOUSEMOVE = 0x00A0,
    WM_NCLBUTTONDOWN = 0x00A1,
    WM_NCLBUTTONUP = 0x00A2,
    WM_NCLBUTTONDBLCLK = 0x00A3,
    WM_NCRBUTTONDOWN = 0x00A4,
    WM_NCRBUTTONUP = 0x00A5,
    WM_NCRBUTTONDBLCLK = 0x00A6,
    WM_NCMBUTTONDOWN = 0x00A7,
    WM_NCMBUTTONUP = 0x00A8,
    WM_NCMBUTTONDBLCLK = 0x00A9,

    //#if(_WIN32_WINNT >= 0x0500)
    WM_NCXBUTTONDOWN = 0x00AB,
    WM_NCXBUTTONUP = 0x00AC,
    WM_NCXBUTTONDBLCLK = 0x00AD,
    //#endif /* _WIN32_WINNT >= 0x0500 */

    //#if(_WIN32_WINNT >= 0x0501)
    WM_INPUT = 0x00FF,
    //#endif /* _WIN32_WINNT >= 0x0501 */

    WM_KEYFIRST = 0x0100,
    WM_KEYDOWN = 0x0100,
    WM_KEYUP = 0x0101,
    WM_CHAR = 0x0102,
    WM_DEADCHAR = 0x0103,
    WM_SYSKEYDOWN = 0x0104,
    WM_SYSKEYUP = 0x0105,
    WM_SYSCHAR = 0x0106,
    WM_SYSDEADCHAR = 0x0107,
    //#if(_WIN32_WINNT >= 0x0501)
    WM_UNICHAR = 0x0109,
    WM_KEYLAST = 0x0109,
    //#define UNICODE_NOCHAR                  0xFFFF

    //#if(WINVER >= 0x0400)
    WM_IME_STARTCOMPOSITION = 0x010D,
    WM_IME_ENDCOMPOSITION = 0x010E,
    WM_IME_COMPOSITION = 0x010F,
    WM_IME_KEYLAST = 0x010F,
    //#endif /* WINVER >= 0x0400 */

    WM_INITDIALOG = 0x0110,
    WM_COMMAND = 0x0111,
    WM_SYSCOMMAND = 0x0112,
    WM_TIMER = 0x0113,
    WM_HSCROLL = 0x0114,
    WM_VSCROLL = 0x0115,
    WM_INITMENU = 0x0116,
    WM_INITMENUPOPUP = 0x0117,
    WM_MENUSELECT = 0x011F,
    WM_MENUCHAR = 0x0120,
    WM_ENTERIDLE = 0x0121,
    //#if(WINVER >= 0x0500)
    //#ifndef _WIN32_WCE
    WM_MENURBUTTONUP = 0x0122,
    WM_MENUDRAG = 0x0123,
    WM_MENUGETOBJECT = 0x0124,
    WM_UNINITMENUPOPUP = 0x0125,
    WM_MENUCOMMAND = 0x0126,

    //#ifndef _WIN32_WCE
    //#if(_WIN32_WINNT >= 0x0500)
    WM_CHANGEUISTATE = 0x0127,
    WM_UPDATEUISTATE = 0x0128,
    WM_QUERYUISTATE = 0x0129,

    WM_CTLCOLORMSGBOX = 0x0132,
    WM_CTLCOLOREDIT = 0x0133,
    WM_CTLCOLORLISTBOX = 0x0134,
    WM_CTLCOLORBTN = 0x0135,
    WM_CTLCOLORDLG = 0x0136,
    WM_CTLCOLORSCROLLBAR = 0x0137,
    WM_CTLCOLORSTATIC = 0x0138,
    //#define MN_GETHMENU                     0x01E1

    WM_MOUSEFIRST = 0x0200,
    WM_MOUSEMOVE = 0x0200,
    WM_LBUTTONDOWN = 0x0201,
    WM_LBUTTONUP = 0x0202,
    WM_LBUTTONDBLCLK = 0x0203,
    WM_RBUTTONDOWN = 0x0204,
    WM_RBUTTONUP = 0x0205,
    WM_RBUTTONDBLCLK = 0x0206,
    WM_MBUTTONDOWN = 0x0207,
    WM_MBUTTONUP = 0x0208,
    WM_MBUTTONDBLCLK = 0x0209,
    //#if (_WIN32_WINNT >= 0x0400) || (_WIN32_WINDOWS > 0x0400)
    WM_MOUSEWHEEL = 0x020A,
    //#endif
    //#if (_WIN32_WINNT >= 0x0500)
    WM_XBUTTONDOWN = 0x020B,
    WM_XBUTTONUP = 0x020C,
    WM_XBUTTONDBLCLK = 0x020D,
    //#endif
    //#if (_WIN32_WINNT >= 0x0500)
    WM_MOUSELAST = 0x020D,

    //#if(_WIN32_WINNT >= 0x0400)
    /* Value for rolling one detent */
    //#define WHEEL_DELTA                     120
    //#define GET_WHEEL_DELTA_WPARAM(wParam)  ((short)HIWORD(wParam))

    /* Setting to scroll one page for SPI_GET/SETWHEELSCROLLLINES */
    //#define WHEEL_PAGESCROLL                (UINT_MAX)
    //#endif /* _WIN32_WINNT >= 0x0400 */

    WM_PARENTNOTIFY = 0x0210,
    WM_ENTERMENULOOP = 0x0211,
    WM_EXITMENULOOP = 0x0212,

    //#if(WINVER >= 0x0400)
    WM_NEXTMENU = 0x0213,
    WM_SIZING = 0x0214,
    WM_CAPTURECHANGED = 0x0215,
    WM_MOVING = 0x0216,
    //#endif /* WINVER >= 0x0400 */

    //#if(WINVER >= 0x0400)
    WM_POWERBROADCAST = 0x0218,
    /*
    #ifndef _WIN32_WCE
    #define PBT_APMQUERYSUSPEND             0x0000
    #define PBT_APMQUERYSTANDBY             0x0001

    #define PBT_APMQUERYSUSPENDFAILED       0x0002
    #define PBT_APMQUERYSTANDBYFAILED       0x0003

    #define PBT_APMSUSPEND                  0x0004
    #define PBT_APMSTANDBY                  0x0005

    #define PBT_APMRESUMECRITICAL           0x0006
    #define PBT_APMRESUMESUSPEND            0x0007
    #define PBT_APMRESUMESTANDBY            0x0008

    #define PBTF_APMRESUMEFROMFAILURE       0x00000001

    #define PBT_APMBATTERYLOW               0x0009
    #define PBT_APMPOWERSTATUSCHANGE        0x000A

    #define PBT_APMOEMEVENT                 0x000B
    #define PBT_APMRESUMEAUTOMATIC          0x0012
    #endif
    */
    //#endif /* WINVER >= 0x0400 */

    //#if(WINVER >= 0x0400)
    WM_DEVICECHANGE = 0x0219,
    //#endif /* WINVER >= 0x0400 */

    WM_MDICREATE = 0x0220,
    WM_MDIDESTROY = 0x0221,
    WM_MDIACTIVATE = 0x0222,
    WM_MDIRESTORE = 0x0223,
    WM_MDINEXT = 0x0224,
    WM_MDIMAXIMIZE = 0x0225,
    WM_MDITILE = 0x0226,
    WM_MDICASCADE = 0x0227,
    WM_MDIICONARRANGE = 0x0228,
    WM_MDIGETACTIVE = 0x0229,

    WM_MDISETMENU = 0x0230,
    WM_ENTERSIZEMOVE = 0x0231,
    WM_EXITSIZEMOVE = 0x0232,
    WM_DROPFILES = 0x0233,
    WM_MDIREFRESHMENU = 0x0234,

    //#if(WINVER >= 0x0400)
    WM_IME_SETCONTEXT = 0x0281,
    WM_IME_NOTIFY = 0x0282,
    WM_IME_CONTROL = 0x0283,
    WM_IME_COMPOSITIONFULL = 0x0284,
    WM_IME_SELECT = 0x0285,
    WM_IME_CHAR = 0x0286,
    //#endif /* WINVER >= 0x0400 */
    //#if(WINVER >= 0x0500)
    WM_IME_REQUEST = 0x0288,
    //#endif /* WINVER >= 0x0500 */
    //#if(WINVER >= 0x0400)
    WM_IME_KEYDOWN = 0x0290,
    WM_IME_KEYUP = 0x0291,
    //#endif /* WINVER >= 0x0400 */

    //#if((_WIN32_WINNT >= 0x0400) || (WINVER >= 0x0500))
    WM_MOUSEHOVER = 0x02A1,
    WM_MOUSELEAVE = 0x02A3,
    //#endif
    //#if(WINVER >= 0x0500)
    WM_NCMOUSEHOVER = 0x02A0,
    WM_NCMOUSELEAVE = 0x02A2,
    //#endif /* WINVER >= 0x0500 */

    //#if(_WIN32_WINNT >= 0x0501)
    WM_WTSSESSION_CHANGE = 0x02B1,

    WM_TABLET_FIRST = 0x02c0,
    WM_TABLET_LAST = 0x02df,
    //#endif /* _WIN32_WINNT >= 0x0501 */

    WM_CUT = 0x0300,
    WM_COPY = 0x0301,
    WM_PASTE = 0x0302,
    WM_CLEAR = 0x0303,
    WM_UNDO = 0x0304,
    WM_RENDERFORMAT = 0x0305,
    WM_RENDERALLFORMATS = 0x0306,
    WM_DESTROYCLIPBOARD = 0x0307,
    WM_DRAWCLIPBOARD = 0x0308,
    WM_PAINTCLIPBOARD = 0x0309,
    WM_VSCROLLCLIPBOARD = 0x030A,
    WM_SIZECLIPBOARD = 0x030B,
    WM_ASKCBFORMATNAME = 0x030C,
    WM_CHANGECBCHAIN = 0x030D,
    WM_HSCROLLCLIPBOARD = 0x030E,
    WM_QUERYNEWPALETTE = 0x030F,
    WM_PALETTEISCHANGING = 0x0310,
    WM_PALETTECHANGED = 0x0311,
    WM_HOTKEY = 0x0312,

    //#if(WINVER >= 0x0400)
    WM_PRINT = 0x0317,
    WM_PRINTCLIENT = 0x0318,
    //#endif /* WINVER >= 0x0400 */

    //#if(_WIN32_WINNT >= 0x0500)
    WM_APPCOMMAND = 0x0319,
    //#endif /* _WIN32_WINNT >= 0x0500 */

    //#if(_WIN32_WINNT >= 0x0501)
    WM_THEMECHANGED = 0x031A,
    //#endif /* _WIN32_WINNT >= 0x0501 */

    //#if(WINVER >= 0x0400)

    WM_HANDHELDFIRST = 0x0358,
    WM_HANDHELDLAST = 0x035F,

    WM_AFXFIRST = 0x0360,
    WM_AFXLAST = 0x037F,
    //#endif /* WINVER >= 0x0400 */

    WM_PENWINFIRST = 0x0380,
    WM_PENWINLAST = 0x038F,

    //#if(WINVER >= 0x0400)
    WM_APP = 0x8000,
    //#endif /* WINVER >= 0x0400 */

    /*
     * NOTE: All Message Numbers below 0x0400 are RESERVED.
     *
     * Private Window Messages Start Here:
     */
    WM_USER = 0x0400
  }

  #endregion

}

Add assembly PresentationCore.

Was looking for that for 5 minutes man..

You have to override OnPaint.
I tried doing this:

using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace testnamespace
{

public class MainWindow : Form
{
  public static int a = 5 ;

  public MainWindow()
  {

    this.SetStyle( ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.Opaque, true ) ;

  }

  public void Render()
  {

    // NOT DOUBLE BUFFERED!  because
    // its not in OnPaint.
    Graphics g = Graphics.FromHwnd( this.Handle ) ;
    g.Clear( Color.White ) ;
    a++;

    g.DrawLine( new Pen( Color.Blue, 5 ), new Point( 5, 5 ), new Point( a, 500 )  );

  }

  protected override void OnPaint( PaintEventArgs e )
  {

    // THIS IS double buffered
    Graphics g = e.Graphics;

    g.Clear( Color.White );
    a++;

    g.DrawLine( new Pen( Color.Blue, 5 ), new Point( 5, 5 ), new Point( a, 500 ) );

    this.Invalidate();
    //base.OnPaint( e );
  }

  static void Main()
  {
    // why not to use while(Created){FullRender();Application.DoEvents();}
    //http://blogs.msdn.com/tmiller/archive/2003/11/07/57524.aspx

    // Also here are records of people burned by it (scroll to bottom)
    //http://msdn.microsoft.com/en-us/library/system.windows.forms.application.doevents.aspx

    // alternative approaches to DoEvents loop
    //http://blogs.msdn.com/tmiller/archive/2003/11/24/57532.aspx

    // Using traditional PeekMessage() loop

    // Create-up a window.
    MainWindow mw = new MainWindow();
    mw.Show();
    // (style init stuff is in its constructor)

    Win32.NativeMessage msg = new Win32.NativeMessage() ;

    Dictionary dic = EnumHelper.ReverseEnumLookup();

    while( true )
    {
      if( !mw.Created )
      {
        // Need this here for the application to shutdown gracefully.
        break ;
      }

      if( Win32.PeekMessage( out msg, mw.Handle, 0, 0, (uint)Win32.PM.REMOVE ) )
      {
        int msgId = (int)msg.message ;

        Console.WriteLine("MESSAGE!! " + msgId ) ;

        if( dic.ContainsKey( msgId ) )
          Console.WriteLine( "That's " + dic[msgId] ) ;
        else
          Console.WriteLine( "Unknown message!");

        if( msg.message == (uint)Win32.WindowsMessage.WM_QUIT )
        {
          Console.WriteLine("QUITTING...");
          break ;
        }
        else
        {
          Win32.TranslateMessage( ref msg ) ;
          Win32.DispatchMessage ( ref msg ) ;
        }

      }

      else
      {

        // Run the game simulation

        // Render current state
        mw.Render();

        System.Threading.Thread.Sleep( 2 );
      }

    }

    Application.Exit();

  }
}

}

But windows won’t double buffer anything you draw unless its in the OnPaint method.

I do this for win32 enums when I feel like it.

Set Visual studio find & replace to "USE: REGULAR EXPRESSIONS"

Find field:
[#]define[:b]+{WM_[A-Z]+}[:b]+{[0][x][0-9A-F]+}

Replace field:
\1 = \2,

Just like that

~page 140 of charles petzold’s Programming windows with C# has a description and example of reflection

he says that

REFLECTION is the process where

the DLL isn’t just a bunch of code. It exists with binary metadata that describes in detail the classes implemented in the file and all the fields, properties, methods and events in these classes. In fact, the C# compiler uses this information to compile programs (that’s why you ned to set the Reference files), and the reference documentation of the .NET framework is derived from this metadata.

So it makes sense that a program might be able to access this metadat at runtime, find out about the .NET classes dynamically, and even execute some methods and properties in them. This process is called reflection, and its a concept borrowed form Java.

Never Put A Sock In A Toaster

(~65:00 into the dvd)

A set of developer DUHs that I develop as I come across them in my own work

  • If you are setting some parameters that are specific to your dev machine, MARK machine specific settings with a comment //!!machine-specific. Before you try to run on another machine then, you can search for //!!mach and you will find all stuff you need to change.

    Origin is I set some parameters in an ogre app that were specific to my GPU. When I tried to run on another machine, it wouldn’t draw at all, and it said the error was coming “from ogre” (VERY generic exception). So it was a very hard bug to track down, and all the while you’re suspecting “maybe Ogre DOES have bugs”..

  • NEVER, please never, do a memset( this, 0, sizeof( SomeClass ) ) ; on any class or struct that inherits from some base class with virtual functions. You will zero out the virtual function pointers.
  • Don’t write member functions in your C++ code that mimic STL member functions. This leads to massive confusion. For example, some code I was reading recently had a class that wrapped TWO stl vectors (it needed them both internally). It them exposed 3 methods: .begin(), .end(), and .next() which were meant to help you iterate over the primary collection. The confusing part was USING this crap: was the class itself a std::vector? No. Then how/why does it have a .begin() and .end() method that looks EXACTLY as if the object WERE a vector? Second, it was confusing WHICH COLLECTION (as a user of the class) you would be iterating over. Remember the class had two collections.
  • Overloads should do the exact same thing to the inputs. For example, say you have two overloads: Matrix.Transform( Vector ) and Matrix.Transform( Point ). The only difference between Vector and Point practically is that Vector supports operator overloading.
    Now you would go and do something stupid like, I don’t know, make it so the translation elements of this matrix (third row) are ignored for Matrix.Transform( Vector ) and NOT for Matrix.Transform( Point ). No. That would be stupid and unintuitive, no? Well, that’s what Microsoft did.

    In the earlier System.Drawing namespace, (before Vector was created) they actually did this right, and provided 2 separate methods which both accepted Point only:

    TransformPoints Applies the geometric transform this Matrix represents to an array of points.
    TransformVectors Multiplies each vector in an array by the matrix. The translation elements of this matrix (third row) are ignored.
  • A math related one. If you happen to write a few matrix functions, PLEASE INDICATE WHETHER YOU ARE PREMULTIPLYING OR POSTMULTIPLYING vectors. Its important. If you created a matrix and intended it to be postmultiplied by a vector, but find out that the library wants to pre-multiply by the vector, you can just transpose your matrix before doing the multiply.
  • When working with angles that you increment (for example, you’re writing something with a spinny thing that goes round and round, with ever-increasing theta), make sure that the angle doesn’t get too big. In fact, its a good idea to regularly just

    // keep theta comfortably between -2*PI and 2*PI
    if( theta > 2*PI ) { theta -= 2*PI ; }
    else if( theta < -2*PI ) { theta += 2*PI ; }
    

    I once had a program that didn’t do this, and when theta got HUGE, the variable got corrupted and the graph looked REALLY weird. I saw the graph was fine, fine, fine, then sometime later it got twisted..

    so the problem was, theta was too big (duh!)

  • If you change the members of a structure or class, IMMEDIATELY UPDATE THE COPY CTOR OR PUT AN ASSERT IN THERE!
  • CHECK THE HRESULT OF EVERY COM OPERATION, NO MATTER WHAT, ALWAYS. A SMALL change can completely fuck up a perfectly good piece of code, and the COM failure can have happened literally HUNDREDS of lines of code before the symptom.
    ALWAYS check, and ALWAYS log the result, if not crash out and bail on fail.
  • Avoid stack allocated struct returns.

    For example, say you have a function

    STRUCT_TYPE initStruct()
    {
      STRUCT_TYPE t ;
      // .. do stuff
      return t ;
    }
    

    Then you call this by

    STRUCT_TYPE myStruct = initStruct() ;
    

    This is BAD because the return is by value. This means that the return t; statement:

    • Returns a COPY of t, and that is assigned to myStruct in the calling function
    • Then, DESTROYS t, invoking its destructor

    THIS IS BAD NEWS. Say STRUCT_TYPE has a destructor like:

    ~STRUCT_TYPE
    {
      delete[] array ;
    }
    

    Then what happens is, even though your returned a copy of STRUCT_TYPE, its internals might have been destroyed by the destructor call.

    So, write functions like this instead:

    void initStruct( STRUCT_TYPE & t )
    {
      // .. do stuff to t
    }
    

    Or:

    void initStruct( STRUCT_TYPE * t )
    {
      // .. do stuff to t
    }
    

    Or

    STRUCT_TYPE* initStruct()
    {
      STRUCT_TYPE * t = new STRUCT_TYPE ;
      // .. do stuff
      return t ;
    }
    
  • The first 2 examples don’t care how t is allocated, all they care is that t is allocated by the caller, so initStruct doesn’t decimate it when it returns and its scope ends.

    The last example heap allocates a STRUCT_TYPE object, so no destructor is invoked when t goes out of scope.