RapierTrimesh.re.ts 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import * as RE from 'rogue-engine';
  2. import * as THREE from 'three';
  3. import RAPIER from '@dimforge/rapier3d-compat';
  4. import RogueRapier from '../../Lib/RogueRapier';
  5. import RapierCollider from './RapierCollider';
  6. export default class RapierTrimesh extends RapierCollider {
  7. worldScale = new THREE.Vector3();
  8. worldPos = new THREE.Vector3();
  9. tmpVec0 = new RAPIER.Vector3(0,0,0);
  10. tmpVec1 = new RAPIER.Vector3(0,0,0);
  11. tmpVec2 = new RAPIER.Vector3(0,0,0);
  12. tmpQuat0 = new RAPIER.Vector3(0,0,0);
  13. createShape() {
  14. if (!(this.object3d instanceof THREE.Mesh)) return;
  15. this.object3d.updateWorldMatrix(true, true);
  16. this.object3d.getWorldScale(this.worldScale);
  17. this.object3d.getWorldPosition(this.worldPos);
  18. this.object3d.getWorldQuaternion(this.worldQuaternion);
  19. const mesh = this.object3d;
  20. let geometry = (mesh.geometry as THREE.BufferGeometry);
  21. // geometry.computeBoundingSphere();
  22. // geometry.normalizeNormals();
  23. const vertices = this.getVertices(geometry);
  24. if (!vertices.length) return;
  25. const indices = geometry.getIndex();
  26. if (!indices) return;
  27. let cleanIndiArray: number[] = [];
  28. for ( let i = 0; i < indices.count; i += 3 ) {
  29. const a = indices.getX( i );
  30. const b = indices.getX( i + 1 );
  31. const c = indices.getX( i + 2 );
  32. cleanIndiArray.push(a,b,c);
  33. }
  34. let colliderDesc = RAPIER.ColliderDesc.trimesh(vertices, new Uint32Array(cleanIndiArray));
  35. this.collider = RogueRapier.world.createCollider(colliderDesc, this.body);
  36. }
  37. getVertices(geometry: THREE.BufferGeometry) {
  38. const position = geometry.attributes.position;
  39. const vertices = new Float32Array(position.count * 3);
  40. for (let i = 0; i < position.count; i++) {
  41. vertices[i * 3] = position.getX(i) * this.worldScale.x;
  42. vertices[i * 3 + 1] = position.getY(i) * this.worldScale.y;
  43. vertices[i * 3 + 2] = position.getZ(i) * this.worldScale.z;
  44. }
  45. return vertices;
  46. }
  47. }
  48. RE.registerComponent(RapierTrimesh);