From 448d2d1d9ac2ebf9fa3f9567aebf683d821cc388 Mon Sep 17 00:00:00 2001 From: Supun-ascentic Date: Fri, 29 Dec 2023 15:35:17 +0530 Subject: [PATCH] Add createConvex --- createConvexRegionHelper.jsx | 64 ++++++++++++++++++++++++++++++++++++ useNavMesh.jsx | 2 +- 2 files changed, 65 insertions(+), 1 deletion(-) create mode 100644 createConvexRegionHelper.jsx diff --git a/createConvexRegionHelper.jsx b/createConvexRegionHelper.jsx new file mode 100644 index 0000000..4b5e79f --- /dev/null +++ b/createConvexRegionHelper.jsx @@ -0,0 +1,64 @@ +/** + * @author Mugen87 / https://github.com/Mugen87 + */ + +import * as THREE from "three"; + +function createConvexRegionHelper(navMesh) { + const regions = navMesh.regions; + + const geometry = new THREE.BufferGeometry(); + const material = new THREE.MeshBasicMaterial({ + vertexColors: true, + }); + + const positions = []; + const colors = []; + + const color = new THREE.Color(); + + for (let region of regions) { + // one color for each convex region + + color.setHex(Math.random() * 0xffffff); + + // count edges + + let edge = region.edge; + const edges = []; + + do { + edges.push(edge); + + edge = edge.next; + } while (edge !== region.edge); + + // triangulate + + const triangleCount = edges.length - 2; + + for (let i = 1, l = triangleCount; i <= l; i++) { + const v1 = edges[0].vertex; + const v2 = edges[i + 0].vertex; + const v3 = edges[i + 1].vertex; + + positions.push(v1.x, v1.y, v1.z); + positions.push(v2.x, v2.y, v2.z); + positions.push(v3.x, v3.y, v3.z); + + colors.push(color.r, color.g, color.b); + colors.push(color.r, color.g, color.b); + colors.push(color.r, color.g, color.b); + } + } + + geometry.setAttribute( + "position", + new THREE.Float32BufferAttribute(positions, 3) + ); + geometry.setAttribute("color", new THREE.Float32BufferAttribute(colors, 3)); + + return { geometry, material }; +} + +export { createConvexRegionHelper }; diff --git a/useNavMesh.jsx b/useNavMesh.jsx index 9fd74b3..fd7faed 100644 --- a/useNavMesh.jsx +++ b/useNavMesh.jsx @@ -1,7 +1,7 @@ import * as THREE from "three"; import { NavMeshLoader, Vector3 } from "yuka"; import { create } from "zustand"; -import { createConvexRegionHelper } from "../utils/createConvexRegionHelper"; +import { createConvexRegionHelper } from "./createConvexRegionHelper"; export const useNavMesh = create((set, get) => ({ raycaster: new THREE.Raycaster(),