m33_ammo_softbody_volume.html 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  5. <meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=0,minimum-scale=1.0,maximum-scale=1.0" />
  6. <meta name="author" content="火星科技 http://mars3d.cn " />
  7. <meta name="apple-touch-fullscreen" content="yes" />
  8. <meta name="apple-mobile-web-app-capable" content="yes" />
  9. <meta name="apple-mobile-web-app-status-bar-style" content="black" />
  10. <meta name="format-detection" content="telephone=no" />
  11. <meta name="x5-fullscreen" content="true" />
  12. <meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1" />
  13. <!-- 标题及搜索关键字 -->
  14. <meta name="keywords" content="火星科技,cesium,3D,GIS,marsgis,三维,地球,地图,开发,框架,系统,示例,资料,模型,离线,外包,合肥,安徽,中国" />
  15. <meta
  16. name="description"
  17. content="火星科技 合肥火星 合肥火星科技 合肥火星科技有限公司 leaflet leaflet框架 leaflet开发 cesium cesium开发 cesium框架 三维 地球 模型 gis marsgis 地图离线 地图开发 地图框架 地图外包 框架 开发 外包 地图离线 二维地图 三维地图 全景漫游 地理信息系统 云GIS 三维GIS GIS平台 WebGIS"
  18. />
  19. <link rel="shortcut icon" type="image/x-icon" href="" />
  20. <title>ammo物理引擎扩展支持 </title>
  21. <script
  22. type="text/javascript"
  23. src="../lib/include-lib.js"
  24. libpath="../lib/"
  25. include="jquery,font-awesome,bootstrap,layer,haoutil,turf,mars3d,cesium-meshVisualizer"
  26. ></script>
  27. <link href="css/style.css" rel="stylesheet" />
  28. </head>
  29. <body class="dark">
  30. <div id="mars3dContainer" class="mars3d-container"></div>
  31. <!-- 面板 -->
  32. <div class="infoview">操作提示:鼠标左键单击进行发射</div>
  33. <script src="./js/common.js"></script>
  34. <script type="text/javascript">
  35. "use script"; //开发环境建议开启严格模式
  36. var map;
  37. function initMap(options) {
  38. //合并属性参数,可覆盖config.json中的对应配置
  39. var mapOptions = mars3d.Util.merge(options, {
  40. scene: {
  41. center: { lat: 31.834648, lng: 117.219733, alt: 83, heading: 64, pitch: -34 },
  42. fxaa: true,
  43. },
  44. });
  45. //创建三维地球场景
  46. map = new mars3d.Map("mars3dContainer", mapOptions);
  47. //
  48. var MeshVisualizer = Cesium.MeshVisualizer;
  49. var Mesh = Cesium.Mesh;
  50. var MeshMaterial = Cesium.MeshMaterial;
  51. var FramebufferTexture = Cesium.FramebufferTexture;
  52. var GeometryUtils = Cesium.GeometryUtils;
  53. var MeshPhongMaterial = Cesium.MeshPhongMaterial;
  54. var BasicMeshMaterial = Cesium.BasicMeshMaterial;
  55. var LOD = Cesium.LOD;
  56. var center = Cesium.Cartesian3.fromDegrees(117.220206, 31.834866, 50);
  57. var modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(center);
  58. var meshVisualizer = new MeshVisualizer({
  59. modelMatrix: modelMatrix,
  60. up: { y: 1 },
  61. referenceAxisParameter: {
  62. length: 100,
  63. width: 0.05,
  64. headLength: 2,
  65. headWidth: 0.1,
  66. },
  67. });
  68. map.scene.primitives.add(meshVisualizer);
  69. meshVisualizer.showReference = true; //显示坐标轴
  70. function createRandomColor() {
  71. return Cesium.Color.fromRandom({ alpha: 1 }); //fromRgba(Math.floor(Math.random() * (1 << 24)));
  72. }
  73. function createMaterial() {
  74. return new MeshPhongMaterial({
  75. defaultColor: createRandomColor(),
  76. side: MeshMaterial.Sides.DOUBLE,
  77. translucent: false,
  78. });
  79. }
  80. Cesium.Cartesian3.prototype.set = function (x, y, z) {
  81. this.x = x;
  82. this.y = y;
  83. this.z = z;
  84. };
  85. Cesium.Cartesian2.prototype.set = function (x, y) {
  86. this.x = x;
  87. this.y = y;
  88. };
  89. Cesium.Quaternion.prototype.set = function (x, y, z, w) {
  90. this.x = x;
  91. this.y = y;
  92. this.z = z;
  93. this.w = w;
  94. };
  95. Ammo().then(function () {
  96. // - Global variables -
  97. // Graphics variables
  98. var clickRequest = false;
  99. var mouseCoords = new Cesium.Cartesian2();
  100. var ballMaterial = createMaterial();
  101. var pos = new Cesium.Cartesian3();
  102. var quat = new Cesium.Quaternion();
  103. // Physics variables
  104. var gravityConstant = -9.8;
  105. var collisionConfiguration;
  106. var dispatcher;
  107. var broadphase;
  108. var solver;
  109. var physicsWorld;
  110. var rigidBodies = [];
  111. var softBodies = [];
  112. var margin = 0.05;
  113. var hinge;
  114. var transformAux1 = new Ammo.btTransform();
  115. var softBodyHelpers = new Ammo.btSoftBodyHelpers();
  116. var armMovement = 0;
  117. var ray = new Cesium.Ray();
  118. var softBodySolver;
  119. function initPhysics() {
  120. // Physics configuration
  121. collisionConfiguration = new Ammo.btSoftBodyRigidBodyCollisionConfiguration();
  122. dispatcher = new Ammo.btCollisionDispatcher(collisionConfiguration);
  123. broadphase = new Ammo.btDbvtBroadphase();
  124. solver = new Ammo.btSequentialImpulseConstraintSolver();
  125. softBodySolver = new Ammo.btDefaultSoftBodySolver();
  126. physicsWorld = new Ammo.btSoftRigidDynamicsWorld(dispatcher, broadphase, solver, collisionConfiguration, softBodySolver);
  127. physicsWorld.setGravity(new Ammo.btVector3(0, gravityConstant, 0));
  128. physicsWorld.getWorldInfo().set_m_gravity(new Ammo.btVector3(0, gravityConstant, 0));
  129. }
  130. function createObjects() {
  131. // Ground
  132. pos.set(0, -0.5, 0);
  133. quat.set(0, 0, 0, 1);
  134. var ground = createParalellepiped(
  135. 40,
  136. 1,
  137. 40,
  138. 0,
  139. pos,
  140. quat,
  141. new MeshPhongMaterial({
  142. defaultColor: "rgb(200,200,200)",
  143. side: MeshMaterial.Sides.DOUBLE,
  144. translucent: false,
  145. })
  146. );
  147. GeometryUtils.computeVertexNormals(ground.geometry);
  148. // Create soft volumes
  149. var volumeMass = 15;
  150. var sphereGeometry = new THREE.SphereBufferGeometry(1.5, 40, 25);
  151. sphereGeometry.translate(5, 5, 0);
  152. createSoftVolume(sphereGeometry, volumeMass, 250);
  153. var boxGeometry = new THREE.BufferGeometry().fromGeometry(new THREE.BoxGeometry(1, 1, 5, 4, 4, 20));
  154. boxGeometry.translate(-2, 5, 0);
  155. createSoftVolume(boxGeometry, volumeMass, 120);
  156. // Ramp
  157. pos.set(3, 1, 0);
  158. Cesium.Quaternion.fromAxisAngle(new Cesium.Cartesian3(0, 0, 1), (30 * Math.PI) / 180, quat);
  159. var obstacle = createParalellepiped(
  160. 10,
  161. 1,
  162. 4,
  163. 0,
  164. pos,
  165. quat,
  166. new MeshPhongMaterial({
  167. defaultColor: "rgb(28,28,28)",
  168. side: MeshMaterial.Sides.DOUBLE,
  169. translucent: false,
  170. })
  171. );
  172. GeometryUtils.computeVertexNormals(obstacle.geometry);
  173. }
  174. function processGeometry(bufGeometry) {
  175. // Obtain a Geometry
  176. var geometry = new THREE.Geometry().fromBufferGeometry(bufGeometry);
  177. // Merge the vertices so the triangle soup is converted to indexed triangles
  178. var vertsDiff = geometry.mergeVertices();
  179. // Convert again to BufferGeometry, indexed
  180. var indexedBufferGeom = createIndexedBufferGeometryFromGeometry(geometry);
  181. // Create index arrays mapping the indexed vertices to bufGeometry vertices
  182. mapIndices(bufGeometry, indexedBufferGeom);
  183. }
  184. function createIndexedBufferGeometryFromGeometry(geometry) {
  185. var numVertices = geometry.vertices.length;
  186. var numFaces = geometry.faces.length;
  187. var bufferGeom = new THREE.BufferGeometry();
  188. var vertices = new Float32Array(numVertices * 3);
  189. var indices = new (numFaces * 3 > 65535 ? Uint32Array : Uint16Array)(numFaces * 3);
  190. for (let i = 0; i < numVertices; i++) {
  191. let p = geometry.vertices[i];
  192. let i3 = i * 3;
  193. vertices[i3] = p.x;
  194. vertices[i3 + 1] = p.y;
  195. vertices[i3 + 2] = p.z;
  196. }
  197. for (let i = 0; i < numFaces; i++) {
  198. let f = geometry.faces[i];
  199. let i3 = i * 3;
  200. indices[i3] = f.a;
  201. indices[i3 + 1] = f.b;
  202. indices[i3 + 2] = f.c;
  203. }
  204. bufferGeom.setIndex(new THREE.BufferAttribute(indices, 1));
  205. bufferGeom.addAttribute("position", new THREE.BufferAttribute(vertices, 3));
  206. return bufferGeom;
  207. }
  208. function isEqual(x1, y1, z1, x2, y2, z2) {
  209. var delta = 0.000001;
  210. return Math.abs(x2 - x1) < delta && Math.abs(y2 - y1) < delta && Math.abs(z2 - z1) < delta;
  211. }
  212. function mapIndices(bufGeometry, indexedBufferGeom) {
  213. // Creates ammoVertices, ammoIndices and ammoIndexAssociation in bufGeometry
  214. var vertices = bufGeometry.attributes.position.array;
  215. var idxVertices = indexedBufferGeom.attributes.position.array;
  216. var indices = indexedBufferGeom.index.array;
  217. var numIdxVertices = idxVertices.length / 3;
  218. var numVertices = vertices.length / 3;
  219. bufGeometry.ammoVertices = idxVertices;
  220. bufGeometry.ammoIndices = indices;
  221. bufGeometry.ammoIndexAssociation = [];
  222. for (var i = 0; i < numIdxVertices; i++) {
  223. var association = [];
  224. bufGeometry.ammoIndexAssociation.push(association);
  225. var i3 = i * 3;
  226. for (var j = 0; j < numVertices; j++) {
  227. var j3 = j * 3;
  228. if (isEqual(idxVertices[i3], idxVertices[i3 + 1], idxVertices[i3 + 2], vertices[j3], vertices[j3 + 1], vertices[j3 + 2])) {
  229. association.push(j3);
  230. }
  231. }
  232. }
  233. }
  234. function createSoftVolume(bufferGeom, mass, pressure) {
  235. processGeometry(bufferGeom);
  236. var volume = new Mesh(
  237. bufferGeom,
  238. new BasicMeshMaterial({
  239. uniforms: {
  240. diffuseColorMap: "img/textures/colors.png",
  241. },
  242. translucent: false,
  243. })
  244. );
  245. volume.geometry.ammoIndexAssociation = bufferGeom.ammoIndexAssociation;
  246. meshVisualizer.add(volume);
  247. // Volume physic object
  248. var volumeSoftBody = softBodyHelpers.CreateFromTriMesh(
  249. physicsWorld.getWorldInfo(),
  250. bufferGeom.ammoVertices,
  251. bufferGeom.ammoIndices,
  252. bufferGeom.ammoIndices.length / 3,
  253. true
  254. );
  255. var sbConfig = volumeSoftBody.get_m_cfg();
  256. sbConfig.set_viterations(40);
  257. sbConfig.set_piterations(40);
  258. // Soft-soft and soft-rigid collisions
  259. sbConfig.set_collisions(0x11);
  260. // Friction
  261. sbConfig.set_kDF(0.1);
  262. // Damping
  263. sbConfig.set_kDP(0.01);
  264. // Pressure
  265. sbConfig.set_kPR(pressure);
  266. // Stiffness
  267. volumeSoftBody.get_m_materials().at(0).set_m_kLST(0.9);
  268. volumeSoftBody.get_m_materials().at(0).set_m_kAST(0.9);
  269. volumeSoftBody.setTotalMass(mass, false);
  270. Ammo.castObject(volumeSoftBody, Ammo.btCollisionObject).getCollisionShape().setMargin(margin);
  271. physicsWorld.addSoftBody(volumeSoftBody, 1, -1);
  272. volume.physicsBody = volumeSoftBody;
  273. // Disable deactivation
  274. volumeSoftBody.setActivationState(4);
  275. softBodies.push(volume);
  276. }
  277. function createParalellepiped(sx, sy, sz, mass, pos, quat, material) {
  278. var box = Cesium.BoxGeometry.fromDimensions({
  279. dimensions: new Cesium.Cartesian3(sx, sy, sz),
  280. vertexFormat: new Cesium.VertexFormat({
  281. position: true,
  282. normal: true,
  283. }),
  284. });
  285. var threeObject = new Mesh(box, material);
  286. var shape = new Ammo.btBoxShape(new Ammo.btVector3(sx * 0.5, sy * 0.5, sz * 0.5));
  287. shape.setMargin(margin);
  288. createRigidBody(threeObject, shape, mass, pos, quat);
  289. return threeObject;
  290. }
  291. function createRigidBody(threeObject, physicsShape, mass, pos, quat) {
  292. Cesium.Cartesian3.clone(pos, threeObject.position);
  293. if (!threeObject.quaternion) {
  294. threeObject.quaternion = new Cesium.Quaternion();
  295. }
  296. Cesium.Quaternion.clone(quat, threeObject.quaternion);
  297. var transform = new Ammo.btTransform();
  298. transform.setIdentity();
  299. transform.setOrigin(new Ammo.btVector3(pos.x, pos.y, pos.z));
  300. transform.setRotation(new Ammo.btQuaternion(quat.x, quat.y, quat.z, quat.w));
  301. var motionState = new Ammo.btDefaultMotionState(transform);
  302. var localInertia = new Ammo.btVector3(0, 0, 0);
  303. physicsShape.calculateLocalInertia(mass, localInertia);
  304. var rbInfo = new Ammo.btRigidBodyConstructionInfo(mass, motionState, physicsShape, localInertia);
  305. var body = new Ammo.btRigidBody(rbInfo);
  306. threeObject.physicsBody = body;
  307. meshVisualizer.add(threeObject);
  308. if (mass > 0) {
  309. rigidBodies.push(threeObject);
  310. // Disable deactivation
  311. body.setActivationState(4);
  312. }
  313. physicsWorld.addRigidBody(body);
  314. return body;
  315. }
  316. function updatePhysics(deltaTime) {
  317. try {
  318. // Step world
  319. physicsWorld.stepSimulation(deltaTime, 10);
  320. // Update soft volumes
  321. for (let i = 0, il = softBodies.length; i < il; i++) {
  322. var volume = softBodies[i];
  323. var geometry = volume.geometry;
  324. var softBody = volume.physicsBody;
  325. var volumePositions = geometry.attributes.position.values;
  326. var volumeNormals = geometry.attributes.normal.values;
  327. var association = geometry.ammoIndexAssociation;
  328. var numVerts = association.length;
  329. var nodes = softBody.get_m_nodes();
  330. for (var j = 0; j < numVerts; j++) {
  331. var node = nodes.at(j);
  332. var nodePos = node.get_m_x();
  333. var x = nodePos.x();
  334. var y = nodePos.y();
  335. var z = nodePos.z();
  336. var nodeNormal = node.get_m_n();
  337. var nx = nodeNormal.x();
  338. var ny = nodeNormal.y();
  339. var nz = nodeNormal.z();
  340. var assocVertex = association[j];
  341. for (var k = 0, kl = assocVertex.length; k < kl; k++) {
  342. var indexVertex = assocVertex[k];
  343. volumePositions[indexVertex] = x;
  344. volumeNormals[indexVertex] = nx;
  345. indexVertex++;
  346. volumePositions[indexVertex] = y;
  347. volumeNormals[indexVertex] = ny;
  348. indexVertex++;
  349. volumePositions[indexVertex] = z;
  350. volumeNormals[indexVertex] = nz;
  351. }
  352. }
  353. geometry.attributes.position.needsUpdate = true;
  354. geometry.attributes.normal.needsUpdate = true;
  355. volume.modelMatrixNeedsUpdate = true;
  356. }
  357. // Update rigid bodies
  358. for (var i = 0, il = rigidBodies.length; i < il; i++) {
  359. var objThree = rigidBodies[i];
  360. var objPhys = objThree.physicsBody;
  361. var ms = objPhys.getMotionState();
  362. if (ms) {
  363. ms.getWorldTransform(transformAux1);
  364. var p = transformAux1.getOrigin();
  365. var q = transformAux1.getRotation();
  366. objThree.position.set(p.x(), p.y(), p.z());
  367. objThree.quaternion.set(q.x(), q.y(), q.z(), q.w());
  368. objThree.modelMatrixNeedsUpdate = true;
  369. }
  370. }
  371. } catch (e) {
  372. meshVisualizer.beforeUpdate.removeEventListener(update);
  373. console.log("崩溃了", e);
  374. }
  375. }
  376. var start = false;
  377. var init = false;
  378. var startTime = new Date();
  379. var rayDir = new Cesium.Cartesian3();
  380. var maxDistance = 100; //发射点与射线和局部场景的交点的距离不能太远,过远会撕碎软体进而碎片过多时导致ammo物理引擎崩溃
  381. function initInput() {
  382. var scene = map.scene;
  383. var handler = new Cesium.ScreenSpaceEventHandler(scene.canvas);
  384. var lastMesh = null;
  385. handler.setInputAction(function (movement) {
  386. if (!clickRequest) {
  387. Cesium.Cartesian2.clone(movement.position, mouseCoords);
  388. clickRequest = true;
  389. }
  390. }, Cesium.ScreenSpaceEventType.LEFT_DOWN);
  391. }
  392. function processClick() {
  393. if (clickRequest) {
  394. meshVisualizer.getPickRay(mouseCoords, ray);
  395. if (!ray) {
  396. clickRequest = false;
  397. return;
  398. }
  399. // Creates a ball
  400. var ballMass = 3;
  401. var ballRadius = 0.4;
  402. var ball = new Mesh(new THREE.SphereGeometry(ballRadius, 18, 16), ballMaterial);
  403. var ballShape = new Ammo.btSphereShape(ballRadius);
  404. ballShape.setMargin(margin);
  405. Cesium.Cartesian3.clone(ray.direction, rayDir);
  406. Cesium.Cartesian3.subtract(ray.origin, ray.direction, pos);
  407. quat.set(0, 0, 0, 1);
  408. var ballBody = createRigidBody(ball, ballShape, ballMass, pos, quat);
  409. ballBody.setFriction(0.5);
  410. Cesium.Cartesian3.normalize(rayDir, rayDir);
  411. Cesium.Cartesian3.multiplyByScalar(rayDir, 30, rayDir);
  412. // console.log(rayDir);
  413. ballBody.setLinearVelocity(new Ammo.btVector3(rayDir.x, rayDir.y, rayDir.z));
  414. clickRequest = false;
  415. }
  416. }
  417. function update(frameState) {
  418. var deltaTime = (new Date() - startTime) / 1000.0;
  419. updatePhysics(deltaTime);
  420. processClick();
  421. startTime = new Date();
  422. }
  423. setTimeout(function () {
  424. if (!init) {
  425. // - Init -
  426. //initGraphics();
  427. initPhysics();
  428. createObjects();
  429. initInput();
  430. init = true;
  431. }
  432. if (!start) {
  433. meshVisualizer.beforeUpdate.addEventListener(update);
  434. start = true;
  435. } else {
  436. meshVisualizer.beforeUpdate.removeEventListener(update);
  437. start = false;
  438. }
  439. }, 1000 * 3);
  440. });
  441. }
  442. </script>
  443. </body>
  444. </html>