Cached Marquee Selection with THREE.js

Thursday, December 5, 2013 Posted by Josh Staples
In my previous post on marquee selection I demonstrated how to marquee select a bunch of elements within a WebGL canvas using THREE.js.  While the approach works great, once you start loading a larger number of meshes into the scene, the approach slows to a crawl.

To resolve this slowdown, I created a caching object that takes all unprojected 3D coordinates and associated meshes and throws them into an array.   This allows us to circumvent gobs of math and processing required to unproject rays and do a comparison during each mouse event.  Using this approach, the cache is created on the first mousemove event (you could pre-create it as well) and subsequently used in all future mousemove events until the "dirty" flag is set.

The speedup is incredible.   Easily 1000 cubes in real time.   If you bump that up to 10,000 cubes, disabled cache use is impossible and there is only a slight lag on the marquee selection with the cache enabled.

One MAJOR caveat:
  • If the camera moves, the cache is worthless.  You'll need to recreate it.
In that regard, I added a "dirty" flag so when the camera does move you can tell the cache and it will re-create the cache on the first mousemove event.   I haven't experimented too much with a moving camera (my current work's 3D environment is pretty static) but it should still provide a pretty good speedup even within a dynamic scene.

FYI, I also included an "active" flag in the cache.   This was included so you can turn the cache on and off from the browser.

Here is a demo

Here is a Gist of the Cache object: