J2i.Net

Nothing at all and Everything in general.

Avoiding Tight Hardware Coupling

As a Software Engineer I'm interested in how tightly coupled that one piece of code is to another. Coupling is the amound of dependencies that one entity has on another and tightly coupled code tends to be less portable and adaptable. But the concept of coupling doesn't stop at software. Coupling is also applicable to the relationship between hardware and software and I'm interested in avoiding tight coupling between the hardware and software for my code too.

With real implementations of Windows Phone 7 devices floating around it would be easy for some one to attempt to write an application that is tightly couple to that implementation. In some cases these low risk associated with doing this; for example if one tightly couples to screen resolutions (and there will only be two screen resolutions) it could be some time before some one needs to address another screen resolution. I'm writing a piece of code that is going to be sensative to the sampling rate of the accelerometer. And easy but tightly coupled way to handle this would be to measure the sample rate of the accelerometer and then write my code accordingly. But if I do this then I assume quite a few things. I would be assuming that other phones have the same sample rate. I would assume that the same phone will always have the same sample rate. I don't know that either of these assumptions are true.

The time information returned in the from DateTime.Now is precise enough for me to perform the measurements that I needed. So I wrote a quick application that would measure the accelerometer sample frequency and display it in a text box.

Here is my initial code

       private Accelerometer _accelerometer;

        // Constructor
        public MainPage()
        {
            InitializeComponent();
            this.DataContext = this;

            _accelerometer = new Accelerometer();
            _accelerometer.ReadingChanged += new EventHandler(_accelerometer_ReadingChanged);
            _accelerometer.Start();
        }

        void _accelerometer_ReadingChanged(object sender, AccelerometerReadingEventArgs e)
        {
            DateTime previousUpdate = LastUpdate;
            LastUpdate = DateTime.Now;
            double period = LastUpdate.Subtract(previousUpdate).TotalSeconds;
            double frequency = 1.0/period;
            if (frequency > HighestFrequency)
                HighestFrequency = frequency;

        }

        
// LastUpdate - generated from ObservableField snippet - Joel Ivory Johnson
  private DateTime _lastUpdate;
  public DateTime LastUpdate
  {
    get { return _lastUpdate; }
      set
      {
          if (_lastUpdate != value)
          {
              _lastUpdate = value;
              OnPropertyChanged("LastUpdate");
          }
      }
  }
 //-----      
// HighestFrequency - generated from ObservableField snippet - Joel Ivory Johnson
  private double _highestFrequency;
  public double HighestFrequency
  {
    get { return _highestFrequency; }
      set
      {
          if (_highestFrequency != value)
          {
              _highestFrequency = value;
              Dispatcher.BeginInvoke(() => { OnPropertyChanged("HighestFrequency"); });
            
          }
      }
  }
 //-----


        void OnPropertyChanged(string propertyName)
        {
            if(PropertyChanged!=null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

        #endregion
    }

Ofcourse there may be those that are curious as to what value a real device will currently returned. Of course publishing that type of information could result in more tightly coupled code being written. I'll post more once the code I am writing is done.

Fun vs Productivity

An off subject observation.  In looking over my CodeProject articles I can't help but notice a trend. If I write something that is of productive value (EX: Windows Mobile development without Visual Studio)it seems to get good ratings over time. But if I write something with no apparent productive values (like the Zune HD Level article) it gets ratings at a faster rate. What does that mean?  It sounds like it means people are more interested in articles about fun things than productive things.  I may take this into consideration in mu future articles. It's already influenced the direction of my next article.

Resources for Getting Started with Windows Mobile Development

If you are just getting started with Windows Mobile development then you will want to check out a page that Mike Francis has posted on his site.  It gives a a rather complete list of software you'll need/want, community resource, example code, guidance documents and other resources to get you started.  Check it out at http://blog.mjfnet.com/blog/FormatPage.aspx?path=content/projects/resources/resources.format.html

DirectDraw code Posted, Uses Samsung Windows Mobile SDK

I posted a code sample on CodeProject a few moments ago.  It is a remake of a simple game.  Best of all if the game is run on a compatible Samsung device it will take advantage of the hardware via the Samsung Mobile SDK. For more information see the article at the following link:

http://www.codeproject.com/KB/mobile/WiMoBubblePuzzle.aspx

Creating a High Performance Message Loop

I've heard criticisms of the Windows and Windows Mobile environment because of the way that the default message pump is implemented and the performance cap that it puts on applications that require constant refreshing of the UI (such as games).  The problem is that the default message pump is geared towards business applications and minimizing CPU usage.  If you need to make a high performance application or game then you should use a different message pump implementation. You should not be waiting on WM_PAINT message.  You should just go ahead and repaint the screen.   Given that many developers will never alter the default message pump implementation it is preferable to have one that has low CPU usage by default.  If you want to do performance graphics you need a loop similar to the following:

	
bool keepRunning = true;
while(keepRunning)
{
	if(PeekMessage(&msg,NULL,0,0,TRUE))
	{
		if(msg.message==WM_QUIT)
			keepRunning=false;
		if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) 
		{
			TranslateMessage(&msg);
			DispatchMessage(&msg);
		}
	}
	else
	{
		//Execute Game Logic Here and rendering here
	}
}

The default message pump handling would be blocked when there are no messages to process and the WM_PAINT message (being low priority) would always be the last thing on the queue. In the message pump above the application will be able to concentrate on the game logic and give attention to messages on the queue when they arrive.  We'll talk about  other things that you would need to do for a game in coming posts.

Unsuccessfully Attempting to Identify the DirectDraw Driver

In my experience identifying the DirectDraw driver on the device is difficult to impossible.  According to documentation the IDIRECTDRAW::GetDeviceIdentifier method should be used to retrieve the driver information.  At the time that I am writing this the Windows Mobile 6 documentation shows that this method has one parameter of type  LPDDDEVICEIDENTIFIER.  But when you try to use the method you’ll find there is a second parameter needed of type DWORD.  When I first came across this I was a little confused because there was no mention of it in the documentation.  But I finally came across documentation for Windows CE 3.0 that mentioned the second parameter as being a flag and DDGDI_GETHOSTIDENTIFIER was the only possible value.  I tried to use the flag but then I found that it wasn’t defined in my header file.  After a bit of searching on the Internet I found this flag has a value of one.  I added a conditional #define to my source code.  It is conditional so that if I ever do get a correct header file it won’t break my code with redundant definitions.

#ifndef DDGDI_GETHOSTIDENTIFIER
#define DDGDI_GETHOSTIDENTIFIER 0x00000001L
#endif

I ran my code an error informing me that the argument was invalid.  I considered the possibility that 1 wasn’t the correct value. So I tried calling the function in a for loop testing out all possible values.  For the value of 0 I received  E_NOTIMPL. For all other values I received E_INVALIDARG.  As a final test I ran this against an emulator image with identical results.  So as far as I am concerned this method cannot be called in confidence.

Windows Mobile Graphic APIs

I recent had to take into consideration the APIs available in Windows Mobile for something I was working on recreationally. As per usual I added my notes and conclusions to my OneNote notebook and thought I would share some of it for those that may need to look up the same information.

GDI A moderate to slow speed performer with wide compatibility.
GDI+ Successor of GDI. GDI+ adds gradients, complex paths, and uses ARGB to represent color.
Imaging API for manipulating Images and manipulating them, but slow.
GAPI An API now officially dead as of WM6.5. Predates DirectX. Nothing more of it will be said here.
DirectDraw Gives extremely fast access to imaging surface. Targets low level operations. Centered around bit blting.
Direct3D Gives access to 3D display hardware and provides emulation where hardware isn’t available. Potentially high performing, though some OEMs use improper/slow implementation. HTC historically installed an improper version of Direct3D on their devices
DirectShow API for handling video and audio streams
OpenGL ES Platform independent graphic API. May or may not be present on your Windows Mobile device. If you use this be prepared to provide an implementation to the target device.

I think I may have to go through all of these APIs and write a general introduction like what I did for Windows Mobile Power Management.

 

Identifying your Direct3D Driver

I had the need to identify the driver being used in a set of Windows Mobile devices a little earlier and have a very simple program for doing so.   I grabbed some code that Mark Prentice had written to do so. Getting the string that identifies the driver is a couple of lines of code.

AdapterListCollection al = Manager.Adapters;
string driver = al.Default.Information.DriverName.ToString();

If you run this code the one thing you want to watch out for is a driver named "d3dmref.dll".  If you have this driver then that means you OEM didn't create/license a driver for your device and the graphics will render in seconds per frame.

 

Samsung Lab.dev Open to the public

Samsung's Lab.dev has come out of beta.  What is Lab.dev?  It is a service offered by samsung that allows you to test your code on real Windows Mobile hardware remotely.  If you don't have a physical device but wanted to see how your code would behave on a Somsung device this is the perfect way to test out your software if you can't afford to purchase multiple physical devices. For more information see http://bit.ly/ds8gN or open up a Samsung Mobile Innovator account at http://innovator.samsungmobile.com