sine cosine Gradient

Actionscript:
  1. [SWF(width=600,height=500,frameRate=30)]
  2. var canvas:BitmapData=new BitmapData(600,500,false,0x000000);
  3. addChild(new Bitmap(canvas));
  4. var size:Number=canvas.width*canvas.height;
  5. var w:Number=canvas.width;
  6. var wd:Number=1/w;
  7. var pix:Vector.<uint> = new Vector.<uint>();
  8. var sin:Number;
  9. var cos:Number;
  10. var dx:Number=110;
  11. var dy:Number=52;
  12. addEventListener(Event.ENTER_FRAME, onLoop);
  13. function onLoop(evt:Event):void {
  14.     dx+=0.001;
  15.     canvas.lock();
  16.     for (var i:int = 0; i<size; i++) {
  17.         var xp:Number=i%w;
  18.         var yp:Number=int(i*wd);
  19.         var xx:Number=xp*0.05+dx;
  20.         var yy:Number=yp*0.05+dy;
  21.         var t:Number= (xx * yy) % 3.14159265;
  22.         //compute sine
  23.         // technique from http://lab.polygonal.de/2007/07/18/fast-and-accurate-sinecosine-approximation/
  24.         // by Michael Baczynski
  25.         if (t<0) {
  26.             sin=1.27323954*t+.405284735*t*t;
  27.         } else {
  28.             sin=1.27323954*t-0.405284735*t*t;
  29.         }
  30.         //compute cosine: sin(t + PI/2) = cos(t)
  31.         t+=1.57079632;
  32.         if (t>3.14159265) {
  33.             t-=6.28318531;
  34.         }
  35.         if (t<0) {
  36.             cos=1.27323954*t+0.405284735*t*t;
  37.         } else {
  38.             cos=1.27323954*t-0.405284735*t*t;
  39.         }
  40.         var c:Number=sin+cos*cos*cos;
  41.         // fast math abs
  42.         c=c<0? -c:c;
  43.         c=c*140;
  44.         // math max 255
  45.         c=c>255?255:c;
  46.         pix[i]=c<<16|c<<8|c;
  47.     }
  48.     canvas.setVector(canvas.rect, pix);
  49.     canvas.unlock();
  50. }

The above snippet will animate a gradient that looks like this:

This entry was posted in BitmapData, Vector, graphics algorithms, pixel manipulation. Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

3 Comments

  1. Posted May 26, 2009 at 4:41 am | Permalink

    Very cool, reminds me that old school C64 demo effect. We used to cycle the colour pallete instead, achievable on MOS 6502 with 1MHz :)

  2. Posted May 26, 2009 at 10:24 am | Permalink

    Thanks. Thinking about C64 brings back fond memories - although I never programmed one myself, I just had a few friends that did…

  3. Posted May 26, 2009 at 10:27 am | Permalink

    oh also… you might be able to mess with BitmapData.paletteMap to achieve some of those demo effects in a similar way …

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*