recastJSPlugin.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556
  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(false);
  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. * Get the Bounding box extent result specified by setDefaultQueryExtent
  255. * @param result output the box extent values
  256. */
  257. getDefaultQueryExtentToRef(result: Vector3): void
  258. {
  259. let p = this.navMesh.getDefaultQueryExtent();
  260. result.set(p.x, p.y, p.z);
  261. }
  262. /**
  263. * Disposes
  264. */
  265. public dispose() {
  266. }
  267. /**
  268. * If this plugin is supported
  269. * @returns true if plugin is supported
  270. */
  271. public isSupported(): boolean {
  272. return this.bjsRECAST !== undefined;
  273. }
  274. }
  275. /**
  276. * Recast detour crowd implementation
  277. */
  278. export class RecastJSCrowd implements ICrowd {
  279. /**
  280. * Recast/detour plugin
  281. */
  282. public bjsRECASTPlugin: RecastJSPlugin;
  283. /**
  284. * Link to the detour crowd
  285. */
  286. public recastCrowd: any = {};
  287. /**
  288. * One transform per agent
  289. */
  290. public transforms: TransformNode[] = new Array<TransformNode>();
  291. /**
  292. * All agents created
  293. */
  294. public agents: number[] = new Array<number>();
  295. /**
  296. * Link to the scene is kept to unregister the crowd from the scene
  297. */
  298. private _scene: Scene;
  299. /**
  300. * Observer for crowd updates
  301. */
  302. private _onBeforeAnimationsObserver: Nullable<Observer<Scene>> = null;
  303. /**
  304. * Constructor
  305. * @param plugin recastJS plugin
  306. * @param maxAgents the maximum agent count in the crowd
  307. * @param maxAgentRadius the maximum radius an agent can have
  308. * @param scene to attach the crowd to
  309. * @returns the crowd you can add agents to
  310. */
  311. public constructor(plugin: RecastJSPlugin, maxAgents: number, maxAgentRadius: number, scene: Scene) {
  312. this.bjsRECASTPlugin = plugin;
  313. this.recastCrowd = new this.bjsRECASTPlugin.bjsRECAST.Crowd(maxAgents, maxAgentRadius, this.bjsRECASTPlugin.navMesh.getNavMesh());
  314. this._scene = scene;
  315. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(() => {
  316. this.update(scene.getEngine().getDeltaTime() * 0.001);
  317. });
  318. }
  319. /**
  320. * Add a new agent to the crowd with the specified parameter a corresponding transformNode.
  321. * You can attach anything to that node. The node position is updated in the scene update tick.
  322. * @param pos world position that will be constrained by the navigation mesh
  323. * @param parameters agent parameters
  324. * @param transform hooked to the agent that will be update by the scene
  325. * @returns agent index
  326. */
  327. addAgent(pos: Vector3, parameters: IAgentParameters, transform: TransformNode): number
  328. {
  329. var agentParams = new this.bjsRECASTPlugin.bjsRECAST.dtCrowdAgentParams();
  330. agentParams.radius = parameters.radius;
  331. agentParams.height = parameters.height;
  332. agentParams.maxAcceleration = parameters.maxAcceleration;
  333. agentParams.maxSpeed = parameters.maxSpeed;
  334. agentParams.collisionQueryRange = parameters.collisionQueryRange;
  335. agentParams.pathOptimizationRange = parameters.pathOptimizationRange;
  336. agentParams.separationWeight = parameters.separationWeight;
  337. agentParams.updateFlags = 7;
  338. agentParams.obstacleAvoidanceType = 0;
  339. agentParams.queryFilterType = 0;
  340. agentParams.userData = 0;
  341. var agentIndex = this.recastCrowd.addAgent(new this.bjsRECASTPlugin.bjsRECAST.Vec3(pos.x, pos.y, pos.z), agentParams);
  342. this.transforms.push(transform);
  343. this.agents.push(agentIndex);
  344. return agentIndex;
  345. }
  346. /**
  347. * Returns the agent position in world space
  348. * @param index agent index returned by addAgent
  349. * @returns world space position
  350. */
  351. getAgentPosition(index: number): Vector3 {
  352. var agentPos = this.recastCrowd.getAgentPosition(index);
  353. return new Vector3(agentPos.x, agentPos.y, agentPos.z);
  354. }
  355. /**
  356. * Returns the agent position result in world space
  357. * @param index agent index returned by addAgent
  358. * @param result output world space position
  359. */
  360. getAgentPositionToRef(index: number, result: Vector3): void {
  361. var agentPos = this.recastCrowd.getAgentPosition(index);
  362. result.set(agentPos.x, agentPos.y, agentPos.z);
  363. }
  364. /**
  365. * Returns the agent velocity in world space
  366. * @param index agent index returned by addAgent
  367. * @returns world space velocity
  368. */
  369. getAgentVelocity(index: number): Vector3 {
  370. var agentVel = this.recastCrowd.getAgentVelocity(index);
  371. return new Vector3(agentVel.x, agentVel.y, agentVel.z);
  372. }
  373. /**
  374. * Returns the agent velocity result in world space
  375. * @param index agent index returned by addAgent
  376. * @param result output world space velocity
  377. */
  378. getAgentVelocityToRef(index: number, result: Vector3): void {
  379. var agentVel = this.recastCrowd.getAgentVelocity(index);
  380. result.set(agentVel.x, agentVel.y, agentVel.z);
  381. }
  382. /**
  383. * Asks a particular agent to go to a destination. That destination is constrained by the navigation mesh
  384. * @param index agent index returned by addAgent
  385. * @param destination targeted world position
  386. */
  387. agentGoto(index: number, destination: Vector3): void {
  388. this.recastCrowd.agentGoto(index, new this.bjsRECASTPlugin.bjsRECAST.Vec3(destination.x, destination.y, destination.z));
  389. }
  390. /**
  391. * Teleport the agent to a new position
  392. * @param index agent index returned by addAgent
  393. * @param destination targeted world position
  394. */
  395. agentTeleport(index: number, destination: Vector3): void {
  396. this.recastCrowd.agentTeleport(index, new this.bjsRECASTPlugin.bjsRECAST.Vec3(destination.x, destination.y, destination.z));
  397. }
  398. /**
  399. * Update agent parameters
  400. * @param index agent index returned by addAgent
  401. * @param parameters agent parameters
  402. */
  403. updateAgentParameters(index: number, parameters: IAgentParameters): void {
  404. var agentParams = this.recastCrowd.getAgentParameters(index);
  405. if (parameters.radius !== undefined) {
  406. agentParams.radius = parameters.radius;
  407. }
  408. if (parameters.height !== undefined) {
  409. agentParams.height = parameters.height;
  410. }
  411. if (parameters.maxAcceleration !== undefined) {
  412. agentParams.maxAcceleration = parameters.maxAcceleration;
  413. }
  414. if (parameters.maxSpeed !== undefined) {
  415. agentParams.maxSpeed = parameters.maxSpeed;
  416. }
  417. if (parameters.collisionQueryRange !== undefined) {
  418. agentParams.collisionQueryRange = parameters.collisionQueryRange;
  419. }
  420. if (parameters.pathOptimizationRange !== undefined) {
  421. agentParams.pathOptimizationRange = parameters.pathOptimizationRange;
  422. }
  423. if (parameters.separationWeight !== undefined) {
  424. agentParams.separationWeight = parameters.separationWeight;
  425. }
  426. this.recastCrowd.setAgentParameters(index, agentParams);
  427. }
  428. /**
  429. * remove a particular agent previously created
  430. * @param index agent index returned by addAgent
  431. */
  432. removeAgent(index: number): void {
  433. this.recastCrowd.removeAgent(index);
  434. var item = this.agents.indexOf(index);
  435. if (item > -1) {
  436. this.agents.splice(item, 1);
  437. this.transforms.splice(item, 1);
  438. }
  439. }
  440. /**
  441. * get the list of all agents attached to this crowd
  442. * @returns list of agent indices
  443. */
  444. getAgents(): number[] {
  445. return this.agents;
  446. }
  447. /**
  448. * Tick update done by the Scene. Agent position/velocity/acceleration is updated by this function
  449. * @param deltaTime in seconds
  450. */
  451. update(deltaTime: number): void {
  452. // update crowd
  453. this.recastCrowd.update(deltaTime);
  454. // update transforms
  455. for (let index = 0; index < this.agents.length; index++)
  456. {
  457. this.transforms[index].position = this.getAgentPosition(this.agents[index]);
  458. }
  459. }
  460. /**
  461. * Set the Bounding box extent for doing spatial queries (getClosestPoint, getRandomPointAround, ...)
  462. * The queries will try to find a solution within those bounds
  463. * default is (1,1,1)
  464. * @param extent x,y,z value that define the extent around the queries point of reference
  465. */
  466. setDefaultQueryExtent(extent: Vector3): void
  467. {
  468. let ext = new this.bjsRECASTPlugin.bjsRECAST.Vec3(extent.x, extent.y, extent.z);
  469. this.recastCrowd.setDefaultQueryExtent(ext);
  470. }
  471. /**
  472. * Get the Bounding box extent specified by setDefaultQueryExtent
  473. * @returns the box extent values
  474. */
  475. getDefaultQueryExtent(): Vector3
  476. {
  477. let p = this.recastCrowd.getDefaultQueryExtent();
  478. return new Vector3(p.x, p.y, p.z);
  479. }
  480. /**
  481. * Get the Bounding box extent result specified by setDefaultQueryExtent
  482. * @param result output the box extent values
  483. */
  484. getDefaultQueryExtentToRef(result: Vector3): void
  485. {
  486. let p = this.recastCrowd.getDefaultQueryExtent();
  487. result.set(p.x, p.y, p.z);
  488. }
  489. /**
  490. * Release all resources
  491. */
  492. dispose() : void
  493. {
  494. this.recastCrowd.destroy();
  495. this._scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  496. this._onBeforeAnimationsObserver = null;
  497. }
  498. }