A Little Delve in to the new Flash VM
A friend of mine Seldaek pointed out a problem which to all intent and purpose seems incredibly stupid. It was a situation where the outcome is predictable and should be certain but the flash program disagreed…
More…Now the problem came down to a very simple program you can try for yourself if you have Adobe CS3 installed. Create a new AS2 Flash file, add a movieclip, give it an instance name. Now type this code on to a frame:
myMovieClip._alpha = 0;
myMovieClip.onEnterFrame = function()
{
trace(this._alpha);
this._alpha += 5;
if(this._alpha >= 100)
delete this.onEnterFrame;
}
If you go ahead and test this, you should see the fairly obvious effect of the MovieClip fading in and then sitting there. Effect wise this is nothing special. What is interesting however is that in the output window you should have something along the lines of:
0
4.6875
9.375
…
93.75
98.4375
Now then this isnt right! We are adding 5 to the alpha not 4.6875! What if we wanted to do something when the alpha == 50 ? It would essentially skip past this value and ignore our if trigger! Now yes we can get around this using round values or diffrent if clauses, but thats not what this article is about, so what is going on here?
Well it is due to the internal format of the _alpha value. The _alpha is held in a byte this gives us 256 possible values of _alpha. Now basically this means the minimum we can increment _alpha by is 0.390625 (100/256 because we are transforming the 0-100 values we have to to internal values) So when ever we read off from _alpha it will be a multiple of 0.390625. Lets prove this, 4.6875 / 0.390625 = 12 see the result is an integer, which says 4.6875 is a multiple of 0.390625. It is the same for all of these numbers in that list.
Now as you maybe thinking, this is stupid. Why cant it just hold a float value or integer instead of a byte, and make my life easier! Well on one hand I agree with you, on the other hand I can see why Adobe did this. Why have 4294967296 (2^32, unsigned integer max value) values for alpha ? Can you honestly tell me you can tell the diffrence between having millions of values and 256 values ? At the end of the day this was a compromise to save memory because we only need 256 alpha values.
Thanks to Seldaek and to Chris Benjaminsen.