Progress: BitmapData.noise() for OpenFL-bitfive

For me this morning started with just another bit of code, some of which has granted BitmapData.noise() function support for my OpenFL backend OpenFL-bitfive, proven to be a more interesting process than expected, and, given that it's otherwise hard to tell what I am working on, I thought that I could write a post about this:

Before proceeding with implementation of a feature, a thing I may do is throwing a glance at works familiar. The logical questions are "Did it work?" and "Was it smart?" (do I get to make something better?). OpenFL-bitfive being an alternative to standard OpenFL-html5 backend, taking a look at function from that would seem logical. Generally I do not approve the way the BitmapData class is implemented there, but that's another topic.

Upon navigating to BitmapData.noise() implementation, first thing that catches the eye is the allocation of a new "generator" instance. Well that is interesting. Looking at the class declaration, it reveals to be a private class declared for use in this single function.

A block comment in the beginning of class looks concerning, and, apart of doubtfully looking (1<<31) - 1, the whole thing looks smart. As fact, very smart. There are signed and unsigned bit shifts involved, value is being split into lower and higher halves, and I would just start wondering how does this whole trick work but... OHH, it doesn't. Of course it doesn't. While it probably did work on it's well-typed original platform, there is that, but this is JavaScript, and things don't work like that. The previously doubted inline value gets precompiled into -2147483649, comparisons fail, and the whole bitwise extravaganza looks pretty moot. Doesn't look like it was exactly tested. Or even attempted to be tested. Well then.

In the same time, comment does cite MINSTD generator usage, which supports my previously gathered information about ways of noise function.

Basic MINSTD implementation is simple. Very simple. In fact, so simple, that many doubt the generator function being a generator at all:

var minstd_seed:Int; // to be set to starting seed
function minstd_rand():Int {
	minstd_seed = (minstd_seed * 16807) % 2147483647;
	return minstd_seed; // (0...2147483647) range, exclusive
}

And, guess what, this is also the method used by Flash - after adding a loop and dealing with a minor algorithm hick-up, I get a BitmapData.noise function that behaves exactly like it's Flash colleague.
Can be used for all "noisy" purposes as-is.

Project repository Example of usage

Related posts:

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.