(X) Hide this
• Join
• Generate New Image

Simulating rain in Silverlight

Lazar Nikolov
Joined Dec 15, 2010
Articles:   7
More Articles
12 comments   /   posted on Mar 14, 2011
Tags:   lazar-nikolov
Categories:   Gaming , General , Design

Introduction

In this article I will try to simulate rain in Silverlight application that can be programmatically configured to meet your expectations. Although Silverlight at the time being is very CPU consuming, rain effect may be a common challenge for a developer or designer.

I believe that there are many computer graphics techniques, such as Particle system, to simulate realistically processes that involve tiny particles interacting with each other. However, in this article I will show you how to simulate rain with almost no effort with some very simple algorithm.

Here is a little demo and source code of what we will have done at the end in just a few minutes:

View live demo - with a small amount of raindrops to avoid performance issues

Also check the second part of this series - "Simulating rain in Silverlight Part 2 - Optimization"!

The idea

Before looking at the algorithm, let me make the main flow clear. As I wrote a few lines above, the designer adjusts programmatically the rain on his own. That is – the height and width of the scene, the interval of falling drops and the amount of drops animated at a time. This all is achieved with a couple of classes that form the rain nature:

• Drop – holds the drop view
• DropSettings – describes a drop and its settings; currently only the height that the drop pours is implemented; this act as a view-model as I use it to bind in the drop view when animating the motion from top to bottom part of the scene
• Rain – this is my main object to maintain the rain process; it uses a simple algorithm, I will next describe, to simulate drops falling randomly through scene

The algorithm

Now it’s time for the algorithm. It, actually, is really very simple one. What determines the average rain? Yes, you are right and this is what I was looking for – direction and intensity.

First, to simulate the rain, we need to perform the algorithm exactly as many times, as we had previously defined to be the amount of drops to fall simultaneously. Furthermore, this should be done exactly as many times as we have specified to be the interval between the raindrops.

`for` `(``int` `i = 0; i < ``this``.DropsPerInterval; ++i)`
`{`
`}`

To distinguish between UI elements in the scene, when constructing the Rain object, a canvas is specified, and this panel is where the rain will be simulated in. Every drop that we create should be a child of this panel.

`Drop drop = ``new` `Drop(``this``.DropSettings);`
`this``.Scene.Children.Add(drop);`

Next step is to generate the depth in which the drop is shown in the scene. Depth visually controls the scale and further you go deep in the scene, drops become smaller.

`double` `depth = rand.NextDouble();`
`drop.RenderTransform = ``new` `ScaleTransform`
`{`
`    ``ScaleX = depth,`
`    ``ScaleY = depth,`
`};`

The direction of the rain affects directly on the angle which drops fall the ground in. In the demo this angle is fixed to be between 0 and 10 degrees clockwise rotation.

`double` `angle = rand.NextDouble() * 10;`
`drop.LayoutRoot.RenderTransform = ``new` `RotateTransform`
`{`
`    ``Angle = angle,`
`};`

So far we had spread the drops randomly in depths and directions between 0 and 10 degrees. To put the finishing touches, we need to randomly scatter the raindrops in the two dimensional perspective of the scene.

`drop.Margin = ``new` `Thickness(Convert.ToInt32(rand.NextDouble() * ``this``.Width), 0, 0, 0);`

This will set gratuitously from 0 to the right most corner the gap between the drop and most left corner.

Finally, the last thing to do is to start the animation.

`drop.Animate();`

That's it!

Designing the drop

To design the raindrop view I use Expression Blend. Here is the XAML for it (for clarity I have omitted the Data attribute):

`<``Path` `Stretch``=``"Fill"` `Data="...``" ``VerticalAlignment``=``"Stretch"` `RenderTransformOrigin``=``"0.5,0.5"`
`    Margin``=``"1.222,-2.518,-4.94,-7.559"` `UseLayoutRounding``=``"False"` `>`
`    ``<``Path.Fill``>`
`        ``<``LinearGradientBrush` `EndPoint``=``"1.420529961586,0.976535022258759"`
`            ``StartPoint``=``"0.331510990858078,0.976535022258759"``>`
`            ``<``LinearGradientBrush.RelativeTransform``>`
`                ``<``TransformGroup``>`
`                    ``<``SkewTransform` `AngleY``=``"0"` `AngleX``=``"17.4704"` `CenterY``=``"0.976535"` `CenterX``=``"0.331511"``/>`
`                    ``<``RotateTransform` `Angle``=``"-61.3206"` `CenterY``=``"0.976535"` `CenterX``=``"0.331511"``/>`
`                ``</``TransformGroup``>`
`            ``</``LinearGradientBrush.RelativeTransform``>`
`            ``<``GradientStop` `Color``=``"#FE739EAD"``/>`
`            ``<``GradientStop` `Color``=``"#FFD3E9F9"` `Offset``=``"1"``/>`
`        ``</``LinearGradientBrush``>`
`    ``</``Path.Fill``>`
`</``Path``>`

It is nothing more than a path with some gradient brush on it. This results in the following, magnified about 20 times:

To simulate the drop falling I use a storyboard that:

1. animates the height the drop is in each moment
2. animate the visibility to collapsed when the desired height is reached, that is the drop has fallen through the whole scene
`<``Storyboard` `x:Name``=``"Pour"``>`
`    ``<``DoubleAnimationUsingKeyFrames` `BeginTime``=``"00:00:00"` `Storyboard.TargetName``=``"drop"`
`Storyboard.TargetProperty``=``"(UIElement.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.Y)"``>`
`        ``<``SplineDoubleKeyFrame` `KeyTime``=``"00:00:00"` `Value``=``"0"``/>`
`        ``<``SplineDoubleKeyFrame` `KeyTime``=``"00:00:00.6"` `Value``=``"{Binding FallHeight}"``/>`
`    ``</``DoubleAnimationUsingKeyFrames``>`
`    ``<``ObjectAnimationUsingKeyFrames` `BeginTime``=``"00:00:00"` `Storyboard.TargetName``=``"drop"`
`Storyboard.TargetProperty``=``"(UIElement.Visibility)"``>`
`        ``<``DiscreteObjectKeyFrame` `KeyTime``=``"00:00:00.6"` `Value``=``"Collapsed"` `/>`
`    ``</``ObjectAnimationUsingKeyFrames``>`
`</``Storyboard``>`

To obtain the scene height I use binding to the DropSettings object that is injected in the constructor when the raindrop is created.

Let’s start raining!

This was all you need to simulate rain. To actually start it you have to call the classes we created in a manner that satisfies our expectations.

`DropSettings dropSettings = ``new` `DropSettings(300);`
`Rain rain = ``new` `Rain(dropSettings, ``this``.Scene, 40, 3, 400);`
`rain.Start();`

Conclusion

Although Silverlight is still very CPU consuming, in this article I’ve shown you how to use a simple algorithm to simulate rain. For all that we still should not expect miracles when it comes to real time particle simulations. But I hope soon we shall have what we wish to make our application look and behave really realistic.

Lazar Nikolov is a software developer at CompletIT - the company behind SilverlightShow.net and leader in Silverlight related technologies in Bulgaria. His main interests are focused on Silverlight rich applications and Windows Phone 7 development.

In addition to authoring Silverlight articles (his series on ‘Simulating rain in Silverlight’ became one of the most popular articles on SilverlightShow!), Lazar is involved in the verification of all SilverlightShow articles, making sure that all content is consistent and in-line with the latest Silverlight/WP7 release updates.

• RE: Simulating rain in Silverlight

posted by Carsten on Mar 14, 2011 16:18

Hi,

IMHO the (rather poor) performance in this situation demands a solution without all those storyboards.

I think you can use a storyboard to get the real-time timer support and do the animation yourself.

• RE: Simulating rain in Silverlight

posted by Andy Beaulieu on Mar 14, 2011 16:36
Adding CacheMode="BitmapCache" to the drops, and EnableGPUAcceleration to the plug-in parameters, will leverage the GPU and should greatly increase performance.
• RE: Simulating rain in Silverlight

posted by Jeric on Mar 25, 2011 14:09
It seems there's a memory leak.  The memory consumption just keeps going up while the silverlight page is open. :-S
• RE: Simulating rain in Silverlight

posted by lnikolov on Mar 25, 2011 14:30

Hi, thank you for your interest in the article.

The demo needs some optimization and I really appreciate your comments, they will definitely save me some effort. This article is part 1 from a series directed in simulating natural effects in Silverlight. The next one is meant to improve this one since it really needs some polishing while describing only a simple algorithm and being simple, in general, also implies imperfection.

• Re: Simulating rain in Silverlight

posted by on May 11, 2013 09:43
thanks for sharing cat houses
• Re: Simulating rain in Silverlight

posted by Yui234 on Feb 13, 2015 16:01
• Re: Simulating rain in Silverlight

posted by jeparaonline on Feb 18, 2015 17:43
• Re: Simulating rain in Silverlight

posted by elbuy10 on Mar 30, 2015 00:56
Beuaty for women agar happy in beautiful beauty tips for women. You cant information here? Click beauty Waw, breast for women in beautifull. Breast kebanggaan women. You pasti tertarik information about breast. Click breast enlargement tips Hair tampil beauty? Get hair yang membuat you happy. And you cant reading in here. hair care for beauty. You reading in blog. Skin in black? Not khawatir. You lakukan tips skin care. In skin care for women, information in blog Go action planing in weight loss. weight loss in diet. Diet Tips for information. diet tips and healt. You can information here? Weight loss for women. weight loss for beauty. Tips and information for weight loss blog for beauty. Get information pelengkap at fat loss beauty blog Editing photo or Photo editing. Tutorial in learn photoshop. Information photoshop tutorials photo manipulation for your photo design Women in fashion. Fashion in beauty. beauty in skin and body. Get product natural beauty products for women with low price natual in care for women's beauty. Get information for women in natural in beauty tips. reading detail in here. Musce in strong with muscle building exercises. how to build muscle - build muscle fast . Not muscle in weak. click here Mulai bisnis dengan langkah kecil. Ikuti informasi menarik tentang bisnis. dapatkan tipsmemulai dalam bisnis untuk pemula. Mau bangun bisnis? selengkapnya di sini Cinta tak selamanya bahagia. Ikuti mutiara dalam kata cinta dalam blog cinta. DVD Valentin day tentang cinta diharamkan. baca informasi disini Bangun bisnis online anda di internet dengan modal kecil. Ikuti kiatcara mulai bisnis online untuk pemula modal kecil dan mudah. info lengkap tips disini Solusi belajar anak. Solusi untuk sukses. kiat sukses belajar untuk pelajar agar lolos dari UN. baca selengkapnya Berdiet dengan sehat dan aman. Diet menurunkan berat badan. Ikuti diet alami untuk sehat agar menghasilkan hasil yang maksimal dalam diet alami. baca lanjutannya disini
• Re: Simulating rain in Silverlight

posted by MarcoBet on Apr 02, 2015 03:57

That is very interesting Smile I love reading and I Cipto Junaedy always searching for informative information like this Jadwal MotoGP 2015. This is exactly what I was looking for Cara Upload Video ke Youtube.  Really this system so amazing. Cipto Junaedy  so happy to browsing this BBM Untuk Android Versi Terbaru. Simply fill out a quick and easy application, and you'll be on your way to getting your new Cara Membuat Email  and Cara Instal Windows 7 avoiding Thanks for sharing this great article . Don't forget for reading the articles about Jinpoker.com Agen Judi Poker Online dan Domino Online Indonesia Terpercaya. And I encourage you to bookmark the following page if Cahayapoker.com Agen Judi Poker Dan Domino Uang Asli Online Terpercaya Indonesia considered important ... Regards ituDewa.net Agen Judi Poker Domino QQ Ceme Online Indonesia

| Nusantarapoker.com Agen Texas Poker Dan Domino Online Tanpa Robot Terpercaya
• Re: Simulating rain in Silverlight

posted by elbuy10 on Apr 12, 2015 22:46
beauty tips. get information in baca selengkapnya, beauty.
• Re: Simulating rain in Silverlight

posted by elbuy10 on Apr 12, 2015 22:47
natural beauty. women's beauty in outward appearance. <a href="http://beautyforwomen135.wordpress.com/">baca detail, natural beuty</a> in site for information.

Deal word with beauty. get information in <a href="http://mybeauty1234.blogspot.com/">lihat di sini, beauty tips</a> for women. women brave in word

heart in beauty for women. happy and health absolut for women <a href="http://naturalbeautyxx1.tumblr.com/">kunjungi disini, best beauty</a>.

get speak my beauty. Get info for speaking my beauty. <a href="http://beautyblog123.ucoz.com/">women rading here ,beauty tips natrally</a>. Visit to here, for your beauty

beauty inspiring. <a href="http://tipsofbeauty123.blog.com/">lihat saja, beauty product</a>. good information for beauty

style for women. beauty in style <a href="http://tipsbeautycoy1.blogspot.com/">bisa lanjutkan baca di, women in natural tips</a>

in word, beauty is absolut. get women's beauty <a href="http://beautytipsoke.ucoz.com/">selengkapnya informasi, beauty for women</a>. get detail here

---

tutoria for beginner in photoshop. <a href="http://photoshoptrialbuyz1.blogspot.com/">visit here to blog</a>.

get tutorial, tutorial tips for photoshop. <a href="http://photoshoptutorialbuyz1.blog.com/">get learning yang happy</a>

design graphic with photoshop. get <a href="http://photoshopbuyz13.blog.com/">information to tutorial</a>.

tutorial for beginner aobut photoshop <a href="http://tutorial-photoshoptips1x.tumblr.com/">detail about tutorial</a>.

<a href="http://tutorialphotoshop1x.tumblr.com/">kunjungi segera, reading here only</a>.

---

Dapatkan tips untuk <a href="http://elbuyz.blogspot.com/">Belajar Mencari Ilmu Hidup</a> agar anda bisa belajar menenai hidup anda. Tidak lupa dengan tips mengatasi akidah sesat dengan tema <a href="http://elbuyz.blogspot.com/2015/04/allah-ada-dimana-sebuah-aqidah-berbahaya.html">Jangan Tanya Allah Ada Dimana</a>. Mempertanyakan tempat Allah adalah ciri-ciri akidah sesat. <a href="http://elbuyz.blogspot.com/2015/04/bukan-voa-islam-tetapi-voice-of-islam.html">Bagaimana Voa Islam</a>. Selamat membaca artikel keislaman
• Re: Simulating rain in Silverlight

posted by elbuy10 on Apr 12, 2015 22:49
natural beauty. women's beauty in outward appearance. baca detail, natural beuty in site for information. Deal word with beauty. get information in lihat di sini, beauty tips for women. women brave in word heart in beauty for women. happy and health absolut for women kunjungi disini, best beauty. get speak my beauty. Get info for speaking my beauty. women rading here ,beauty tips natrally. Visit to here, for your beauty beauty inspiring. lihat saja, beauty product. good information for beauty style for women. beauty in style bisa lanjutkan baca di, women in natural tips in word, beauty is absolut. get women's beauty selengkapnya informasi, beauty for women. get detail here --- get tutorial in photoshop. reading to detail tutoria for beginner in photoshop. visit here to blog. get tutorial, tutorial tips for photoshop. get learning yang happy design graphic with photoshop. get information to tutorial. tutorial for beginner aobut photoshop detail about tutorial. kunjungi segera, reading here only. --- Dapatkan tips untuk Belajar Mencari Ilmu Hidup agar anda bisa belajar menenai hidup anda. Tidak lupa dengan tips mengatasi akidah sesat dengan tema Jangan Tanya Allah Ada Dimana. Mempertanyakan tempat Allah adalah ciri-ciri akidah sesat. Bagaimana Voa Islam. Selamat membaca artikel keislaman

*      *