HTML and CSS Reference
In-Depth Information
// Load the file via XHR
var xhr = new XMLHttpRequest();
xhr.addEventListener('load', function (ev) {
if (xhr.status == 200) {
// If the file loaded successfully parse and decompress it.
decompressCRN(xhr.response, uploadCallback, errorCallback);
} else {
errorCallback(xhr.statusText);
}
}, false);
xhr.open('GET', "../" + src, true);
xhr.responseType = 'arraybuffer';
xhr.send(null);
};
To communicate with the worker “thread,” you will send it messages, which is this case will be a simple JSON
object containing a URL to load and a unique ID to identify which texture is being loaded. onmessage is the function
that will handle those messages as you send them. You may notice that the code shown here is very similar to that
of the previously defined loadCRN function. In fact, it is mostly the same—the big difference being that once the
decompression is complete, or if an error occurs, you call postMessage with the results rather than making any
WebGL calls. This is because workers cannot access any part of the DOM, and since WebGL is tightly bound to the
canvas tag it means WebGL cannot be used in a worker either. Instead you need to pass the decompressed data back
to the main script, which is what postMessage does.
That's it for the worker file, so now let's go back to dxt-util.js to add the code to create the worker and
communicate with it. First off, since the texture decompression will now be asynchronous and handled in a different
thread, you need a way to track textures between the time you request it be loaded and the time the worker sends it
back. For this purpose you'll define a very simple CrunchPendingTexture class, as shown in Listing 21-15.
Listing 21-15. CrunchPendingTexture Class
var nextPendingTextureId = 0;
var CrunchPendingTexture = function(texture, callback) {
this.id = nextPendingTextureId++;
this.texture = texture;
this.callback = callback;
}
As you can see, each CrunchPendingTexture is given a unique ID which will be passed to the worker and back,
and holds the texture that is being loaded and the callback the library user specified should be called when the
loading was completed.
Next, you'll update the DXTLoader constructor function, as shown in Listing 21-16.
Listing 21-16. Worker-enabled DXTLoader Constructor
var DXTLoader = function(gl) {
this.gl = gl;
// Load the S3TC extension, if it's available
this.ext = null;
var vendorPrefixes = ["", "WEBKIT_", "MOZ_"];
for(i in vendorPrefixes) {
 
Search WWH ::




Custom Search