├── .github ├── codeql │ └── codeql-config.yml └── workflows │ ├── codeql.yml │ ├── docs.yaml │ ├── eslint.yml │ ├── node.js.yml │ └── npm-publish.yml ├── .gitignore ├── LICENSE ├── README.md ├── docs ├── .gitignore ├── CONTRIBUTE.md ├── astro.config.mjs ├── package-lock.json ├── package.json ├── public │ ├── android-chrome-192x192.png │ ├── android-chrome-512x512.png │ ├── apple-touch-icon.png │ ├── favicon-16x16.png │ ├── favicon-32x32.png │ ├── favicon.ico │ └── low_poly_space_ship.glb ├── src │ ├── assets │ │ ├── samoyed-mascot-moved.png │ │ ├── samoyed-mascot.png │ │ └── site.webmanifest │ ├── components │ │ ├── Example │ │ │ ├── CodeWrapper.astro │ │ │ ├── Example.astro │ │ │ ├── OpenInStackblitz.astro │ │ │ ├── stackblitz-files │ │ │ │ ├── index.html │ │ │ │ ├── stackblitz-package.json │ │ │ │ ├── stackblitz-tsconfig.json │ │ │ │ └── stackblitz-vite.config.ts │ │ │ ├── stackblitz-template.ts │ │ │ └── types.ts │ │ └── Intro │ │ │ ├── Intro.astro │ │ │ ├── floor.ts │ │ │ ├── intro.ts │ │ │ ├── random.ts │ │ │ ├── smoke.ts │ │ │ └── spaceship.ts │ ├── content │ │ ├── config.ts │ │ └── docs │ │ │ ├── advanced │ │ │ ├── buffer-capacity.mdx │ │ │ ├── lod.mdx │ │ │ ├── multimaterial.mdx │ │ │ ├── patch-shader.mdx │ │ │ ├── shadow-lod.mdx │ │ │ ├── skinning.mdx │ │ │ └── texture-partial-update.mdx │ │ │ ├── basics │ │ │ ├── 00-add-remove.mdx │ │ │ ├── 01-Instancedentity.mdx │ │ │ ├── 02-animation.mdx │ │ │ ├── 03-euler.mdx │ │ │ ├── 04-tween.mdx │ │ │ ├── 05-custom-data.mdx │ │ │ ├── 06-frustum-culling.mdx │ │ │ ├── 07-sorting.mdx │ │ │ ├── 08-raycasting.mdx │ │ │ ├── 09-bvh-build.mdx │ │ │ └── 10-uniform-per-instance.mdx │ │ │ ├── getting-started │ │ │ ├── 00-introduction.mdx │ │ │ ├── 01-installation.mdx │ │ │ └── 02-first-instancedmesh2.mdx │ │ │ ├── index.mdx │ │ │ └── more │ │ │ ├── faq.mdx │ │ │ ├── know-issue.mdx │ │ │ └── performance-tips.mdx │ ├── env.d.ts │ ├── examples │ │ ├── add-remove │ │ │ └── index.ts │ │ ├── animation │ │ │ ├── app.ts │ │ │ └── index.ts │ │ ├── euler │ │ │ ├── app.ts │ │ │ └── index.ts │ │ ├── first │ │ │ ├── app.ts │ │ │ └── index.ts │ │ ├── frustum-culling │ │ │ ├── app.ts │ │ │ └── index.ts │ │ ├── instances-array │ │ │ ├── app.ts │ │ │ └── index.ts │ │ ├── instances-custom-data │ │ │ ├── app.ts │ │ │ └── index.ts │ │ ├── raycasting │ │ │ └── index.ts │ │ ├── sorting │ │ │ ├── app.ts │ │ │ └── index.ts │ │ └── tween │ │ │ ├── app.ts │ │ │ └── index.ts │ └── pages │ │ └── examples │ │ ├── Loader.astro │ │ └── [...slug].astro ├── tsconfig.build.json └── tsconfig.json ├── eslint.config.js ├── examples ├── LOD.ts ├── createEntities.ts ├── customMaterial.ts ├── customMaterialTextureArray.ts ├── dynamicBVH.ts ├── fastRaycasting.ts ├── instancedMeshParse.ts ├── morph.ts ├── multimaterial.ts ├── multimaterial_tree.ts ├── objects │ ├── createSimplifiedGeometry.ts │ ├── random.ts │ ├── tileLambertMaterial.ts │ └── tileMaterial.ts ├── overrideMaterial.ts ├── remove-instance.ts ├── remove-instances.ts ├── shadowLOD.ts ├── skeleton.ts ├── sorting.ts ├── template.ts ├── test.ts ├── trees.ts ├── tween.ts └── uniforms.ts ├── index.html ├── package-lock.json ├── package.json ├── public ├── banner.png ├── grass.jpg ├── grass_normal.jpg ├── js.png ├── pattern.jpg ├── pine.glb ├── pine_low.glb ├── planks.jpg ├── texture.png ├── tree.glb ├── ts.png └── wall.jpg ├── src ├── core │ ├── InstancedEntity.ts │ ├── InstancedMesh2.ts │ ├── InstancedMeshBVH.ts │ ├── feature │ │ ├── Capacity.ts │ │ ├── FrustumCulling.ts │ │ ├── Instances.ts │ │ ├── LOD.ts │ │ ├── Morph.ts │ │ ├── Raycasting.ts │ │ ├── Skeleton.ts │ │ └── Uniforms.ts │ └── utils │ │ ├── GLInstancedBufferAttribute.ts │ │ ├── InstancedRenderList.ts │ │ └── SquareDataTexture.ts ├── index.ts ├── shaders │ ├── ShaderChunk.ts │ └── chunks │ │ ├── instanced_color_pars_vertex.glsl │ │ ├── instanced_color_vertex.glsl │ │ ├── instanced_pars_vertex.glsl │ │ ├── instanced_skinning_pars_vertex.glsl │ │ └── instanced_vertex.glsl └── utils │ ├── CreateFrom.ts │ └── SortingUtils.ts ├── tsconfig.build.json ├── tsconfig.json └── vite.config.js /.github/codeql/codeql-config.yml: -------------------------------------------------------------------------------- 1 | name: "CodeQL config" 2 | 3 | paths-ignore: 4 | - "node_modules" 5 | - "examples" -------------------------------------------------------------------------------- /.github/workflows/codeql.yml: -------------------------------------------------------------------------------- 1 | # For most projects, this workflow file will not need changing; you simply need 2 | # to commit it to your repository. 3 | # 4 | # You may wish to alter this file to override the set of languages analyzed, 5 | # or to provide custom queries or build logic. 6 | # 7 | # ******** NOTE ******** 8 | # We have attempted to detect the languages in your repository. Please check 9 | # the `language` matrix defined below to confirm you have the correct set of 10 | # supported CodeQL languages. 11 | # 12 | name: "CodeQL" 13 | 14 | on: 15 | push: 16 | branches: [ "master" ] 17 | pull_request: 18 | branches: [ "master" ] 19 | schedule: 20 | - cron: '23 22 * * 3' 21 | 22 | jobs: 23 | analyze: 24 | name: Analyze (${{ matrix.language }}) 25 | # Runner size impacts CodeQL analysis time. To learn more, please see: 26 | # - https://gh.io/recommended-hardware-resources-for-running-codeql 27 | # - https://gh.io/supported-runners-and-hardware-resources 28 | # - https://gh.io/using-larger-runners (GitHub.com only) 29 | # Consider using larger runners or machines with greater resources for possible analysis time improvements. 30 | runs-on: ${{ (matrix.language == 'swift' && 'macos-latest') || 'ubuntu-latest' }} 31 | permissions: 32 | # required for all workflows 33 | security-events: write 34 | 35 | # required to fetch internal or private CodeQL packs 36 | packages: read 37 | 38 | # only required for workflows in private repositories 39 | actions: read 40 | contents: read 41 | 42 | strategy: 43 | fail-fast: false 44 | matrix: 45 | include: 46 | - language: javascript-typescript 47 | build-mode: none 48 | # CodeQL supports the following values keywords for 'language': 'c-cpp', 'csharp', 'go', 'java-kotlin', 'javascript-typescript', 'python', 'ruby', 'swift' 49 | # Use `c-cpp` to analyze code written in C, C++ or both 50 | # Use 'java-kotlin' to analyze code written in Java, Kotlin or both 51 | # Use 'javascript-typescript' to analyze code written in JavaScript, TypeScript or both 52 | # To learn more about changing the languages that are analyzed or customizing the build mode for your analysis, 53 | # see https://docs.github.com/en/code-security/code-scanning/creating-an-advanced-setup-for-code-scanning/customizing-your-advanced-setup-for-code-scanning. 54 | # If you are analyzing a compiled language, you can modify the 'build-mode' for that language to customize how 55 | # your codebase is analyzed, see https://docs.github.com/en/code-security/code-scanning/creating-an-advanced-setup-for-code-scanning/codeql-code-scanning-for-compiled-languages 56 | steps: 57 | - name: Checkout repository 58 | uses: actions/checkout@v4 59 | - run: npm ci 60 | - run: npm run build 61 | 62 | 63 | # Initializes the CodeQL tools for scanning. 64 | - name: Initialize CodeQL 65 | uses: github/codeql-action/init@v3 66 | with: 67 | languages: ${{ matrix.language }} 68 | build-mode: ${{ matrix.build-mode }} 69 | 70 | # If you wish to specify custom queries, you can do so here or in a config file. 71 | # By default, queries listed here will override any specified in a config file. 72 | # Prefix the list here with "+" to use these queries and those in the config file. 73 | 74 | # For more details on CodeQL's query packs, refer to: https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs 75 | # queries: security-extended,security-and-quality 76 | 77 | - name: Autobuild 78 | uses: github/codeql-action/autobuild@v3 79 | 80 | - name: Perform CodeQL Analysis 81 | uses: github/codeql-action/analyze@v3 82 | with: 83 | category: "/language:${{matrix.language}}" 84 | -------------------------------------------------------------------------------- /.github/workflows/docs.yaml: -------------------------------------------------------------------------------- 1 | name: Deploy docs to GitHub Pages 2 | 3 | on: 4 | # Trigger the workflow every time you push or open pull_request to the `master` branch 5 | # Using a different branch name? Replace `master` with your branch’s name 6 | push: 7 | branches: [ master ] 8 | pull_request: 9 | branches: [ master ] 10 | workflow_dispatch: 11 | 12 | # Allow this job to clone the repo and create a page deployment 13 | permissions: 14 | contents: read 15 | pages: write 16 | id-token: write 17 | 18 | jobs: 19 | build: 20 | runs-on: ubuntu-latest 21 | steps: 22 | - name: Checkout your repository using git 23 | uses: actions/checkout@v4 24 | - name: Install dependencies 25 | shell: bash 26 | working-directory: ./docs 27 | run: npm install 28 | - name: Build documentation 29 | shell: bash 30 | working-directory: ./docs 31 | run: npm run build 32 | - name: Upload Pages artifact 33 | if: github.event_name != 'pull_request' 34 | uses: actions/upload-pages-artifact@v3 35 | with: 36 | path: "./docs/dist/" 37 | deploy: 38 | needs: build 39 | if: github.event_name != 'pull_request' 40 | runs-on: ubuntu-latest 41 | environment: 42 | name: github-pages 43 | url: ${{ steps.deployment.outputs.page_url }} 44 | steps: 45 | - name: Deploy to GitHub Pages 46 | id: deployment 47 | uses: actions/deploy-pages@v4 -------------------------------------------------------------------------------- /.github/workflows/eslint.yml: -------------------------------------------------------------------------------- 1 | name: ESLint 2 | 3 | on: 4 | push: 5 | branches: [ "master" ] 6 | pull_request: 7 | # The branches below must be a subset of the branches above 8 | branches: [ "*" ] 9 | schedule: 10 | - cron: '19 7 * * 2' 11 | 12 | jobs: 13 | eslint: 14 | name: Run eslint scanning 15 | runs-on: ubuntu-latest 16 | permissions: 17 | contents: read 18 | security-events: write 19 | actions: read # only required for a private repository by github/codeql-action/upload-sarif to get the Action run status 20 | steps: 21 | - name: Checkout code 22 | uses: actions/checkout@v4 23 | 24 | - name: Install ESLint 25 | run: | 26 | npm ci 27 | npm install @microsoft/eslint-formatter-sarif@2.1.7 28 | 29 | - name: Run ESLint 30 | run: npx eslint . 31 | --format @microsoft/eslint-formatter-sarif 32 | --output-file eslint-results.sarif 33 | continue-on-error: true 34 | 35 | - name: Upload analysis results to GitHub 36 | uses: github/codeql-action/upload-sarif@v3 37 | with: 38 | sarif_file: eslint-results.sarif 39 | wait-for-processing: true -------------------------------------------------------------------------------- /.github/workflows/node.js.yml: -------------------------------------------------------------------------------- 1 | # This workflow will do a clean installation of node dependencies, cache/restore them, build the source code and run tests across different versions of node 2 | # For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-nodejs 3 | 4 | name: Node.js CI 5 | 6 | on: 7 | push: 8 | branches: [ "master" ] 9 | pull_request: 10 | branches: [ "*" ] 11 | 12 | jobs: 13 | build: 14 | 15 | runs-on: ubuntu-latest 16 | 17 | strategy: 18 | matrix: 19 | node-version: [20.x] 20 | # See supported Node.js release schedule at https://nodejs.org/en/about/releases/ 21 | 22 | steps: 23 | - uses: actions/checkout@v4 24 | - name: Use Node.js ${{ matrix.node-version }} 25 | uses: actions/setup-node@v4 26 | with: 27 | node-version: ${{ matrix.node-version }} 28 | cache: 'npm' 29 | - run: npm ci 30 | - run: npm run build --if-present 31 | - run: npm test 32 | -------------------------------------------------------------------------------- /.github/workflows/npm-publish.yml: -------------------------------------------------------------------------------- 1 | # This workflow will run tests using node and then publish a package to GitHub Packages when a release is created 2 | # For more information see: https://docs.github.com/en/actions/publishing-packages/publishing-nodejs-packages 3 | 4 | name: Node.js Package 5 | 6 | on: 7 | release: 8 | types: [created] 9 | 10 | jobs: 11 | build: 12 | runs-on: ubuntu-latest 13 | steps: 14 | - uses: actions/checkout@v4 15 | - uses: actions/setup-node@v4 16 | with: 17 | node-version: 20 18 | - run: npm ci 19 | - run: npm test 20 | 21 | publish-npm: 22 | needs: build 23 | runs-on: ubuntu-latest 24 | steps: 25 | - uses: actions/checkout@v4 26 | - uses: actions/setup-node@v4 27 | with: 28 | node-version: 20 29 | registry-url: https://registry.npmjs.org/ 30 | - run: npm ci 31 | - run: npm run build 32 | - run: npm publish 33 | env: 34 | NODE_AUTH_TOKEN: ${{secrets.npm_token}} 35 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | dist 3 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2024 Andrea Gargaro 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |

Three.ez - InstancedMesh2

4 |

5 | Simplify your three.js application development with three.ez!

6 | three.ez/batched-mesh-extensions - BatchedMesh extension methods and enhancements for better performance and usability 7 |

8 | 9 | banner
10 | 11 | [![Discord](https://img.shields.io/badge/chat-discord-blue?style=flat&logo=discord)](https://discord.gg/MVTwrdX3JM) 12 | [![npm](https://img.shields.io/npm/v/@three.ez/instanced-mesh)](https://www.npmjs.com/package/@three.ez/instanced-mesh) 13 | [![Stars](https://badgen.net/github/stars/three-ez/instanced-mesh)](https://github.com/three-ez/instanced-mesh) 14 | [![BundlePhobia](https://badgen.net/bundlephobia/min/@three.ez/instanced-mesh)](https://bundlephobia.com/package/@three.ez/instanced-mesh) 15 | [![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=agargaro_instanced-mesh&metric=alert_status)](https://sonarcloud.io/summary/new_code?id=agargaro_instanced-mesh) 16 | [![DeepScan grade](https://deepscan.io/api/teams/21196/projects/27990/branches/896898/badge/grade.svg)](https://deepscan.io/dashboard#view=project&tid=21196&pid=27990&bid=896898) 17 | 18 |
19 | 20 | `InstancedMesh2` is an alternative version of `InstancedMesh` with enhanced features for performance and usability. 21 | 22 | ```ts 23 | const myInstancedMesh = new InstancedMesh2(geometry, material); 24 | 25 | myInstancedMesh.addInstances(count, (obj, index) => { 26 | obj.position.x = index; 27 | }); 28 | ``` 29 | 30 | - [**Dynamic capacity**](#dynamic-capacity): *add or remove instances seamlessly.* 31 | - [**Object3D-like instances**](#object3d-like-instances): *use instances like `Object3D` with transforms and custom data.* 32 | - [**Per-instance frustum culling**](#per-instance-frustum-culling): *skip rendering for out-of-view instances.* 33 | - [**Spatial indexing (dynamic BVH)**](#spatial-indexing-dynamic-bvh): *speed up raycasting and frustum culling.* 34 | - [**Sorting**](#sorting): *reduce overdraw and manage transparent objects efficiently.* 35 | - [**Per-instance visibility**](#per-instance-visibility): *toggle visibility for each instance individually.* 36 | - [**Per-instance opacity**](#per-instance-opacity): *set opacity for each instance individually.* 37 | - [**Per-instance uniforms**](#per-instance-uniforms): *assign unique shader data to individual instances.* 38 | - [**Level of Detail (LOD)**](#level-of-detail-lod): *dynamically adjust instance detail based on distance.* 39 | - [**Shadow LOD**](#shadow-lod): *optimize shadow rendering with lower detail for distant instances.* 40 | - [**Skinning**](#skinning): *apply skeletal animations to instances for more complex and dynamic movements.* 41 | 42 | ## 🧑‍💻 Live Examples 43 | 44 | **Vanilla** 45 | - js [Dynamic adding with BVH](https://stackblitz.com/edit/stackblitz-starters-au96fmqz?file=index.html) (thanks to [Saumac](https://github.com/saumac)) 46 | 47 | **Using three.ez/main** 48 | - ts [1kk static trees](https://stackblitz.com/edit/three-ezinstancedmesh2-1kk-static-trees?file=src%2Fmain.ts&embed=1&hideDevTools=1&view=preview) 49 | - ts [Instances array dynamic](https://stackblitz.com/edit/three-ezinstancedmesh2-instances-array-dynamic?file=src%2Fmain.ts&embed=1&hideDevTools=1&view=preview) 50 | - ts [Sorting](https://stackblitz.com/edit/three-ezinstancedmesh2-sorting?file=src%2Fmain.ts&embed=1&hideDevTools=1&view=preview) 51 | - ts [Uniforms per instance](https://stackblitz.com/edit/three-ezinstancedmesh2-custom-material?file=src%2Fmain.ts&embed=1&hideDevTools=1&view=preview) 52 | - ts [Dynamic BVH (no vite)](https://stackblitz.com/edit/three-ezinstancedmesh2-dynamic-bvh?file=index.ts&embed=1&hideDevTools=1&view=preview) 53 | - ts [Fast raycasting](https://stackblitz.com/edit/three-ezinstancedmesh2-fast-raycasting?file=src%2Fmain.ts&embed=1&hideDevTools=1&view=preview) 54 | - ts [LOD](https://stackblitz.com/edit/three-ezinstancedmesh2-instancedmeshlod?file=src%2Fmain.ts&embed=1&hideDevTools=1&view=preview) 55 | - ts [Shadow LOD](https://stackblitz.com/edit/three-ezinstancedmesh2-shadow-lod?file=src%2Fmain.ts&embed=1&hideDevTools=1&view=preview) 56 | - js [Skinning 3k instances](https://stackblitz.com/edit/three-ezinstancedmesh2-skinning?file=src%2Fmain.ts&embed=1&hideDevTools=1&view=preview) 57 | - js [Dynamic adding with BVH](https://glitch.com/edit/#!/three-ez-instanced-mesh-dynamic-adding-with-bvh?path=main.js) 58 | - js [Skinning](https://glitch.com/edit/#!/instancedmesh2-skinning?path=main.js) 59 | 60 | **Using other libraries** 61 | - Threlte 62 | - js [Tres.js](https://stackblitz.com/edit/vitejs-vite-nhoadwww?file=src/components/TheExperience.vue) (thanks to [JaimeTorrealba](https://github.com/JaimeTorrealba)) 63 | - ts [React-three-fiber](https://stackblitz.com/edit/vitejs-vite-zahmbaan?file=src%2FApp.tsx) (thanks to [Saumac](https://github.com/saumac)) 64 | - js [React-three-fiber](https://stackblitz.com/~/github.com/Lunakepio/ac-2-dna-ui) (thanks to [Lunakepio](https://github.com/Lunakepio)) 65 | 66 | ## ❔ Need help? 67 | 68 | Join us on [Discord](https://discord.gg/MVTwrdX3JM) or open an issue on GitHub. 69 | 70 | ## ⭐ Like it? 71 | 72 | If you like this project, please leave a star. Thank you! ❤️ 73 | 74 | ## 📚 Documentation 75 | 76 | The documentation is available [here](https://agargaro.github.io/instanced-mesh). 77 | 78 | ## ⬇️ Installation 79 | 80 | You can install it via npm using the following command: 81 | 82 | ```bash 83 | npm install @three.ez/instanced-mesh 84 | ``` 85 | 86 | Or you can import it from CDN: 87 | 88 | ```html 89 | 99 | ``` 100 | 101 | ## 🚀 Features 102 | 103 | ### Dynamic capacity 104 | 105 | Manage a dynamic number of instances, automatically expanding the data buffers as needed to accommodate additional instances.
106 | 107 | If not specified, `capacity` is `1000`.
108 | 109 | ```ts 110 | const myInstancedMesh = new InstancedMesh2(geometry, material, { capacity: count }); 111 | 112 | myInstancedMesh.addInstances(count, (obj, index) => { ... }); // add instances and expand buffer if necessary 113 | 114 | myInstancedMesh.removeInstances(id0, id1, ...); 115 | 116 | myInstancedMesh.clearInstances(); // remove all instances 117 | ``` 118 | 119 | ### Object3D-like instances 120 | 121 | It's possible to create an array of `InstancedEntity` **(Object3D-like)** in order to easily manipulate instances, using more memory. 122 | 123 | ```ts 124 | const myInstancedMesh = new InstancedMesh2(geometry, material, { createEntities: true }); 125 | 126 | myInstancedMesh.instances[0].customData = {}; 127 | myInstancedMesh.instances[0].position.random(); 128 | myInstancedMesh.instances[0].rotateX(Math.PI); 129 | myInstancedMesh.instances[0].updateMatrix(); // necessary after transformations 130 | ``` 131 | 132 | ### Per-instance frustum culling 133 | 134 | Avoiding rendering objects outside the camera frustum can drastically improve performance (especially for complex geometries).
135 | Frustum culling by default is performed by iterating all instances, [but it is possible to speed up this process by creating a spatial indexing data structure **(BVH)**](#spatial-indexing-dynamic-bvh).
136 | 137 | By default `perObjectFrustumCulled` is `true`. 138 | 139 | ### Spatial indexing (dynamic BVH) 140 | 141 | **To speed up raycasting and frustum culling**, a spatial indexing data structure can be created to contain the boundingBoxes of all instances.
142 | This works very well if the instances are **mostly static** (updating a BVH can be expensive) and scattered in world space.
143 | 144 | Setting a margin makes BVH updating faster, but may make raycasting and frustum culling slightly slower. 145 | ```ts 146 | myInstancedMesh.computeBVH({ margin: 0 }); // margin is optional 147 | ``` 148 | 149 | ### Sorting 150 | 151 | Sorting can be used to decrease overdraw and render transparent objects.
152 | 153 | It's possible to improve sort performance adding a `customSort`, like built-in `createRadixSort`. 154 | 155 | By default `sortObjects` is `false`.
156 | 157 | ```ts 158 | import { createRadixSort } from '@three.ez/instanced-mesh'; 159 | 160 | myInstancedMesh.sortObjects = true; 161 | myInstancedMesh.customSort = createRadixSort(myInstancedMesh); 162 | ``` 163 | 164 | ### Per-instance visibility 165 | 166 | Set the visibility status of each instance. 167 | 168 | ```ts 169 | myInstancedMesh.setVisibilityAt(index, false); 170 | myInstancedMesh.instances[0].visible = false; // if instances array is created 171 | ``` 172 | 173 | ### Per-instance opacity 174 | 175 | Set the opacity of each instance. It's recommended to enable [**instances sorting**](#sorting) and disable the `depthWriting` of the material. 176 | 177 | ```ts 178 | myInstancedMesh.setOpacityAt(index, 0.5); 179 | myInstancedMesh.instances[0].opacity = 0.5; // if instances array is created 180 | ``` 181 | 182 | ### Per-instance uniforms 183 | 184 | Assign unique shader uniforms to each instance, working with every materials. 185 | 186 | ```ts 187 | myInstancedMesh.initUniformsPerInstance({ fragment: { metalness: 'float', roughness: 'float', emissive: 'vec3' } }); 188 | 189 | myInstancedMesh.setUniformAt(index, 'metalness', 0.5); 190 | myInstancedMesh.instances[0].setUniform('emissive', new Color('white')); // if instances array is created 191 | ``` 192 | 193 | ### Level of Detail (LOD) 194 | 195 | Improve rendering performance by dynamically adjusting the detail level of instances based on their distance from the camera.
196 | Use simplified geometries for distant objects to optimize resources. 197 | 198 | ```ts 199 | myInstancedMesh.addLOD(geometryMid, material, 50); 200 | myInstancedMesh.addLOD(geometryLow, material, 200); 201 | ``` 202 | 203 | ### Shadow LOD 204 | 205 | Optimize shadow rendering by reducing the detail level of instances casting shadows based on their distance from the camera. 206 | 207 | ```ts 208 | myInstancedMesh.addShadowLOD(geometryMid); 209 | myInstancedMesh.addShadowLOD(geometryLow, 100); 210 | ``` 211 | 212 | ### Skinning 213 | 214 | Apply skeletal animations to instances for more complex and dynamic movements. 215 | 216 | ```ts 217 | myInstancedMesh.initSkeleton(skeleton); 218 | 219 | mixer.update(time); 220 | myInstancedMesh.setBonesAt(index); 221 | ``` 222 | 223 | ### Raycasting tips 224 | 225 | If you are not using a BVH, you can set the `raycastOnlyFrustum` property to **true** to avoid iterating over all instances. 226 | 227 | It's recommended to use [three-mesh-bvh](https://github.com/gkjohnson/three-mesh-bvh) to create a geometry BVH. 228 | 229 | ## 🤝 Special thanks to 230 | 231 | - [gkjohnson](https://github.com/gkjohnson) 232 | - [manthrax](https://github.com/manthrax) 233 | - [jungle_hacker](https://github.com/lambocorp) 234 | 235 | ## 📖 References 236 | 237 | - [three-mesh-bvh](https://github.com/gkjohnson/three-mesh-bvh) 238 | - [ErinCatto_DynamicBVH](https://box2d.org/files/ErinCatto_DynamicBVH_Full.pdf) 239 | -------------------------------------------------------------------------------- /docs/.gitignore: -------------------------------------------------------------------------------- 1 | # build output 2 | dist/ 3 | # generated types 4 | .astro/ 5 | 6 | # dependencies 7 | node_modules/ 8 | 9 | # generated api 10 | src/content/docs/api/ 11 | docs/public/examples/ 12 | # logs 13 | npm-debug.log* 14 | yarn-debug.log* 15 | yarn-error.log* 16 | pnpm-debug.log* 17 | # generate js examples 18 | public/examples/** 19 | 20 | # environment variables 21 | .env 22 | .env.production 23 | 24 | # macOS-specific files 25 | .DS_Store 26 | -------------------------------------------------------------------------------- /docs/CONTRIBUTE.md: -------------------------------------------------------------------------------- 1 | # Contributing to Documentation 2 | 3 | This guide explains how to add and maintain documentation for this project, following the [Diátaxis](https://diataxis.fr/) framework principles. 4 | 5 | ## Documentation Types 6 | 7 | We organize documentation into: 8 | 9 | - **Tutorials**: Step-by-step lessons for beginners 10 | - **How-to Guides**: Practical guides in `src/content/docs/guides/` 11 | - **Reference**: Technical details in `src/content/docs/reference/` 12 | - **Explanation**: Concept discussions and background 13 | 14 | ## Adding Documentation Pages 15 | 16 | 1. Choose appropriate directory based on content type: 17 | 18 | ``` 19 | src/content/docs/guides/ # For how-to guides 20 | src/content/docs/reference/ # For technical reference 21 | src/content/docs/tutorials/ # For tutorials 22 | src/content/docs/concepts/ # For explanations 23 | ``` 24 | 25 | 2. Add required frontmatter: 26 | ```md 27 | --- 28 | title: Your Page Title 29 | description: Brief description 30 | --- 31 | ``` 32 | 33 | ## Adding Code Examples 34 | 35 | 1. Create your example: 36 | 37 | ```bash 38 | code src/examples/myExample/index.ts 39 | ``` 40 | 41 | > **Note**: Maximum 2 levels of nesting allowed. Deeper nesting is not supported. 42 | 43 | 2. Write your Three.js code in `index.ts`: 44 | 45 | ```typescript 46 | import { Scene, PerspectiveCamera } from 'three'; 47 | 48 | // Your Three.js example code here 49 | ``` 50 | 51 | > **Note**: you can also import from local files, like `import { MyComponent } from './MyComponent'`. 52 | 53 | 3. Reference in docs with: 54 | 55 | ```md 56 | 57 | ``` 58 | 59 | | Prop | Type | Default | Description | 60 | | ---------------- | ------- | -------- | --------------------------------------- | 61 | | `path` | string | required | Directory path relative to src/examples | 62 | | `hideCode` | boolean | `false` | Hides the source code section | 63 | | `hidePreview` | boolean | `false` | Hides the example preview | 64 | | `hideStackblitz` | boolean | `false` | Hides "Open in Stackblitz" button | 65 | 66 | > **Note**: You can see the example in full screen in path `http://localhost:4321/instanced-mesh/examples/` 67 | 68 | ## Example Guidelines 69 | 70 | ### Keep It Simple 71 | 72 | - Focus on one concept per example 73 | - Add clear code comments 74 | - Avoid mixing multiple complex features 75 | 76 | ### Use Clear Names 77 | 78 | - Use descriptive directory names (e.g. `frustum-culling`) 79 | - Follow kebab-case for directory names 80 | - Avoid generic names 81 | 82 | ### Development 83 | 84 | 1. Available scripts: 85 | 86 | ```bash 87 | npm run dev # Dev mode with hot reload 88 | npm run start # Production preview 89 | npm run build # Production build 90 | ``` 91 | 92 | > **Note**: all of those scripts build the examples, in the public folder. 93 | 94 | ### Dependencies 95 | 96 | - Examples use import maps in `[...slug].astro` 97 | ### Dependencies 98 | 99 | - Examples use import maps in `[...slug].astro` 100 | - Pre-configured libraries: 101 | - `three` 102 | - `@three.ez/main` 103 | - `@three.ez/instanced-mesh` 104 | - `three/examples/jsm/` 105 | - `bvh.js` 106 | - Add new dependencies to `importmap` if needed. 107 | -------------------------------------------------------------------------------- /docs/astro.config.mjs: -------------------------------------------------------------------------------- 1 | // @ts-check 2 | import { defineConfig } from 'astro/config'; 3 | import starlight from '@astrojs/starlight'; 4 | import starlightTypeDoc, { typeDocSidebarGroup } from 'starlight-typedoc'; 5 | import AutoImport from 'astro-auto-import'; 6 | import { resolve } from 'path'; 7 | import mdx from '@astrojs/mdx'; 8 | // https://astro.build/config 9 | export default defineConfig({ 10 | site: 'https://agargaro.github.io/instanced-mesh', 11 | base: 'instanced-mesh', 12 | output: 'static', 13 | vite: { 14 | resolve: { 15 | alias: { $components: resolve('./src/components') }, 16 | }, 17 | }, 18 | integrations: [ 19 | AutoImport({ 20 | imports: ['./src/components/Example/Example.astro'], 21 | }), 22 | starlight({ 23 | plugins: [ 24 | // Generate the documentation. 25 | starlightTypeDoc({ 26 | entryPoints: ['../src/index.ts'], 27 | typeDoc: { 28 | exclude: ['./examples/**/*'], 29 | skipErrorChecking: true, 30 | excludeExternals: true, 31 | }, 32 | tsconfig: '../tsconfig.json', 33 | }), 34 | ], 35 | title: 'InstancedMesh2', 36 | logo: { 37 | src: './src/assets/samoyed-mascot.png', 38 | alt: 'logo-samoyed-mascot', 39 | }, 40 | favicon: './favicon.ico', 41 | social: { 42 | github: 'https://github.com/agargaro/instanced-mesh', 43 | discord: 'https://discord.gg/MVTwrdX3JM', 44 | }, 45 | sidebar: [ 46 | { 47 | label: 'Getting Started', 48 | autogenerate: { directory: 'getting-started' }, 49 | }, 50 | { 51 | label: 'Basics', 52 | autogenerate: { directory: 'basics' }, 53 | }, 54 | { 55 | label: 'Advanced', 56 | autogenerate: { directory: 'advanced' }, 57 | }, 58 | { 59 | label: 'More', 60 | autogenerate: { directory: 'more' }, 61 | }, 62 | // { 63 | // label: 'Reference', 64 | // autogenerate: { directory: 'reference' }, 65 | // }, 66 | // Add the generated sidebar group to the sidebar. 67 | typeDocSidebarGroup, 68 | ], 69 | }), 70 | // Make sure the MDX integration is included AFTER astro-auto-import 71 | mdx(), 72 | ], 73 | }); 74 | -------------------------------------------------------------------------------- /docs/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "docs", 3 | "type": "module", 4 | "version": "0.0.1", 5 | "scripts": { 6 | "dev": "tsc --project tsconfig.build.json & astro dev --host", 7 | "start": "tsc --project tsconfig.build.json & astro dev", 8 | "build": "tsc --project tsconfig.build.json & astro check && astro build", 9 | "preview": "astro preview", 10 | "astro": "astro" 11 | }, 12 | "dependencies": { 13 | "@astrojs/check": "^0.9.4", 14 | "@astrojs/mdx": "^4.1.1", 15 | "@astrojs/starlight": "^0.32.2", 16 | "@stackblitz/sdk": "^1.11.0", 17 | "@three.ez/instanced-mesh": "^0.3.1", 18 | "@three.ez/main": "latest", 19 | "astro": "^5.4.3", 20 | "astro-auto-import": "^0.4.4", 21 | "sharp": "^0.32.5", 22 | "starlight-typedoc": "^0.20.0", 23 | "three": "~0.172.0", 24 | "tweakpane": "^4.0.5", 25 | "typedoc-plugin-markdown": "^4.2.10", 26 | "typescript": "~5.7.2", 27 | "vite": "^6.2.0" 28 | }, 29 | "devDependencies": { 30 | "@types/three": "~0.171.0" 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /docs/public/android-chrome-192x192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/agargaro/instanced-mesh/d1fce71da8552395a10f5e48e4a37d1d28218eca/docs/public/android-chrome-192x192.png -------------------------------------------------------------------------------- /docs/public/android-chrome-512x512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/agargaro/instanced-mesh/d1fce71da8552395a10f5e48e4a37d1d28218eca/docs/public/android-chrome-512x512.png -------------------------------------------------------------------------------- /docs/public/apple-touch-icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/agargaro/instanced-mesh/d1fce71da8552395a10f5e48e4a37d1d28218eca/docs/public/apple-touch-icon.png -------------------------------------------------------------------------------- /docs/public/favicon-16x16.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/agargaro/instanced-mesh/d1fce71da8552395a10f5e48e4a37d1d28218eca/docs/public/favicon-16x16.png -------------------------------------------------------------------------------- /docs/public/favicon-32x32.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/agargaro/instanced-mesh/d1fce71da8552395a10f5e48e4a37d1d28218eca/docs/public/favicon-32x32.png -------------------------------------------------------------------------------- /docs/public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/agargaro/instanced-mesh/d1fce71da8552395a10f5e48e4a37d1d28218eca/docs/public/favicon.ico -------------------------------------------------------------------------------- /docs/public/low_poly_space_ship.glb: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/agargaro/instanced-mesh/d1fce71da8552395a10f5e48e4a37d1d28218eca/docs/public/low_poly_space_ship.glb -------------------------------------------------------------------------------- /docs/src/assets/samoyed-mascot-moved.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/agargaro/instanced-mesh/d1fce71da8552395a10f5e48e4a37d1d28218eca/docs/src/assets/samoyed-mascot-moved.png -------------------------------------------------------------------------------- /docs/src/assets/samoyed-mascot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/agargaro/instanced-mesh/d1fce71da8552395a10f5e48e4a37d1d28218eca/docs/src/assets/samoyed-mascot.png -------------------------------------------------------------------------------- /docs/src/assets/site.webmanifest: -------------------------------------------------------------------------------- 1 | {"name":"","short_name":"","icons":[{"src":"/android-chrome-192x192.png","sizes":"192x192","type":"image/png"},{"src":"/android-chrome-512x512.png","sizes":"512x512","type":"image/png"}],"theme_color":"#ffffff","background_color":"#ffffff","display":"standalone"} -------------------------------------------------------------------------------- /docs/src/components/Example/CodeWrapper.astro: -------------------------------------------------------------------------------- 1 | --- 2 | import { Code } from '@astrojs/starlight/components'; 3 | 4 | type SourceFile = { 5 | [key: string]: string; 6 | }; 7 | 8 | interface Props { 9 | files: SourceFile; 10 | } 11 | 12 | const filesEntries = Object.entries(Astro.props.files); 13 | 14 | type TreeElement = { 15 | filePath: string; 16 | name: string; 17 | } & ( 18 | | { 19 | isFile: true; 20 | content: string; 21 | children?: never; 22 | } 23 | | { 24 | isFile: false; 25 | children: TreeElement[]; 26 | content?: never; 27 | } 28 | ); 29 | 30 | function createRecursiveTree(entries: [string, string][], currentDir: string = ''): TreeElement[] { 31 | const tree: TreeElement[] = []; 32 | const filteredEntries = entries.filter(([path]) => path.startsWith(currentDir)); 33 | 34 | for (const [path, content] of filteredEntries) { 35 | const relativePath = path.slice(currentDir.length).split('/').filter(Boolean); 36 | const [first, ...rest] = relativePath; 37 | 38 | if (rest.length === 0) { 39 | tree.push({ 40 | filePath: path, 41 | name: relativePath[relativePath.length - 1], 42 | isFile: true, 43 | content, 44 | }); 45 | } else { 46 | const existingDir = tree.find((item) => !item.isFile); 47 | 48 | if (existingDir) { 49 | (existingDir as any).children = createRecursiveTree(entries, `${currentDir}${first}/`); 50 | } else { 51 | tree.push({ 52 | filePath: path, 53 | isFile: false, 54 | name: first, 55 | children: createRecursiveTree(entries, `${currentDir}${first}/`), 56 | }); 57 | } 58 | } 59 | } 60 | 61 | return tree; 62 | } 63 | 64 | const tree = createRecursiveTree(filesEntries); 65 | --- 66 | 67 | 175 | 176 | 177 |
178 | 179 |
180 |
181 | 182 | 233 | 234 |
235 | 236 | { 237 | filesEntries.map(([filePath, content], index) => { 238 | if(index === 0) { 239 | return
240 | 241 |
242 | } else { 243 | return
244 | 245 |
} 246 | }) 247 | } 248 |
249 |
250 |
251 | 280 | -------------------------------------------------------------------------------- /docs/src/components/Example/Example.astro: -------------------------------------------------------------------------------- 1 | --- 2 | import CodeWrapper from './CodeWrapper.astro'; 3 | import OpenInStackblitz from './OpenInStackblitz.astro'; 4 | 5 | export const c = (...args: (string | boolean)[]) => { 6 | return args.filter(Boolean).join(' '); 7 | }; 8 | 9 | /** 10 | * Interface defining the properties (Props) that can be passed to the Example component. 11 | * 12 | * @interface Props 13 | * @example 14 | * ```astro 15 | * 16 | * ``` 17 | */ 18 | export interface Props { 19 | /** 20 | * The file path to be processed 21 | * @type {string} 22 | */ 23 | path: string; 24 | /** 25 | * Flag to control the visibility of code section 26 | * @property {boolean} [hideCode] - When true, hides the code section of the component. 27 | * Default is false, showing the code section. 28 | */ 29 | hideCode?: boolean; 30 | /** 31 | * Flag to control whether to hide the preview section. 32 | * When set to true, the preview section will not be displayed. 33 | * @type {boolean} 34 | * @optional 35 | */ 36 | hidePreview?: boolean; 37 | /** 38 | * Whether to hide the Stackblitz editor button. 39 | * @property {boolean} [hideStackblitz=false] - When true, the Stackblitz editor button will not be displayed 40 | */ 41 | hideStackblitz?: boolean; 42 | } 43 | 44 | const allModules = import.meta.glob('../../examples/**/*', { 45 | query: '?raw', 46 | import: 'default', 47 | eager: true, 48 | }) as Record; 49 | 50 | for (const path in allModules) { 51 | if (!path.replace('../../examples/', '').startsWith(Astro.props.path)) { 52 | delete allModules[path]; 53 | } 54 | } 55 | 56 | const files = Astro.props.files ?? {}; 57 | 58 | for (const modulePath in allModules) { 59 | let relativePath = modulePath.replace('../../examples/', '').replace(Astro.props.path, '').slice(1); 60 | if (relativePath.startsWith('/')) { 61 | relativePath = relativePath.slice(1); 62 | } 63 | files[relativePath] = allModules[modulePath]; 64 | } 65 | 66 | const hideCodeResolved = Astro.props.hideCode ?? false; 67 | const hidePreview = Astro.props.hidePreview ?? false; 68 | --- 69 | 70 |
71 | {!hidePreview &&