cleanup.html 17 KB

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