recastJSPlugin.ts 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592
  1. import { INavigationEnginePlugin, ICrowd, IAgentParameters, INavMeshParameters } from "../../Navigation/INavigationEngine";
  2. import { Logger } from "../../Misc/logger";
  3. import { VertexData } from "../../Meshes/mesh.vertexData";
  4. import { Mesh } from "../../Meshes/mesh";
  5. import { Scene } from "../../scene";
  6. import { Vector3 } from '../../Maths/math';
  7. import { TransformNode } from "../../Meshes/transformNode";
  8. import { Observer } from "../../Misc/observable";
  9. import { Nullable } from "../../types";
  10. import { VertexBuffer } from "../../Meshes/buffer";
  11. declare var Recast: any;
  12. /**
  13. * RecastJS navigation plugin
  14. */
  15. export class RecastJSPlugin implements INavigationEnginePlugin {
  16. /**
  17. * Reference to the Recast library
  18. */
  19. public bjsRECAST: any = {};
  20. /**
  21. * plugin name
  22. */
  23. public name: string = "RecastJSPlugin";
  24. /**
  25. * the first navmesh created. We might extend this to support multiple navmeshes
  26. */
  27. public navMesh: any;
  28. /**
  29. * Initializes the recastJS plugin
  30. * @param recastInjection can be used to inject your own recast reference
  31. */
  32. public constructor(recastInjection: any = Recast) {
  33. if (typeof recastInjection === "function") {
  34. recastInjection(this.bjsRECAST);
  35. } else {
  36. this.bjsRECAST = recastInjection;
  37. }
  38. if (!this.isSupported()) {
  39. Logger.Error("RecastJS is not available. Please make sure you included the js file.");
  40. return;
  41. }
  42. }
  43. /**
  44. * Creates a navigation mesh
  45. * @param meshes array of all the geometry used to compute the navigatio mesh
  46. * @param parameters bunch of parameters used to filter geometry
  47. */
  48. createNavMesh(meshes: Array<Mesh>, parameters: INavMeshParameters): void {
  49. const rc = new this.bjsRECAST.rcConfig();
  50. rc.cs = parameters.cs;
  51. rc.ch = parameters.ch;
  52. rc.borderSize = 0;
  53. rc.tileSize = 0;
  54. rc.walkableSlopeAngle = parameters.walkableSlopeAngle;
  55. rc.walkableHeight = parameters.walkableHeight;
  56. rc.walkableClimb = parameters.walkableClimb;
  57. rc.walkableRadius = parameters.walkableRadius;
  58. rc.maxEdgeLen = parameters.maxEdgeLen;
  59. rc.maxSimplificationError = parameters.maxSimplificationError;
  60. rc.minRegionArea = parameters.minRegionArea;
  61. rc.mergeRegionArea = parameters.mergeRegionArea;
  62. rc.maxVertsPerPoly = parameters.maxVertsPerPoly;
  63. rc.detailSampleDist = parameters.detailSampleDist;
  64. rc.detailSampleMaxError = parameters.detailSampleMaxError;
  65. this.navMesh = new this.bjsRECAST.NavMesh();
  66. var index: number;
  67. var tri: number;
  68. var pt: number;
  69. var indices = [];
  70. var positions = [];
  71. var offset = 0;
  72. for (index = 0; index < meshes.length; index++) {
  73. if (meshes[index]) {
  74. var mesh = meshes[index];
  75. const meshIndices = mesh.getIndices();
  76. if (!meshIndices) {
  77. continue;
  78. }
  79. const meshPositions = mesh.getVerticesData(VertexBuffer.PositionKind, false, false);
  80. if (!meshPositions) {
  81. continue;
  82. }
  83. const wm = mesh.computeWorldMatrix(true);
  84. for (tri = 0; tri < meshIndices.length; tri++) {
  85. indices.push(meshIndices[tri] + offset);
  86. }
  87. var transformed = Vector3.Zero();
  88. var position = Vector3.Zero();
  89. for (pt = 0; pt < meshPositions.length; pt += 3) {
  90. Vector3.FromArrayToRef(meshPositions, pt, position);
  91. Vector3.TransformCoordinatesToRef(position, wm, transformed);
  92. positions.push(transformed.x, transformed.y, transformed.z);
  93. }
  94. offset += meshPositions.length / 3;
  95. }
  96. }
  97. this.navMesh.build(positions, offset, indices, indices.length, rc);
  98. }
  99. /**
  100. * Create a navigation mesh debug mesh
  101. * @param scene is where the mesh will be added
  102. * @returns debug display mesh
  103. */
  104. createDebugNavMesh(scene: Scene): Mesh {
  105. var tri: number;
  106. var pt: number;
  107. var debugNavMesh = this.navMesh.getDebugNavMesh();
  108. let triangleCount = debugNavMesh.getTriangleCount();
  109. var indices = [];
  110. var positions = [];
  111. for (tri = 0; tri < triangleCount * 3; tri++)
  112. {
  113. indices.push(tri);
  114. }
  115. for (tri = 0; tri < triangleCount; tri++)
  116. {
  117. for (pt = 0; pt < 3 ; pt++)
  118. {
  119. let point = debugNavMesh.getTriangle(tri).getPoint(pt);
  120. positions.push(point.x, point.y, point.z);
  121. }
  122. }
  123. var mesh = new Mesh("NavMeshDebug", scene);
  124. var vertexData = new VertexData();
  125. vertexData.indices = indices;
  126. vertexData.positions = positions;
  127. vertexData.applyToMesh(mesh, false);
  128. return mesh;
  129. }
  130. /**
  131. * Get a navigation mesh constrained position, closest to the parameter position
  132. * @param position world position
  133. * @returns the closest point to position constrained by the navigation mesh
  134. */
  135. getClosestPoint(position: Vector3) : Vector3
  136. {
  137. var p = new this.bjsRECAST.Vec3(position.x, position.y, position.z);
  138. var ret = this.navMesh.getClosestPoint(p);
  139. var pr = new Vector3(ret.x, ret.y, ret.z);
  140. return pr;
  141. }
  142. /**
  143. * Get a navigation mesh constrained position, closest to the parameter position
  144. * @param position world position
  145. * @param result output the closest point to position constrained by the navigation mesh
  146. */
  147. getClosestPointToRef(position: Vector3, result: Vector3) : void {
  148. var p = new this.bjsRECAST.Vec3(position.x, position.y, position.z);
  149. var ret = this.navMesh.getClosestPoint(p);
  150. result.set(ret.x, ret.y, ret.z);
  151. }
  152. /**
  153. * Get a navigation mesh constrained position, within a particular radius
  154. * @param position world position
  155. * @param maxRadius the maximum distance to the constrained world position
  156. * @returns the closest point to position constrained by the navigation mesh
  157. */
  158. getRandomPointAround(position: Vector3, maxRadius: number): Vector3 {
  159. var p = new this.bjsRECAST.Vec3(position.x, position.y, position.z);
  160. var ret = this.navMesh.getRandomPointAround(p, maxRadius);
  161. var pr = new Vector3(ret.x, ret.y, ret.z);
  162. return pr;
  163. }
  164. /**
  165. * Get a navigation mesh constrained position, within a particular radius
  166. * @param position world position
  167. * @param maxRadius the maximum distance to the constrained world position
  168. * @param result output the closest point to position constrained by the navigation mesh
  169. */
  170. getRandomPointAroundToRef(position: Vector3, maxRadius: number, result: Vector3): void {
  171. var p = new this.bjsRECAST.Vec3(position.x, position.y, position.z);
  172. var ret = this.navMesh.getRandomPointAround(p, maxRadius);
  173. result.set(ret.x, ret.y, ret.z);
  174. }
  175. /**
  176. * Compute the final position from a segment made of destination-position
  177. * @param position world position
  178. * @param destination world position
  179. * @returns the resulting point along the navmesh
  180. */
  181. moveAlong(position: Vector3, destination: Vector3): Vector3 {
  182. var p = new this.bjsRECAST.Vec3(position.x, position.y, position.z);
  183. var d = new this.bjsRECAST.Vec3(destination.x, destination.y, destination.z);
  184. var ret = this.navMesh.moveAlong(p, d);
  185. var pr = new Vector3(ret.x, ret.y, ret.z);
  186. return pr;
  187. }
  188. /**
  189. * Compute the final position from a segment made of destination-position
  190. * @param position world position
  191. * @param destination world position
  192. * @param result output the resulting point along the navmesh
  193. */
  194. moveAlongToRef(position: Vector3, destination: Vector3, result: Vector3): void {
  195. var p = new this.bjsRECAST.Vec3(position.x, position.y, position.z);
  196. var d = new this.bjsRECAST.Vec3(destination.x, destination.y, destination.z);
  197. var ret = this.navMesh.moveAlong(p, d);
  198. result.set(ret.x, ret.y, ret.z);
  199. }
  200. /**
  201. * Compute a navigation path from start to end. Returns an empty array if no path can be computed
  202. * @param start world position
  203. * @param end world position
  204. * @returns array containing world position composing the path
  205. */
  206. computePath(start: Vector3, end: Vector3): Vector3[]
  207. {
  208. var pt: number;
  209. let startPos = new this.bjsRECAST.Vec3(start.x, start.y, start.z);
  210. let endPos = new this.bjsRECAST.Vec3(end.x, end.y, end.z);
  211. let navPath = this.navMesh.computePath(startPos, endPos);
  212. let pointCount = navPath.getPointCount();
  213. var positions = [];
  214. for (pt = 0; pt < pointCount; pt++)
  215. {
  216. let p = navPath.getPoint(pt);
  217. positions.push(new Vector3(p.x, p.y, p.z));
  218. }
  219. return positions;
  220. }
  221. /**
  222. * Create a new Crowd so you can add agents
  223. * @param maxAgents the maximum agent count in the crowd
  224. * @param maxAgentRadius the maximum radius an agent can have
  225. * @param scene to attach the crowd to
  226. * @returns the crowd you can add agents to
  227. */
  228. createCrowd(maxAgents: number, maxAgentRadius: number, scene: Scene) : ICrowd
  229. {
  230. var crowd = new RecastJSCrowd(this, maxAgents, maxAgentRadius, scene);
  231. return crowd;
  232. }
  233. /**
  234. * Set the Bounding box extent for doing spatial queries (getClosestPoint, getRandomPointAround, ...)
  235. * The queries will try to find a solution within those bounds
  236. * default is (1,1,1)
  237. * @param extent x,y,z value that define the extent around the queries point of reference
  238. */
  239. setDefaultQueryExtent(extent: Vector3): void
  240. {
  241. let ext = new this.bjsRECAST.Vec3(extent.x, extent.y, extent.z);
  242. this.navMesh.setDefaultQueryExtent(ext);
  243. }
  244. /**
  245. * Get the Bounding box extent specified by setDefaultQueryExtent
  246. * @returns the box extent values
  247. */
  248. getDefaultQueryExtent(): Vector3
  249. {
  250. let p = this.navMesh.getDefaultQueryExtent();
  251. return new Vector3(p.x, p.y, p.z);
  252. }
  253. /**
  254. * build the navmesh from a previously saved state using getNavmeshData
  255. * @param data the Uint8Array returned by getNavmeshData
  256. */
  257. buildFromNavmeshData(data: Uint8Array): void
  258. {
  259. var nDataBytes = data.length * data.BYTES_PER_ELEMENT;
  260. var dataPtr = this.bjsRECAST._malloc(nDataBytes);
  261. var dataHeap = new Uint8Array(this.bjsRECAST.HEAPU8.buffer, dataPtr, nDataBytes);
  262. dataHeap.set(data);
  263. let buf = new this.bjsRECAST.NavmeshData();
  264. buf.dataPointer = dataHeap.byteOffset;
  265. buf.size = data.length;
  266. this.navMesh = new this.bjsRECAST.NavMesh();
  267. this.navMesh.buildFromNavmeshData(buf);
  268. // Free memory
  269. this.bjsRECAST._free(dataHeap.byteOffset);
  270. }
  271. /**
  272. * returns the navmesh data that can be used later. The navmesh must be built before retrieving the data
  273. * @returns data the Uint8Array that can be saved and reused
  274. */
  275. getNavmeshData(): Uint8Array
  276. {
  277. let navmeshData = this.navMesh.getNavmeshData();
  278. var arrView = new Uint8Array(this.bjsRECAST.HEAPU8.buffer, navmeshData.dataPointer, navmeshData.size);
  279. var ret = new Uint8Array(navmeshData.size);
  280. ret.set(arrView);
  281. this.navMesh.freeNavmeshData(navmeshData);
  282. return ret;
  283. }
  284. /**
  285. * Get the Bounding box extent result specified by setDefaultQueryExtent
  286. * @param result output the box extent values
  287. */
  288. getDefaultQueryExtentToRef(result: Vector3): void
  289. {
  290. let p = this.navMesh.getDefaultQueryExtent();
  291. result.set(p.x, p.y, p.z);
  292. }
  293. /**
  294. * Disposes
  295. */
  296. public dispose() {
  297. }
  298. /**
  299. * If this plugin is supported
  300. * @returns true if plugin is supported
  301. */
  302. public isSupported(): boolean {
  303. return this.bjsRECAST !== undefined;
  304. }
  305. }
  306. /**
  307. * Recast detour crowd implementation
  308. */
  309. export class RecastJSCrowd implements ICrowd {
  310. /**
  311. * Recast/detour plugin
  312. */
  313. public bjsRECASTPlugin: RecastJSPlugin;
  314. /**
  315. * Link to the detour crowd
  316. */
  317. public recastCrowd: any = {};
  318. /**
  319. * One transform per agent
  320. */
  321. public transforms: TransformNode[] = new Array<TransformNode>();
  322. /**
  323. * All agents created
  324. */
  325. public agents: number[] = new Array<number>();
  326. /**
  327. * Link to the scene is kept to unregister the crowd from the scene
  328. */
  329. private _scene: Scene;
  330. /**
  331. * Observer for crowd updates
  332. */
  333. private _onBeforeAnimationsObserver: Nullable<Observer<Scene>> = null;
  334. /**
  335. * Constructor
  336. * @param plugin recastJS plugin
  337. * @param maxAgents the maximum agent count in the crowd
  338. * @param maxAgentRadius the maximum radius an agent can have
  339. * @param scene to attach the crowd to
  340. * @returns the crowd you can add agents to
  341. */
  342. public constructor(plugin: RecastJSPlugin, maxAgents: number, maxAgentRadius: number, scene: Scene) {
  343. this.bjsRECASTPlugin = plugin;
  344. this.recastCrowd = new this.bjsRECASTPlugin.bjsRECAST.Crowd(maxAgents, maxAgentRadius, this.bjsRECASTPlugin.navMesh.getNavMesh());
  345. this._scene = scene;
  346. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(() => {
  347. this.update(scene.getEngine().getDeltaTime() * 0.001);
  348. });
  349. }
  350. /**
  351. * Add a new agent to the crowd with the specified parameter a corresponding transformNode.
  352. * You can attach anything to that node. The node position is updated in the scene update tick.
  353. * @param pos world position that will be constrained by the navigation mesh
  354. * @param parameters agent parameters
  355. * @param transform hooked to the agent that will be update by the scene
  356. * @returns agent index
  357. */
  358. addAgent(pos: Vector3, parameters: IAgentParameters, transform: TransformNode): number
  359. {
  360. var agentParams = new this.bjsRECASTPlugin.bjsRECAST.dtCrowdAgentParams();
  361. agentParams.radius = parameters.radius;
  362. agentParams.height = parameters.height;
  363. agentParams.maxAcceleration = parameters.maxAcceleration;
  364. agentParams.maxSpeed = parameters.maxSpeed;
  365. agentParams.collisionQueryRange = parameters.collisionQueryRange;
  366. agentParams.pathOptimizationRange = parameters.pathOptimizationRange;
  367. agentParams.separationWeight = parameters.separationWeight;
  368. agentParams.updateFlags = 7;
  369. agentParams.obstacleAvoidanceType = 0;
  370. agentParams.queryFilterType = 0;
  371. agentParams.userData = 0;
  372. var agentIndex = this.recastCrowd.addAgent(new this.bjsRECASTPlugin.bjsRECAST.Vec3(pos.x, pos.y, pos.z), agentParams);
  373. this.transforms.push(transform);
  374. this.agents.push(agentIndex);
  375. return agentIndex;
  376. }
  377. /**
  378. * Returns the agent position in world space
  379. * @param index agent index returned by addAgent
  380. * @returns world space position
  381. */
  382. getAgentPosition(index: number): Vector3 {
  383. var agentPos = this.recastCrowd.getAgentPosition(index);
  384. return new Vector3(agentPos.x, agentPos.y, agentPos.z);
  385. }
  386. /**
  387. * Returns the agent position result in world space
  388. * @param index agent index returned by addAgent
  389. * @param result output world space position
  390. */
  391. getAgentPositionToRef(index: number, result: Vector3): void {
  392. var agentPos = this.recastCrowd.getAgentPosition(index);
  393. result.set(agentPos.x, agentPos.y, agentPos.z);
  394. }
  395. /**
  396. * Returns the agent velocity in world space
  397. * @param index agent index returned by addAgent
  398. * @returns world space velocity
  399. */
  400. getAgentVelocity(index: number): Vector3 {
  401. var agentVel = this.recastCrowd.getAgentVelocity(index);
  402. return new Vector3(agentVel.x, agentVel.y, agentVel.z);
  403. }
  404. /**
  405. * Returns the agent velocity result in world space
  406. * @param index agent index returned by addAgent
  407. * @param result output world space velocity
  408. */
  409. getAgentVelocityToRef(index: number, result: Vector3): void {
  410. var agentVel = this.recastCrowd.getAgentVelocity(index);
  411. result.set(agentVel.x, agentVel.y, agentVel.z);
  412. }
  413. /**
  414. * Asks a particular agent to go to a destination. That destination is constrained by the navigation mesh
  415. * @param index agent index returned by addAgent
  416. * @param destination targeted world position
  417. */
  418. agentGoto(index: number, destination: Vector3): void {
  419. this.recastCrowd.agentGoto(index, new this.bjsRECASTPlugin.bjsRECAST.Vec3(destination.x, destination.y, destination.z));
  420. }
  421. /**
  422. * Teleport the agent to a new position
  423. * @param index agent index returned by addAgent
  424. * @param destination targeted world position
  425. */
  426. agentTeleport(index: number, destination: Vector3): void {
  427. this.recastCrowd.agentTeleport(index, new this.bjsRECASTPlugin.bjsRECAST.Vec3(destination.x, destination.y, destination.z));
  428. }
  429. /**
  430. * Update agent parameters
  431. * @param index agent index returned by addAgent
  432. * @param parameters agent parameters
  433. */
  434. updateAgentParameters(index: number, parameters: IAgentParameters): void {
  435. var agentParams = this.recastCrowd.getAgentParameters(index);
  436. if (parameters.radius !== undefined) {
  437. agentParams.radius = parameters.radius;
  438. }
  439. if (parameters.height !== undefined) {
  440. agentParams.height = parameters.height;
  441. }
  442. if (parameters.maxAcceleration !== undefined) {
  443. agentParams.maxAcceleration = parameters.maxAcceleration;
  444. }
  445. if (parameters.maxSpeed !== undefined) {
  446. agentParams.maxSpeed = parameters.maxSpeed;
  447. }
  448. if (parameters.collisionQueryRange !== undefined) {
  449. agentParams.collisionQueryRange = parameters.collisionQueryRange;
  450. }
  451. if (parameters.pathOptimizationRange !== undefined) {
  452. agentParams.pathOptimizationRange = parameters.pathOptimizationRange;
  453. }
  454. if (parameters.separationWeight !== undefined) {
  455. agentParams.separationWeight = parameters.separationWeight;
  456. }
  457. this.recastCrowd.setAgentParameters(index, agentParams);
  458. }
  459. /**
  460. * remove a particular agent previously created
  461. * @param index agent index returned by addAgent
  462. */
  463. removeAgent(index: number): void {
  464. this.recastCrowd.removeAgent(index);
  465. var item = this.agents.indexOf(index);
  466. if (item > -1) {
  467. this.agents.splice(item, 1);
  468. this.transforms.splice(item, 1);
  469. }
  470. }
  471. /**
  472. * get the list of all agents attached to this crowd
  473. * @returns list of agent indices
  474. */
  475. getAgents(): number[] {
  476. return this.agents;
  477. }
  478. /**
  479. * Tick update done by the Scene. Agent position/velocity/acceleration is updated by this function
  480. * @param deltaTime in seconds
  481. */
  482. update(deltaTime: number): void {
  483. // update crowd
  484. this.recastCrowd.update(deltaTime);
  485. // update transforms
  486. for (let index = 0; index < this.agents.length; index++)
  487. {
  488. this.transforms[index].position = this.getAgentPosition(this.agents[index]);
  489. }
  490. }
  491. /**
  492. * Set the Bounding box extent for doing spatial queries (getClosestPoint, getRandomPointAround, ...)
  493. * The queries will try to find a solution within those bounds
  494. * default is (1,1,1)
  495. * @param extent x,y,z value that define the extent around the queries point of reference
  496. */
  497. setDefaultQueryExtent(extent: Vector3): void
  498. {
  499. let ext = new this.bjsRECASTPlugin.bjsRECAST.Vec3(extent.x, extent.y, extent.z);
  500. this.recastCrowd.setDefaultQueryExtent(ext);
  501. }
  502. /**
  503. * Get the Bounding box extent specified by setDefaultQueryExtent
  504. * @returns the box extent values
  505. */
  506. getDefaultQueryExtent(): Vector3
  507. {
  508. let p = this.recastCrowd.getDefaultQueryExtent();
  509. return new Vector3(p.x, p.y, p.z);
  510. }
  511. /**
  512. * Get the Bounding box extent result specified by setDefaultQueryExtent
  513. * @param result output the box extent values
  514. */
  515. getDefaultQueryExtentToRef(result: Vector3): void
  516. {
  517. let p = this.recastCrowd.getDefaultQueryExtent();
  518. result.set(p.x, p.y, p.z);
  519. }
  520. /**
  521. * Release all resources
  522. */
  523. dispose() : void
  524. {
  525. this.recastCrowd.destroy();
  526. this._scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  527. this._onBeforeAnimationsObserver = null;
  528. }
  529. }