m33_ammo_turn_rope.html 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  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. <!--第三方lib-->
  22. <script
  23. type="text/javascript"
  24. src="../lib/include-lib.js"
  25. libpath="../lib/"
  26. include="jquery,font-awesome,bootstrap,layer,haoutil,turf,mars3d,cesium-meshVisualizer"
  27. ></script>
  28. <link href="css/style.css" rel="stylesheet" />
  29. </head>
  30. <body class="dark">
  31. <div id="mars3dContainer" class="mars3d-container"></div>
  32. <!-- 面板 -->
  33. <div class="infoview">操作提示: Q 左摆动、 A 右摆动</div>
  34. <script src="./js/common.js"></script>
  35. <script type="text/javascript">
  36. "use script"; //开发环境建议开启严格模式
  37. var map;
  38. function initMap(options) {
  39. //合并属性参数,可覆盖config.json中的对应配置
  40. var mapOptions = mars3d.Util.merge(options, {
  41. scene: {
  42. center: { lat: 31.83456, lng: 117.219861, alt: 83, heading: 46, pitch: -35 },
  43. fxaa: true,
  44. },
  45. });
  46. //创建三维地球场景
  47. map = new mars3d.Map("mars3dContainer", mapOptions);
  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 BasicGeometry = Cesium.BasicGeometry;
  56. var LOD = Cesium.LOD;
  57. var center = Cesium.Cartesian3.fromDegrees(117.220206, 31.834866, 50);
  58. var modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(center);
  59. var meshVisualizer = new MeshVisualizer({
  60. modelMatrix: modelMatrix,
  61. up: { y: 1 },
  62. referenceAxisParameter: {
  63. length: 100,
  64. width: 0.05,
  65. headLength: 2,
  66. headWidth: 0.1,
  67. },
  68. });
  69. map.scene.primitives.add(meshVisualizer);
  70. meshVisualizer.showReference = true; //显示坐标轴
  71. function createRandomColor() {
  72. return Cesium.Color.fromRandom({ alpha: 1 }); //fromRgba(Math.floor(Math.random() * (1 << 24)));
  73. }
  74. function createMaterial() {
  75. return new MeshPhongMaterial({
  76. defaultColor: createRandomColor(),
  77. side: MeshMaterial.Sides.DOUBLE,
  78. translucent: false,
  79. });
  80. }
  81. Cesium.Cartesian3.prototype.set = function (x, y, z) {
  82. this.x = x;
  83. this.y = y;
  84. this.z = z;
  85. };
  86. Cesium.Cartesian3.prototype.copy = function (src) {
  87. this.x = src.x;
  88. this.y = src.y;
  89. this.z = src.z;
  90. };
  91. Cesium.Cartesian2.prototype.set = function (x, y) {
  92. this.x = x;
  93. this.y = y;
  94. };
  95. Cesium.Cartesian2.prototype.copy = function (src) {
  96. this.x = src.x;
  97. this.y = src.y;
  98. };
  99. Cesium.Quaternion.prototype.set = function (x, y, z, w) {
  100. this.x = x;
  101. this.y = y;
  102. this.z = z;
  103. this.w = w;
  104. };
  105. Cesium.Quaternion.prototype.copy = function (src) {
  106. this.x = src.x;
  107. this.y = src.y;
  108. this.z = src.z;
  109. this.w = src.w;
  110. };
  111. Ammo().then(function () {
  112. // - Global variables -
  113. // - Global variables -
  114. // Physics variables
  115. var gravityConstant = -9.8;
  116. var collisionConfiguration;
  117. var dispatcher;
  118. var broadphase;
  119. var solver;
  120. var physicsWorld;
  121. var rigidBodies = [];
  122. var margin = 0.05;
  123. var hinge;
  124. var rope;
  125. var transformAux1 = new Ammo.btTransform();
  126. var time = 0;
  127. var armMovement = 0;
  128. var softBodySolver;
  129. function initPhysics() {
  130. // Physics configuration
  131. collisionConfiguration = new Ammo.btSoftBodyRigidBodyCollisionConfiguration();
  132. dispatcher = new Ammo.btCollisionDispatcher(collisionConfiguration);
  133. broadphase = new Ammo.btDbvtBroadphase();
  134. solver = new Ammo.btSequentialImpulseConstraintSolver();
  135. softBodySolver = new Ammo.btDefaultSoftBodySolver();
  136. physicsWorld = new Ammo.btSoftRigidDynamicsWorld(dispatcher, broadphase, solver, collisionConfiguration, softBodySolver);
  137. physicsWorld.setGravity(new Ammo.btVector3(0, gravityConstant, 0));
  138. physicsWorld.getWorldInfo().set_m_gravity(new Ammo.btVector3(0, gravityConstant, 0));
  139. }
  140. function createObjects() {
  141. var pos = new Cesium.Cartesian3();
  142. var quat = new Cesium.Quaternion();
  143. // Ground
  144. pos.set(0, -0.5, 0);
  145. quat.set(0, 0, 0, 1);
  146. var ground = createParalellepiped(
  147. 40,
  148. 1,
  149. 40,
  150. 0,
  151. pos,
  152. quat,
  153. new MeshPhongMaterial({
  154. defaultColor: Cesium.Color.fromRgba(0xffffff).withAlpha(1), //"rgb(200,200,200)",
  155. side: MeshMaterial.Sides.DOUBLE,
  156. translucent: false,
  157. })
  158. );
  159. ground.quaternion = null;
  160. // Ball
  161. var ballMass = 1.2;
  162. var ballRadius = 0.6;
  163. var ball = new Mesh(
  164. new Cesium.SphereGeometry({
  165. radius: ballRadius,
  166. stackPartitions: 20,
  167. slicePartitions: 20,
  168. }),
  169. new MeshPhongMaterial({
  170. defaultColor: Cesium.Color.fromRgba(0x000000).withAlpha(1),
  171. side: MeshMaterial.Sides.DOUBLE,
  172. translucent: false,
  173. })
  174. );
  175. var ballShape = new Ammo.btSphereShape(ballRadius);
  176. ballShape.setMargin(margin);
  177. pos.set(-3, 2, 0);
  178. quat.set(0, 0, 0, 1);
  179. createRigidBody(ball, ballShape, ballMass, pos, quat);
  180. ball.physicsBody.setFriction(0.5);
  181. // Wall
  182. var brickMass = 0.5;
  183. var brickLength = 1.2;
  184. var brickDepth = 0.6;
  185. var brickHeight = brickLength * 0.5;
  186. var numBricksLength = 6;
  187. var numBricksHeight = 8;
  188. var z0 = -numBricksLength * brickLength * 0.5;
  189. pos.set(0, brickHeight * 0.5, z0);
  190. quat.set(0, 0, 0, 1);
  191. for (var j = 0; j < numBricksHeight; j++) {
  192. var oddRow = j % 2 == 1;
  193. pos.z = z0;
  194. if (oddRow) {
  195. pos.z -= 0.25 * brickLength;
  196. }
  197. var nRow = oddRow ? numBricksLength + 1 : numBricksLength;
  198. for (let i = 0; i < nRow; i++) {
  199. var brickLengthCurrent = brickLength;
  200. var brickMassCurrent = brickMass;
  201. if (oddRow && (i == 0 || i == nRow - 1)) {
  202. brickLengthCurrent *= 0.5;
  203. brickMassCurrent *= 0.5;
  204. }
  205. var brick = createParalellepiped(brickDepth, brickHeight, brickLengthCurrent, brickMassCurrent, pos, quat, createMaterial());
  206. if (oddRow && (i == 0 || i == nRow - 2)) {
  207. pos.z += 0.75 * brickLength;
  208. } else {
  209. pos.z += brickLength;
  210. }
  211. }
  212. pos.y += brickHeight;
  213. }
  214. // The rope
  215. // Rope graphic object
  216. var ropeNumSegments = 10;
  217. var ropeLength = 4;
  218. var ropeMass = 3;
  219. var ropePos = ball.position.clone();
  220. ropePos.y += ballRadius;
  221. var segmentLength = ropeLength / ropeNumSegments;
  222. var ropeMaterial = new MeshMaterial({
  223. defaultColor: Cesium.Color.fromRgba(0x000000).withAlpha(1),
  224. side: MeshMaterial.Sides.DOUBLE,
  225. translucent: false,
  226. wireframe: true,
  227. });
  228. var ropePositions = [];
  229. var ropeIndices = [];
  230. for (let i = 0; i < ropeNumSegments + 1; i++) {
  231. ropePositions.push(ropePos.x, ropePos.y + i * segmentLength, ropePos.z);
  232. }
  233. for (let i = 0; i < ropeNumSegments; i++) {
  234. ropeIndices.push(i, i + 1);
  235. }
  236. var ropeGeometry = new Cesium.Geometry({
  237. attributes: {
  238. position: new Cesium.GeometryAttribute({
  239. componentDatatype: Cesium.ComponentDatatype.DOUBLE,
  240. componentsPerAttribute: 3,
  241. values: new Float32Array(ropePositions),
  242. }),
  243. },
  244. indices: new Uint16Array(ropeIndices),
  245. primitiveType: Cesium.PrimitiveType.LINES,
  246. boundingSphere: Cesium.BoundingSphere.fromVertices(ropePositions),
  247. });
  248. rope = new Mesh(ropeGeometry, ropeMaterial);
  249. meshVisualizer.add(rope);
  250. // Rope physic object
  251. var softBodyHelpers = new Ammo.btSoftBodyHelpers();
  252. var ropeStart = new Ammo.btVector3(ropePos.x, ropePos.y, ropePos.z);
  253. var ropeEnd = new Ammo.btVector3(ropePos.x, ropePos.y + ropeLength, ropePos.z);
  254. var ropeSoftBody = softBodyHelpers.CreateRope(physicsWorld.getWorldInfo(), ropeStart, ropeEnd, ropeNumSegments - 1, 0);
  255. var sbConfig = ropeSoftBody.get_m_cfg();
  256. sbConfig.set_viterations(10);
  257. sbConfig.set_piterations(10);
  258. ropeSoftBody.setTotalMass(ropeMass, false);
  259. Ammo.castObject(ropeSoftBody, Ammo.btCollisionObject)
  260. .getCollisionShape()
  261. .setMargin(margin * 3);
  262. physicsWorld.addSoftBody(ropeSoftBody, 1, -1);
  263. rope.physicsBody = ropeSoftBody;
  264. // Disable deactivation
  265. ropeSoftBody.setActivationState(4);
  266. // The base
  267. var armMass = 2;
  268. var armLength = 3;
  269. var pylonHeight = ropePos.y + ropeLength;
  270. var baseMaterial = createMaterial();
  271. pos.set(ropePos.x, 0.1, ropePos.z - armLength);
  272. quat.set(0, 0, 0, 1);
  273. var base = createParalellepiped(1, 0.2, 1, 0, pos, quat, baseMaterial);
  274. base.quaternion = null;
  275. pos.set(ropePos.x, 0.5 * pylonHeight, ropePos.z - armLength);
  276. var pylon = createParalellepiped(0.4, pylonHeight, 0.4, 0, pos, quat, baseMaterial);
  277. pylon.quaternion = null;
  278. pos.set(ropePos.x, pylonHeight + 0.2, ropePos.z - 0.5 * armLength);
  279. var arm = createParalellepiped(0.4, 0.4, armLength + 0.4, armMass, pos, quat, baseMaterial);
  280. // Glue the rope extremes to the ball and the arm
  281. var influence = 1;
  282. ropeSoftBody.appendAnchor(0, ball.physicsBody, true, influence);
  283. ropeSoftBody.appendAnchor(ropeNumSegments, arm.physicsBody, true, influence);
  284. // Hinge constraint to move the arm
  285. var pivotA = new Ammo.btVector3(0, pylonHeight * 0.5, 0);
  286. var pivotB = new Ammo.btVector3(0, -0.2, -armLength * 0.5);
  287. var axis = new Ammo.btVector3(0, 1, 0);
  288. hinge = new Ammo.btHingeConstraint(pylon.physicsBody, arm.physicsBody, pivotA, pivotB, axis, axis, true);
  289. physicsWorld.addConstraint(hinge, true);
  290. }
  291. function createParalellepiped(sx, sy, sz, mass, pos, quat, material) {
  292. var box = Cesium.BoxGeometry.fromDimensions({
  293. dimensions: new Cesium.Cartesian3(sx, sy, sz),
  294. vertexFormat: new Cesium.VertexFormat({
  295. position: true,
  296. normal: true,
  297. }),
  298. });
  299. var threeObject = new Mesh(box, material);
  300. var shape = new Ammo.btBoxShape(new Ammo.btVector3(sx * 0.5, sy * 0.5, sz * 0.5));
  301. shape.setMargin(margin);
  302. createRigidBody(threeObject, shape, mass, pos, quat);
  303. return threeObject;
  304. }
  305. function createRigidBody(threeObject, physicsShape, mass, pos, quat) {
  306. threeObject.position.copy(pos);
  307. threeObject.quaternion = new Cesium.Quaternion(quat);
  308. var transform = new Ammo.btTransform();
  309. transform.setIdentity();
  310. transform.setOrigin(new Ammo.btVector3(pos.x, pos.y, pos.z));
  311. transform.setRotation(new Ammo.btQuaternion(quat.x, quat.y, quat.z, quat.w));
  312. var motionState = new Ammo.btDefaultMotionState(transform);
  313. var localInertia = new Ammo.btVector3(0, 0, 0);
  314. physicsShape.calculateLocalInertia(mass, localInertia);
  315. var rbInfo = new Ammo.btRigidBodyConstructionInfo(mass, motionState, physicsShape, localInertia);
  316. var body = new Ammo.btRigidBody(rbInfo);
  317. threeObject.physicsBody = body;
  318. meshVisualizer.add(threeObject);
  319. if (mass > 0) {
  320. rigidBodies.push(threeObject);
  321. // Disable deactivation
  322. body.setActivationState(4);
  323. }
  324. physicsWorld.addRigidBody(body);
  325. }
  326. function initInput() {
  327. window.addEventListener(
  328. "keydown",
  329. function (event) {
  330. switch (event.keyCode) {
  331. // Q
  332. case 81:
  333. armMovement = 1;
  334. break;
  335. // A
  336. case 65:
  337. armMovement = -1;
  338. break;
  339. }
  340. },
  341. false
  342. );
  343. window.addEventListener(
  344. "keyup",
  345. function (event) {
  346. armMovement = 0;
  347. },
  348. false
  349. );
  350. }
  351. function updatePhysics(deltaTime) {
  352. // Hinge control
  353. hinge.enableAngularMotor(true, 1.5 * armMovement, 50);
  354. // Step world
  355. physicsWorld.stepSimulation(deltaTime, 10);
  356. // Update rope
  357. var softBody = rope.physicsBody;
  358. var ropePositions = rope.geometry.attributes.position.values;
  359. var numVerts = ropePositions.length / 3;
  360. var nodes = softBody.get_m_nodes();
  361. var indexFloat = 0;
  362. for (let i = 0; i < numVerts; i++) {
  363. var node = nodes.at(i);
  364. var nodePos = node.get_m_x();
  365. ropePositions[indexFloat++] = nodePos.x();
  366. ropePositions[indexFloat++] = nodePos.y();
  367. ropePositions[indexFloat++] = nodePos.z();
  368. }
  369. rope.geometry.attributes.position.needsUpdate = true;
  370. // Update rigid bodies
  371. for (let i = 0, il = rigidBodies.length; i < il; i++) {
  372. var objThree = rigidBodies[i];
  373. var objPhys = objThree.physicsBody;
  374. var ms = objPhys.getMotionState();
  375. if (ms) {
  376. ms.getWorldTransform(transformAux1);
  377. var p = transformAux1.getOrigin();
  378. var q = transformAux1.getRotation();
  379. objThree.position.set(p.x(), p.y(), p.z());
  380. if (objThree.quaternion) {
  381. objThree.quaternion.set(q.x(), q.y(), q.z(), q.w());
  382. }
  383. objThree.modelMatrixNeedsUpdate = true;
  384. }
  385. }
  386. }
  387. var init = false;
  388. var start = false;
  389. var startTime = new Date();
  390. function update(frameState) {
  391. var deltaTime = (new Date() - startTime) / 1000.0;
  392. updatePhysics(deltaTime);
  393. startTime = new Date();
  394. }
  395. setTimeout(function () {
  396. if (!init) {
  397. // - Init -
  398. initPhysics();
  399. createObjects();
  400. initInput();
  401. init = true;
  402. }
  403. if (!start) {
  404. startTime = new Date();
  405. meshVisualizer.beforeUpdate.addEventListener(update);
  406. start = true;
  407. } else {
  408. meshVisualizer.beforeUpdate.removeEventListener(update);
  409. start = false;
  410. }
  411. }, 1000 * 3);
  412. });
  413. }
  414. </script>
  415. </body>
  416. </html>