cleanup.html 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  1. Title: Three.js Cleanup
  2. Description: How to use free memory used by Three.js
  3. TOC: Freeing Resources
  4. Three.js apps often use lots of memory. A 3D model
  5. might be 1 to 20 meg memory for all of its vertices.
  6. A model might use many textures that even if they are
  7. compressed into jpg files they have to be expanded
  8. to their uncompressed form to use. Each 1024x1024
  9. texture takes 4 to 6meg of memory.
  10. Most three.js apps load resources at init time and
  11. then use those resources forever until the page is
  12. closed. But, what if you want to load and change resources
  13. over time?
  14. Unlike most JavaScript, three.js can not automatically
  15. clean these resources up. The browser will clean them
  16. up if you switch pages but otherwise it's up to you
  17. to manage them. This is an issue of how WebGL is designed
  18. and so three.js has no recourse but to pass on the
  19. responsibility to free resources back to you.
  20. You free three.js resource this by calling the `dispose` function on
  21. [textures](threejs-textures.html),
  22. [geometries](threejs-primitives.html), and
  23. [materials](threejs-materials.html).
  24. You could do this manually. At the start you might create
  25. some of these resources
  26. ```js
  27. const boxGeometry = new THREE.BoxGeometry(...);
  28. const boxTexture = textureLoader.load(...);
  29. const boxMaterial = new THREE.MeshPhongMaterial({map: texture});
  30. ```
  31. and then when you're done with them you'd free them
  32. ```js
  33. boxGeometry.dispose();
  34. boxTexture.dispose();
  35. boxMaterial.dispose();
  36. ```
  37. As you use more and more resources that would get more and
  38. more tedious.
  39. To help remove some of the tedium let's make a class to track
  40. the resources. We'll then ask that class to do the cleanup
  41. for us.
  42. Here's a first pass at such a class
  43. ```js
  44. class ResourceTracker {
  45. constructor() {
  46. this.resources = new Set();
  47. }
  48. track(resource) {
  49. if (resource.dispose) {
  50. this.resources.add(resource);
  51. }
  52. return resource;
  53. }
  54. untrack(resource) {
  55. this.resources.delete(resource);
  56. }
  57. dispose() {
  58. for (const resource of this.resources) {
  59. resource.dispose();
  60. }
  61. this.resources.clear();
  62. }
  63. }
  64. ```
  65. Let's use this class with the first example from [the article on textures](threejs-textures.html).
  66. We can create an instance of this class
  67. ```js
  68. const resTracker = new ResourceTracker();
  69. ```
  70. and then just to make it easier to use let's create a bound function for the `track` method
  71. ```js
  72. const resTracker = new ResourceTracker();
  73. +const track = resTracker.track.bind(resTracker);
  74. ```
  75. Now to use it we just need to call `track` with for each geometry, texture, and material
  76. we create
  77. ```js
  78. const boxWidth = 1;
  79. const boxHeight = 1;
  80. const boxDepth = 1;
  81. -const geometry = new THREE.BoxGeometry(boxWidth, boxHeight, boxDepth);
  82. +const geometry = track(new THREE.BoxGeometry(boxWidth, boxHeight, boxDepth));
  83. const cubes = []; // an array we can use to rotate the cubes
  84. const loader = new THREE.TextureLoader();
  85. -const material = new THREE.MeshBasicMaterial({
  86. - map: loader.load('resources/images/wall.jpg'),
  87. -});
  88. +const material = track(new THREE.MeshBasicMaterial({
  89. + map: track(loader.load('resources/images/wall.jpg')),
  90. +}));
  91. const cube = new THREE.Mesh(geometry, material);
  92. scene.add(cube);
  93. cubes.push(cube); // add to our list of cubes to rotate
  94. ```
  95. And then to free them we'd want to remove the cubes from the scene
  96. and then call `resTracker.dispose`
  97. ```js
  98. for (const cube of cubes) {
  99. scene.remove(cube);
  100. }
  101. cubes.length = 0; // clears the cubes array
  102. resTracker.dispose();
  103. ```
  104. That would work but I find having to remove the cubes from the
  105. scene kind of tedious. Let's add that functionality to the `ResourceTracker`.
  106. ```js
  107. class ResourceTracker {
  108. constructor() {
  109. this.resources = new Set();
  110. }
  111. track(resource) {
  112. - if (resource.dispose) {
  113. + if (resource.dispose || resource instanceof THREE.Object3D) {
  114. this.resources.add(resource);
  115. }
  116. return resource;
  117. }
  118. untrack(resource) {
  119. this.resources.delete(resource);
  120. }
  121. dispose() {
  122. for (const resource of this.resources) {
  123. - resource.dispose();
  124. + if (resource instanceof THREE.Object3D) {
  125. + if (resource.parent) {
  126. + resource.parent.remove(resource);
  127. + }
  128. + }
  129. + if (resource.dispose) {
  130. + resource.dispose();
  131. + }
  132. + }
  133. this.resources.clear();
  134. }
  135. }
  136. ```
  137. And now we can track the cubes
  138. ```js
  139. const material = track(new THREE.MeshBasicMaterial({
  140. map: track(loader.load('resources/images/wall.jpg')),
  141. }));
  142. const cube = track(new THREE.Mesh(geometry, material));
  143. scene.add(cube);
  144. cubes.push(cube); // add to our list of cubes to rotate
  145. ```
  146. We no longer need the code to remove the cubes from the scene.
  147. ```js
  148. -for (const cube of cubes) {
  149. - scene.remove(cube);
  150. -}
  151. cubes.length = 0; // clears the cube array
  152. resTracker.dispose();
  153. ```
  154. Let's arrange this code so that we can re-add the cube,
  155. texture, and material.
  156. ```js
  157. const scene = new THREE.Scene();
  158. *const cubes = []; // just an array we can use to rotate the cubes
  159. +function addStuffToScene() {
  160. const resTracker = new ResourceTracker();
  161. const track = resTracker.track.bind(resTracker);
  162. const boxWidth = 1;
  163. const boxHeight = 1;
  164. const boxDepth = 1;
  165. const geometry = track(new THREE.BoxGeometry(boxWidth, boxHeight, boxDepth));
  166. const loader = new THREE.TextureLoader();
  167. const material = track(new THREE.MeshBasicMaterial({
  168. map: track(loader.load('resources/images/wall.jpg')),
  169. }));
  170. const cube = track(new THREE.Mesh(geometry, material));
  171. scene.add(cube);
  172. cubes.push(cube); // add to our list of cubes to rotate
  173. + return resTracker;
  174. +}
  175. ```
  176. And then let's write some code to add and remove things over time.
  177. ```js
  178. function waitSeconds(seconds = 0) {
  179. return new Promise(resolve => setTimeout(resolve, seconds * 1000));
  180. }
  181. async function process() {
  182. for (;;) {
  183. const resTracker = addStuffToScene();
  184. await wait(2);
  185. cubes.length = 0; // remove the cubes
  186. resTracker.dispose();
  187. await wait(1);
  188. }
  189. }
  190. process();
  191. ```
  192. This code will create the cube, texture and material, wait for 2 seconds, then dispose of them and wait for 1 second
  193. and repeat.
  194. {{{example url="../threejs-cleanup-simple.html" }}}
  195. So that seems to work.
  196. For a loaded file though it's a little more work. Most loaders only return an `Object3D`
  197. as a root of the hierarchy of objects they load so we need to discover what all the resources
  198. are.
  199. Let's update our `ResourceTracker` to try to do that.
  200. First we'll check if the object is an `Object3D` then track its geometry, material, and children
  201. ```js
  202. class ResourceTracker {
  203. constructor() {
  204. this.resources = new Set();
  205. }
  206. track(resource) {
  207. if (resource.dispose || resource instanceof THREE.Object3D) {
  208. this.resources.add(resource);
  209. }
  210. + if (resource instanceof THREE.Object3D) {
  211. + this.track(resource.geometry);
  212. + this.track(resource.material);
  213. + this.track(resource.children);
  214. + }
  215. return resource;
  216. }
  217. ...
  218. }
  219. ```
  220. Now, because any of `resource.geometry`, `resource.material`, and `resource.children`
  221. might be null or undefined we'll check at the top of `track`.
  222. ```js
  223. class ResourceTracker {
  224. constructor() {
  225. this.resources = new Set();
  226. }
  227. track(resource) {
  228. + if (!resource) {
  229. + return resource;
  230. + }
  231. if (resource.dispose || resource instanceof THREE.Object3D) {
  232. this.resources.add(resource);
  233. }
  234. if (resource instanceof THREE.Object3D) {
  235. this.track(resource.geometry);
  236. this.track(resource.material);
  237. this.track(resource.children);
  238. }
  239. return resource;
  240. }
  241. ...
  242. }
  243. ```
  244. Also because `resource.children` is an array and because `resource.material` can be
  245. an array let's check for arrays
  246. ```js
  247. class ResourceTracker {
  248. constructor() {
  249. this.resources = new Set();
  250. }
  251. track(resource) {
  252. if (!resource) {
  253. return resource;
  254. }
  255. + // handle children and when material is an array of materials.
  256. + if (Array.isArray(resource)) {
  257. + resource.forEach(resource => this.track(resource));
  258. + return resource;
  259. + }
  260. if (resource.dispose || resource instanceof THREE.Object3D) {
  261. this.resources.add(resource);
  262. }
  263. if (resource instanceof THREE.Object3D) {
  264. this.track(resource.geometry);
  265. this.track(resource.material);
  266. this.track(resource.children);
  267. }
  268. return resource;
  269. }
  270. ...
  271. }
  272. ```
  273. And finally we need to walk the properties and uniforms
  274. of a material looking for textures.
  275. ```js
  276. class ResourceTracker {
  277. constructor() {
  278. this.resources = new Set();
  279. }
  280. track(resource) {
  281. if (!resource) {
  282. return resource;
  283. }
  284. * // handle children and when material is an array of materials or
  285. * // uniform is array of textures
  286. if (Array.isArray(resource)) {
  287. resource.forEach(resource => this.track(resource));
  288. return resource;
  289. }
  290. if (resource.dispose || resource instanceof THREE.Object3D) {
  291. this.resources.add(resource);
  292. }
  293. if (resource instanceof THREE.Object3D) {
  294. this.track(resource.geometry);
  295. this.track(resource.material);
  296. this.track(resource.children);
  297. - }
  298. + } else if (resource instanceof THREE.Material) {
  299. + // We have to check if there are any textures on the material
  300. + for (const value of Object.values(resource)) {
  301. + if (value instanceof THREE.Texture) {
  302. + this.track(value);
  303. + }
  304. + }
  305. + // We also have to check if any uniforms reference textures or arrays of textures
  306. + if (resource.uniforms) {
  307. + for (const value of Object.values(resource.uniforms)) {
  308. + if (value) {
  309. + const uniformValue = value.value;
  310. + if (uniformValue instanceof THREE.Texture ||
  311. + Array.isArray(uniformValue)) {
  312. + this.track(uniformValue);
  313. + }
  314. + }
  315. + }
  316. + }
  317. + }
  318. return resource;
  319. }
  320. ...
  321. }
  322. ```
  323. And with that let's take an example from [the article on loading gltf files](threejs-load-gltf.html)
  324. and make it load and free files.
  325. ```js
  326. const gltfLoader = new GLTFLoader();
  327. function loadGLTF(url) {
  328. return new Promise((resolve, reject) => {
  329. gltfLoader.load(url, resolve, undefined, reject);
  330. });
  331. }
  332. function waitSeconds(seconds = 0) {
  333. return new Promise(resolve => setTimeout(resolve, seconds * 1000));
  334. }
  335. const fileURLs = [
  336. 'resources/models/cartoon_lowpoly_small_city_free_pack/scene.gltf',
  337. 'resources/models/3dbustchallange_submission/scene.gltf',
  338. 'resources/models/mountain_landscape/scene.gltf',
  339. 'resources/models/simple_house_scene/scene.gltf',
  340. ];
  341. async function loadFiles() {
  342. for (;;) {
  343. for (const url of fileURLs) {
  344. const resMgr = new ResourceTracker();
  345. const track = resMgr.track.bind(resMgr);
  346. const gltf = await loadGLTF(url);
  347. const root = track(gltf.scene);
  348. scene.add(root);
  349. // compute the box that contains all the stuff
  350. // from root and below
  351. const box = new THREE.Box3().setFromObject(root);
  352. const boxSize = box.getSize(new THREE.Vector3()).length();
  353. const boxCenter = box.getCenter(new THREE.Vector3());
  354. // set the camera to frame the box
  355. frameArea(boxSize * 1.1, boxSize, boxCenter, camera);
  356. await waitSeconds(2);
  357. renderer.render(scene, camera);
  358. resMgr.dispose();
  359. await waitSeconds(1);
  360. }
  361. }
  362. }
  363. loadFiles();
  364. ```
  365. and we get
  366. {{{example url="../threejs-cleanup-loaded-files.html"}}}
  367. Some notes about the code.
  368. If we wanted to load 2 or more files at once and free them at
  369. anytime we would use one `ResourceTracker` per file.
  370. Above we are only tracking `gltf.scene` right after loading.
  371. Based on our current implementation of `ResourceTracker` that
  372. will track all the resources just loaded. If we added more
  373. things to the scene we need to decide whether or not to track them.
  374. For example let's say after we loaded a character we put a tool
  375. in their hand by making the tool a child of their hand. As it is
  376. that tool will not be freed. I'm guessing more often than not
  377. this is what we want.
  378. That brings up a point. Originally when I first wrote the `ResourceTracker`
  379. above I walked through everything inside the `dispose` method instead of `track`.
  380. It was only later as I thought about the tool as a child of hand case above
  381. that it became clear that tracking exactly what to free in `track` was more
  382. flexible and arguably more correct since we could then track what was loaded
  383. from the file rather than just freeing the state of the scene graph later.
  384. I honestly am not 100% happy with `ResourceTracker`. Doing things this
  385. way is not common in 3D engines. We shouldn't have to guess what
  386. resources were loaded, we should know. It would be nice if three.js
  387. changed so that all file loaders returned some standard object with
  388. references to all the resources loaded. At least at the moment,
  389. three.js doesn't give us any more info when loading a scene so this
  390. solution seems to work.
  391. I hope you find this example useful or at least a good reference for what is
  392. required to free resources in three.js