## Monday, May 25, 2009

### An Oscar Algorithm - Silverlight Real-time 3D Perlin Noise

Perlin Noise is a computer graphics algorithm, which is widely used in computer games and movies as a visual effect. It was developed by Ken Perlin in the early 1980's and was used in the movie TRON. In 1997 Perlin received a Technical Achievement Award from the Academy of Motion Picture Arts for his work. So Perlin Noise is an Oscar-winning algorithm and I'm pretty sure almost everyone has seen it before.
Perlin Noise could produce pseudo-random semi-natural textures with fractal characteristics and is mostly used for procedural image generation. The algorithm can be controlled with various parameters and is able to produce good looking cloud / sky, fire, smoke, wood or marble textures and height maps, just to name a few.
In short, the Perlin Noise algorithm generates random noise functions with various frequencies and amplitudes, sums them up and smoothes the result. I don't want to bore you with more mathematical details, which were already explained several times on the web. If you are interested, I refer you to the Wikipedia article and the link section, Ken Perlin's site and to this excellent explanation.

Live
My Silverlight implementation is the three dimensional improved Perlin Noise algorithm.

The initial Frequency and the Amplitude of the noise function can be changed. The Octaves parameter defines how many iterations of the noise function are summed up. Like in music the frequency is doubled in every subsequent octave. The Persistence controls how much the amplitude changes after each iteration. Press the Randomize button to reinitialize the noise function with new pseudo-random seeds.

How it works
The Perlin Noise computing loop:
```for (int i = 0; i < this.Octaves; i++)
{
noise += Noise(x * freq, y * freq, z * freq) * amp;
freq  *= 2;
amp   *= Persistence;
}
```

Each frame the Perlin Noise for every pixel of the 2D destination image is computed in real-time and is used as the alpha value for blending the noise color over the base color, then the z-value is increased. The noise's third dimension, the z-value, is actually used as time for the animation. So each frame the next slice of the 3D noise cube is computed and shown, thus resulting in a smooth animation.
For the source of the destination image the great RawPngBufferStream from the open source GameEngine Balder is used.
```int off = 0;
for (int y = 0; y < bufferStream.Height; y++)
{
for (int x = 0; x < bufferStream.Width; x++)
{
float a = perlinNoise.Compute(x, y, perlinZ);
float ai = 1 - a;
bufferStream[off + aOff] = (byte)(a * noiseColor.A + ai * baseColor.A);
bufferStream[off + rOff] = (byte)(a * noiseColor.R + ai * baseColor.R);
bufferStream[off + gOff] = (byte)(a * noiseColor.G + ai * baseColor.G);
bufferStream[off + bOFF] = (byte)(a * noiseColor.B + ai * baseColor.B);
off += 4;
}
off++;
}
if (Chk3D.IsChecked.Value)
{
perlinZ++;
}
imgSource.SetSource(bufferStream);
```

Source code
You can download the Silverlight 2 version here. Feel free to use or modify it as you like. If you do so please drop me a line, because I'm curious to know where (you want to) use it. Have fun!

Update 07-26-2009
I updated the project to Silverlight 3. Now it uses the WriteableBitmap instead of Balder's RawPngBufferStream. You can download the updated Visual Studio 2008 solution from here.

## Friday, May 22, 2009

### Silverlight 2 Real-time Physics Website

It's been 5 years since I developed my previous website in 2004 with Macromedia (Adobe) Flash. A couple of months ago I decided to work on a makeover, which was long overdue. As a media & computer scientist and .Net developer it was a matter of course to give Microsoft's Silverlight 2 a try. I love the ability to write the code in my favorite language C# and having most functionality of the .Net library at hand.

Lightning it up
However, the first Show Stopper was the lack of basic HTML or rich text support in Silverlight 2. I was quite surprised and disappointed that Silverlight Text controls don't provide basic HTML formatting or at least WPF's Inline Hyperlink. I think a lot of people need such a feature. Some guys on Twitter told me that there isn't really a demand for this and it could be done with other techniques, but sometimes performance does matter and an overlayed DIV using Silverlight's windowless mode is just terribly slow.
HTML Link support is essential for this project, because the HTML formatted text is stored in XML files and loaded asynchronously by the ContentPages and then deserialized to POCOs. The controls in turn use Silverlight's great Data Binding mechanism to present the data and load the images.
This XML-based approach gives me the ability to change the content of my site without any recompilation. I also have a fallback solution for non-Silverlight visitors and all that without a redundand information storage. Non-Silverlight visitors could use the POH (Plain Old HTML) version, which is simply the XSL transformation of the underlying XML data. And there's another advantage: If I ever decide to store the data in a database, I just need to change the internal functionality of the data assembly and integrate an ORM framework like NHibernate. The domain models and therefore the DataBinding won't be touched.
My Silverlight website uses the Dependency Injection framework NInject. The whole project, including the physics engine, is developed keeping a contract first design in mind. The usage of the DI pattern and a appropriate framework helps a lot to separate the concerns and produce code with a high maintainability.

As I mentioned earlier I was really annoyed by the lack of HTML support in Silverlight and it forced me to extend the Silverlight LinkLabel Control so it supports HTML tags. I was also able to improve the performance of it. TextBlock's performance is still bad, but that's not the fault of the LinkLabel control.
Here is how it works: The original LinkLabel control "parses" the input text and creates a HyperlinkButton for each of the links it founds. The rest of the text is splitted into single words and for each word (!) a TextBlock is created. These many controls are then all added to a WrapPanel, which provides the word wrapping functionality.
I measured the LinkLabel control and encountered that the high number of TextBlocks are killing the performance. Therefore I extended the LinkLabel control by a word grouping functionality. Single words are now grouped to n words and assigned to one TextBlock. This modification reduced the number of TextBlocks and in turn increased the performance significantly. However, a lot of text has still a huge negative impact on the performance. So please Microsoft, implement WPF's Inline Hyperlink into Silverlight. WPF is a desktop technology and has the Inline Hyperlink, but Silverlight as a subset of WPF and RIA platform doesn't come with Inline Hyperlink?! I don't get it.

Soft Body Physics Engine

With my passion for computer graphics and physical simulations it was also a must that my new website simulates real-time physics. That's why I developed a flexible Silverlight soft body physics engine and a simple Renderer. The soft body physic is based on a Newtonian mass-spring system and also implements the Pressure Soft Body Model by Maciej Matyka. The resulting differential equations are solved numerically with a Verlet integration. The engine is flexible designed and could easily be extended. It comes with a constraint system, various types of bodies and force generators, basic collision detection and so on.
The work on the engine is in progress and there's still a lot to be done, but if you want to see it in action, just go to my website click near the balloon and throw it around or grab a corner of the content element. If I find the time, I will continue my work on the engine, hack some demos, release it as open source and blog about it. But I demand high standards of myself and I currently have other projects in the queue, so don't expect a release soon. Especaillay the implemented collision detection is just basic and the development of a proper collision detection system takes some time.

Conclusion

It was a long and tricky task for my first Silverlight and XAML project, but
mostly it was a lot of fun and Silverlight 2 is an awesome step in the right direction. I don't regret that decision. Silverlight is definitely now my favorite platform.

Update 08-07-2009

I submitted my website to the Summer Silverlight Coding Competition. Feel free to vote for it here.

## Thursday, May 21, 2009

### Silverlight Logging Extension Method

Most of you will know that a Silverlight application runs in the Browser and Console.WriteLine() doesn’t work. During the development process you could use System.Diagnostics.Debug.WriteLine() to write messages to Visual Studio’s Output window. But what if an application is deployed and no Visual Studio is nearby and you just want simple Console output and not a logging framework like Clog, where a web service is involved? Or don’t want to use Visual Studio’s Output window?

The answer is simple if you are using Firefox with the Firebug add-on or Internet Explorer 8: Use the console.log mechanism and write your debug output to the Browser’s debug console.

Here's a simple extension method, which logs an object to the console.log:

```public static void Log(this object obj)
{
HtmlWindow window = HtmlPage.Window;
var isConsoleAvailable = (bool)window.Eval("typeof(console) != 'undefined' && typeof(console.log) != 'undefined'");
if (isConsoleAvailable)
{
var console = (window.Eval("console.log") as ScriptObject);
if (console != null)
{
console.InvokeSelf(obj);
}
}
}
```

How to you use it:
```"Hello Universe!".Log();
int a = 42;
a.Log();
String.Format("The answer to all questions is {0}.", a).Log();
```

And that's how the
debug output looks within Firebug:

## Wednesday, May 20, 2009

### Better late than never…

I know I'm late to the game, but I think I'm at a point where I have something to share with the .Net community.
This blog will especially focus on .Net, C# and Silverlight software development and (Microsoft) technology in general. Nothing special you may think, but I also have a passion for algorithms, computer graphics and physical simulations and therefore I always try to implement nice algorithms using modern software development technologies. If you are interested in my previous projects, please visit my website.

You might ask why I have chosen Blogger / Blogspot as platform. It’s easy to use, the setup was smooth, it's free and not over-featured and I don't need super styled Themes. Not at least I could use my Google account. However I was a bit disappointed that Blogger has no integrated syntax highlighting, but I have seen other Google blogs with highlighted syntax. If you have any tips for me, I would appreciate it if you could drop a line in the comments or contact me in another way.

OK, enough for the first introductory post. In the next post I will write about a Silverlight topic.
Let the journey
begin...

Photo by Jayme Frye

## Tuesday, May 19, 2009

### Impressum und Disclaimer

Deutsch

Dies ist eine private Website, welche die Inhalte hauptsächlich in englischer Sprache bereitstellt.
Sie wird betrieben von René Schulte aus Dresden, Deutschland.
Wenn Sie weitere Informationen benötigen, kontaktieren Sie mich bitte über meine Website http://rene-schulte.info

English

This is a private website. The content is primarily written in English.
It is operated by René Schulte from Dresden, Germany.

Disclaimer - rechtliche Hinweise

1. Haftungsbeschränkung

Die Inhalte dieser Website werden mit größtmöglicher Sorgfalt erstellt. Der Anbieter übernimmt jedoch keine Gewähr für die Richtigkeit, Vollständigkeit und Aktualität der bereitgestellten Inhalte. Die Nutzung der Inhalte der Website erfolgt auf eigene
Gefahr des Nutzers. Namentlich gekennzeichnete Beiträge geben die Meinung des jeweiligen Autors und nicht immer die Meinung des Anbieters wieder. Mit der reinen Nutzung der Website des Anbieters kommt keinerlei Vertragsverhältnis zwischen dem Nutzer und dem Anbieter zustande.

Diese Website enthält Verknüpfungen zu Websites Dritter ("externe
Links"). Diese Websites unterliegen der Haftung der jeweiligen
Betreiber. Der Anbieter hat bei der erstmaligen Verknüpfung der
externen Links die fremden Inhalte daraufhin überprüft, ob etwaige
Rechtsverstöße bestehen. Zu dem Zeitpunkt waren keine
Rechtsverstöße ersichtlich. Der Anbieter hat keinerlei Einfluss auf
die aktuelle und zukünftige Gestaltung und auf die Inhalte der
verknüpften Seiten. Das Setzen von externen Links bedeutet nicht,
dass sich der Anbieter die hinter dem Verweis oder Link liegenden
Inhalte zu Eigen macht. Eine ständige Kontrolle dieser externen
Links ist für den Anbieter ohne konkrete Hinweise auf
Rechtsverstöße nicht zumutbar. Bei Kenntnis von Rechtsverstößen
werden jedoch derartige externe Links unverzüglich gelöscht.

3. Urheber- und Leistungsschutzrechte

Die auf dieser Website veröffentlichten Inhalte unterliegen dem deutschen Urheber- und Leistungsschutzrecht. Jede vom deutschen Urheber- und Leistungsschutzrecht nicht zugelassene Verwertung bedarf der vorherigen schriftlichen Zustimmung des Anbieters oder jeweiligen Rechteinhabers. Dies gilt insbesondere für Vervielfältigung, Bearbeitung, Übersetzung, Einspeicherung, Verarbeitung bzw. Wiedergabe von Inhalten in Datenbanken oder anderen elektronischen Medien und Systemen. Inhalte und Rechte Dritter sind dabei als solche gekennzeichnet. Die unerlaubte Vervielfältigung oder Weitergabe einzelner Inhalte oder kompletter Seiten ist nicht gestattet und strafbar. Lediglich die Herstellung von Kopien und Downloads für den persönlichen, privaten und nicht kommerziellen Gebrauch ist erlaubt.

Die Darstellung dieser Website in fremden Frames ist nur mit schriftlicher Erlaubnis zulässig.

4. Datenschutz

Durch den Besuch der Website des Anbieters können Informationen
über den Zugriff (Datum, Uhrzeit, betrachtete Seite) gespeichert werden. Diese Daten gehören nicht zu den
personenbezogenen Daten, sondern sind anonymisiert. Sie werden
ausschließlich zu statistischen Zwecken ausgewertet. Eine
Weitergabe an Dritte, zu kommerziellen oder nichtkommerziellen
Zwecken, findet nicht statt.

Der Anbieter weist ausdrücklich darauf hin, dass die
Datenübertragung im Internet (z.B. bei der Kommunikation per
E-Mail) Sicherheitslücken aufweisen und nicht lückenlos vor dem
Zugriff durch Dritte geschützt werden kann.

Die Verwendung der Kontaktdaten des Impressums zur gewerblichen Werbung ist ausdrücklich nicht erwünscht, es sei denn der Anbieter hatte zuvor seine schriftliche Einwilligung erteilt oder es besteht bereits eine Geschäftsbeziehung. Der Anbieter und alle auf dieser Website genannten Personen widersprechen hiermit jeder kommerziellen Verwendung und Weitergabe ihrer Daten.

5. Besondere Nutzungsbedingungen

Soweit besondere Bedingungen für einzelne Nutzungen dieser Website
von den vorgenannten Nummern 1. bis 4. abweichen, wird an
entsprechender Stelle ausdrücklich darauf hingewiesen. In diesem
Falle gelten im jeweiligen Einzelfall die besonderen
Nutzungsbedingungen.