[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7EHXJETHSQSPH1VH1JEX0C9":3,"skill-same:01M7EHXJETHSQSPH1VH1JEX0C9":67},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":18,"linkOnly":19,"markdownContent":20,"markdownBody":21,"frontMatter":22,"refName":28,"commitSha":29,"skillDirectory":30,"forksCount":13,"repositoryHtmlUrl":31,"repositoryHomepageUrl":6,"ownerHtmlUrl":32,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":33,"install":34,"resources":47},"01M7EHXJETHSQSPH1VH1JEX0C9","threejs-errors-performance",null,"Use when a Three.js scene has performance problems: low FPS, memory leaks, too many draw calls, or high GPU memory usage. Prevents the common mistake of forgetting dispose(), creating objects in the render loop, or not using InstancedMesh for repeated objects. Covers disposal patterns, draw call optimization, InstancedMesh, LOD, texture compression, renderer.info, Stats.js profiling. Keywords: performance, memory leak, dispose, draw calls, FPS, slow, optimization, InstancedMesh, LOD, renderer.info, Stats, profiling, laggy, low FPS, stuttering, browser freezes.","mhyahya854\u002FAI-Second-Brain_Universal-Rules","mhyahya854","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F194078115?v=4","01M7EGSP2M9T858SDHJMXQ257Y","01M7EGSP3N6HN6879SVDPMD4DZ",0,"MIT","https:\u002F\u002Fgithub.com\u002Fmhyahya854\u002FAI-Second-Brain_Universal-Rules\u002Fblob\u002Fmain\u002Fskills\u002F_intake\u002Fgithub\u002FImpertio-Studio\u002FThree.js-Claude-Skill-Package\u002Fthreejs-errors-performance\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: threejs-errors-performance\ndescription: >\n  Use when a Three.js scene has performance problems: low FPS, memory\n  leaks, too many draw calls, or high GPU memory usage. Prevents the\n  common mistake of forgetting dispose(), creating objects in the render\n  loop, or not using InstancedMesh for repeated objects. Covers disposal\n  patterns, draw call optimization, InstancedMesh, LOD, texture compression,\n  renderer.info, Stats.js profiling.\n  Keywords: performance, memory leak, dispose, draw calls, FPS, slow, optimization, InstancedMesh, LOD, renderer.info, Stats, profiling, laggy, low FPS, stuttering, browser freezes.\nlicense: MIT\ncompatibility: \"Designed for Claude Code. Requires Three.js r160+.\"\nmetadata:\n  author: OpenAEC-Foundation\n  version: \"1.0\"\n---\n\n# threejs-errors-performance\n\n## Performance Diagnosis Flowchart\n\n```\nScene is slow \u002F low FPS\n│\n├─ Check renderer.info.render.calls\n│  ├─ > 200 draw calls ──────────────── Go to: Draw Call Optimization\n│  └─ \u003C 200 draw calls\n│\n├─ Check renderer.info.memory\n│  ├─ geometries\u002Ftextures growing ──── Go to: Memory Leak Diagnosis\n│  └─ stable counts\n│\n├─ Check renderer.info.render.triangles\n│  ├─ > 2M triangles ────────────────── Go to: Geometry Optimization (LOD, merge)\n│  └─ \u003C 2M triangles\n│\n├─ Check GPU load (DevTools Performance tab)\n│  ├─ GPU-bound (long GPU tasks) ───── Go to: Shader \u002F Material Optimization\n│  └─ CPU-bound (long JS tasks) ────── Go to: CPU Optimization\n│\n└─ Check Stats.js memory panel\n   ├─ JS heap growing ─────────────── Go to: JavaScript Object Leaks\n   └─ Heap stable ──────────────────── Profile specific bottleneck\n```\n\n## Quick Reference\n\n### renderer.info: Your First Diagnostic Tool\n\n```javascript\nimport * as THREE from 'three';\n\n\u002F\u002F ALWAYS check renderer.info when diagnosing performance\nconsole.log(renderer.info.render);\n\u002F\u002F { calls: number, triangles: number, points: number, lines: number, frame: number }\n\nconsole.log(renderer.info.memory);\n\u002F\u002F { geometries: number, textures: number }\n\nconsole.log(renderer.info.programs);\n\u002F\u002F Array of compiled shader programs (length = unique material combinations)\n```\n\n**Rule**: If `renderer.info.memory.geometries` or `renderer.info.memory.textures` grows continuously over time, you have a memory leak. ALWAYS monitor these values during development.\n\n### Stats.js: FPS and Memory Monitoring\n\n```javascript\nimport Stats from 'three\u002Faddons\u002Flibs\u002Fstats.module.js';\n\nconst stats = new Stats();\nstats.showPanel(0); \u002F\u002F 0 = FPS, 1 = MS per frame, 2 = MB heap\ndocument.body.appendChild(stats.dom);\n\nfunction animate() {\n  stats.begin();\n  renderer.render(scene, camera);\n  stats.end();\n  requestAnimationFrame(animate);\n}\n```\n\n### Performance Budgets\n\n| Metric | Target (60 FPS) | Warning | Critical |\n|--------|-----------------|---------|----------|\n| Draw calls | \u003C 100 | 100-500 | > 500 |\n| Triangles | \u003C 1M | 1M-3M | > 3M |\n| Textures (GPU) | \u003C 50 | 50-200 | > 200 |\n| Shader programs | \u003C 20 | 20-50 | > 50 |\n| Frame time | \u003C 16.6ms | 16.6-33ms | > 33ms |\n\n---\n\n## Memory Management: Disposal Rules\n\n### What MUST Be Disposed\n\nThree.js allocates GPU resources that are NOT automatically garbage collected by JavaScript. ALWAYS dispose these manually:\n\n| Object Type | Method | GPU Resource Released |\n|-------------|--------|---------------------|\n| `BufferGeometry` | `geometry.dispose()` | Vertex\u002Findex buffers |\n| `Material` (all types) | `material.dispose()` | Shader programs, uniforms |\n| `Texture` (all types) | `texture.dispose()` | GPU texture memory |\n| `WebGLRenderTarget` | `renderTarget.dispose()` | Framebuffer + textures |\n| `WebGLRenderer` | `renderer.dispose()` | Entire WebGL context |\n| `PMREMGenerator` | `pmremGenerator.dispose()` | Prefiltered env maps |\n| Controls (all types) | `controls.dispose()` | DOM event listeners |\n\n### Complete Material Disposal\n\n```javascript\nfunction disposeMaterial(material) {\n  const textureProps = [\n    'map', 'lightMap', 'bumpMap', 'normalMap', 'specularMap',\n    'envMap', 'alphaMap', 'aoMap', 'displacementMap',\n    'emissiveMap', 'gradientMap', 'metalnessMap', 'roughnessMap',\n    'clearcoatMap', 'clearcoatNormalMap', 'clearcoatRoughnessMap',\n    'transmissionMap', 'thicknessMap', 'sheenColorMap', 'sheenRoughnessMap'\n  ];\n  for (const prop of textureProps) {\n    if (material[prop]) material[prop].dispose();\n  }\n  material.dispose();\n}\n```\n\n### Full Scene Disposal\n\n```javascript\nfunction disposeScene(scene) {\n  scene.traverse((object) => {\n    if (object.geometry) {\n      object.geometry.dispose();\n    }\n    if (object.material) {\n      if (Array.isArray(object.material)) {\n        object.material.forEach(disposeMaterial);\n      } else {\n        disposeMaterial(object.material);\n      }\n    }\n  });\n  scene.clear();\n}\n```\n\n### When to Dispose vs. When to Reuse\n\n**ALWAYS dispose when:**\n- Removing objects permanently from the scene\n- Switching between completely different scenes\n- Unloading loaded models (GLTF, FBX, OBJ)\n- Component unmount (React, Vue, Angular)\n\n**NEVER dispose when:**\n- Temporarily hiding objects (use `visible = false` instead)\n- Objects will be re-added to the scene later\n- Multiple meshes share the same geometry\u002Fmaterial (dispose ONLY when ALL users are done)\n\n---\n\n## Draw Call Optimization\n\n### InstancedMesh: Render Thousands in One Call\n\nALWAYS use `InstancedMesh` when rendering more than ~100 copies of the same geometry+material combination.\n\n```javascript\nimport * as THREE from 'three';\n\nconst geometry = new THREE.BoxGeometry(1, 1, 1);\nconst material = new THREE.MeshStandardMaterial({ color: 0x00ff00 });\nconst count = 5000;\nconst mesh = new THREE.InstancedMesh(geometry, material, count);\n\nconst dummy = new THREE.Object3D();\nfor (let i = 0; i \u003C count; i++) {\n  dummy.position.set(Math.random() * 200 - 100, 0, Math.random() * 200 - 100);\n  dummy.rotation.y = Math.random() * Math.PI * 2;\n  dummy.scale.setScalar(0.5 + Math.random());\n  dummy.updateMatrix();\n  mesh.setMatrixAt(i, dummy.matrix);\n}\n\u002F\u002F CRITICAL: without this, instances render at origin\nmesh.instanceMatrix.needsUpdate = true;\nscene.add(mesh);\n```\n\n| Instance Count | Recommendation |\n|---------------|----------------|\n| \u003C 10 | Individual `Mesh` objects are fine |\n| 10-100 | Either approach; profile your case |\n| 100-10,000 | ALWAYS use `InstancedMesh` |\n| > 10,000 | `InstancedMesh` with spatial subdivision or `BatchedMesh` (r160+) |\n\n### BatchedMesh (r160+): Multiple Geometries in One Call\n\n`BatchedMesh` extends instancing to support different geometries and materials in a single draw call. Use for heterogeneous repeated objects.\n\n### Geometry Merging: Static Objects\n\nFor static objects that NEVER move independently, merge them into a single geometry:\n\n```javascript\nimport { mergeGeometries } from 'three\u002Faddons\u002Futils\u002FBufferGeometryUtils.js';\n\nconst geometries = meshArray.map((m) => {\n  const geo = m.geometry.clone();\n  geo.applyMatrix4(m.matrixWorld);\n  return geo;\n});\nconst merged = mergeGeometries(geometries, false);\nconst mergedMesh = new THREE.Mesh(merged, sharedMaterial);\n\n\u002F\u002F Dispose originals after merge\nmeshArray.forEach((m) => {\n  m.geometry.dispose();\n  scene.remove(m);\n});\n```\n\n**Rule**: NEVER merge geometries that need independent transforms, materials, or raycasting targets. Merging makes individual object interaction impossible.\n\n---\n\n## LOD (Level of Detail)\n\n```javascript\nimport * as THREE from 'three';\n\nconst lod = new THREE.LOD();\nlod.addLevel(highDetailMesh, 0);    \u002F\u002F visible 0-50 units\nlod.addLevel(mediumDetailMesh, 50); \u002F\u002F visible 50-200 units\nlod.addLevel(lowDetailMesh, 200);   \u002F\u002F visible 200+ units\nscene.add(lod);\n\n\u002F\u002F ALWAYS call in animation loop for distance-based switching\nlod.update(camera);\n```\n\n**Rule**: ALWAYS provide at least 3 LOD levels for objects visible across a wide distance range. Triangle counts MUST decrease by at least 50% between each level.\n\n---\n\n## Texture Optimization\n\n| Technique | Impact | When to Use |\n|-----------|--------|-------------|\n| Resize textures | High | ALWAYS use the smallest resolution that looks acceptable |\n| Power-of-two dimensions | Medium | Required for mipmaps; ALWAYS use (256, 512, 1024, 2048) |\n| Compressed formats (KTX2\u002FBasis) | High | ALWAYS for production; 4-6x smaller GPU footprint |\n| Texture atlases | High | Combine multiple small textures into one to reduce draw calls |\n| `texture.dispose()` on swap | Critical | ALWAYS dispose old texture before assigning new one |\n| `generateMipmaps: false` | Low | Use for UI textures or textures that NEVER need filtering at distance |\n\n### KTX2 Compressed Textures\n\n```javascript\nimport { KTX2Loader } from 'three\u002Faddons\u002Floaders\u002FKTX2Loader.js';\n\nconst ktx2Loader = new KTX2Loader()\n  .setTranscoderPath('three\u002Faddons\u002Flibs\u002Fbasis\u002F')\n  .detectSupport(renderer);\n\nktx2Loader.load('texture.ktx2', (texture) => {\n  material.map = texture;\n  material.needsUpdate = true;\n});\n```\n\n---\n\n## Frustum Culling\n\nFrustum culling is enabled by default (`object.frustumCulled = true`). The renderer skips objects outside the camera view.\n\n**NEVER disable frustum culling globally.** Only set `frustumCulled = false` on specific objects that MUST render regardless of camera (skyboxes, large particle systems, full-screen post-processing quads).\n\n**Rule**: For `InstancedMesh`, frustum culling operates on the entire instance group as one bounding sphere. If instances are spread across a large area, split them into spatial groups for effective culling.\n\n---\n\n## Object Pooling\n\nNEVER create and destroy objects every frame. Use object pools for frequently spawned\u002Fdespawned objects:\n\n```javascript\nclass MeshPool {\n  constructor(geometry, material, poolSize) {\n    this.pool = [];\n    for (let i = 0; i \u003C poolSize; i++) {\n      const mesh = new THREE.Mesh(geometry, material);\n      mesh.visible = false;\n      this.pool.push(mesh);\n    }\n    this.activeIndex = 0;\n  }\n\n  acquire() {\n    if (this.activeIndex >= this.pool.length) return null;\n    const mesh = this.pool[this.activeIndex++];\n    mesh.visible = true;\n    return mesh;\n  }\n\n  release(mesh) {\n    mesh.visible = false;\n    const idx = this.pool.indexOf(mesh);\n    if (idx !== -1 && idx \u003C this.activeIndex) {\n      [this.pool[idx], this.pool[this.activeIndex - 1]] =\n        [this.pool[this.activeIndex - 1], this.pool[idx]];\n      this.activeIndex--;\n    }\n  }\n}\n```\n\n---\n\n## CPU-Side Optimization\n\n### Static Object Matrix Optimization\n\nFor objects that NEVER move after initial placement:\n\n```javascript\nobject.matrixAutoUpdate = false;\nobject.updateMatrix(); \u002F\u002F compute once\n```\n\nThis prevents the renderer from recalculating the local matrix every frame for static objects.\n\n### Avoid Allocations in the Render Loop\n\n```javascript\n\u002F\u002F WRONG: creates new Vector3 every frame — GC pressure\nfunction animate() {\n  const pos = new THREE.Vector3(1, 2, 3); \u002F\u002F NEVER allocate in loop\n  mesh.position.copy(pos);\n}\n\n\u002F\u002F CORRECT: reuse pre-allocated objects\nconst _tempVec = new THREE.Vector3();\nfunction animate() {\n  _tempVec.set(1, 2, 3);\n  mesh.position.copy(_tempVec);\n}\n```\n\n**Rule**: ALWAYS declare temporary math objects (`Vector3`, `Matrix4`, `Quaternion`, `Color`, `Box3`) outside the animation loop. Prefix with `_` to indicate they are reusable scratch variables.\n\n---\n\n## Shader and Material Optimization\n\n| Action | Impact |\n|--------|--------|\n| Use `MeshStandardMaterial` instead of `MeshPhysicalMaterial` | Fewer shader instructions unless you need clearcoat\u002Ftransmission\u002Fsheen |\n| Minimize unique material count | Fewer shader compilations; ALWAYS share materials across identical meshes |\n| Set `material.precision = 'mediump'` on mobile | Faster fragment shading on mobile GPUs |\n| Avoid `onBeforeCompile` unless necessary | Each unique modification creates a new shader variant |\n\n---\n\n## Chrome DevTools Profiling\n\n1. **Performance tab**: Record a few seconds, look for long \"GPU\" tasks and JS frame duration\n2. **Memory tab**: Take heap snapshots before and after scene changes to find unreleased objects\n3. **`renderer.info` logging**: Add a periodic `console.log(renderer.info.memory)` to detect leaks\n4. **WebGL Inspector** (browser extension): Inspect draw calls, textures, and shader programs\n\n---\n\n## Critical Warnings\n\n**NEVER** create `BufferGeometry`, `Material`, or `Texture` objects inside the render\u002Fanimation loop. This causes memory to grow without bound.\n\n**NEVER** call `renderer.render()` after `renderer.dispose()`. The WebGL context is destroyed.\n\n**NEVER** dispose shared geometry\u002Fmaterial\u002Ftexture while other meshes still reference it. Track reference counts or dispose only when ALL consumers are removed.\n\n**ALWAYS** dispose old textures before replacing: `if (material.map) material.map.dispose(); material.map = newTexture;`\n\n**ALWAYS** call `controls.dispose()` when removing OrbitControls or other control instances. Failing to do so leaks DOM event listeners.\n\n**ALWAYS** set `instanceMatrix.needsUpdate = true` after calling `setMatrixAt()` on an `InstancedMesh`. Without this, instances render at the origin.\n\n---\n\n## Reference Links\n\n- [references\u002Fmethods.md](references\u002Fmethods.md) -- Disposal and profiling API signatures\n- [references\u002Fexamples.md](references\u002Fexamples.md) -- Performance optimization code examples\n- [references\u002Fanti-patterns.md](references\u002Fanti-patterns.md) -- Common performance mistakes and fixes\n\n### Official Sources\n\n- Disposal guide: https:\u002F\u002Fthreejs.org\u002Fdocs\u002F#manual\u002Fen\u002Fintroduction\u002FHow-to-dispose-of-objects\n- WebGLRenderer.info: https:\u002F\u002Fthreejs.org\u002Fdocs\u002F#api\u002Fen\u002Frenderers\u002FWebGLRenderer\n- InstancedMesh: https:\u002F\u002Fthreejs.org\u002Fdocs\u002F#api\u002Fen\u002Fobjects\u002FInstancedMesh\n- LOD: https:\u002F\u002Fthreejs.org\u002Fdocs\u002F#api\u002Fen\u002Fobjects\u002FLOD\n- BufferGeometryUtils: https:\u002F\u002Fthreejs.org\u002Fdocs\u002F#examples\u002Fen\u002Futils\u002FBufferGeometryUtils\n","# threejs-errors-performance\n\n## Performance Diagnosis Flowchart\n\n```\nScene is slow \u002F low FPS\n│\n├─ Check renderer.info.render.calls\n│  ├─ > 200 draw calls ──────────────── Go to: Draw Call Optimization\n│  └─ \u003C 200 draw calls\n│\n├─ Check renderer.info.memory\n│  ├─ geometries\u002Ftextures growing ──── Go to: Memory Leak Diagnosis\n│  └─ stable counts\n│\n├─ Check renderer.info.render.triangles\n│  ├─ > 2M triangles ────────────────── Go to: Geometry Optimization (LOD, merge)\n│  └─ \u003C 2M triangles\n│\n├─ Check GPU load (DevTools Performance tab)\n│  ├─ GPU-bound (long GPU tasks) ───── Go to: Shader \u002F Material Optimization\n│  └─ CPU-bound (long JS tasks) ────── Go to: CPU Optimization\n│\n└─ Check Stats.js memory panel\n   ├─ JS heap growing ─────────────── Go to: JavaScript Object Leaks\n   └─ Heap stable ──────────────────── Profile specific bottleneck\n```\n\n## Quick Reference\n\n### renderer.info: Your First Diagnostic Tool\n\n```javascript\nimport * as THREE from 'three';\n\n\u002F\u002F ALWAYS check renderer.info when diagnosing performance\nconsole.log(renderer.info.render);\n\u002F\u002F { calls: number, triangles: number, points: number, lines: number, frame: number }\n\nconsole.log(renderer.info.memory);\n\u002F\u002F { geometries: number, textures: number }\n\nconsole.log(renderer.info.programs);\n\u002F\u002F Array of compiled shader programs (length = unique material combinations)\n```\n\n**Rule**: If `renderer.info.memory.geometries` or `renderer.info.memory.textures` grows continuously over time, you have a memory leak. ALWAYS monitor these values during development.\n\n### Stats.js: FPS and Memory Monitoring\n\n```javascript\nimport Stats from 'three\u002Faddons\u002Flibs\u002Fstats.module.js';\n\nconst stats = new Stats();\nstats.showPanel(0); \u002F\u002F 0 = FPS, 1 = MS per frame, 2 = MB heap\ndocument.body.appendChild(stats.dom);\n\nfunction animate() {\n  stats.begin();\n  renderer.render(scene, camera);\n  stats.end();\n  requestAnimationFrame(animate);\n}\n```\n\n### Performance Budgets\n\n| Metric | Target (60 FPS) | Warning | Critical |\n|--------|-----------------|---------|----------|\n| Draw calls | \u003C 100 | 100-500 | > 500 |\n| Triangles | \u003C 1M | 1M-3M | > 3M |\n| Textures (GPU) | \u003C 50 | 50-200 | > 200 |\n| Shader programs | \u003C 20 | 20-50 | > 50 |\n| Frame time | \u003C 16.6ms | 16.6-33ms | > 33ms |\n\n---\n\n## Memory Management: Disposal Rules\n\n### What MUST Be Disposed\n\nThree.js allocates GPU resources that are NOT automatically garbage collected by JavaScript. ALWAYS dispose these manually:\n\n| Object Type | Method | GPU Resource Released |\n|-------------|--------|---------------------|\n| `BufferGeometry` | `geometry.dispose()` | Vertex\u002Findex buffers |\n| `Material` (all types) | `material.dispose()` | Shader programs, uniforms |\n| `Texture` (all types) | `texture.dispose()` | GPU texture memory |\n| `WebGLRenderTarget` | `renderTarget.dispose()` | Framebuffer + textures |\n| `WebGLRenderer` | `renderer.dispose()` | Entire WebGL context |\n| `PMREMGenerator` | `pmremGenerator.dispose()` | Prefiltered env maps |\n| Controls (all types) | `controls.dispose()` | DOM event listeners |\n\n### Complete Material Disposal\n\n```javascript\nfunction disposeMaterial(material) {\n  const textureProps = [\n    'map', 'lightMap', 'bumpMap', 'normalMap', 'specularMap',\n    'envMap', 'alphaMap', 'aoMap', 'displacementMap',\n    'emissiveMap', 'gradientMap', 'metalnessMap', 'roughnessMap',\n    'clearcoatMap', 'clearcoatNormalMap', 'clearcoatRoughnessMap',\n    'transmissionMap', 'thicknessMap', 'sheenColorMap', 'sheenRoughnessMap'\n  ];\n  for (const prop of textureProps) {\n    if (material[prop]) material[prop].dispose();\n  }\n  material.dispose();\n}\n```\n\n### Full Scene Disposal\n\n```javascript\nfunction disposeScene(scene) {\n  scene.traverse((object) => {\n    if (object.geometry) {\n      object.geometry.dispose();\n    }\n    if (object.material) {\n      if (Array.isArray(object.material)) {\n        object.material.forEach(disposeMaterial);\n      } else {\n        disposeMaterial(object.material);\n      }\n    }\n  });\n  scene.clear();\n}\n```\n\n### When to Dispose vs. When to Reuse\n\n**ALWAYS dispose when:**\n- Removing objects permanently from the scene\n- Switching between completely different scenes\n- Unloading loaded models (GLTF, FBX, OBJ)\n- Component unmount (React, Vue, Angular)\n\n**NEVER dispose when:**\n- Temporarily hiding objects (use `visible = false` instead)\n- Objects will be re-added to the scene later\n- Multiple meshes share the same geometry\u002Fmaterial (dispose ONLY when ALL users are done)\n\n---\n\n## Draw Call Optimization\n\n### InstancedMesh: Render Thousands in One Call\n\nALWAYS use `InstancedMesh` when rendering more than ~100 copies of the same geometry+material combination.\n\n```javascript\nimport * as THREE from 'three';\n\nconst geometry = new THREE.BoxGeometry(1, 1, 1);\nconst material = new THREE.MeshStandardMaterial({ color: 0x00ff00 });\nconst count = 5000;\nconst mesh = new THREE.InstancedMesh(geometry, material, count);\n\nconst dummy = new THREE.Object3D();\nfor (let i = 0; i \u003C count; i++) {\n  dummy.position.set(Math.random() * 200 - 100, 0, Math.random() * 200 - 100);\n  dummy.rotation.y = Math.random() * Math.PI * 2;\n  dummy.scale.setScalar(0.5 + Math.random());\n  dummy.updateMatrix();\n  mesh.setMatrixAt(i, dummy.matrix);\n}\n\u002F\u002F CRITICAL: without this, instances render at origin\nmesh.instanceMatrix.needsUpdate = true;\nscene.add(mesh);\n```\n\n| Instance Count | Recommendation |\n|---------------|----------------|\n| \u003C 10 | Individual `Mesh` objects are fine |\n| 10-100 | Either approach; profile your case |\n| 100-10,000 | ALWAYS use `InstancedMesh` |\n| > 10,000 | `InstancedMesh` with spatial subdivision or `BatchedMesh` (r160+) |\n\n### BatchedMesh (r160+): Multiple Geometries in One Call\n\n`BatchedMesh` extends instancing to support different geometries and materials in a single draw call. Use for heterogeneous repeated objects.\n\n### Geometry Merging: Static Objects\n\nFor static objects that NEVER move independently, merge them into a single geometry:\n\n```javascript\nimport { mergeGeometries } from 'three\u002Faddons\u002Futils\u002FBufferGeometryUtils.js';\n\nconst geometries = meshArray.map((m) => {\n  const geo = m.geometry.clone();\n  geo.applyMatrix4(m.matrixWorld);\n  return geo;\n});\nconst merged = mergeGeometries(geometries, false);\nconst mergedMesh = new THREE.Mesh(merged, sharedMaterial);\n\n\u002F\u002F Dispose originals after merge\nmeshArray.forEach((m) => {\n  m.geometry.dispose();\n  scene.remove(m);\n});\n```\n\n**Rule**: NEVER merge geometries that need independent transforms, materials, or raycasting targets. Merging makes individual object interaction impossible.\n\n---\n\n## LOD (Level of Detail)\n\n```javascript\nimport * as THREE from 'three';\n\nconst lod = new THREE.LOD();\nlod.addLevel(highDetailMesh, 0);    \u002F\u002F visible 0-50 units\nlod.addLevel(mediumDetailMesh, 50); \u002F\u002F visible 50-200 units\nlod.addLevel(lowDetailMesh, 200);   \u002F\u002F visible 200+ units\nscene.add(lod);\n\n\u002F\u002F ALWAYS call in animation loop for distance-based switching\nlod.update(camera);\n```\n\n**Rule**: ALWAYS provide at least 3 LOD levels for objects visible across a wide distance range. Triangle counts MUST decrease by at least 50% between each level.\n\n---\n\n## Texture Optimization\n\n| Technique | Impact | When to Use |\n|-----------|--------|-------------|\n| Resize textures | High | ALWAYS use the smallest resolution that looks acceptable |\n| Power-of-two dimensions | Medium | Required for mipmaps; ALWAYS use (256, 512, 1024, 2048) |\n| Compressed formats (KTX2\u002FBasis) | High | ALWAYS for production; 4-6x smaller GPU footprint |\n| Texture atlases | High | Combine multiple small textures into one to reduce draw calls |\n| `texture.dispose()` on swap | Critical | ALWAYS dispose old texture before assigning new one |\n| `generateMipmaps: false` | Low | Use for UI textures or textures that NEVER need filtering at distance |\n\n### KTX2 Compressed Textures\n\n```javascript\nimport { KTX2Loader } from 'three\u002Faddons\u002Floaders\u002FKTX2Loader.js';\n\nconst ktx2Loader = new KTX2Loader()\n  .setTranscoderPath('three\u002Faddons\u002Flibs\u002Fbasis\u002F')\n  .detectSupport(renderer);\n\nktx2Loader.load('texture.ktx2', (texture) => {\n  material.map = texture;\n  material.needsUpdate = true;\n});\n```\n\n---\n\n## Frustum Culling\n\nFrustum culling is enabled by default (`object.frustumCulled = true`). The renderer skips objects outside the camera view.\n\n**NEVER disable frustum culling globally.** Only set `frustumCulled = false` on specific objects that MUST render regardless of camera (skyboxes, large particle systems, full-screen post-processing quads).\n\n**Rule**: For `InstancedMesh`, frustum culling operates on the entire instance group as one bounding sphere. If instances are spread across a large area, split them into spatial groups for effective culling.\n\n---\n\n## Object Pooling\n\nNEVER create and destroy objects every frame. Use object pools for frequently spawned\u002Fdespawned objects:\n\n```javascript\nclass MeshPool {\n  constructor(geometry, material, poolSize) {\n    this.pool = [];\n    for (let i = 0; i \u003C poolSize; i++) {\n      const mesh = new THREE.Mesh(geometry, material);\n      mesh.visible = false;\n      this.pool.push(mesh);\n    }\n    this.activeIndex = 0;\n  }\n\n  acquire() {\n    if (this.activeIndex >= this.pool.length) return null;\n    const mesh = this.pool[this.activeIndex++];\n    mesh.visible = true;\n    return mesh;\n  }\n\n  release(mesh) {\n    mesh.visible = false;\n    const idx = this.pool.indexOf(mesh);\n    if (idx !== -1 && idx \u003C this.activeIndex) {\n      [this.pool[idx], this.pool[this.activeIndex - 1]] =\n        [this.pool[this.activeIndex - 1], this.pool[idx]];\n      this.activeIndex--;\n    }\n  }\n}\n```\n\n---\n\n## CPU-Side Optimization\n\n### Static Object Matrix Optimization\n\nFor objects that NEVER move after initial placement:\n\n```javascript\nobject.matrixAutoUpdate = false;\nobject.updateMatrix(); \u002F\u002F compute once\n```\n\nThis prevents the renderer from recalculating the local matrix every frame for static objects.\n\n### Avoid Allocations in the Render Loop\n\n```javascript\n\u002F\u002F WRONG: creates new Vector3 every frame — GC pressure\nfunction animate() {\n  const pos = new THREE.Vector3(1, 2, 3); \u002F\u002F NEVER allocate in loop\n  mesh.position.copy(pos);\n}\n\n\u002F\u002F CORRECT: reuse pre-allocated objects\nconst _tempVec = new THREE.Vector3();\nfunction animate() {\n  _tempVec.set(1, 2, 3);\n  mesh.position.copy(_tempVec);\n}\n```\n\n**Rule**: ALWAYS declare temporary math objects (`Vector3`, `Matrix4`, `Quaternion`, `Color`, `Box3`) outside the animation loop. Prefix with `_` to indicate they are reusable scratch variables.\n\n---\n\n## Shader and Material Optimization\n\n| Action | Impact |\n|--------|--------|\n| Use `MeshStandardMaterial` instead of `MeshPhysicalMaterial` | Fewer shader instructions unless you need clearcoat\u002Ftransmission\u002Fsheen |\n| Minimize unique material count | Fewer shader compilations; ALWAYS share materials across identical meshes |\n| Set `material.precision = 'mediump'` on mobile | Faster fragment shading on mobile GPUs |\n| Avoid `onBeforeCompile` unless necessary | Each unique modification creates a new shader variant |\n\n---\n\n## Chrome DevTools Profiling\n\n1. **Performance tab**: Record a few seconds, look for long \"GPU\" tasks and JS frame duration\n2. **Memory tab**: Take heap snapshots before and after scene changes to find unreleased objects\n3. **`renderer.info` logging**: Add a periodic `console.log(renderer.info.memory)` to detect leaks\n4. **WebGL Inspector** (browser extension): Inspect draw calls, textures, and shader programs\n\n---\n\n## Critical Warnings\n\n**NEVER** create `BufferGeometry`, `Material`, or `Texture` objects inside the render\u002Fanimation loop. This causes memory to grow without bound.\n\n**NEVER** call `renderer.render()` after `renderer.dispose()`. The WebGL context is destroyed.\n\n**NEVER** dispose shared geometry\u002Fmaterial\u002Ftexture while other meshes still reference it. Track reference counts or dispose only when ALL consumers are removed.\n\n**ALWAYS** dispose old textures before replacing: `if (material.map) material.map.dispose(); material.map = newTexture;`\n\n**ALWAYS** call `controls.dispose()` when removing OrbitControls or other control instances. Failing to do so leaks DOM event listeners.\n\n**ALWAYS** set `instanceMatrix.needsUpdate = true` after calling `setMatrixAt()` on an `InstancedMesh`. Without this, instances render at the origin.\n\n---\n\n## Reference Links\n\n- [references\u002Fmethods.md](references\u002Fmethods.md) -- Disposal and profiling API signatures\n- [references\u002Fexamples.md](references\u002Fexamples.md) -- Performance optimization code examples\n- [references\u002Fanti-patterns.md](references\u002Fanti-patterns.md) -- Common performance mistakes and fixes\n\n### Official Sources\n\n- Disposal guide: https:\u002F\u002Fthreejs.org\u002Fdocs\u002F#manual\u002Fen\u002Fintroduction\u002FHow-to-dispose-of-objects\n- WebGLRenderer.info: https:\u002F\u002Fthreejs.org\u002Fdocs\u002F#api\u002Fen\u002Frenderers\u002FWebGLRenderer\n- InstancedMesh: https:\u002F\u002Fthreejs.org\u002Fdocs\u002F#api\u002Fen\u002Fobjects\u002FInstancedMesh\n- LOD: https:\u002F\u002Fthreejs.org\u002Fdocs\u002F#api\u002Fen\u002Fobjects\u002FLOD\n- BufferGeometryUtils: https:\u002F\u002Fthreejs.org\u002Fdocs\u002F#examples\u002Fen\u002Futils\u002FBufferGeometryUtils\n",{"name":5,"license":14,"metadata":23,"description":26,"compatibility":27},{"author":24,"version":25},"OpenAEC-Foundation","1.0","Use when a Three.js scene has performance problems: low FPS, memory leaks, too many draw calls, or high GPU memory usage. Prevents the common mistake of forgetting dispose(), creating objects in the render loop, or not using InstancedMesh for repeated objects. Covers disposal patterns, draw call optimization, InstancedMesh, LOD, texture compression, renderer.info, Stats.js profiling. Keywords: performance, memory leak, dispose, draw calls, FPS, slow, optimization, InstancedMesh, LOD, renderer.info, Stats, profiling, laggy, low FPS, stuttering, browser freezes.\n","Designed for Claude Code. Requires Three.js r160+.","main","4c174e06a831864e98c30f630a7aa6c04738b094","skills\u002F_intake\u002Fgithub\u002FImpertio-Studio\u002FThree.js-Claude-Skill-Package\u002Fthreejs-errors-performance","https:\u002F\u002Fgithub.com\u002Fmhyahya854\u002FAI-Second-Brain_Universal-Rules","https:\u002F\u002Fgithub.com\u002Fmhyahya854","2026-11-06 02:03:37",{"source":8,"skillName":5,"commands":35,"prompt":45,"zipAvailable":46},[36,39,42],{"tool":37,"command":38},"npx","npx skills add mhyahya854\u002FAI-Second-Brain_Universal-Rules --skill threejs-errors-performance",{"tool":40,"command":41},"bunx","bunx skills add mhyahya854\u002FAI-Second-Brain_Universal-Rules --skill threejs-errors-performance",{"tool":43,"command":44},"pnpm","pnpm dlx skills add mhyahya854\u002FAI-Second-Brain_Universal-Rules --skill threejs-errors-performance","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fmhyahya854\u002FAI-Second-Brain_Universal-Rules\u002Fblob\u002Fmain\u002Fskills\u002F_intake\u002Fgithub\u002FImpertio-Studio\u002FThree.js-Claude-Skill-Package\u002Fthreejs-errors-performance\u002FSKILL.md",true,[48,53,59,63],{"path":49,"resourceType":50,"resourceTypeDesc":51,"sizeBytes":13,"sourceHtmlUrl":52},".gitkeep","OTHER","其他","https:\u002F\u002Fgithub.com\u002Fmhyahya854\u002FAI-Second-Brain_Universal-Rules\u002Fblob\u002Fmain\u002Fskills\u002F_intake\u002Fgithub\u002FImpertio-Studio\u002FThree.js-Claude-Skill-Package\u002Fthreejs-errors-performance\u002F.gitkeep",{"path":54,"resourceType":55,"resourceTypeDesc":56,"sizeBytes":57,"sourceHtmlUrl":58},"references\u002Fanti-patterns.md","REFERENCE","参考文档",7607,"https:\u002F\u002Fgithub.com\u002Fmhyahya854\u002FAI-Second-Brain_Universal-Rules\u002Fblob\u002Fmain\u002Fskills\u002F_intake\u002Fgithub\u002FImpertio-Studio\u002FThree.js-Claude-Skill-Package\u002Fthreejs-errors-performance\u002Freferences\u002Fanti-patterns.md",{"path":60,"resourceType":55,"resourceTypeDesc":56,"sizeBytes":61,"sourceHtmlUrl":62},"references\u002Fexamples.md",6972,"https:\u002F\u002Fgithub.com\u002Fmhyahya854\u002FAI-Second-Brain_Universal-Rules\u002Fblob\u002Fmain\u002Fskills\u002F_intake\u002Fgithub\u002FImpertio-Studio\u002FThree.js-Claude-Skill-Package\u002Fthreejs-errors-performance\u002Freferences\u002Fexamples.md",{"path":64,"resourceType":55,"resourceTypeDesc":56,"sizeBytes":65,"sourceHtmlUrl":66},"references\u002Fmethods.md",5571,"https:\u002F\u002Fgithub.com\u002Fmhyahya854\u002FAI-Second-Brain_Universal-Rules\u002Fblob\u002Fmain\u002Fskills\u002F_intake\u002Fgithub\u002FImpertio-Studio\u002FThree.js-Claude-Skill-Package\u002Fthreejs-errors-performance\u002Freferences\u002Fmethods.md",[68,76,84,92,99,106],{"skillNo":69,"name":70,"nameZh":6,"description":71,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":72,"sourceHtmlUrl":73,"categories":74,"keywords":75,"publishedAt":18},"01M7EX4T721AAH60R0239P8WBZ","frontend-slides","Create stunning, animation-rich HTML presentations from scratch or by converting PowerPoint files. Use when the user wants to build a presentation, convert a PPT\u002FPPTX to web, or create slides for a talk\u002Fpitch. Helps non-designers discover their aesthetic through visual exploration rather than abstract choices.","https:\u002F\u002Fgithub.com\u002Fmhyahya854\u002FAI-Second-Brain_Universal-Rules\u002Fblob\u002Fmain\u002Fskills\u002F_intake\u002Fgithub\u002Fzarazhangrui\u002Ffrontend-slides\u002Ffrontend-slides\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fmhyahya854\u002FAI-Second-Brain_Universal-Rules\u002Fblob\u002Fmain\u002Fskills\u002F_intake\u002Fgithub\u002Fzarazhangrui\u002Ffrontend-slides\u002Ffrontend-slides\u002FSKILL.md",[],[],{"skillNo":77,"name":78,"nameZh":6,"description":79,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":80,"sourceHtmlUrl":81,"categories":82,"keywords":83,"publishedAt":18},"01M7EX495RSHTTCEJVX7C83FA3","design-dna","Extract, define, and apply design DNA across three dimensions: design system (tokens), design style (qualitative feel), and visual effects (Canvas, WebGL, 3D, particles, shaders, scroll effects, etc.). Use this skill when: (1) a user wants to see the full 3-dimension design structure\u002Fschema, (2) a user provides images, screenshots, or URLs of reference designs and wants them analyzed into a structured JSON profile covering all three dimensions, (3) a user has a Design DNA JSON and content and wants a design generated from it, or (4) any combination of these phases. Triggers on \"design DNA\", \"extract design style\", \"analyze design\", \"design tokens from reference\", \"generate design from JSON\", \"design system from screenshot\", \"design profile\", \"style guide JSON\", \"visual effects analysis\", \"design with effects\", \"3d design analysis\".","https:\u002F\u002Fgithub.com\u002Fmhyahya854\u002FAI-Second-Brain_Universal-Rules\u002Fblob\u002Fmain\u002Fskills\u002F_intake\u002Fgithub\u002Fzanwei\u002Fdesign-dna\u002Fdesign-dna\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fmhyahya854\u002FAI-Second-Brain_Universal-Rules\u002Fblob\u002Fmain\u002Fskills\u002F_intake\u002Fgithub\u002Fzanwei\u002Fdesign-dna\u002Fdesign-dna\u002FSKILL.md",[],[],{"skillNo":85,"name":86,"nameZh":6,"description":87,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":88,"sourceHtmlUrl":89,"categories":90,"keywords":91,"publishedAt":18},"01M7EX45RF2XZKRC3KDJDTT1PH","wireframe","Generate JSON wireframe with HTML preview","https:\u002F\u002Fgithub.com\u002Fmhyahya854\u002FAI-Second-Brain_Universal-Rules\u002Fblob\u002Fmain\u002Fskills\u002F_intake\u002Fgithub\u002Fyhassy\u002Fwireframe-skill\u002Fwireframe-skill\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fmhyahya854\u002FAI-Second-Brain_Universal-Rules\u002Fblob\u002Fmain\u002Fskills\u002F_intake\u002Fgithub\u002Fyhassy\u002Fwireframe-skill\u002Fwireframe-skill\u002FSKILL.md",[],[],{"skillNo":93,"name":94,"nameZh":6,"description":95,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":96,"categories":97,"keywords":98,"publishedAt":18},"01M7EWZEM3MHD48AYSYFR2C9JP","social-publishing","Schedule and publish social media posts across 13 platforms (X, LinkedIn, Instagram, Facebook Pages, TikTok, Discord, Telegram, YouTube, Reddit, WordPress, Pinterest) via the SocialClaw API. Use when the user wants to publish, schedule, or manage social media content programmatically. Requires SOCIALCLAW_API_KEY.","https:\u002F\u002Fgithub.com\u002Fmhyahya854\u002FAI-Second-Brain_Universal-Rules\u002Fblob\u002Fmain\u002Fskills\u002F_intake\u002Fgithub\u002Fwshobson\u002Fagents\u002Fsocial-publishing\u002FSKILL.md",[],[],{"skillNo":100,"name":101,"nameZh":6,"description":102,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":103,"categories":104,"keywords":105,"publishedAt":18},"01M7EWKDEK9840C728VXT78EQ9","hermes-tweet","Install and operate Hermes Tweet, a Hermes Agent plugin for X\u002FTwitter research, timeline reading, tweet analysis, and approval-gated private or state-changing operations. Use this skill when installing Hermes Tweet, researching X\u002FTwitter accounts, monitoring launch signals, investigating mentions, auditing giveaways, or preparing gated X operations. Use proactively when a Hermes Agent workflow needs current X\u002FTwitter context. Requires XQUIK_API_KEY for read and action tools.","https:\u002F\u002Fgithub.com\u002Fmhyahya854\u002FAI-Second-Brain_Universal-Rules\u002Fblob\u002Fmain\u002Fskills\u002F_intake\u002Fgithub\u002Fwshobson\u002Fagents\u002Fhermes-tweet\u002FSKILL.md",[],[],{"skillNo":107,"name":108,"nameZh":6,"description":109,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":110,"categories":111,"keywords":112,"publishedAt":18},"01M7EWASXP3NZWW95CJPT2CRWN","refactoring-ui","Audit and fix visual hierarchy, spacing, color, and depth in web UIs. Use when the user mentions \"my UI looks off\" (or amateur\u002Funprofessional), \"fix the design\", \"Tailwind styling\", \"color palette\", \"visual hierarchy\", \"design system\", \"spacing scale\", or \"component styling\". Also trigger when building consistent design tokens, creating dark mode themes, improving data-visualization clarity, or polishing UI details before launch. Covers grayscale-first workflow, constrained design scales, shadows, and component styling. For typeface selection, see web-typography. For usability audits, see ux-heuristics.","https:\u002F\u002Fgithub.com\u002Fmhyahya854\u002FAI-Second-Brain_Universal-Rules\u002Fblob\u002Fmain\u002Fskills\u002F_intake\u002Fgithub\u002Fwondelai\u002Fskills\u002Frefactoring-ui\u002FSKILL.md",[],[]]